Skip to content

fix(security): CodeQL-recognized path-injection sanitizer for heatmap embed (PR #283 follow-up) - #287

Closed
cursor[bot] wants to merge 3 commits into
mainfrom
cursor/sre-agent-protocol-1f12
Closed

cursor[bot] wants to merge 3 commits into
mainfrom
cursor/sre-agent-protocol-1f12

Conversation

@cursor

@cursor cursor Bot commented Apr 28, 2026

Copy link
Copy Markdown
Contributor

Summary

Closes the CodeQL py/path-injection alert that PR #283 left open at report/generator.py:46. Replaces the Path.is_relative_to containment check (not recognized by CodeQL as a sanitizer) with the same two-step mold already accepted by CodeQL in api/routes.py:

  1. Whitelist barrier — _heatmap_basename: os.path.basename then re.fullmatch(_HEATMAP_BASENAME_PATTERN, name) (^heatmap_[A-Za-z0-9_-]{4,64}\.png$).
  2. Containment — _safe_heatmap_path_under_output_dir: realpath-canonical base + os.path.normpath(os.path.join(base, name)) + startswith(base) + isfile().

The user-influenced heatmap_path argument is never passed to os.path.join or Path.resolve; only the validated basename is joined with the operator-controlled output_dir, so CodeQL's data-flow stops at the barrier. session_id-derived report and heatmap filenames continue through report.safe_prefix.safe_session_prefix (existing helper).

A backwards-compatible alias _heatmap_path_under_output_dir is kept for callers that imported the previous helper name.

Why the previous fix failed CI

Path.is_relative_to may be useful for application logic, but CodeQL's py/path-injection query does not treat it as a barrier. Bandit, Semgrep, Sonar, and the duplicate Analyze (Python) job in .github/workflows/codeql.yml were all green precisely because the issue is strictly Python data-flow in the GHAS CodeQL job — the same point the Slack thread RCA called out.

Engineering DNA

  • docs/ops/inspirations/DEFENSIVE_SCANNING_MANIFESTO.md — "no surprise side effects" extends to the report writer; filenames must never let a tainted segment pivot away from the operator-controlled output directory. Zero impact on database locks: this PR only edits filename validation and image embedding; no SQL, connector, or session lifecycle code is touched. The WITH (NOLOCK) / sampling cap / statement-attribution clauses are unaffected.
  • docs/ops/inspirations/THE_ART_OF_THE_FALLBACK.md — when containment fails, the generator degrades silently (no embed) and the Excel still ships. This honours the "diagnostic on fall" rule via the existing try/except: pass around OpenpyxlImage, without raising and without writing a sink.
  • NASA/Gibson/Savage: small, instrumented, reversible. The change is one helper plus one call-site swap, behind 26 new unit tests that pin the sanitizer mold so the same defect class cannot return silently.

RCA (Julia Evans-style)

CodeQL is reading the shape of the code, not your intent.

When the resolved candidate came from Path(heatmap_path).resolve(), every byte of heatmap_path was still in scope as far as the analyzer was concerned. is_relative_to runs at runtime; the analyzer does not model it as a barrier. So when OpenpyxlImage(str(safe_heatmap)) ran two lines later, CodeQL still saw a path expression "depending on a user-provided value."

The fix flips the order: shrink the input first, then rebuild the path inside the trusted base. os.path.basename is a documented sanitizer; re.fullmatch against a literal allowlist regex is a barrier; normpath(join(base, name)) + startswith(base) + isfile() is the canonical containment check. Same mold the dashboard already uses in api/routes.py — and that one CodeQL accepts.

Tests

  • tests/test_report_generator_path_safety.py (new): 26 tests covering basename allowlist accept/reject, traversal-collapses-to-safe-basename, off-allowlist rejection, missing file under output_dir, unresolvable output_dir (OSError + ValueError on embedded NUL), and symlinked output_dir realpath.
  • Existing path/security suites still green: tests/test_report_path_safety.py (5), tests/test_safe_prefix.py (3), tests/test_security.py (22), and the wider report surface (test_report_trends, test_executive_report, test_scan_evidence, test_report_recommendations, test_report_data_source_inventory, test_routes_responses, …).
  • 136 scoped tests pass (-k "report or generator or path or safe or heatmap or security"); Ruff lint and format clean.

Documentation

  • ADR 0044-codeql-path-injection-sanitizer-mold.md — locks in the basename-allowlist + normpath/startswith/isfile mold for both api/routes.py and report/generator.py, with explicit guidance that Path.is_relative_to is not a CodeQL barrier.
  • docs/adr/README.md index row added; AGENTS.md "Current last" pointer bumped to ADR 0044.

Verification checklist (LMDE-style)

  • Reproduced the failing CodeQL annotation via gh api repos/FabioLeitao/data-boar/check-runs/73292858146/annotations — report/generator.py:46, "Uncontrolled data used in path expression".
  • Identified the unrecognized sanitizer (Path.is_relative_to) and the accepted sibling pattern in api/routes.py (_real_file_under_out_dir_str + _HEATMAP_FILENAME_PATTERN).
  • Applied the accepted mold to report/generator.py; helper is isolated and named clearly so CodeQL can validate the contract on a tight scope.
  • Added unit tests covering both sanitizers and the documented edge cases.
  • Confirmed zero impact on customer DB / connector / session code (defensive architecture clause).
  • Will monitor the GHAS CodeQL job on this PR per the Slack ask (gh run view).

Refs

Open in Web View Automation 

cursoragent and others added 3 commits April 28, 2026 01:16
…eatmap embed

Replace Path.is_relative_to() (not recognized by CodeQL py/path-injection)
with the same sanitizer mold already accepted in api/routes.py:

- _heatmap_basename: os.path.basename + re.fullmatch on allowlist (whitelist barrier)
- _safe_heatmap_path_under_output_dir: realpath base + normpath(join(base, name))
  + startswith + isfile (containment under operator-controlled output_dir)

The user-influenced heatmap_path argument is never passed to os.path.join or
Path.resolve; only the validated basename flows into the join, so CodeQL data-flow
stops at the barrier. session_id-derived filenames continue to flow through
report.safe_prefix.safe_session_prefix.

Backwards-compatible alias _heatmap_path_under_output_dir is kept for callers that
imported the previous helper name.

Refs PR #283 RCA (Slack thread); see ADR 0044.

Co-authored-by: Fabio Tavares Leitão <[email protected]>
…sanitizer

Pin the CodeQL py/path-injection sanitizer mold so the same defect class
cannot return silently if someone tries to 'simplify' the helper back to
Path.is_relative_to or skip the basename allowlist.

Covers:
- _heatmap_basename: allowlist accept + reject (traversal, off-pattern, oversize)
- _safe_heatmap_path_under_output_dir: real-file containment, traversal collapse
  to safe basename, off-allowlist rejection, missing file, unresolvable output_dir
  (OSError + ValueError on embedded NUL), and symlinked output_dir realpath

26 tests, all pass alongside existing tests/test_report_path_safety.py and
tests/test_safe_prefix.py.

Co-authored-by: Fabio Tavares Leitão <[email protected]>
Document the basename allowlist + normpath/startswith/isfile sanitizer mold
as the workflow lock-in for both api/routes.py (already accepted by CodeQL)
and report/generator.py (this slice). Calls out:

- Why Path.is_relative_to is not a CodeQL barrier (PR #283 RCA).
- The two-step sanitizer chain that CodeQL recognizes.
- safe_session_prefix() for session_id-derived filenames.
- Silent fallback (no embed) on rejection per THE_ART_OF_THE_FALLBACK.md.
- Zero blast radius on customer DB (DEFENSIVE_SCANNING_MANIFESTO.md clauses
  unaffected).

Index row added to docs/adr/README.md; AGENTS.md 'Current last' bumped to 0044.

Co-authored-by: Fabio Tavares Leitão <[email protected]>
Comment thread report/generator.py

# Backwards-compatible alias kept for tests/external callers that imported the
# previous helper name. New code should call :func:`_safe_heatmap_path_under_output_dir`.
_heatmap_path_under_output_dir = _safe_heatmap_path_under_output_dir
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants