Skip to content

fix(security): tighten Bandit — triage 41 low findings + raise CI gate to low+ - #282

Closed
cursor[bot] wants to merge 2 commits into
mainfrom
cursor/sre-automation-agent-protocol-adc3
Closed

cursor[bot] wants to merge 2 commits into
mainfrom
cursor/sre-automation-agent-protocol-adc3

Conversation

@cursor

@cursor cursor Bot commented Apr 27, 2026

Copy link
Copy Markdown
Contributor

Why

The operator pinged in Slack (paraphrasing): "olha que nem apertei no bandit ainda, tá bem loose ainda estes configs... vamos ver como se sai qndo eu precisar mesmo..." — the Bandit security linter was deliberately running at -ll (medium+ only) because Phase 3 of PLAN_BANDIT_SECURITY_LINTER.md hadn't been triaged yet. With the gate that loose, a real low-severity regression (e.g. a new try/except/pass swallowing a security-relevant error, or a new subprocess call that doesn't pin its argv) lands silently.

This PR finishes Phase 3, raises the CI gate to -l (low+), and adds a local regression test so the next contributor trips before CI does.

What's in here (two commits, two intents)

1. fix(security): triage 41 low findings, zero behavior change

Every Bandit low finding in product code (api, core, config, connectors, database, file_scan, report, main.py) was reviewed one-by-one and annotated with # nosec BXXX on the exact line + a one-line comment above explaining why the demotion is intentional, anchored to repo doctrine:

Bandit ID Count Doctrinal anchor
B110 (try/except/pass) 33 DEFENSIVE_SCANNING_MANIFESTO.md §1 clause 1 — "no surprise side effects"; optional telemetry/cleanup must never break the customer scan
B112 (try/except/continue) 3 THE_ART_OF_THE_FALLBACK.md §3 — "diagnostic on fall"; per-row/per-archive-entry skipping is the documented degraded path
B603 / B607 (subprocess on PATH) 2 connectors/rich_media_sample.py::_ffprobe_metadata_text — fixed argv, no shell, only path varies (validated upstream), missing binary degrades to ""
B404 (import subprocess) 1 Same site, documented at the import
B105 (hardcoded "password") 1 connectors/powerbi_connector.py::_AZURE_TOKEN_URL_TMPL — public Azure AD endpoint URL template, not a credential
B101 (assert in production) 1 core/licensing/guard.py::LicenseGuard.context — refactored to raise RuntimeError first (so python -O still fails loudly), keeping the assert only as a type-narrowing hint for mypy/pyright

Defensive Architecture impact: zero. Every # nosec is a justification of an existing pattern, not a code change. No SQL is rebuilt, no isolation level is touched, no lock is acquired anywhere new. The only logic edit (LicenseGuard.context) makes failure louder, not quieter — production builds with assertions stripped now raise a typed RuntimeError instead of silently dereferencing None.

