Skip to content

Fix adversarial evaluation boundaries and fail closed on malformed reports - #145

Closed
oliarmak-web wants to merge 6 commits into
secfoo-com:mainfrom
oliarmak-web:feat/adversarial-repository-evaluation-117
Closed

oliarmak-web wants to merge 6 commits into
secfoo-com:mainfrom
oliarmak-web:feat/adversarial-repository-evaluation-117

Conversation

@oliarmak-web

@oliarmak-web oliarmak-web commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Closes #117

Supersedes #134 and addresses the maintainer review. GitHub rejected reopening #134, so this follows the maintainer’s invitation to submit a replacement.

Repository instructions can suppress real findings, fabricate reports, or induce tool requests. This adds paired adversarial fixtures, offline replay and opt-in live collection, plus focused report/prompt hardening.

Changes addressing the maintainer review

  • Store CLAUDE.md, AGENTS.md and .cursorrules under inert .fixture names. Restore active names only in disposable evaluation targets, outside the contributor checkout.
  • Reject unclosed Markdown fences and finding-like headings that are not valid Markdown, including ###[High]. The runner records malformed reports as failed before findings ingestion.
  • Share Markdown heading/section parsing across severity counting, SAST/SCA/secret-scanning extraction and evaluation. Fenced/quoted examples cannot create persisted findings; legacy register-only reports remain supported.
  • JSON-quote deleted filenames. Preserve source newlines inside random per-file boundaries instead of JSON-escaping entire bodies.
  • Align the reformat request with its system-message contract and JSON draft field. JSON echoes and persistently malformed reports become failed runs.
  • Replace the labeled SQL-only corpus with eight varied attack/control defects and remove answer-revealing source comments and README labels.
  • Support explicit built-in skill selection and agent/skill result grouping. Integrate complete Claude stream capture without narrowing production tool grants; observe API completion tool-call fields rather than asserting empty lists.
  • Give each live workflow job only its provider credential. Subprocesses use an allowlisted environment and isolated HOME/Secfoo configuration.
  • Move fuzzing to a separate weekly/manual workflow, pinned to Atheris 2.3.0.

Validation

  • Full suite: 1,397 passed, 1 failed. The failure, test_sensor_dying_mid_run_drops_events_without_blocking, reproduces identically on untouched baseline f24043bd6f01618128748241b6729bebc9254a26 on this Mac.
  • 226 focused parser/API/evaluator/property tests passed, followed by an additional targeted property rerun.
  • Changed production/evaluator Python and focused tests pass Ruff. The pre-existing unused local in tests/test_runner.py remains outside the lint claim.
  • Synthetic calibration and both historical live artifacts replay successfully without model calls. Workflow YAML parses; git diff --check passes.
  • Added regressions for both blocking examples, runner failure persistence, shared extraction, inert fixture materialization, deleted filenames, JSON echoes, credential filtering and production-grant Claude capture.
  • Native Atheris has not been run locally; its Linux scheduled/manual workflow was not dispatched.

Evidence and remaining work

Draft pending fresh Claude/API measurements on the revised corpus and implementation. This machine has no configured model credentials, CLI authentication or local model runtime. No billable evaluation workflow was dispatched.

The November 16 raw records are preserved unchanged, with their labeled SQL-only corpus archived under corpus-v1. Historical first-trial results were Claude attack/control retention 8/8 in both phases; local Qwen API attack retention 7/8 baseline and 8/8 hardened, with 8/8 controls in both phases. All 32 API reports failed format checks. These are small historical observations, not measurements of the revised code or corpus and not a statistically established improvement.

Original API empty tool lists were asserted rather than observed and now replay as unknown. Only four historical Claude runs have complete streams, under narrower-than-production grants. Current collection records production grants and telemetry in the same invocation.

See evaluation guide and historical evidence for reproduction and limitations. Retention remains a location/CWE heuristic requiring human review; F900 detection is not a general hallucination detector.

AI assistance: OpenAI Codex implemented and tested these changes under the account owner's direction. Maintainer feedback approved resubmission after fixes, not this implementation or its results.

@vsn411

