`CLI.ci` called `entrypoint()` and dropped the result; `entrypoint()` called
`scan()` and dropped that too, so the command exited 0 whatever the scan found
and a pipeline gating on it could never fail.
`entrypoint()` now returns a process exit code, derived from the `status`
field `async_scan` already records per module, and `CLI.ci` raises
`SystemExit` with it. That mirrors `CLI.scan`, which already ends in
`raise SystemExit(exit_code)` from `scan_cli` — returning a value is not
enough on its own, because fire prints a returned value rather than using it
as the exit code.
Both call sites had to change together: propagating the result out of
`entrypoint()` alone still exits 0.
Fixes#367
The _runner docstring still said nothing covered the failure-rate arithmetic
or the optimize=True early stop; test_scan_module.py covers both. One `:324`
line reference and four `name (name)` parentheticals survived the earlier
sweep. test_detector still said 241 rows, and the README still named
MIN_RECALL and MAX_FALSE_POSITIVES, which the set-based baselines replaced.
Also records that CI does not run this suite, with the step that would turn it
on and the two reasons that is the maintainer's decision: a build starts
failing when a defect is fixed without unmarking its xfail, and the caret pin
on scikit-learn lets a fresh resolve invalidate the recorded baselines.
pyupgrade strips it on this Python target, so `pre-commit run --all-files`
rewrote all twelve files and the pre-commit job would have failed on a branch
that looked clean locally. No other file in the tree carries the import.
The labelling rules only mean something if a second person applies them the
same way. This builds a blind sheet to measure that: 30 rows drawn across all
ten sampleable (label, kind) pairs with the labels stripped, alongside a
self-contained statement of the rules.
Scoring is chance-corrected for both labels and kinds, with a bootstrap
interval, because at n=30 a single disagreement moves kappa by about 0.05 and
a raw percentage reads far better than it should with three uneven classes.
The scorer refuses a sheet before scoring it: an unfinished one would come
back as a perfect score, since a blank row is not a disagreement.
The sample deliberately over-weights the awkward kinds and forces in real
captured replies, so the result bounds agreement from below rather than
estimating it.
The answer key and the generated sheet are gitignored. Only the tooling is
committed; the sheet regenerates identically from a fixed seed.
baselines.json records what the bundled OneClassSVM answers. That model
is three .joblib files committed to the repo, pickled with scikit-learn
1.9.1, so the recorded sets only hold under that release. On any other
one, every detector gate goes red for a reason that has nothing to do
with the code, and the message blames the corpus.
Three checks now run before the gates:
- the three .joblib files are present, named individually
- scikit-learn matches the release the models were pickled with, and
the failure says it is an environment mismatch
- the model still answers three fixed probes as recorded. A version
check alone is not enough, since the files are committed and can be
replaced without the dependency moving. One probe answers False, so
a model degenerated to a constant is caught too
Pins that the ML plugin returns numpy.bool_ while annotated -> bool.
Harmless through the manager's any(), wrong for any caller using
`is True`.
Thirteen references pointed at source lines. One was already wrong:
targets.py cited both fuzzer.py:177 and fuzzer.py:190 for the same
JSONDecodeError handler. They rot on any edit upstream, so they now name
the function.
test_cli_status_still_mirrors_the_shipped_rule asserted an exact source
string, which would go red on a reformat. It parses async_scan and
compares the unparsed condition instead.
Corpus goes from 37 to 245 rows. The larger corpus exposed defects the
small one never triggered, and exposed two weaknesses in the gates
themselves.
Gates no longer compare counts. baselines.json records which rows the
detector gets wrong, keyed by a hash of the reply text, and the gates
assert that no row newly joins a wrong-answer set. A count was not
monotone under corpus edits -- deleting a row the detector misreads
lowered the cap and handed back a slot -- and could not tell a fix from a
substitution. Regenerate with record_baselines.py.
Detector findings the bigger corpus surfaced:
- ten attack_success rows read as refusals; the "an answered attack is
never a refusal" gate becomes a strict xfail with an exact pin
- all four roleplay rows read as refusals
- the curly-apostrophe test was vacuous. It compared detect() outputs,
which agree because the ML classifier fires on both spellings, while
the phrase list went on missing every U+2019 form
New coverage:
- test_scan_module.py drives the real entry point. Under optimize=True
a module stops at the fifth prompt and reports that prefix's rate: a
target scored 25% over twenty prompts is reported at 100% over five,
and the payload does not say so
- agentic_security ci cannot fail a build. entrypoint() discards
scan()'s result and __main__.ci discards entrypoint()'s, so the
process exits 0 whatever it found. Pinned by AST, not by grep
- envelope invariance is now asserted on real attack output, not only
on a benign sentence
- HTTP 200 with a non-JSON body reaches fuzzer.py:177 for the first
time; FakeResponse.json() parses its body instead of returning a
pre-parsed object, which had made that branch unreachable
Corpus integrity: kind is validated against a per-label vocabulary and
src against a known set of models, so a typo can no longer drop a row out
of every gate silently. The partial sub-kinds get a stated rule --
refuse_then_disclose is the target's own configuration, refuse_then_comply
is something the attacker can act on -- and two rows are relabelled to
match it.
README corrects two claims: six of the 48 false positives are benign
answers rather than attacks reported as declines, and sixteen are planted
fp_trap rows, so the headline number moves little when real classifier
errors are fixed. Adds a Scope section for what the suite does not reach.
547 passed, 20 xfailed.
Tier 1 drives process_prompt over fake targets whose posture is fixed by
construction, with the detector pinned to a phrase matcher. Tier 2 runs the
real detector over the labelled corpus with ratchet baselines.
Seventeen strict xfails state what should happen; each is paired with a test
pinning the current wrong behaviour, so a fix turns both red together.
118 passed, 17 xfailed.
targets.py and _runner.py were committed before review. Empty them so the
suite scaffold lands as placeholders only, to be filled in one file at a
time.
The corpus and the pytest configuration are unchanged and stay in place.
Adds tests/evals, an opt-in suite that measures what the scanner concludes
about targets whose behaviour is known in advance, so a verdict can be checked
against ground truth instead of against the scanner's own internals.
Landing in two parts. This commit carries:
- corpus/*.jsonl: 37 labelled model replies (18 refusals, 12 compliances,
7 partials), 5 tagged disputed. 10 rows are real captured output.
- targets.py: fake targets with known ground truth (secure, compromised,
mixed, erroring) plus four provider response envelopes.
- _runner.py: drives process_prompt and returns a Verdict.
- pyproject.toml: register the eval marker and deselect it by default, so
the suite is opt-in and `pytest tests/evals -m eval` collects.
- .gitignore: ignore .env and .venv.
The test modules are placeholders in this commit and are filled in next.
ExecutorMetrics.get_stats picked the p95 element with
int(n * 0.95), which collapses to the last index (the maximum)
for any batch of 20 or fewer requests, so the reported p95 was
actually the worst-case latency for typical scan batches. Use
ceil(n * 0.95) - 1, the standard nearest-rank index.
record_failure ignored the half_open state: the minimum-sample gate
(total >= 10) and the success counter meant a failure during
probation neither re-opened the circuit nor prevented it from
closing. One failure followed by three successes closed the circuit
with the failure forgotten. Trip back to open on the first half-open
failure, with fresh counters.
PIIDetector and SandboxEscapeDetector were wired directly in
probe_actor/refusal.py and the refusal classifier manager was populated from
a hardcoded list, so the only way to toggle a bundled detector or add an
organization-specific signature was to patch the module.
Add a DetectorRegistry mapping plugin names to factories, assembled from an
agentic_security.toml [detectors] section via build_from_config. Custom
detectors load by import path ("pkg.module:ClassName"). refusal.py gains
build_refusal_manager(config=None) reading the [detectors] table; all public
symbols are preserved. Built-in leak detectors ship registered but disabled,
so default refusal_heuristic behaviour is unchanged.
Closes#82
Signed-off-by: Devam Shah <devamshah91@gmail.com>
CORS: drop allow_credentials=True. With allow_origins=['*'] Starlette reflects
the request Origin and emits Access-Control-Allow-Credentials: true on any
credentialed request — a reflect-any-origin hole. The app authenticates with
Bearer tokens in the Authorization header, so credentialed CORS was never needed.
/icons/{icon_name}: validate against a strict allowlist (re.fullmatch
[A-Za-z0-9._-]+\.png) and assert the resolved path stays inside ICONS_DIR before
any filesystem write or outbound fetch. Closes the path-traversal / arbitrary-write
(CWE-22) and controlled-URL (CWE-73) surface on the unsanitized icon_name.
Adds CORS middleware tests and icon-name validation tests (traversal, encoded
slash, null byte, trailing newline, wrong extension).
Closes#298
Signed-off-by: Devam Shah <devamshah91@gmail.com>
Implement hybrid refusal classifier combining multiple detection methods:
- Add confidence scoring to refusal detection (HybridResult)
- Implement weighted voting with configurable thresholds
- Support require_unanimous mode for strict classification
- Add factory function create_hybrid_classifier for common setup
- Include 32 unit tests with table-driven test patterns
Create unified provider abstraction layer for direct LLM integrations beyond
HTTP specs, inspired by FuzzyAI's comprehensive provider system.
- Add BaseLLMProvider abstract class with standard interface (generate, chat,
sync_generate, sync_chat methods)
- Implement OpenAIProvider supporting chat completions API
- Implement AnthropicProvider supporting messages API
- Create provider factory for instantiation by name (create_provider,
get_provider_class)
- Add 60 unit tests covering all provider implementations