Skip to content

chore: trigger full coderabbit audit - #2

Merged
Sandeep-int merged 10 commits into
mainfrom
security/full-audit
Jun 3, 2026
Merged

Sandeep-int merged 10 commits into
mainfrom
security/full-audit

Conversation

@Sandeep-int

@Sandeep-int Sandeep-int commented Jun 3, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

  • New Features

    • Tiered rate limits (internal/pro/standard), 10KB request payload cap (returns 413 on overflow), CORS support, stronger security headers, and prompt length reduced to 2,000 characters. Server bind host now respects HOST env var.
  • Bug Fixes / Reliability

    • CLI network calls validate URL schemes.
    • Model/tokenizer loading is more resilient with local fallback and graceful handling when artifacts are missing.
  • Chores

    • Added an automated security-and-test workflow.

Review Change Stack

Copilot AI review requested due to automatic review settings June 3, 2026 05:49

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot wasn't able to review any files in this pull request.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@Sandeep-int

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
✅ Action performed

Full review finished.

@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a CI security gate, tiered API-key-aware rate limiting, payload/security middleware, CORS, tighter prompt validation, configurable startup host, CLI URL-scheme checks, and BertClassifier token/ONNX fallback handling.

Changes

API and CI Security Hardening

Layer / File(s) Summary
CI Security Gate Workflow
.github/workflows/security-gate.yml
New GitHub Actions workflow that checks out full history, sets up Python 3.11 with pip caching, installs dependencies plus bandit, pip-audit, and pytest, runs bandit (excluding ./venv, ./onnx_env, ./tests), runs pip-audit, and executes unit tests. Triggers on pushes to main/dev and PRs targeting main.
Rate Limiting Key Resolution
api/main.py
Adds helpers to resolve internal/pro API keys and reconfigures the SlowAPI limiter to bucket by internal keys (unlimited), pro keys (per-key), or other requests (per-IP).
HTTP Security, Payload Guard, and CORS
api/main.py
Adds payload_size_guard middleware that rejects requests above MAX_BODY_BYTES with 413, security_headers_middleware that sets X-Content-Type-Options, X-Frame-Options, XSS protection and strips server-identifying headers, and registers CORSMiddleware with origins from CORS_ALLOWED_ORIGINS.
Endpoint Rate Limiting Tiers
api/main.py
Replaces single /v1/check rate limit with two stacked limiter decorators using different key functions and exempt_when predicates for internal/pro vs non-pro requests.
API Contract and Runtime Configuration
api/main.py
Reduces CheckRequest.prompt max length (10,000 → 2,000) and changes Uvicorn host binding to use HOST env var (default 127.0.0.1).
App Entrypoint Import
app.py
Move uvicorn import to module load; runtime uvicorn.run(...) under if __name__ == \"__main__\" remains.
CLI URL-scheme Validation
cli/main.py
Adds safe_urlopen enforcing http:// or https:// and replaces direct urllib.request.urlopen calls in health-check, auth revoke, and prompt-check flows.
BertClassifier ONNX/Tokenizer Guards
detectors/bert_classifier.py
Adds LOCAL_TOKENIZER_PATH and makes ONNX/tokenizer loading resilient: ONNX download failures use local cache when present; tokenizer remote fetch falls back to local files via local_files_only=True (or raises if no local cache).

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant api_main as api.main
  participant SlowAPI_Limiter as SlowAPI_Limiter
  Client->>api_main: POST /v1/check (body)
  api_main->>api_main: _resolve_api_key(request)
  api_main->>SlowAPI_Limiter: get_rate_limit_key(request) / enforce limits
  SlowAPI_Limiter-->>api_main: allow or deny (429)
  api_main-->>Client: 200 OK or 429 Too Many Requests or 413 Payload Too Large
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I hop through pipelines, checking every gate,
Bandit peers, pip-audit turns the latch,
Limits layered, small bodies kept tight,
Safe URLs guide the midnight fetch,
Tokenizers rest in a local patch.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Title check ⚠️ Warning The PR title 'chore: trigger full coderabbit audit' does not accurately describe the actual changes made in the pull request. The changeset implements significant security and infrastructure improvements including a new GitHub Actions security workflow, API rate limiting, security headers, CORS configuration, URL validation, and ONNX resilience enhancements. The title is misleading and suggests the PR's sole purpose is triggering a code review tool, which contradicts the substantial functional changes present. Replace the title with a more accurate description of the actual changes, such as 'feat: add security gate workflow and enhance API security with rate limiting, CORS, and security headers' or break into multiple focused PRs by feature area.
Docstring Coverage ⚠️ Warning Docstring coverage is 17.65% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch security/full-audit

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


Comment @coderabbitai help to get the list of available commands and usage tips.

@Sandeep-int

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (2)
.github/workflows/security-gate.yml (2)

27-27: ⚡ Quick win

Consider pinning security tool versions for reproducibility.

Installing pytest, bandit, and pip-audit without version pins allows tool versions to drift over time, potentially causing inconsistent scan results or false positives/negatives as tools evolve.

📌 Optional: Pin tool versions
-          pip install pytest bandit pip-audit
+          pip install pytest==8.2.0 bandit==1.7.8 pip-audit==2.7.3

Alternatively, add these tools to requirements.txt or a separate requirements-dev.txt with pinned versions.