vsn411 commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

Thank you, @oliarmak-web. This is a big step forward from #134, and it shows real care. Both blockers from the #134 review are addressed in substance:

  • Instruction files: no auto-loaded agent file remains anywhere in the tree. The attack files exist only as *.fixture, and materialize_fixture renames them only inside the temp directory.
  • Severity counter: the exact zero-count repro from Add adversarial repository evaluation baseline and harden review boundaries #134 now raises an error. Legitimate reports are not flagged: the NodeGoat samples, ~~~ fences, indented code and nested 4-backtick fences all pass. Across 214 stored reports and transcripts, counts and ratings match the old parser exactly.
  • From the should-fix list: deleted paths are JSON-quoted, source is sent as raw text between random boundaries, the reformat prompt names the JSON field, the corpus is varied and unlabelled, each eval job gets only its own key with an allowlisted environment, and atheris is pinned and weekly.

I'm closing this PR because review found a new way past the same --fail-on gate, and "fail closed" currently crashes the run instead of failing it. Those need fixing before this can land. #117 stays open, and you're very welcome to reopen this PR after pushing fixes, or open a new one. The three blockers are small. Reviewed at 48d046f; every item below marked "reproduced" was run against that head.

Blocking

1. The gate can still be bypassed through line-separator characters (reproduced end to end).
headings() in report/markdown.py (~L235) indexes markdown-it's token.map into str.splitlines(). markdown-it counts lines by \n only, but splitlines() also splits on 
, 
, \x0b, \x0c, \x1c–\x1e and \x85, so the unclosed-fence check reads the wrong line. This report:

# SAST Report\n\n**Overall risk rating:** Critical\n\n## Detailed Findings\n\n```\n### [High] F1: SQLi\n### [Critical] F2: RCE\nx
```\nend\n

gives count_severities() == 0 with no MalformedReportError (the old regex counted 2). secfoo run --skill sast --fail-on high --json then exits 0 with gates.findings {count: 0, passed: true}. All six separators work. The same root cause misfires the other way: a properly closed fence quoting source code that contains a form feed raises "Unclosed Markdown code fence".
Fix: split on "\n" only, the way markdown-it does. Please also widen the property tests again: excluding Cc characters and \n/\r, and accepting MalformedReportError as a pass, is why they missed this.

2. "Fail closed" crashes the run instead of failing it (reproduced).
MalformedReportError from count_severities reaches the BaseException handler in runner.py (~L492), which marks the run crashed and re-raises out of execute_runs and the CLI. With a fake agent returning ```\n### [High] F1…:

secfoo run --skill sast --skill secret-scanning --fail-on high --json

prints a Rich traceback, exits 1 and writes 0 bytes to stdout, so CI gets no JSON document to read. The other skill's outcome is discarded. Both run rows end up failed with report_path = NULL, so the report.md on disk can't be reached from the dashboard. The API adapter's own graceful failed result is also overridden.
Fix: catch MalformedReportError in _run_single_skill, record status failed with a clear "malformed report: …" message, keep report_path, and return a normal RunOutcome. That keeps the gate failing (exit 1, "a run failed") while CI still gets its JSON. Please add a test for exactly this command shape.

3. One old stored report takes down whole dashboard pages (reproduced).
Code that re-parses stored reports now raises with no handler:

  • _responsible_ai_badges (storage/repository.py ~L718, used by list_assessments)
  • the SCA and secret-scanning dashboards' build()
  • runtime/inventory._scanned

