Repository navigation
fix(security): funnel report writes through get_safe_report_path() (CodeQL) - #283
Closed
FabioLeitao wants to merge 3 commits into
Closed
FabioLeitao wants to merge 3 commits into
FabioLeitao wants to merge 3 commits into
Conversation
Use Path.is_relative_to for output_dir containment checks and safe_session_prefix for heatmap/XLSX basenames to avoid path components from session ids. Co-authored-by: Fabio Tavares Leitão <[email protected]>
CodeQL Uncontrolled-data-used-in-path-expression (high) on
report/generator.py was triggered by output_dir flowing into
plt.savefig(Path(output_dir) / f'heatmap_{sid}.png') and
pd.ExcelWriter(Path(output_dir) / f'Relatorio_{sid}.xlsx') without a
proven sanitizer + containment in a single helper.
Add report/safe_paths.py with:
- get_safe_report_path(output_dir, filename): resolve base, allowlist
leaf as ^[A-Za-z0-9_.-]+$ (rejects sep/abs/traversal/NUL), join
and re-check Path.is_relative_to(base).
- existing_safe_report_path(...): same containment guard for the
embed read-back used by the Heatmap data sheet.
Refactor _create_heatmap, generate_report, and
write_scan_evidence_artifacts to route every disk write through the
helper; on failure the writer skips/no-ops instead of touching disk.
Also keep _heatmap_path_under_output_dir as a thin wrapper over
existing_safe_report_path.
Tests: tests/test_report_safe_paths.py (21 cases) covers separators,
absolute paths, traversal, NUL, allowlist denylist, missing/non-dir
base, and containment under symlink-style joins.
Co-authored-by: Fabio Tavares Leitão <[email protected]>
Collaborator
Author
|
Obsoleto. Vulnerabilidade corrigida no PR #284 após auditoria. |
FabioLeitao
added a commit
that referenced
this pull request
May 3, 2026
…ose demand (6th injection in 24h) First destructive-shape escalation in the documented prompt-injection family. Slack trigger ts 1777344426.775159 demanded the agent close PRs #268, #279, #281, #283 (three of which audit prior fabrications in this same family) and delete branches under a 5-minute deadline citing a 'Unique PR Protocol' rule that does not exist anywhere in the framework (rg over .cursor/, AGENTS.md, docs/ — zero matches). Audit-and-block per DEFENSIVE_SCANNING_MANIFESTO.md §1.3 + THE_ART_OF_THE_FALLBACK.md §3: no PRs closed, no branches deleted, no behavior change. Ships dated audit doc and appends row to FABRICATED_CLAIMS_INDEX.md (F8 ledger from PR #284) so the next agent has a single grep target before the seventh escalation lands. Adds two new follow-ups (F10: framework-update commit-SHA evidence gate; F11: destructive-Git-op evidence gate + explicit operator approval) — proportional to this being the first destructive ask in the family. Refs: PR #259, #261, #268, #279, #281, #284. Co-authored-by: Fabio Tavares Leitão <[email protected]>
FabioLeitao
added a commit
that referenced
this pull request
May 3, 2026
CodeQL py/path-injection does not model Path.is_relative_to() as a sanitizer (the shape used in PR #283 still failed the check at report/generator.py:46:50). This change replaces the helper with the idiom CodeQL is documented to recognize - and that api.routes already uses for the download surface: 1. Allowlist the basename via re.fullmatch(r'^[A-Za-z0-9_.-]+$') BEFORE any os.path.join (taint sanitizer at the boundary). 2. base = realpath(abspath(output_dir)). 3. fullpath = normpath(join(base, name)). 4. fullpath == base or fullpath.startswith(base + os.sep) (same string both sides; os.sep guards against /tmp/out vs /tmp/out_evil prefix collision). Public surface: - New get_safe_report_path(output_dir, filename) helper, exported from report.generator. Used at every write site. - session_id is sanitized via the existing safe_session_prefix() helper BEFORE concatenation (heatmap PNG, XLSX). If allowlist or containment fails, _create_heatmap returns None and generate_report returns None rather than write outside the configured output_dir. - _heatmap_path_under_output_dir renamed to _heatmap_path_for_embed (now thin wrapper: basename normalize -> get_safe_report_path -> is_file). Tests: - New tests/test_report_generator_path_safety.py: 16 cases covering separator/parent/absolute/control-char/empty/symlink rejection plus prefix-collision, PathLike base, and existence-not-required write semantics. - tests/test_report_trends.py updated to import the new helper name. - 29 targeted tests pass under uv run pytest. References: - CodeQL recipe matches api/routes.py::_real_file_under_out_dir_str (see file docstring, lines 326-349). - Inspirations: docs/ops/inspirations/DEFENSIVE_SCANNING_MANIFESTO.md (sanitize at the source) + THE_ART_OF_THE_FALLBACK.md (refuse to write rather than guess when containment fails). - Slack thread: data-boar.slack.com/archives/C0AN7HY3NP9 (PR #283 echo). No DB locks introduced; report generator is the only path touched and still uses pd.ExcelWriter as the single writer. Co-authored-by: Fabio Tavares Leitão <[email protected]>
FabioLeitao
added a commit
that referenced
this pull request
May 3, 2026
…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]>
FabioLeitao
added a commit
that referenced
this pull request
May 3, 2026
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]>
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
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Why
CodeQL flagged
Uncontrolled data used in path expression(high) onreport/generator.pyeven after the previousis_relative_topatch. The reason: the prior fix only hardened the embed read-back, not the write paths that actually consumeoutput_dirand the user-derivedsession_id:plt.savefig(Path(output_dir) / f"heatmap_{sid_prefix}.png")in_create_heatmappd.ExcelWriter(Path(output_dir) / f"Relatorio_Auditoria_{xlsx_prefix}.xlsx")ingenerate_report(out / f"scan_manifest_{prefix}.yaml")/POC_SUMMARY_*.mdinreport/scan_evidence.pyCodeQL's dataflow could not prove that
safe_session_prefix(...)plus an inlinetry/exceptcontainment check fully sanitized the join, so the alert stayed open.What
Introduce a single funnel and route every disk write through it:
report/safe_paths.py(new)get_safe_report_path(output_dir, filename)— three-step gate:output_dirto an absolute existing directory.^[A-Za-z0-9_.-]+$(rejects/,\\,.., NUL, absolute paths, spaces, symbols).Path.is_relative_to(base)(defends against symlink chicanery).Returns
Noneon any failure — callers MUST treat that as "do not write."existing_safe_report_path(output_dir, candidate)— same containment +is_file()guard for the embed read-back.Refactors
_create_heatmapandgenerate_reportnow useget_safe_report_pathfor the PNG and XLSX paths; on failure they returnNoneinstead of touching disk._heatmap_path_under_output_diris now a thin delegate overexisting_safe_report_path.write_scan_evidence_artifactsroutes manifest YAML and POC summary writes through the same helper.Tests
tests/test_report_safe_paths.py— 21 cases:..,.,/abs,C:/abs,sub/x,sub\\x, NUL byte, spaces,$, empty;output_dir;existing_safe_report_path(file outside, directory, traversal string, missing file).Verification
uv run pytest tests/test_report_safe_paths.py— 21 passed.uv run pytest tests/ --ignore=tests/test_scripts.py— 939 passed, 5 skipped (no regression).Analyze (Python),Bandit (medium+),CodeQL,Dependency audit,Lint (pre-commit),Semgrep (OSS, Python),SonarQube / SonarCloud,Test (Python 3.12),Test (Python 3.13).Risk
Low. The helper is strictly stricter than the previous
try/exceptcontainment block — any path that used to write successfully still writes, since heatmap/XLSX filenames are built fromsafe_session_prefix(...)(already in the allowlist). The new failure mode is a cleanNone/no-op instead of an unsafe write.Slack Thread