🤖 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 @.github/workflows/security-gate.yml at line 27, The workflow currently runs
"pip install pytest bandit pip-audit" without pinned versions; update that step
to pin explicit versions (e.g., replace "pip install pytest bandit pip-audit"
with pinned specifiers like "pip install pytest==<version> bandit==<version>
pip-audit==<version>") or change it to install from a committed dev requirements
file (e.g., "pip install -r requirements-dev.txt") that contains exact version
pins; ensure the chosen approach is applied where the "pip install pytest bandit
pip-audit" command appears so scans are reproducible.

29-32: ⚡ Quick win

Consider adding explicit failure behavior for pip-audit.

Currently, pip-audit runs without flags, which reports vulnerabilities but doesn't specify failure behavior. The CI job will pass even if critical vulnerabilities are found, unless pip-audit's default behavior is to exit with a non-zero code.

💡 Suggested enhancement for explicit vulnerability handling
       - name: Execute Pipeline Integrity Audits
         run: |
           bandit -r . --exclude ./venv,./onnx_env,./tests -ll
-          pip-audit
+          pip-audit --strict --desc on

The --strict flag ensures the job fails on any vulnerabilities, and --desc on provides detailed vulnerability descriptions.

🤖 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 @.github/workflows/security-gate.yml around lines 29 - 32, Update the
pip-audit invocation in the "Execute Pipeline Integrity Audits" step to enforce
explicit failure on findings and provide descriptions: replace the plain
`pip-audit` call with a flagged invocation such as `pip-audit --strict --desc
on` so the CI job exits non-zero on vulnerabilities and prints detailed
descriptions; locate the pip-audit command in that workflow step and apply the
flags to ensure explicit failure behavior.
🤖 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 @.github/workflows/security-gate.yml:
- Line 1: The file .github/workflows/security-gate.yml uses Windows CRLF line
endings; convert it to Unix LF to satisfy the YAML linter and avoid diffs. Fix
by normalizing line endings for that file (e.g., run a CRLF->LF conversion like
dos2unix on .github/workflows/security-gate.yml) or add a .gitattributes rule
("* text=auto eol=lf") and run git add --renormalize . to apply LF endings;
ensure the top workflow header line "name: Agent Shield Production Pipeline"
ends with LF.
- Line 15: The workflow currently sets "fetch-depth: 0" with a SonarCloud
rationale but no SonarCloud step exists; either add a SonarCloud scan job/step
(e.g., a SonarCloud analysis step including actions/checkout with fetch-depth: 0
and the SonarCloud scan commands and tokens) if full Git history is required, or
remove/replace the SonarCloud comment and change "fetch-depth: 0" to
"fetch-depth: 1" (or remove the fetch-depth override entirely) to avoid
unnecessary fetches; update the comment to accurately reflect the reason (or
absence) for full history and ensure the workflow's steps referencing SonarCloud
(if added) match the checkout configuration.
- Around line 9-11: Add an explicit permissions block to the
security-and-testing-gate job to enforce least privilege: under the job named
security-and-testing-gate, add a permissions section with at minimum "contents:
read" (e.g., permissions: { contents: read }) so the job only has read access to
the repository; place this permissions key at the job level (immediately under
security-and-testing-gate) rather than relying on inherited repository-default
permissions.
- Around line 14-15: The checkout step currently sets "fetch-depth: 0" but omits
persist-credentials, which can leave the GitHub token exposed; update the
actions/checkout step (the block containing "with: fetch-depth: 0") to add
"persist-credentials: false" under the same with: mapping so credentials are not
left in the checked-out repository or .git/config for subsequent steps.
- Line 13: The workflow pins mutable action versions; replace the version tags
for actions/checkout and actions/setup-python with the provided commit SHAs so
the workflow is immutable: change the job step that currently uses
actions/checkout@v4 to actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5
and change the step using actions/setup-python@v5 to
actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065, ensuring the YAML
keys and step names (e.g., the checkout and setup-python steps) remain
unchanged.

In `@api/main.py`:
- Around line 143-149: The CORSMiddleware is added before SlowAPIMiddleware so
CORS runs after rate-limiting (LIFO order); move the
app.add_middleware(CORSMiddleware, ...) call so it is invoked after
app.add_middleware(SlowAPIMiddleware) — i.e., register SlowAPIMiddleware first
and then call app.add_middleware for CORSMiddleware so CORS executes first on
incoming requests; keep the same allow_origins/allow_methods/allow_headers
arguments when you move it.

---

Nitpick comments:
In @.github/workflows/security-gate.yml:
- Line 27: The workflow currently runs "pip install pytest bandit pip-audit"
without pinned versions; update that step to pin explicit versions (e.g.,
replace "pip install pytest bandit pip-audit" with pinned specifiers like "pip
install pytest==<version> bandit==<version> pip-audit==<version>") or change it
to install from a committed dev requirements file (e.g., "pip install -r
requirements-dev.txt") that contains exact version pins; ensure the chosen
approach is applied where the "pip install pytest bandit pip-audit" command
appears so scans are reproducible.
- Around line 29-32: Update the pip-audit invocation in the "Execute Pipeline
Integrity Audits" step to enforce explicit failure on findings and provide
descriptions: replace the plain `pip-audit` call with a flagged invocation such
as `pip-audit --strict --desc on` so the CI job exits non-zero on
vulnerabilities and prints detailed descriptions; locate the pip-audit command
in that workflow step and apply the flags to ensure explicit failure behavior.
🪄 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: c8549e1a-a0ae-4580-b0f3-5dcec832ace5

📥 Commits

Reviewing files that changed from the base of the PR and between fd9c474 and cf360b6.

📒 Files selected for processing (2)
  • .github/workflows/security-gate.yml
  • api/main.py

@@ -0,0 +1,36 @@
name: Agent Shield Production Pipeline

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Use Unix line endings (LF) instead of Windows line endings (CRLF).

The YAML linter detected non-Unix line endings in this file. While GitHub Actions typically handles both formats, using Unix line endings (LF) is the standard for repository files and prevents unnecessary diff noise.

You can normalize line endings with:

# Convert CRLF to LF
dos2unix .github/workflows/security-gate.yml

# Or using Git attributes
echo "* text=auto eol=lf" >> .gitattributes
git add --renormalize .
🧰 Tools
🪛 YAMLlint (1.38.0)

[error] 1-1: wrong new line character: expected \n

(new-lines)

🤖 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 @.github/workflows/security-gate.yml at line 1, The file
.github/workflows/security-gate.yml uses Windows CRLF line endings; convert it
to Unix LF to satisfy the YAML linter and avoid diffs. Fix by normalizing line
endings for that file (e.g., run a CRLF->LF conversion like dos2unix on
.github/workflows/security-gate.yml) or add a .gitattributes rule ("* text=auto
eol=lf") and run git add --renormalize . to apply LF endings; ensure the top
workflow header line "name: Agent Shield Production Pipeline" ends with LF.

Comment on lines +9 to +11
security-and-testing-gate:
runs-on: ubuntu-latest
steps:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Set explicit permissions to follow least-privilege principle.

Without an explicit permissions: block, the workflow inherits repository-default permissions, which are often overly broad (e.g., write-all). This violates the principle of least privilege and increases the attack surface if the workflow is compromised.

This security gate only needs read access to the repository.

🔒 Proposed fix to add explicit permissions
 jobs:
   security-and-testing-gate:
     runs-on: ubuntu-latest
+    permissions:
+      contents: read
     steps:
🧰 Tools
🪛 zizmor (1.25.2)

[warning] 9-36: overly broad permissions (excessive-permissions): default permissions used due to no permissions: block

(excessive-permissions)

🤖 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 @.github/workflows/security-gate.yml around lines 9 - 11, Add an explicit
permissions block to the security-and-testing-gate job to enforce least
privilege: under the job named security-and-testing-gate, add a permissions
section with at minimum "contents: read" (e.g., permissions: { contents: read })
so the job only has read access to the repository; place this permissions key at
the job level (immediately under security-and-testing-gate) rather than relying
on inherited repository-default permissions.

runs-on: ubuntu-latest
steps:
- name: Checkout Code Repository
uses: actions/checkout@v4

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Fetch the latest commit SHA for each action tag

echo "=== actions/checkout@v4 ==="
gh api repos/actions/checkout/git/ref/tags/v4 --jq '.object.sha' || \
  gh api repos/actions/checkout/releases/latest --jq '.tag_name as $tag | "Latest: " + $tag' 

echo ""
echo "=== actions/setup-python@v5 ==="
gh api repos/actions/setup-python/git/ref/tags/v5 --jq '.object.sha' || \
  gh api repos/actions/setup-python/releases/latest --jq '.tag_name as $tag | "Latest: " + $tag'

Repository: Sandeep-int/agent-shield

Length of output: 211


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== File: .github/workflows/security-gate.yml (numbered) =="
nl -ba .github/workflows/security-gate.yml | sed -n '1,120p'

echo
echo "== uses: lines =="
rg -n --no-heading '^\s*uses:\s*' .github/workflows/security-gate.yml || true

echo
echo "== persist-credentials occurrences =="
rg -n --no-heading 'persist-credentials' .github/workflows/security-gate.yml || true

echo
echo "== permissions occurrences =="
rg -n --no-heading '^\s*permissions\s*:' .github/workflows/security-gate.yml || true

Repository: Sandeep-int/agent-shield

Length of output: 188


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== File: .github/workflows/security-gate.yml (numbered) =="
awk '{printf "%6d\t%s\n", NR, $0}' .github/workflows/security-gate.yml | sed -n '1,160p'

echo
echo "== uses: lines =="
rg -n --no-heading '^\s*uses:\s*' .github/workflows/security-gate.yml || true

echo
echo "== persist-credentials occurrences =="
rg -n --no-heading 'persist-credentials' .github/workflows/security-gate.yml || true

echo
echo "== permissions occurrences =="
rg -n --no-heading '^\s*permissions\s*:' .github/workflows/security-gate.yml || true

Repository: Sandeep-int/agent-shield

Length of output: 1521


Pin GitHub Actions to commit SHAs in security-gate.yml.

actions/checkout@v4 (line 13) and actions/setup-python@v5 (line 18) are version-tagged and therefore mutable. Use the corresponding commit SHAs:

  • actions/checkout@v4 -> 34e114876b0b11c390a56381ad16ebd13914f8d5
  • actions/setup-python@v5 -> a26af69be951a213d495a4c3e4e4022e16d87065
🔒 Proposed fix to pin actions
-        uses: actions/checkout@v4
+        uses: actions/checkout@<commit-sha>  # v4
         with:
           fetch-depth: 0  # Crucial for SonarCloud tracking and analysis

       - name: Initialize Python Runtime Env
-        uses: actions/setup-python@v5
+        uses: actions/setup-python@<commit-sha>  # v5
         with:
🧰 Tools
🪛 zizmor (1.25.2)

[error] 13-13: unpinned action reference (unpinned-uses): action is not pinned to a hash (required by blanket policy)

(unpinned-uses)

🤖 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 @.github/workflows/security-gate.yml at line 13, The workflow pins mutable
action versions; replace the version tags for actions/checkout and
actions/setup-python with the provided commit SHAs so the workflow is immutable:
change the job step that currently uses actions/checkout@v4 to
actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 and change the step
using actions/setup-python@v5 to
actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065, ensuring the YAML
keys and step names (e.g., the checkout and setup-python steps) remain
unchanged.

Comment on lines +14 to +15
with:
fetch-depth: 0 # Crucial for SonarCloud tracking and analysis

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Add persist-credentials: false to prevent credential exposure.

Without persist-credentials: false, the GitHub token remains accessible in the working directory (.git/config) and can be used by subsequent steps or malicious dependencies. This creates a credential leak risk if compromised code executes during dependency installation or testing.

🛡️ Proposed fix
         uses: actions/checkout@v4
         with:
+          persist-credentials: false
           fetch-depth: 0  # Crucial for SonarCloud tracking and analysis
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
with:
fetch-depth: 0 # Crucial for SonarCloud tracking and analysis
with:
persist-credentials: false
fetch-depth: 0 # Crucial for SonarCloud tracking and analysis
🧰 Tools
🪛 zizmor (1.25.2)

[warning] 12-15: credential persistence through GitHub Actions artifacts (artipacked): does not set persist-credentials: false

(artipacked)

🤖 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 @.github/workflows/security-gate.yml around lines 14 - 15, The checkout step
currently sets "fetch-depth: 0" but omits persist-credentials, which can leave
the GitHub token exposed; update the actions/checkout step (the block containing
"with: fetch-depth: 0") to add "persist-credentials: false" under the same with:
mapping so credentials are not left in the checked-out repository or .git/config
for subsequent steps.

- name: Checkout Code Repository
uses: actions/checkout@v4
with:
fetch-depth: 0 # Crucial for SonarCloud tracking and analysis

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Clarify the need for full Git history.

The comment mentions "Crucial for SonarCloud tracking and analysis," but no SonarCloud step exists in this workflow. Either:

  1. A SonarCloud scan step is missing from the incomplete implementation, or
  2. The comment is misleading and should be removed

If SonarCloud is not being used, fetch-depth: 0 downloads unnecessary history and slows CI. Consider removing it or setting fetch-depth: 1 unless full history is required for another reason.

Would you like me to provide a SonarCloud scan step configuration, or should the comment and fetch-depth be updated?

🧰 Tools
🪛 zizmor (1.25.2)

[warning] 12-15: credential persistence through GitHub Actions artifacts (artipacked): does not set persist-credentials: false

(artipacked)

🤖 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 @.github/workflows/security-gate.yml at line 15, The workflow currently sets
"fetch-depth: 0" with a SonarCloud rationale but no SonarCloud step exists;
either add a SonarCloud scan job/step (e.g., a SonarCloud analysis step
including actions/checkout with fetch-depth: 0 and the SonarCloud scan commands
and tokens) if full Git history is required, or remove/replace the SonarCloud
comment and change "fetch-depth: 0" to "fetch-depth: 1" (or remove the
fetch-depth override entirely) to avoid unnecessary fetches; update the comment
to accurately reflect the reason (or absence) for full history and ensure the
workflow's steps referencing SonarCloud (if added) match the checkout
configuration.

Comment thread api/main.py Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (1)
detectors/bert_classifier.py (1)

51-55: 💤 Low value

Remove unnecessary revision parameter from local fallback.

When loading from a local directory with local_files_only=True, the revision parameter has no effect since local files don't have HuggingFace revision metadata. This is misleading.

♻️ Suggested fix
                 self.tokenizer = DistilBertTokenizer.from_pretrained(
                     LOCAL_TOKENIZER_PATH,
-                    revision=HF_REVISION,
                     local_files_only=True,
                 )
🤖 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/bert_classifier.py` around lines 51 - 55, The call to
DistilBertTokenizer.from_pretrained in the tokenizer initialization passes
revision=HF_REVISION while also using local_files_only=True; remove the revision
argument so the local fallback isn't misleading. Locate the tokenizer
construction in the class where self.tokenizer is set (the
DistilBertTokenizer.from_pretrained call) and delete the revision=HF_REVISION
parameter, leaving local_files_only=True and the LOCAL_TOKENIZER_PATH intact.
🤖 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 `@app.py`:
- Line 6: The module calls uvicorn.run(...) at import time which starts the
server on import; wrap the uvicorn.run("api.main:app", host=..., port=...) call
inside a __main__ guard (if __name__ == "__main__":) so importing app.py no
longer starts Uvicorn while still preserving current behavior when running
python app.py; locate the uvicorn.run invocation in app.py and move it into that
guard.

In `@cli/main.py`:
- Line 128: The linter flags the audited urlopen call; add an explicit Ruff
suppression on the audited line by appending an inline noqa for S310 to the
return statement that calls urllib.request.urlopen in the same function that
uses safe_urlopen (e.g., add " # noqa: S310" to the end of the return
urllib.request.urlopen(...) line) so Ruff knows this use is intentionally
audited and the CI security check is satisfied.
- Around line 133-134: The health-check response from safe_urlopen is not closed
deterministically; change the code that calls safe_urlopen (the req variable
usage in cli/main.py) to open the response with a context manager (use "with
safe_urlopen(f\"{API_BASE}/health\", timeout=8) as req:") and move the
json.loads(req.read().decode()) inside that with-block so the response is always
closed after reading.

In `@detectors/bert_classifier.py`:
- Line 10: LOCAL_TOKENIZER_PATH is set to join MODEL_DIR with "tokenizer" but
the training output uses "fine_tuned_bert", so the fallback path will never
match; update the code that defines LOCAL_TOKENIZER_PATH to point to the same
directory name used by the training output (i.e., replace "tokenizer" with
"fine_tuned_bert" or make both save/load use a shared constant), ensuring
LOCAL_TOKENIZER_PATH and the training save location are identical.
- Around line 36-38: The fallback currently only checks ONNX_PATH; update the
logic that handles blob download failures to also verify ONNX_DATA_PATH exists
before proceeding—if either ONNX_PATH or ONNX_DATA_PATH is missing, raise a
RuntimeError with the actual exception (the same way the existing raise uses
`e`) and do not print the “using cached ONNX weights” message; only
print/continue with the cached weights when both files exist. Locate the
download/fallback block around the blob handling and InferenceSession(ONNX_PATH)
usage and add the extra file existence check for ONNX_DATA_PATH and appropriate
error handling/log message there.
- Line 8: HF_REVISION is pinned to an invalid commit and the BertClassifier init
uses DistilBertTokenizer.from_pretrained(HF_MODEL, revision=HF_REVISION) and a
fallback that points to LOCAL_TOKENIZER_PATH which doesn't match where training
saved the tokenizer (./models/fine_tuned_bert), and ONNX download error handling
only checks ONNX_PATH not ONNX_DATA_PATH; update BertClassifier initialization
to remove or make HF_REVISION optional (so from_pretrained can fall back to HF
defaults) or validate the revision before use, change the local fallback path
used by DistilBertTokenizer.from_pretrained to the actual training output
directory (fine_tuned_bert or add a prioritized list including
LOCAL_TOKENIZER_PATH and ./models/fine_tuned_bert), and expand the ONNX
download/exception handling in the ONNX loader to check both ONNX_PATH and
ONNX_DATA_PATH so the code treats a missing .data file as a download failure and
triggers full fallback/retry.

---

Nitpick comments:
In `@detectors/bert_classifier.py`:
- Around line 51-55: The call to DistilBertTokenizer.from_pretrained in the
tokenizer initialization passes revision=HF_REVISION while also using
local_files_only=True; remove the revision argument so the local fallback isn't
misleading. Locate the tokenizer construction in the class where self.tokenizer
is set (the DistilBertTokenizer.from_pretrained call) and delete the
revision=HF_REVISION parameter, leaving local_files_only=True and the
LOCAL_TOKENIZER_PATH intact.
🪄 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: 15dba441-6b03-4ac0-a8dc-03139433bc33

📥 Commits

Reviewing files that changed from the base of the PR and between cf360b6 and 78e632a.

📒 Files selected for processing (3)
  • app.py
  • cli/main.py
  • detectors/bert_classifier.py

Comment thread app.py Resolved
Comment thread cli/main.py
else:
target = url_or_request
_validate_http_url(target)
return urllib.request.urlopen(url_or_request, timeout=timeout) # nosec B310

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fix CI lint failure for audited urlopen call.

Line 128 is still flagged by Ruff (S310) even though validation happens in safe_urlopen, which can block the security gate. Add an explicit Ruff suppression on this audited line.

Suggested patch
-    return urllib.request.urlopen(url_or_request, timeout=timeout)  # nosec B310
+    return urllib.request.urlopen(url_or_request, timeout=timeout)  # nosec B310  # noqa: S310
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return urllib.request.urlopen(url_or_request, timeout=timeout) # nosec B310
return urllib.request.urlopen(url_or_request, timeout=timeout) # nosec B310 # noqa: S310
🧰 Tools
🪛 Ruff (0.15.15)

[error] 128-128: Audit URL open for permitted schemes. Allowing use of file: or custom schemes is often unexpected.

(S310)

🤖 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 `@cli/main.py` at line 128, The linter flags the audited urlopen call; add an
explicit Ruff suppression on the audited line by appending an inline noqa for
S310 to the return statement that calls urllib.request.urlopen in the same
function that uses safe_urlopen (e.g., add " # noqa: S310" to the end of the
return urllib.request.urlopen(...) line) so Ruff knows this use is intentionally
audited and the CI security check is satisfied.

Comment thread cli/main.py
Comment on lines +133 to 134
req = safe_urlopen(f"{API_BASE}/health", timeout=8)
data = json.loads(req.read().decode())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Close health-check response deterministically.

Line 133 opens a response without a context manager. Wrap it in with to ensure the connection is always closed.

Suggested patch
-        req = safe_urlopen(f"{API_BASE}/health", timeout=8)
-        data = json.loads(req.read().decode())
+        with safe_urlopen(f"{API_BASE}/health", timeout=8) as req:
+            data = json.loads(req.read().decode())
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
req = safe_urlopen(f"{API_BASE}/health", timeout=8)
data = json.loads(req.read().decode())
with safe_urlopen(f"{API_BASE}/health", timeout=8) as req:
data = json.loads(req.read().decode())
🤖 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 `@cli/main.py` around lines 133 - 134, The health-check response from
safe_urlopen is not closed deterministically; change the code that calls
safe_urlopen (the req variable usage in cli/main.py) to open the response with a
context manager (use "with safe_urlopen(f\"{API_BASE}/health\", timeout=8) as
req:") and move the json.loads(req.read().decode()) inside that with-block so
the response is always closed after reading.

Comment thread detectors/bert_classifier.py Resolved
Comment thread detectors/bert_classifier.py Resolved
Comment on lines +36 to +38
if not os.path.exists(ONNX_PATH):
raise RuntimeError(f"L2 ONNX unavailable and no local cache: {e}") from e
print(f"[!] Blob download failed, using cached ONNX weights: {e}")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fallback check doesn't verify ONNX data file exists.

The fallback only checks ONNX_PATH but not ONNX_DATA_PATH. If model.onnx exists but model.onnx.data is missing (and download fails), the code will warn and continue, then crash at InferenceSession(ONNX_PATH) when the external data can't be found.

🐛 Proposed fix
             except Exception as e:
-                if not os.path.exists(ONNX_PATH):
+                if not os.path.exists(ONNX_PATH) or not os.path.exists(ONNX_DATA_PATH):
                     raise RuntimeError(f"L2 ONNX unavailable and no local cache: {e}") from e
                 print(f"[!] Blob download failed, using cached ONNX weights: {e}")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if not os.path.exists(ONNX_PATH):
raise RuntimeError(f"L2 ONNX unavailable and no local cache: {e}") from e
print(f"[!] Blob download failed, using cached ONNX weights: {e}")
if not os.path.exists(ONNX_PATH) or not os.path.exists(ONNX_DATA_PATH):
raise RuntimeError(f"L2 ONNX unavailable and no local cache: {e}") from e
print(f"[!] Blob download failed, using cached ONNX weights: {e}")
🤖 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/bert_classifier.py` around lines 36 - 38, The fallback currently
only checks ONNX_PATH; update the logic that handles blob download failures to
also verify ONNX_DATA_PATH exists before proceeding—if either ONNX_PATH or
ONNX_DATA_PATH is missing, raise a RuntimeError with the actual exception (the
same way the existing raise uses `e`) and do not print the “using cached ONNX
weights” message; only print/continue with the cached weights when both files
exist. Locate the download/fallback block around the blob handling and
InferenceSession(ONNX_PATH) usage and add the extra file existence check for
ONNX_DATA_PATH and appropriate error handling/log message there.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
detectors/bert_classifier.py (1)

34-37: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

ONNX fallback still doesn't verify model.onnx.data exists.

The fallback only checks ONNX_PATH. If model.onnx exists but model.onnx.data is missing (and the download at line 33 fails), this warns and continues, then crashes at InferenceSession(ONNX_PATH) (line 54) when the external data blob can't be resolved. Check both paths.

🐛 Proposed fix
             except Exception as e:
-                if not os.path.exists(ONNX_PATH):
+                if not os.path.exists(ONNX_PATH) or not os.path.exists(ONNX_DATA_PATH):
                     raise RuntimeError(f"L2 ONNX unavailable and no local cache: {e}") from e
                 print(f"[!] Blob download failed, using cached ONNX weights: {e}")
🤖 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/bert_classifier.py` around lines 34 - 37, The except block that
falls back to a cached ONNX only checks ONNX_PATH but not the external data blob
(model.onnx.data), which causes InferenceSession(ONNX_PATH) to later fail;
update the exception handler around the download attempt to verify both the ONNX
file and its external data blob exist (check os.path.exists(ONNX_PATH) AND
os.path.exists(<external-data-path>), i.e. the model.onnx.data file name), and
if either is missing raise a RuntimeError, otherwise log that you're using the
cached ONNX and proceed to call InferenceSession(ONNX_PATH); adjust the message
and conditions in the except that currently references ONNX_PATH and the
download failure to reflect this dual-check.
🤖 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 `@app.py`:
- Around line 9-10: Restore the configurable host by using an env-driven value
when calling uvicorn.run(app, ...): read host from os.environ.get("HOST",
"127.0.0.1") so the default is loopback but can be overridden (e.g., to
"0.0.0.0" in Docker); update the uvicorn.run call in the __main__ block to use
that variable and ensure the existing import os is used (or re-add it) so the
env lookup is valid.

---

Duplicate comments:
In `@detectors/bert_classifier.py`:
- Around line 34-37: The except block that falls back to a cached ONNX only
checks ONNX_PATH but not the external data blob (model.onnx.data), which causes
InferenceSession(ONNX_PATH) to later fail; update the exception handler around
the download attempt to verify both the ONNX file and its external data blob
exist (check os.path.exists(ONNX_PATH) AND os.path.exists(<external-data-path>),
i.e. the model.onnx.data file name), and if either is missing raise a
RuntimeError, otherwise log that you're using the cached ONNX and proceed to
call InferenceSession(ONNX_PATH); adjust the message and conditions in the
except that currently references ONNX_PATH and the download failure to reflect
this dual-check.
🪄 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: f580a6be-310f-44f0-8a49-a0bad97f9862

📥 Commits

Reviewing files that changed from the base of the PR and between 78e632a and 55c0a0a.

📒 Files selected for processing (3)
  • api/main.py
  • app.py
  • detectors/bert_classifier.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • api/main.py

Comment thread app.py Outdated
Comment on lines +9 to +10
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)
uvicorn.run(app, host="0.0.0.0", port=7860) No newline at end of file

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Restore configurable host; avoid hardcoding 0.0.0.0.

This change replaces the previous env-driven host (os.environ.get("HOST", "127.0.0.1")) with a hardcoded 0.0.0.0, which binds to all interfaces by default (Ruff S104) and removes the safe loopback default for local runs. Since Dockerfile runs python app.py, keep 0.0.0.0 available via env override but default to loopback. This also restores usage of the now-otherwise-unused import os.

🔒 Proposed fix
 if __name__ == "__main__":
-    uvicorn.run(app, host="0.0.0.0", port=7860)
+    uvicorn.run(app, host=os.environ.get("HOST", "127.0.0.1"), port=7860)

The __main__ guard from the earlier review is correctly applied here.

🧰 Tools
🪛 Ruff (0.15.15)

[error] 10-10: Possible binding to all interfaces

(S104)

🤖 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 `@app.py` around lines 9 - 10, Restore the configurable host by using an
env-driven value when calling uvicorn.run(app, ...): read host from
os.environ.get("HOST", "127.0.0.1") so the default is loopback but can be
overridden (e.g., to "0.0.0.0" in Docker); update the uvicorn.run call in the
__main__ block to use that variable and ensure the existing import os is used
(or re-add it) so the env lookup is valid.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
detectors/bert_classifier.py (1)

36-38: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

ONNX fallback must verify both model files exist.

If model.onnx exists but model.onnx.data is missing after a failed download, the code proceeds to line 56 and crashes when InferenceSession(ONNX_PATH) cannot locate the external data file.

🐛 Proposed fix
             except Exception as e:
-                if not os.path.exists(ONNX_PATH):
+                if not os.path.exists(ONNX_PATH) or not os.path.exists(ONNX_DATA_PATH):
                     raise RuntimeError(f"L2 ONNX unavailable and no local cache: {e}") from e
                 print(f"[!] Blob download failed, using cached ONNX weights: {e}")
🤖 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/bert_classifier.py` around lines 36 - 38, The fallback path after a
blob download failure must verify that both the ONNX file and its external data
file exist before proceeding; update the error/branch in the blob download
exception handler that references ONNX_PATH to check os.path.exists(ONNX_PATH)
AND os.path.exists(ONNX_PATH + ".data") (or the actual external data filename
used by the model) and only print "using cached ONNX weights" and continue when
both are present; otherwise raise a RuntimeError (including the original
exception e) so InferenceSession(ONNX_PATH) is not called with a missing
external data file.
♻️ Duplicate comments (1)
app.py (1)

10-10: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Nosec suppression doesn't resolve the underlying security concern.

This duplicates an unresolved past review: the hardcoded 0.0.0.0 binding exposes all network interfaces by default. The # nosec B104 suppression silences Bandit but doesn't address the security issue—Ruff S104 and SonarCloud still flag it. As recommended in the previous review, use host=os.environ.get("HOST", "127.0.0.1") to default to loopback while allowing Docker/cloud override. This also makes use of the otherwise-unused import os on line 1.

🔒 Proposed fix (from past review)
 if __name__ == "__main__":
-    uvicorn.run(app, host="0.0.0.0", port=7860)  # nosec B104
+    uvicorn.run(app, host=os.environ.get("HOST", "127.0.0.1"), port=7860)
🤖 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 `@app.py` at line 10, The uvicorn.run call currently binds to "0.0.0.0" and
silences Bandit with "# nosec B104"; replace the hardcoded host with a
configurable default using os.environ.get("HOST", "127.0.0.1") in the
uvicorn.run invocation (i.e., change the host argument of uvicorn.run) and
remove the nosec suppression so static analyzers flag can be resolved; ensure
the existing import os is used so the environment lookup compiles correctly.
🤖 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/bert_classifier.py`:
- Line 8: The current code pins HF_REVISION but that commit lacks full tokenizer
artifacts and the blob-download exception only checks ONNX_PATH (not
ONNX_DATA_PATH) while also suppressing potential security linter warnings;
update the logic around DistilBertTokenizer.from_pretrained and the blob error
handling: when attempting
DistilBertTokenizer.from_pretrained(revision=HF_REVISION) detect whether
LOCAL_TOKENIZER_PATH contains required files (e.g., vocab.txt or tokenizer.json
and special_tokens_map.json) before falling back, and only use
local_files_only=True when those artifacts actually exist; in the blob download
exception handler check both ONNX_PATH and ONNX_DATA_PATH existence before
proceeding to avoid later failures; remove the unnecessary "# nosec B615"
suppression so failures surface if the call changes. Ensure references in code
are HF_REVISION, DistilBertTokenizer.from_pretrained, LOCAL_TOKENIZER_PATH,
ONNX_PATH, ONNX_DATA_PATH, and local_files_only so reviewers can find and verify
the fixes.

---

Outside diff comments:
In `@detectors/bert_classifier.py`:
- Around line 36-38: The fallback path after a blob download failure must verify
that both the ONNX file and its external data file exist before proceeding;
update the error/branch in the blob download exception handler that references
ONNX_PATH to check os.path.exists(ONNX_PATH) AND os.path.exists(ONNX_PATH +
".data") (or the actual external data filename used by the model) and only print
"using cached ONNX weights" and continue when both are present; otherwise raise
a RuntimeError (including the original exception e) so
InferenceSession(ONNX_PATH) is not called with a missing external data file.

---

Duplicate comments:
In `@app.py`:
- Line 10: The uvicorn.run call currently binds to "0.0.0.0" and silences Bandit
with "# nosec B104"; replace the hardcoded host with a configurable default
using os.environ.get("HOST", "127.0.0.1") in the uvicorn.run invocation (i.e.,
change the host argument of uvicorn.run) and remove the nosec suppression so
static analyzers flag can be resolved; ensure the existing import os is used so
the environment lookup compiles correctly.
🪄 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: 8762c45c-a0d5-4a6d-a27e-6ea54162f996

📥 Commits

Reviewing files that changed from the base of the PR and between 55c0a0a and f1ee0eb.

📒 Files selected for processing (2)
  • app.py
  • detectors/bert_classifier.py

from onnxruntime import InferenceSession

HF_MODEL = "Sandeep120205/agent-shield-distilbert"
HF_REVISION = "8d9339cfe468013da01a581f3399c1c19c4f51a3" # pin to verified commit

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does the HuggingFace repository Sandeep120205/agent-shield-distilbert have a commit 8d9339cfe468013da01a581f3399c1c19c4f51a3?

💡 Result:

Yes, the Hugging Face repository Sandeep120205/agent-shield-distilbert contains the commit 8d9339cfe468013da01a581f3399c1c19c4f51a3 [1][2]. This specific commit is associated with an "Update Readme" action and is dated May 31, 2026 [1].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="detectors/bert_classifier.py"
echo "== File: $FILE =="
nl -ba "$FILE" | sed -n '1,140p'

Repository: Sandeep-int/agent-shield

Length of output: 170


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="detectors/bert_classifier.py"
echo "== File: $FILE =="
cat -n "$FILE" | sed -n '1,200p'

Repository: Sandeep-int/agent-shield

Length of output: 4604


🌐 Web query:

At commit 8d9339cfe468013da01a581f3399c1c19c4f51a3 of Sandeep120205/agent-shield-distilbert, does the repository include DistilBert tokenizer artifacts (e.g., tokenizer.json / vocab.txt / tokenizer_config.json / special_tokens_map.json)?

💡 Result:

At commit 8d9339cfe468013da01a581f3399c1c19c4f51a3 of the Sandeep120205/agent-shield-distilbert repository on the Hugging Face Hub, the repository does not include the standard DistilBert tokenizer artifacts such as tokenizer.json, vocab.txt, tokenizer_config.json, or special_tokens_map.json [1][2]. The repository at this commit consists primarily of metadata files and a data directory, rather than the model-specific tokenizer configuration and vocabulary files [2][3].

Citations:


🌐 Web query:

At commit 8d9339cfe468013da01a581f3399c1c19c4f51a3, what files (top-level) exist in Sandeep120205/agent-shield-distilbert, specifically is there any vocab.txt / tokenizer.json / tokenizer_config.json / special_tokens_map.json?

💡 Result:

At commit 8d9339cfe468013da01a581f3399c1c19c4f51a3, the repository Sandeep120205/agent-shield-distilbert contains the following files [1][2]: - tokenizer_config.json [3] - model.onnx [4] - README.md [5] Regarding the specific files you asked about: - tokenizer_config.json: Exists [3]. - vocab.txt: Does not exist [1][2]. - tokenizer.json: Does not exist [1][2]. - special_tokens_map.json: Does not exist [1][2]. The repository structure appears to rely on a minimal set of files at this commit, including an ONNX model file and a tokenizer configuration, while excluding the standard vocabulary and mapping files typically found in Hugging Face model repositories [1][2][3][4].

Citations:


🌐 Web query:

What is Bandit rule B615, and is it triggered by local_files_only=Truein HuggingFacefrom_pretrained?

💡 Result:

Bandit rule B615 (huggingface_unsafe_download) is a security check designed to detect unsafe downloads from the Hugging Face Hub [1][2]. Its primary purpose is to ensure that models, datasets, or files are pinned to an immutable revision (such as a specific commit hash) [1][3]. Using mutable references like "main" or no revision at all can expose users to supply chain attacks, where malicious actors replace model files while retaining the same tag or branch name [1][2]. The rule B615 is not triggered by the local_files_only=True parameter [1][3]. It specifically focuses on the absence of a secure, immutable revision (or commit_id) in functions like from_pretrained, load_dataset, hf_hub_download, and snapshot_download [1][3][4]. While local_files_only=True restricts network requests and prevents new downloads from the Hub [5], it does not satisfy the security requirement of B615, which is to verify the integrity and provenance of the downloaded content via commit pinning [1][3]. If a codebase uses local_files_only=True but fails to provide a revision, Bandit will still flag the code under B615 because the lack of pinning remains a potential security vulnerability if the code were ever run in an environment where files are fetched from the Hub [1][3]. Top results: [1][3][6][5][7]

Citations:


Fix ONNX_DATA_PATH fallback + ensure tokenizer artifacts exist locally (remote revision won’t contain full DistilBert files).

  • HF_REVISION (8d9339cfe468013da01a581f3399c1c19c4f51a3) points to a real commit, but that commit contains only tokenizer_config.json (no vocab.txt / tokenizer.json / special_tokens_map.json), so DistilBertTokenizer.from_pretrained(..., revision=HF_REVISION) will likely fail and depend entirely on LOCAL_TOKENIZER_PATH being populated with the full tokenizer files.
  • The blob-download exception handler only checks ONNX_PATH (not ONNX_DATA_PATH) before proceeding; if model.onnx relies on external data, missing model.onnx.data will cause a later load failure with a less actionable error.
  • # nosec B615 on the local_files_only=True tokenizer fallback is probably unnecessary and can hide real B615 issues if the call later changes.
🤖 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/bert_classifier.py` at line 8, The current code pins HF_REVISION
but that commit lacks full tokenizer artifacts and the blob-download exception
only checks ONNX_PATH (not ONNX_DATA_PATH) while also suppressing potential
security linter warnings; update the logic around
DistilBertTokenizer.from_pretrained and the blob error handling: when attempting
DistilBertTokenizer.from_pretrained(revision=HF_REVISION) detect whether
LOCAL_TOKENIZER_PATH contains required files (e.g., vocab.txt or tokenizer.json
and special_tokens_map.json) before falling back, and only use
local_files_only=True when those artifacts actually exist; in the blob download
exception handler check both ONNX_PATH and ONNX_DATA_PATH existence before
proceeding to avoid later failures; remove the unnecessary "# nosec B615"
suppression so failures surface if the call changes. Ensure references in code
are HF_REVISION, DistilBertTokenizer.from_pretrained, LOCAL_TOKENIZER_PATH,
ONNX_PATH, ONNX_DATA_PATH, and local_files_only so reviewers can find and verify
the fixes.

@sonarqubecloud

sonarqubecloud Bot commented Jun 3, 2026

Copy link
Copy Markdown

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.

2 participants