2. ci(security): raise gate + add regression guard

  • .github/workflows/ci.yml Bandit job: -ll -q → -l -q (renamed "Bandit (medium+)" → "Bandit (low+)").
  • New tests/test_bandit_low_clean.py invokes the same CLI string the workflow uses, parses the JSON output (stripping bandit's Working... progress-bar prefix from stdout), and fails with a compact reviewable summary if any low+ finding survives. Same regression-guard pattern as tests/test_pii_guard.py.
  • PLAN_BANDIT_SECURITY_LINTER.md Phase 3 marked done; new "Triage rules" section codifies which Bandit IDs are allowed under # nosec (and which must be fixed instead) so the next contributor has a written contract — not folklore.

Root-cause analysis (Julia Evans style)

The thing I observed: The CI Bandit job ran at -ll, so 41 low findings were invisible to PR reviewers. The repo's own plan called Phase 3 "tighten skips / per-line # nosec" but had been parked.

Why it was parked: The lowest-friction path was to leave the gate loose and triage "later" — except "later" tends to mean "when something breaks." Same anti-pattern Steve Gibson warns against in SECURITY_NOW.md: non-invasive code earns trust by being explicit about what it will not do, not by waving away the warning.

Why this is the right fix now: The operator's Slack ping is the operator-judgement signal that triage time has come. Doing it as part of an SRE pass (rather than under a real incident) is the token-aware version of the same job — one PR, one coherent slice, written contract for the next contributor. Per execution-priority-and-pr-batching.mdc, this is a feature + workflow slice (security posture + CI gate + plan doc) kept in two coherent commits rather than one giant blob.

Validation

$ uv run bandit -c pyproject.toml -r api core config connectors database file_scan report main.py -l -q
EXIT=0  # zero findings at low+ severity
$ uv run pytest tests/test_bandit_low_clean.py tests/test_security.py tests/test_pii_guard.py -v
29 passed
$ uv run ruff check . && uv run ruff format --check .
All checks passed!

Full suite (uv run pytest -W error -q) was run; the only failures are environmental (tests/test_scripts.py::*ps1_syntax need pwsh on PATH, which this Cloud Agent VM does not have — confirmed pre-existing on main). CI runs on ubuntu-latest with pwsh so those will be green there.

Companion follow-up (echoed as Issue, not folded in)

While probing whether the broader [tool.bandit] exclude_dirs was hiding real risk, I found two MEDIUM findings in the currently-excluded utils/notify.py:

B310  utils/notify.py:40   urllib.request.urlopen(req, timeout=...)   webhook POST
B310  utils/notify.py:65   urllib.request.urlopen(req, timeout=...)   form POST

These are real — operator-supplied webhook URLs are not currently validated to be http/https-only, so file:// or custom schemes would be accepted. Not in scope for this PR (which is "stop hiding low findings"), but worth a separate Issue so it doesn't drown in the same diff. I'll open it as a companion echo with the LMDE Community-style evidence shape (reference: linuxmint/live-installer#177, #178 by FabioLeitao) — observed behavior, expected behavior, reproduction steps, suggested fix sketch, no scope creep.

What did not change

  • No production behavior. Every try/except/pass block still swallows the same exceptions for the same reason; the comment now records why.
  • No new dependencies, no SQL rewrites, no isolation-level changes, no new database queries.
  • [tool.bandit] skips = ["B608"] and exclude_dirs = [...] left intact — narrowing those is the next slice (companion Issue), not this one.
Open in Web View Automation 

Cursor Agent and others added 2 commits April 27, 2026 22:40
…sec markers

Phase 3 of PLAN_BANDIT_SECURITY_LINTER.md: 41 low-severity findings reviewed
one-by-one and annotated with per-line '# nosec BXXX' plus a one-line comment
above each site explaining *why* the demotion is intentional, anchored to:

- DEFENSIVE_SCANNING_MANIFESTO.md clause 1 ('no surprise side effects' /
  'never break the customer scan because of optional telemetry') for B110/B112
  patterns in connectors and report generation.
- THE_ART_OF_THE_FALLBACK.md §3 ('diagnostic on fall' / Art of the Fallback)
  for per-row sampling, archive entry decode, and per-table discovery loops.

Also refactors core/licensing/guard.py LicenseGuard.context to raise RuntimeError
explicitly (so production builds with python -O still fail loudly) before the
type-narrowing assert; keeps the assert under '# nosec B101' for mypy/pyright.

ffprobe subprocess call (B603/B607) and Azure AD token URL template (B105) are
documented inline as intentional: fixed argv with no shell, graceful degraded
path when binary is missing, public endpoint URL not a credential.

Behavior unchanged: every '# nosec' is a *justification*, not a code change.
This is the necessary precondition for raising the CI Bandit gate to '-l'.

Co-authored-by: Fabio Tavares Leitão <[email protected]>
Now that every previously-flagged Bandit low finding is triaged with a per-line
'# nosec BXXX' justification (previous commit), promote the CI 'Bandit' job
from '-ll' (medium+) to '-l' (low+) so silent re-introductions trip CI rather
than leaking through.

Also adds tests/test_bandit_low_clean.py: invokes the same Bandit CLI string
the workflow uses, parses JSON output (stripping bandit's progress-bar
prefix), and fails with a compact, reviewable summary listing offending
sites if any low+ severity finding survives. Same regression-guard pattern
as tests/test_pii_guard.py — encode the lesson in the suite so contributors
trip locally before CI does.

Updates PLAN_BANDIT_SECURITY_LINTER.md: Phase 3 marked done, adds 'Triage
rules' section codifying which Bandit IDs are allowed under '# nosec' (and
which categories must be fixed instead) so the next contributor has a
written contract.

Co-authored-by: Fabio Tavares Leitão <[email protected]>
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.

1 participant