Repository navigation
fix: L3 leet concat block, safe context tighten, FP fix - #35
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds safe-context regex allowlists and original-prompt fallback to CustomL3, threads fallback through all preprocessing/decoding layers, adds many tests and debug runners, replaces silent excepts with debug logging, and updates CI workflow, requirements, and local fix-and-test scripts. ChangesL3 Safe-Context Detection Enhancement
CI Workflow and Dependency Management
Docs and Reports
Runtime Observability and Small API/CLI Fixes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (12)
detectors/l3_custom.py (1)
381-425: ⚖️ Poor tradeoffConsider extracting helper methods to reduce cognitive complexity.
SonarCloud reports cognitive complexity of 39 (allowed: 15). While the logic is correct and security-critical code often warrants explicitness, extracting helper methods would improve maintainability:
_is_safe_context(toxic: str, text: str, original_prompt: Optional[str]) -> bool_check_toxic_words(prompt: str, allow_substring: bool, original_prompt: Optional[str]) -> dict | None🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@detectors/l3_custom.py` around lines 381 - 425, The _check_content method is too complex (high cognitive complexity); refactor by extracting the toxic-word logic into two helpers: implement _is_safe_context(toxic: str, text: str, original_prompt: Optional[str]) -> bool which encapsulates the safe_contexts loop and fallback to original_prompt checks, and implement _check_toxic_words(prompt: str, allow_substring: bool, original_prompt: Optional[str]) -> dict | None which iterates self.toxic_words, handles allow_substring vs word-boundary checks, calls _is_safe_context to decide safety, and returns the same {"passed": False, "reason": ...} or None; then simplify _check_content to run the PII loop and call _check_toxic_words, returning its result if any.Source: Linters/SAST tools
test_debug2.py (2)
20-20: ⚡ Quick winRemove unnecessary f-string prefix.
These strings don't contain any placeholders, so the
fprefix is unnecessary.🔧 Proposed fix
if re.search(r'\bkill\b', v.lower()): - print(f" ^ Contains 'kill' as word") + print(" ^ Contains 'kill' as word") if 'kill' in v.lower() and ' ' not in v: - print(f" ^ Contains 'kill' substring (no spaces)") + print(" ^ Contains 'kill' substring (no spaces)")Also applies to: 22-22
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test_debug2.py` at line 20, Remove the unnecessary f-string prefixes on the print calls that have no interpolations (e.g., the print invocation that currently uses print(f" ^ Contains 'kill' as word") and the similar print at lines referenced in the comment); change them to plain string literals so the prints use print(" ^ Contains 'kill' as word") (and the analogous second print) to eliminate the unnecessary f prefix.
17-17: ⚡ Quick winUse explicit conversion flag in f-string.
Instead of calling
repr()inside the f-string, use the!rconversion flag for cleaner syntax.🔧 Proposed fix
for i, v in enumerate(variants): - print(f"{i}: {repr(v)}") + print(f"{i}: {v!r}")🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test_debug2.py` at line 17, Replace the explicit call to repr inside the f-string with the f-string conversion flag: locate the print statement using print(f"{i}: {repr(v)}") and change it to use the !r conversion for variable v (i.e., f"{i}: {v!r}") to produce the same repr output with cleaner syntax.docs/L3_FALSE_POSITIVE_FIX.md (1)
77-80: ⚡ Quick winAdd language specifier to code block.
The fenced code block should specify a language identifier for proper syntax highlighting and rendering.
📝 Proposed fix
-``` +```text FINAL RESULTS: 38 passed, 0 failed [PASS] ALL TESTS PASSED - False positive bug is FIXED!</details> <details> <summary>🤖 Prompt for AI Agents</summary>Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.In
@docs/L3_FALSE_POSITIVE_FIX.mdaround lines 77 - 80, The fenced code block
showing "FINAL RESULTS: 38 passed, 0 failed" lacks a language specifier; update
the opening fence (theline) in docs/L3_FALSE_POSITIVE_FIX.md so it includes a language identifier (e.g., changetotext orbash) to enable proper
syntax highlighting and rendering for the block containing "[PASS] ALL TESTS
PASSED - False positive bug is FIXED!".</details> <!-- cr-comment:v1:8b60d5a06e76b9b6024ab02e --> </blockquote></details> <details> <summary>test_preprocess.py (1)</summary><blockquote> `9-9`: _⚡ Quick win_ **Use explicit conversion flag in f-string.** Instead of calling `repr()` inside the f-string, use the `!r` conversion flag for cleaner syntax. <details> <summary>🔧 Proposed fix</summary> ```diff for i, v in enumerate(variants): - print(f"{i}: {repr(v)}") + print(f"{i}: {v!r}") ``` </details> <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@test_preprocess.py` at line 9, Replace the explicit call to repr inside the f-string in the print statement: locate the print statement that currently uses print(f"{i}: {repr(v)}") (variables i and v) and change it to use the f-string conversion flag by formatting v with !r (i.e., use {v!r}) so the representation is produced by the f-string itself. ``` </details> <!-- cr-comment:v1:b7d728ade4d7bffd0ac37a3f --> </blockquote></details> <details> <summary>tests/test_l3_toxic_wordboundary.py (1)</summary><blockquote> `32-32`: _💤 Low value_ **Consider using truthiness checks instead of explicit boolean comparisons.** Ruff flags 98 instances of explicit boolean comparisons (`== True` / `== False`). While functionally correct, Python style prefers truthiness checks: `result["passed"]` instead of `result["passed"] == True`, and `not result["passed"]` instead of `result["passed"] == False`. <details> <summary>Example fix pattern</summary> ```diff def test_benign_skills_01(l3_detector): result = l3_detector.check("I need to improve my Python programming skills") - assert result["passed"] == True + assert result["passed"] def test_malicious_kill_01(l3_detector): result = l3_detector.check("How do I kill someone without leaving evidence?") - assert result["passed"] == False + assert not result["passed"] ``` </details> Also applies to: 36-36, 40-40, 44-44, 48-48, 52-52, 56-56, 60-60, 64-64, 68-68, 72-72, 76-76, 80-80, 84-84, 88-88, 92-92, 96-96, 100-100, 104-104, 108-108, 112-112, 116-116, 120-120, 124-124, 128-128, 132-132, 136-136, 140-140, 144-144, 148-148, 152-152, 156-156, 160-160, 164-164, 168-168, 172-172, 176-176, 180-180, 184-184, 188-188, 192-192, 196-196, 200-200, 204-204, 208-208, 212-212, 216-216, 220-220, 224-224, 233-233, 237-237, 241-241, 245-245, 249-249, 253-253, 257-257, 261-261, 265-265, 269-269, 279-279, 295-295, 299-299, 303-303, 307-307, 311-311, 315-315, 319-319, 323-323, 327-327, 331-331, 335-335, 345-345, 349-349, 353-353, 357-357, 361-361, 365-365, 369-369, 373-373, 377-377, 381-381, 385-385, 389-389, 395-395, 399-399, 403-403, 419-419, 423-423, 427-427, 431-431, 435-435, 439-439 <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_l3_toxic_wordboundary.py` at line 32, Replace explicit boolean comparisons in the tests (e.g., assertions like assert result["passed"] == True and assert result["passed"] == False) with truthiness checks: use assert result["passed"] for True checks and assert not result["passed"] for False checks; update occurrences in tests/test_l3_toxic_wordboundary.py wherever result["passed"] is compared to True/False to improve style and satisfy the linter. ``` </details> <!-- cr-comment:v1:734082ea18b37e5c31284602 --> </blockquote></details> <details> <summary>tests/test_word_boundary.py (1)</summary><blockquote> `7-7`: _⚡ Quick win_ **Remove extraneous `f` prefix from string without placeholders.** Line 7 uses an f-string without any replacement fields. <details> <summary>♻️ Proposed fix</summary> ```diff -print(f"=" * 80) +print("=" * 80) ``` </details> <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/test_word_boundary.py` at line 7, The print statement uses an unnecessary f-string with no interpolation; update the print call in tests/test_word_boundary.py (the print(f"=" * 80) statement) to use a normal string literal (remove the leading "f") so it becomes print("=" * 80), preserving the same behavior without the redundant f-prefix. ``` </details> <!-- cr-comment:v1:7a16688e3893fe94490e6a8d --> _Source: Linters/SAST tools_ </blockquote></details> <details> <summary>tests/debug_safe_context.py (1)</summary><blockquote> `29-29`: _⚡ Quick win_ **Remove extraneous `f` prefix from strings without placeholders.** Lines 29 and 31 use f-strings without any replacement fields. <details> <summary>♻️ Proposed fix</summary> ```diff - print(f" Word boundary match: YES") + print(" Word boundary match: YES") ``` ```diff - print(f" Word boundary match: NO") + print(" Word boundary match: NO") ``` </details> Also applies to: 31-31 <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/debug_safe_context.py` at line 29, Remove the unnecessary f-string prefixes from the print statements that contain no interpolation (e.g., the calls currently written as print(f" Word boundary match: YES") and the similar print(f"...") on the other line); change them to plain string literals by dropping the leading f so they are standard prints without formatting overhead. ``` </details> <!-- cr-comment:v1:08561deb412271d3590a52dc --> _Source: Linters/SAST tools_ </blockquote></details> <details> <summary>tests/trace_leetspeak.py (2)</summary><blockquote> `21-21`: _⚡ Quick win_ **Move import statement to module top.** The `re` module is imported inside a conditional block. All imports should be placed at the beginning of the file following PEP 8 conventions. <details> <summary>♻️ Proposed fix</summary> Move the import to the top of the file: ```diff import sys +import re from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent)) ``` And remove it from line 21: ```diff leet_lower = leet_decoded.lower() for toxic in detector.toxic_words: - import re pattern = r'\b' + re.escape(toxic) + r'\b' ``` </details> <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/trace_leetspeak.py` at line 21, Move the in-block import of the re module out to the top of the module (after any module docstring and before other code) and delete the conditional/internal import; ensure all uses of re in the file still work by leaving the single top-level "import re" and removing the duplicated import inside the conditional block. ``` </details> <!-- cr-comment:v1:2be8b1cc81d0b991eb6cac7b --> --- `26-26`: _⚡ Quick win_ **Remove extraneous `f` prefix from string without placeholders.** Line 26 uses an f-string without any replacement fields. <details> <summary>♻️ Proposed fix</summary> ```diff - print(f" Would BLOCK") + print(" Would BLOCK") ``` </details> <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/trace_leetspeak.py` at line 26, In tests/trace_leetspeak.py locate the print statement that currently reads print(f" Would BLOCK") and remove the unnecessary f-prefix (change to a regular string literal) since there are no placeholders; update the print call accordingly to avoid an unused f-string in the test. ``` </details> <!-- cr-comment:v1:2ed17f005ae7ba5bd62979c1 --> _Source: Linters/SAST tools_ </blockquote></details> <details> <summary>tests/debug_k1llc0mmand.py (1)</summary><blockquote> `12-12`: _⚡ Quick win_ **Remove extraneous `f` prefix from strings without placeholders.** Lines 12 and 27 use f-strings without any replacement fields. <details> <summary>♻️ Proposed fix</summary> ```diff -print(f"=" * 80) +print("=" * 80) ``` ```diff -print(f"\nLeetspeak decode for each variant:") +print("\nLeetspeak decode for each variant:") ``` </details> Also applies to: 27-27 <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@tests/debug_k1llc0mmand.py` at line 12, Remove the unnecessary f-string prefixes on plain string prints that have no replacement fields: replace occurrences of print(f"=" * 80) and the similar print(f"...") at the other occurrence in the tests/debug_k1llc0mmand.py file with ordinary string literals (remove the leading "f") so they are regular print("=" * 80) style calls. ``` </details> <!-- cr-comment:v1:4d4a24991dd5ee006d30ca41 --> _Source: Linters/SAST tools_ </blockquote></details> <details> <summary>.github/workflows/security-gate.yml (1)</summary><blockquote> `22-34`: _⚖️ Poor tradeoff_ **Consider pinning actions to commit SHA for supply-chain security.** Static analysis flags that actions are referenced by mutable tags (`@v4`, `@v5`) rather than immutable commit SHAs. While using semantic version tags is common practice, pinning to SHAs prevents supply-chain attacks where action maintainers could push malicious updates to existing tags. Additionally, `actions/checkout@v4` does not set `persist-credentials: false`, which leaves GitHub credentials in the workspace that could be accessed by malicious code in dependencies. <details> <summary>🔒 Security hardening example</summary> ```diff - name: Checkout Code Repository - uses: actions/checkout@v4 + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 with: fetch-depth: 1 + persist-credentials: false ``` Apply similar pinning to `actions/setup-python@v5` and `actions/cache@v4`. </details> <details> <summary>🤖 Prompt for AI Agents</summary> ``` Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.github/workflows/security-gate.yml around lines 22 - 34, Replace mutable action tags with immutable commit SHAs for actions/checkout, actions/setup-python, and actions/cache (i.e., change uses: actions/checkout@v4, actions/setup-python@v5, actions/cache@v4 to their respective pinned commit SHAs) and add persist-credentials: false to the actions/checkout step to avoid leaking GitHub credentials; update the workflow entries referencing these symbols so they use the SHA pins and include persist-credentials: false under the Checkout Code Repository step. ``` </details> <!-- cr-comment:v1:f53a99b976a413fe0a3c000e --> _Source: Linters/SAST tools_ </blockquote></details> </blockquote></details> <details> <summary>🤖 Prompt for all review comments with AI agents</summary>Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.Inline comments:
In @.github/workflows/security-gate.yml:
- Around line 33-51: The workflow incorrectly skips installing requirements.txt
when the pip cache is a hit; update .github/workflows/security-gate.yml so the
"Install System Dependencies" step (or a single unified install step) always
runs pip install -r requirements.txt and installs pytest, bandit and pip-audit
regardless of steps.pip-cache.outputs.cache-hit, and remove the separate
"Install audit tools only (cached run)" step or its cache-hit conditional; keep
the existing cache step ("Cache dependencies") so pip's download cache still
speeds installs but do not rely on cache-hit to determine whether to install
packages.In
@detectors/l3_custom.py:
- Line 381: The parameter typing for original_prompt in _check_content should
use an explicit Optional[str] instead of implicit nullable typing; import
Optional from typing at the top of the file and change the method signature of
_check_content to annotate original_prompt: Optional[str] so it adheres to PEP
484 (refer to the _check_content function to update its annotation and add the
typing import).- Around line 493-507: The early-block that checks spaceless leet-decoded text
(using leet_decoded and iterating self.toxic_words) currently returns a BLOCK
before consulting safe_contexts; update that block so that for each matching
toxic (toxic in leet_lower) you also verify whether the match is allowed by
safe_contexts (use the existing safe_contexts lookup/logic used elsewhere in
this module) and only return the BLOCK if no safe_contexts rule applies; ensure
the returned payload still uses the same keys ("passed", "reason", "layer",
"latency_ms") and compute latency_ms from start as before.In
@requirements.txt:
- Around line 1-12: The requirements.txt pins several packages with known
high-severity vulnerabilities; update the affected package pins (fastapi,
gunicorn, transformers) to secure, actively maintained versions or safe version
ranges—e.g., bump fastapi to a patched release, upgrade gunicorn to a release
that fixes the HTTP request-smuggling issues, and move transformers to a
security-patched release (or constrain to a safe minor/patch range); update the
corresponding entries in requirements.txt (the package names fastapi, gunicorn,
transformers) and then run your test suite and dependency-scan to confirm
compatibility, adjust any breaking API changes after consulting each package's
changelog, and commit the updated requirements.- Around line 1-12: The app is missing Azure packages required by
api/secrets_manager.py (SecretClient, DefaultAzureCredential) and api/main.py
(TableServiceClient, ResourceNotFoundError) causing ImportError when
SECRET_BACKEND=azure or AZURE_CONNECTION_STRING is set; fix by adding an
optional extras/secondary requirements file (e.g., requirements-azure.txt)
containing azure-keyvault-secrets, azure-identity and azure-data-tables
(versions compatible with your runtime) and update install docs to instruct pip
install -r requirements-azure.txt for Azure deployments, or alternatively
restore these packages into the main requirements.txt if you want them installed
by default.- Around line 1-12: The repo removed runtime deps but code still imports them;
restore or guard them: either add back packages cryptography (for
cryptography.fernet used in ui.py), keyring (used in cli/main.py), python-dotenv
(for dotenv.load_dotenv in api/secrets_manager.py), pandas and datasets (used
across scripts/.py and detectors/train_bert.py) to requirements.txt, or
refactor those import sites to optional imports with clear fallbacks/errors;
update references in ui.py, cli/main.py, api/secrets_manager.py,
detectors/train_bert.py and scripts/ to use try/except ImportError or move
imports into functions if keeping deps optional.
Nitpick comments:
In @.github/workflows/security-gate.yml:
- Around line 22-34: Replace mutable action tags with immutable commit SHAs for
actions/checkout, actions/setup-python, and actions/cache (i.e., change uses:
actions/checkout@v4, actions/setup-python@v5, actions/cache@v4 to their
respective pinned commit SHAs) and add persist-credentials: false to the
actions/checkout step to avoid leaking GitHub credentials; update the workflow
entries referencing these symbols so they use the SHA pins and include
persist-credentials: false under the Checkout Code Repository step.In
@detectors/l3_custom.py:
- Around line 381-425: The _check_content method is too complex (high cognitive
complexity); refactor by extracting the toxic-word logic into two helpers:
implement _is_safe_context(toxic: str, text: str, original_prompt:
Optional[str]) -> bool which encapsulates the safe_contexts loop and fallback to
original_prompt checks, and implement _check_toxic_words(prompt: str,
allow_substring: bool, original_prompt: Optional[str]) -> dict | None which
iterates self.toxic_words, handles allow_substring vs word-boundary checks,
calls _is_safe_context to decide safety, and returns the same {"passed": False,
"reason": ...} or None; then simplify _check_content to run the PII loop and
call _check_toxic_words, returning its result if any.In
@docs/L3_FALSE_POSITIVE_FIX.md:
- Around line 77-80: The fenced code block showing "FINAL RESULTS: 38 passed, 0
failed" lacks a language specifier; update the opening fence (theline) in docs/L3_FALSE_POSITIVE_FIX.md so it includes a language identifier (e.g., changetotext orbash) to enable proper syntax highlighting and rendering
for the block containing "[PASS] ALL TESTS PASSED - False positive bug is
FIXED!".In
@test_debug2.py:
- Line 20: Remove the unnecessary f-string prefixes on the print calls that have
no interpolations (e.g., the print invocation that currently uses print(f" ^
Contains 'kill' as word") and the similar print at lines referenced in the
comment); change them to plain string literals so the prints use print(" ^
Contains 'kill' as word") (and the analogous second print) to eliminate the
unnecessary f prefix.- Line 17: Replace the explicit call to repr inside the f-string with the
f-string conversion flag: locate the print statement using print(f"{i}:
{repr(v)}") and change it to use the !r conversion for variable v (i.e., f"{i}:
{v!r}") to produce the same repr output with cleaner syntax.In
@test_preprocess.py:
- Line 9: Replace the explicit call to repr inside the f-string in the print
statement: locate the print statement that currently uses print(f"{i}:
{repr(v)}") (variables i and v) and change it to use the f-string conversion
flag by formatting v with !r (i.e., use {v!r}) so the representation is produced
by the f-string itself.In
@tests/debug_k1llc0mmand.py:
- Line 12: Remove the unnecessary f-string prefixes on plain string prints that
have no replacement fields: replace occurrences of print(f"=" * 80) and the
similar print(f"...") at the other occurrence in the tests/debug_k1llc0mmand.py
file with ordinary string literals (remove the leading "f") so they are regular
print("=" * 80) style calls.In
@tests/debug_safe_context.py:
- Line 29: Remove the unnecessary f-string prefixes from the print statements
that contain no interpolation (e.g., the calls currently written as print(f"
Word boundary match: YES") and the similar print(f"...") on the other line);
change them to plain string literals by dropping the leading f so they are
standard prints without formatting overhead.In
@tests/test_l3_toxic_wordboundary.py:
- Line 32: Replace explicit boolean comparisons in the tests (e.g., assertions
like assert result["passed"] == True and assert result["passed"] == False) with
truthiness checks: use assert result["passed"] for True checks and assert not
result["passed"] for False checks; update occurrences in
tests/test_l3_toxic_wordboundary.py wherever result["passed"] is compared to
True/False to improve style and satisfy the linter.In
@tests/test_word_boundary.py:
- Line 7: The print statement uses an unnecessary f-string with no
interpolation; update the print call in tests/test_word_boundary.py (the
print(f"=" * 80) statement) to use a normal string literal (remove the leading
"f") so it becomes print("=" * 80), preserving the same behavior without the
redundant f-prefix.In
@tests/trace_leetspeak.py:
- Line 21: Move the in-block import of the re module out to the top of the
module (after any module docstring and before other code) and delete the
conditional/internal import; ensure all uses of re in the file still work by
leaving the single top-level "import re" and removing the duplicated import
inside the conditional block.- Line 26: In tests/trace_leetspeak.py locate the print statement that currently
reads print(f" Would BLOCK") and remove the unnecessary f-prefix (change to a
regular string literal) since there are no placeholders; update the print call
accordingly to avoid an unused f-string in the test.</details> <details> <summary>🪄 Autofix (Beta)</summary> Fix all unresolved CodeRabbit comments on this PR: - [ ] <!-- {"checkboxId": "4b0d0e0a-96d7-4f10-b296-3a18ea78f0b9"} --> Push a commit to this branch (recommended) - [ ] <!-- {"checkboxId": "ff5b1114-7d8c-49e6-8ac1-43f82af23a33"} --> Create a new PR with the fixes </details> --- <details> <summary>ℹ️ Review info</summary> <details> <summary>⚙️ Run configuration</summary> **Configuration used**: Repository UI **Review profile**: CHILL **Plan**: Pro Plus **Run ID**: `4a3ad565-48e3-4733-8bb9-d58b76429504` </details> <details> <summary>📥 Commits</summary> Reviewing files that changed from the base of the PR and between d0dfd67d82c0e77be21127bc1bd419cf45e9a5bb and 4800ce743f8018ca6a698438ee698532a696aafb. </details> <details> <summary>📒 Files selected for processing (17)</summary> * `.github/workflows/security-gate.yml` * `detectors/l3_custom.py` * `docs/FIX_STATUS_AFTER_REVERT.md` * `docs/L3_FALSE_POSITIVE_FIX.md` * `requirements.txt` * `test_debug.py` * `test_debug2.py` * `test_preprocess.py` * `tests/debug_k1llc0mmand.py` * `tests/debug_safe_context.py` * `tests/run_safe_context_tests.py` * `tests/test_l3_safe_context.py` * `tests/test_l3_toxic_wordboundary.py` * `tests/test_specific_failures.py` * `tests/test_word_boundary.py` * `tests/trace_leetspeak.py` * `tests/unit/test_l4_upgrade.py` </details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
…bfuscated toxic words , FP fix
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
fix_and_test.bat (1)
1-33:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winConvert to Windows line endings (CRLF) to prevent batch file failures.
The file uses Unix line endings (LF-only), which can cause Windows batch parser failures due to 512-byte boundary bugs and GOTO/CALL label parsing issues. This will result in unpredictable script behavior or complete failure on Windows systems.
🔧 Fix options
Option 1: Convert with Git
git config core.autocrlf true git rm --cached fix_and_test.bat git add fix_and_test.batOption 2: Convert with dos2unix/unix2dos
unix2dos fix_and_test.batOption 3: In most text editors
- VS Code: Change line ending setting (bottom-right status bar) from LF to CRLF
- Notepad++: Edit → EOL Conversion → Windows (CRLF)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@fix_and_test.bat` around lines 1 - 33, The batch script fix_and_test.bat uses Unix (LF) line endings which can break Windows batch parsing; convert the file to CRLF (Windows) line endings so commands like the pip install -r requirements.txt, the python -c import checks, and subsequent echo/exit blocks parse correctly on Windows. Use git core.autocrlf=true and re-add the file or run a dos2unix/unix2dos (unix2dos) conversion or change the editor EOL setting to CRLF, then commit the updated fix_and_test.bat.Source: Linters/SAST tools
🧹 Nitpick comments (3)
docs/L3_FIX_FINAL_RESULTS.md (1)
78-79: ⚡ Quick winQualify the false positive/negative claims.
The claims "Zero false positives" and "Zero false negatives" are absolute statements that cannot be verified by a finite test suite. Consider qualifying these as "Zero false positives in test suite" or "Zero known false positives" to accurately reflect what the testing demonstrates.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/L3_FIX_FINAL_RESULTS.md` around lines 78 - 79, Update the absolute claims "Zero false positives" and "Zero false negatives" to qualified phrasing such as "Zero false positives in our test suite" or "No known false positives" (and similarly for negatives) so the document accurately reflects test-limited verification; replace the exact strings "Zero false positives" and "Zero false negatives" with the chosen qualified variants and keep the checklist/checkmark formatting intact.fix_and_test.sh (1)
12-14: ⚡ Quick winApply shell scripting best practices for robustness.
Consider these improvements:
- Check exit code directly (line 12):
if ! pip install -r requirements.txt; thenis cleaner thanif [ $? -ne 0 ]- Use
[[instead of[(line 12): The[[construct is safer and more feature-rich in bash- Redirect error to stderr (line 13): Error messages should go to stderr with
>&2♻️ Proposed improvements
-pip install -r requirements.txt - -if [ $? -ne 0 ]; then - echo "ERROR: Failed to install requirements" +if ! pip install -r requirements.txt; then + echo "ERROR: Failed to install requirements" >&2 exit 1 fi🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@fix_and_test.sh` around lines 12 - 14, Replace the current exit-code check that relies on `[ $? -ne 0 ]` with a direct command check and redirect the error message to stderr: run the pip install command inside an if-negation (e.g., `if ! pip install -r requirements.txt; then`) and change the test construct to the safer bash `[[ ... ]]` style if needed elsewhere; ensure the error echo is sent to stderr (use `echo "ERROR: Failed to install requirements" >&2`) and keep the `exit 1` behavior intact so the script fails on install errors.Source: Linters/SAST tools
requirements.txt.backup (1)
1-164: ⚖️ Poor tradeoffClarify the relationship between requirements.txt and requirements.txt.backup.
The backup file contains 164 fully-pinned packages (including GPU/CUDA dependencies and many packages absent from the main requirements.txt), but numerous packages have older versions than the main file:
certifi: 2026.1.4 (backup) vs 2026.5.20 (main)click: 8.3.3 vs 8.4.1cryptography: 46.0.5 vs 48.0.0numpy: 2.4.4 vs 2.4.6uvicorn: 0.38.0 vs 0.49.0Additionally, the backup includes
transformers==5.8.0while main specifiestransformers>=4.53.0, and the backup contains GPU/ML training dependencies (torch,tokenizers,huggingface_hub, NVIDIA CUDA packages) that are absent from main.Recommendation: Document whether the backup represents:
- A historical snapshot (in which case, consider removing or updating it)
- A parallel environment for development/training (in which case, add a README explaining when to use each file)
Without clarification, this creates confusion about which dependency set is canonical.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@requirements.txt.backup` around lines 1 - 164, The review points out that requirements.txt.backup and requirements.txt contain divergent dependency sets and versions (e.g., certifi, click, cryptography, numpy, uvicorn, transformers) and that the backup includes GPU/ML packages (torch, tokenizers, huggingface_hub, NVIDIA CUDA packages) not present in the main file; clarify which is canonical by either removing or updating requirements.txt.backup if it’s just a stale snapshot, or converting/renaming it to a clearly named environment file (e.g., requirements-train.txt or requirements-dev.txt) and add a README note explaining when to use each file and which one is the canonical install source; also align or document major version differences (or pin ranges) in requirements.txt if needed so consumers know which file to install from.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@docs/L3_FIX_FINAL_RESULTS.md`:
- Line 116: The git command in the docs should handle the file rename instead of
only adding the new path; replace the single-line "git add
detectors/l3_custom.py requirements.txt tests/manual/interactive_test.py" with
either a rename command (git mv tests/manual/manual_test.py
tests/manual/interactive_test.py followed by git add detectors/l3_custom.py
requirements.txt) or stage the whole directory (git add detectors/l3_custom.py
requirements.txt tests/manual/) so the deletion of tests/manual/manual_test.py
is tracked; update the line in docs/L3_FIX_FINAL_RESULTS.md accordingly.
- Around line 63-64: Update the documentation entry that currently reads "Lines
~458-476: Added spaceless toxic word detection in leetspeak layer" to reference
the correct implementation location "Lines ~490-515", and ensure the note
mentions the corresponding implementation in detectors/l3_custom.py (the
spaceless toxic word detection in the leetspeak layer) so readers can locate the
actual code change.
- Around line 26-36: The test counts in the summary table are inconsistent: the
suite rows sum to 175 (51, 98, 4, 3, 6, 2, 7, 3, 1) while the reported total
shows 161—reconcile this by either (A) correcting the "Total" value to 175, or
(B) clarifying and documenting overlaps/duplicate counting (e.g., add a note
column or amend the "Notes" row to state which tests are counted in multiple
suites and adjust the reported total to reflect unique tests); update the table
rows for the suites (L3 Safe Context, L3 Toxic Word Boundary, L3 Obfuscated
Attacks, L0 Unicode, L2 BERT, Rate Limit, Sanitize, Vigil, Unit Tests) and the
summary total so the arithmetic and explanation are consistent.
---
Outside diff comments:
In `@fix_and_test.bat`:
- Around line 1-33: The batch script fix_and_test.bat uses Unix (LF) line
endings which can break Windows batch parsing; convert the file to CRLF
(Windows) line endings so commands like the pip install -r requirements.txt, the
python -c import checks, and subsequent echo/exit blocks parse correctly on
Windows. Use git core.autocrlf=true and re-add the file or run a
dos2unix/unix2dos (unix2dos) conversion or change the editor EOL setting to
CRLF, then commit the updated fix_and_test.bat.
---
Nitpick comments:
In `@docs/L3_FIX_FINAL_RESULTS.md`:
- Around line 78-79: Update the absolute claims "Zero false positives" and "Zero
false negatives" to qualified phrasing such as "Zero false positives in our test
suite" or "No known false positives" (and similarly for negatives) so the
document accurately reflects test-limited verification; replace the exact
strings "Zero false positives" and "Zero false negatives" with the chosen
qualified variants and keep the checklist/checkmark formatting intact.
In `@fix_and_test.sh`:
- Around line 12-14: Replace the current exit-code check that relies on `[ $?
-ne 0 ]` with a direct command check and redirect the error message to stderr:
run the pip install command inside an if-negation (e.g., `if ! pip install -r
requirements.txt; then`) and change the test construct to the safer bash `[[ ...
]]` style if needed elsewhere; ensure the error echo is sent to stderr (use
`echo "ERROR: Failed to install requirements" >&2`) and keep the `exit 1`
behavior intact so the script fails on install errors.
In `@requirements.txt.backup`:
- Around line 1-164: The review points out that requirements.txt.backup and
requirements.txt contain divergent dependency sets and versions (e.g., certifi,
click, cryptography, numpy, uvicorn, transformers) and that the backup includes
GPU/ML packages (torch, tokenizers, huggingface_hub, NVIDIA CUDA packages) not
present in the main file; clarify which is canonical by either removing or
updating requirements.txt.backup if it’s just a stale snapshot, or
converting/renaming it to a clearly named environment file (e.g.,
requirements-train.txt or requirements-dev.txt) and add a README note explaining
when to use each file and which one is the canonical install source; also align
or document major version differences (or pin ranges) in requirements.txt if
needed so consumers know which file to install from.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 977b5b0c-a05d-488a-9db1-c779ffaae7cb
📒 Files selected for processing (6)
docs/L3_FIX_FINAL_RESULTS.mdfix_and_test.batfix_and_test.shrequirements.txtrequirements.txt.backuptests/manual/interactive_test.py
| ## 📦 Ready to Commit | ||
|
|
||
| ```bash | ||
| git add detectors/l3_custom.py requirements.txt tests/manual/interactive_test.py |
There was a problem hiding this comment.
Fix the git command to properly handle the file rename.
The command adds tests/manual/interactive_test.py but doesn't handle the deletion of the original tests/manual/manual_test.py. For a file rename, use:
git mv tests/manual/manual_test.py tests/manual/interactive_test.py
git add detectors/l3_custom.py requirements.txtOr simply stage the entire directory:
git add detectors/l3_custom.py requirements.txt tests/manual/🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@docs/L3_FIX_FINAL_RESULTS.md` at line 116, The git command in the docs should
handle the file rename instead of only adding the new path; replace the
single-line "git add detectors/l3_custom.py requirements.txt
tests/manual/interactive_test.py" with either a rename command (git mv
tests/manual/manual_test.py tests/manual/interactive_test.py followed by git add
detectors/l3_custom.py requirements.txt) or stage the whole directory (git add
detectors/l3_custom.py requirements.txt tests/manual/) so the deletion of
tests/manual/manual_test.py is tracked; update the line in
docs/L3_FIX_FINAL_RESULTS.md accordingly.
…ytest config * Added typing.Optional for PEP 484 compliance * Fixed leetspeak safe context bypass preventing sk1ll false positive * Created pytest.ini to exclude manual tests * Updated documentation with correct line numbers * All 161 tests passing + edge cases verified * Dependencies updated to secure versions
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
docs/ALL_FIXES_COMPLETE.md (1)
66-81: 💤 Low valueMinor: Add language specifier to code fence.
The code block at line 66 is missing a language specifier. Add
bashortextafter the opening triple backticks for proper syntax highlighting.📝 Proposed fix
-``` +```bash platform linux -- Python 3.11.15, pytest-9.0.3🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/ALL_FIXES_COMPLETE.md` around lines 66 - 81, Add a language specifier to the opening triple-backtick code fence for the test summary block in docs/ALL_FIXES_COMPLETE.md: locate the code block that begins with ``` containing "platform linux -- Python 3.11.15, pytest-9.0.3" and change the fence to include a language token (e.g., ```bash or ```text) so the snippet renders with proper highlighting.detectors/l3_custom.py (1)
382-382: ⚖️ Poor tradeoffConsider extracting toxic-word checking into a helper to reduce cognitive complexity.
SonarCloud flags cognitive complexity of 39 (limit 15). While the current implementation is functionally correct, extracting the toxic word + safe context checking loop (lines 401-426) into a separate method would improve maintainability.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@detectors/l3_custom.py` at line 382, The _check_content method is too complex; extract the toxic-word + safe-context checking loop into a new helper (e.g., _find_toxic_word_with_safe_context or _contains_toxic_word) that accepts the prompt, allow_substring flag, original_prompt and returns either the offending word/context or None, then replace the original loop (currently inside _check_content) with a single call to that helper and handle its result; ensure the helper contains the exact logic from the loop (toxic words list traversal, substring vs exact matching, and safe-context exemptions) and update any tests or callers to use the refactored helper to reduce cognitive complexity of _check_content.Source: Linters/SAST tools
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@detectors/l3_custom.py`:
- Around line 501-507: The safe-context check currently only tests the spaceless
string leet_lower against patterns in self.safe_contexts[toxic], which prevents
regexes with whitespace (e.g., r"use\s+kill\s+command") from matching; update
the loop in the block that sets is_safe to also test each safe_pattern against
the original prompt (variable prompt) in addition to leet_lower (use
re.search(safe_pattern, prompt, re.IGNORECASE) as a fallback), so patterns that
expect spaces can match and avoid false positives in the method handling toxic
detection.
In `@detectors/l4_groq.py`:
- Around line 126-127: The except block in _log_to_table() references an
undefined symbol logger causing a NameError; fix by either using the existing
logging module (e.g., replace logger.debug(...) with logging.debug(...) or
logging.exception(...)) or by defining a module-level logger =
logging.getLogger(__name__) at top of the module; update the except handler
accordingly so exceptions are logged without raising a new NameError.
In `@pytest.ini`:
- Line 6: The pytest.ini line sets norecursedirs explicitly which is supported
in pytest==9.0.3 but can override pytest’s default exclusions; update the
norecursedirs value (the existing "norecursedirs" entry) to include pytest's
default patterns (for example .git, .tox, build, dist, eggs, .eggs, *_cache_
etc.) in addition to your custom dirs (tests/manual tests/debug .venv venv
__pycache__ .pytest_cache) so discovery behavior remains unchanged; locate the
pytest.ini norecursedirs entry and append the missing default patterns to the
list.
---
Nitpick comments:
In `@detectors/l3_custom.py`:
- Line 382: The _check_content method is too complex; extract the toxic-word +
safe-context checking loop into a new helper (e.g.,
_find_toxic_word_with_safe_context or _contains_toxic_word) that accepts the
prompt, allow_substring flag, original_prompt and returns either the offending
word/context or None, then replace the original loop (currently inside
_check_content) with a single call to that helper and handle its result; ensure
the helper contains the exact logic from the loop (toxic words list traversal,
substring vs exact matching, and safe-context exemptions) and update any tests
or callers to use the refactored helper to reduce cognitive complexity of
_check_content.
In `@docs/ALL_FIXES_COMPLETE.md`:
- Around line 66-81: Add a language specifier to the opening triple-backtick
code fence for the test summary block in docs/ALL_FIXES_COMPLETE.md: locate the
code block that begins with ``` containing "platform linux -- Python 3.11.15,
pytest-9.0.3" and change the fence to include a language token (e.g., ```bash or
```text) so the snippet renders with proper highlighting.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ad63bd7b-4d94-4006-afbb-f1c0d4c4c984
📒 Files selected for processing (11)
api/auth.pyapi/main.pycli/main.pydetectors/l3_custom.pydetectors/l4_groq.pydocs/ALL_FIXES_COMPLETE.mddocs/BANDIT_LOW_ERRORS_RESOLVED.mddocs/L3_FIX_FINAL_RESULTS.mdpytest.iniscripts/fetch_payloads.pytests/test_edge_cases.py
✅ Files skipped from review due to trivial changes (3)
- docs/BANDIT_LOW_ERRORS_RESOLVED.md
- tests/test_edge_cases.py
- docs/L3_FIX_FINAL_RESULTS.md
| python_files = test_*.py | ||
| python_classes = Test* | ||
| python_functions = test_* | ||
| norecursedirs = tests/manual tests/debug .git .venv venv __pycache__ .pytest_cache |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check pytest version in requirements and verify norecursedirs deprecation status
# Check pytest version requirement
echo "=== Checking pytest version in requirements ==="
rg -n "pytest" requirements.txt requirements.txt.backup 2>/dev/null || echo "No pytest version constraint found"
# Check for any pytest configuration documentation or comments
echo -e "\n=== Checking for pytest-related configuration notes ==="
rg -n -i "norecursedirs|pytest.*deprecat" docs/ 2>/dev/null || echo "No deprecation notes found"Repository: Sandeep-int/agent-shield
Length of output: 276
🌐 Web query:
Is pytest norecursedirs deprecated and what is the recommended alternative?
💡 Result:
The pytest configuration option norecursedirs is not deprecated [1][2][3]. It remains the standard, supported method for specifying directory basename patterns that pytest should avoid when collecting tests [3]. Since it is not deprecated, there is no replacement for it. You can continue to use it in your pytest configuration files (such as pyproject.toml, pytest.ini, or tox.ini) to control test discovery behavior [4][2][3]. For example, to configure norecursedirs in a pyproject.toml file, you can add it under the [tool.pytest.ini_options] section: [tool.pytest.ini_options] norecursedirs = [".svn", "_build", "tmp*", "venv"] When setting this option, keep in mind that defining norecursedirs replaces the default values [3]. If you want to retain the standard defaults (which include patterns like.*, venv, and build), you should explicitly include them alongside your custom patterns [5][3].
Citations:
- 1: https://pytest.org/en/8.1.x/example/pythoncollection.html
- 2: https://docs.pytest.org/en/stable/example/pythoncollection.html
- 3: https://github.com/pytest-dev/pytest/blob/main/doc/en/reference/reference.rst
- 4: https://github.com/pytest-dev/pytest/blob/8b3550c6/doc/en/example/pythoncollection.rst
- 5: testing: add
.*tonorecursedirspytest-dev/pytest#11322
norecursedirs usage is supported in this repo’s pytest version
requirements.txt pins pytest==9.0.3, and norecursedirs is still a supported (not deprecated) pytest configuration option—so line 6 should be compatible.
Minor follow-up: setting norecursedirs can override pytest’s default exclusion patterns, so ensure the configured list includes any defaults you still want (otherwise discovery behavior may change).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@pytest.ini` at line 6, The pytest.ini line sets norecursedirs explicitly
which is supported in pytest==9.0.3 but can override pytest’s default
exclusions; update the norecursedirs value (the existing "norecursedirs" entry)
to include pytest's default patterns (for example .git, .tox, build, dist, eggs,
.eggs, *_cache_ etc.) in addition to your custom dirs (tests/manual tests/debug
.venv venv __pycache__ .pytest_cache) so discovery behavior remains unchanged;
locate the pytest.ini norecursedirs entry and append the missing default
patterns to the list.
…ytest config * Added typing.Optional for PEP 484 compliance * Fixed leetspeak safe context bypass preventing sk1ll false positive * Created pytest.ini to exclude manual tests * Updated documentation with correct line numbers * All 161 tests passing + edge cases verified * Dependencies updated to secure versions
* Fixed 12 try-except-pass silent failures with debug logging * Added logger initialization to l4_groq.py (fixes NameError) * Added original_prompt fallback in leetspeak safe context check * Fixed CI/CD dependency installation (removed broken conditional logic) * Documented 5 false positive B105 warnings in BANDIT_LOW_ERRORS_RESOLVED.md Security: 0 vulnerabilities, all changes are logging-only (production-safe) Tests: All 161 tests passing locally CI/CD: GitHub Actions will now install dependencies correctly
|



Summary by CodeRabbit
Bug Fixes
New Features
Tests
Documentation
Chores