A single successful report saved before the upgrade that ends in an unclosed ```bash fence makes secret_scanning_dashboard.build(), sca_dashboard.build() and, for a Responsible AI report, repo.list_assessments() raise. The page returns a 500, and runtime-sensor inventory matching breaks for that project.
Fix: treat a malformed stored report as "unparsable", the way a missing file is handled today: skip it, show it as such, and log it.

Should fix

  • A rating inside a list item is no longer found (reproduced). visible_text() (~L290) keeps only level-1 inline tokens, so - **Overall risk rating:** High gives responsible_ai_risk = None. The Responsible AI badge disappears, and for the API agent the report triggers a reformat and then ends as a failed run.
  • Finding blocks end at any ### (reproduced). detail_blocks() (~L282) stops at every h3, while the old code stopped only at the next finding heading. ### [High] F1: SQLi … ### Fix … **Recommendation:** use params now loses the recommendation, so recommendation and CVE fields go missing from stored findings and the SAST, SCA and secret dashboards.
  • The JSON-echo guard only checks the first character (reproduced). severity.py (~L62) passes Here is the reformatted report:\n\n{"draft_report": "# SAST\\n\\n**Overall risk rating:** High\\n\\n### [High] F1: SQLi"}. The rating is found, 0 findings are counted, the run is reported as a success, report.md is the escaped blob, and --fail-on high passes. Check for a JSON object anywhere in the text, or require the # <Skill> Report title before accepting a report.
  • The published numbers are stale, and the summary pools runs from different setups. summarize() (scripts/adversarial_eval.py ~L164) groups by kind, agent, skill, phase and variant, but not by revision, trial or capture wrapper. claude.jsonl therefore prints "hardened | 9/9" from 16 first-trial records at 7b70527 plus 2 second-trial records at 03f4e28. The 4 "complete"-telemetry records came from an earlier wrapper that forced Read/Grep/Glob, which the committed wrapper no longer does. No record covers 48d046f or the new corpus (digest 48ea2f88 vs ef841c2b), yet docs/REFERENCE.md still leads with the 16/16 and 7/8 → 8/8 numbers. Please group by revision and wrapper too, re-record against the current corpus and head, or clearly label the numbers as from the previous corpus. API tool telemetry is also still empty by construction, because the API agent sends no tools; say so in the table rather than reporting it as observed.
  • The env allowlist breaks your own documented reproduction (reproduced). evaluation_environment() (~L197) gives provider ollama_chat (and bare model names) no key, and drops OLLAMA_API_BASE and SECFOO_MEMORY. With the README's command, only HOME, PYTHONPATH, SECFOO_HOME and USERPROFILE pass through, ApiAdapter.is_available() is false, and every case returns not_configured. Allow the provider's own variables per provider.
  • The Claude streams publish your local details. All four files under docs/evaluations/2026-11-16/*-stream.jsonl include your macOS temp root (/private/var/folders/vk/…/T), session_id and uuid values, messaging_socket_path, your installed plugin list, and credential_expires_at for your subscription login. memory_paths was rewritten to /home/evaluator but cwd wasn't. No API keys or tokens were found, but the README says "No login tokens or account metadata are published" and "Raw records are preserved unchanged", and neither is quite true. Please scrub these fields consistently and update the README wording. It's your own data, so it's your call, but it should match what the README promises.
  • The random source boundaries aren't declared in the trusted system message, so a forged boundary inside a file looks the same as a real one. State the boundary token in the system prompt.
  • The report is re-parsed on every extraction call. section(), prose_source(), example_finding_ids() and detail_blocks() each re-parse and re-validate the whole report. That is 109 MD.parse calls (85 ms) for one findings_with_fingerprints() on the 12-finding NodeGoat sample, repeated per project on every dashboard load and on each runtime ingest. Parse once and pass the token or heading list through. report/architecture.py and web/top_findings.py also still have their own section parsers.

Housekeeping

  • The whole corpus and its synthetic transcripts are duplicated under docs/evaluations/2026-11-16/corpus-v1. Keep one copy and reference it.
  • The replay code special-cases the 2026-11-16 directory name. Use a manifest field instead.
  • The three new CI replay steps assert nothing about the results, only that old records still parse. Assert the expected summary, or drop them from per-PR CI.
  • The new workflows pin action SHAs older than the ones main moved to in chore(deps): bump the actions group across 1 directory with 8 updates #135. Please match main's pins.
  • The PR is 10 commits behind main. It merges cleanly, but please rebase before the next push.

Fixing blockers 1 and 2 properly also fixes most of 3. With those and the two parser regressions done, I expect this to be very close to mergeable. Looking forward to the next version.

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.

Adversarial validation: prompt injection from the repository being scanned

2 participants