Repository navigation
chore: trigger full coderabbit audit - #2
Conversation
There was a problem hiding this comment.
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.
|
@coderabbitai full review |
✅ Action performedFull review finished. |
|
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:
📝 WalkthroughWalkthroughAdds 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. ChangesAPI and CI Security Hardening
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the Comment |
|
@coderabbitai review |
✅ Action performedReview finished.
|
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (2)
.github/workflows/security-gate.yml (2)
27-27: ⚡ Quick winConsider pinning security tool versions for reproducibility.
Installing
pytest,bandit, andpip-auditwithout 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.3Alternatively, add these tools to
requirements.txtor a separaterequirements-dev.txtwith 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 winConsider adding explicit failure behavior for
pip-audit.Currently,
pip-auditruns 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 onThe
--strictflag ensures the job fails on any vulnerabilities, and--desc onprovides 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
📒 Files selected for processing (2)
.github/workflows/security-gate.ymlapi/main.py
| @@ -0,0 +1,36 @@ | |||
| name: Agent Shield Production Pipeline | |||
There was a problem hiding this comment.
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.
| security-and-testing-gate: | ||
| runs-on: ubuntu-latest | ||
| steps: |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
🧩 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 || trueRepository: 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 || trueRepository: 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->34e114876b0b11c390a56381ad16ebd13914f8d5actions/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.
| with: | ||
| fetch-depth: 0 # Crucial for SonarCloud tracking and analysis |
There was a problem hiding this comment.
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.
| 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 |
There was a problem hiding this comment.
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:
- A SonarCloud scan step is missing from the incomplete implementation, or
- 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.
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (1)
detectors/bert_classifier.py (1)
51-55: 💤 Low valueRemove unnecessary
revisionparameter from local fallback.When loading from a local directory with
local_files_only=True, therevisionparameter 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
📒 Files selected for processing (3)
app.pycli/main.pydetectors/bert_classifier.py
| else: | ||
| target = url_or_request | ||
| _validate_http_url(target) | ||
| return urllib.request.urlopen(url_or_request, timeout=timeout) # nosec B310 |
There was a problem hiding this comment.
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.
| 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.
| req = safe_urlopen(f"{API_BASE}/health", timeout=8) | ||
| data = json.loads(req.read().decode()) |
There was a problem hiding this comment.
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.
| 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.
| 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}") |
There was a problem hiding this comment.
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.
| 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.
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
detectors/bert_classifier.py (1)
34-37:⚠️ Potential issue | 🟠 Major | ⚡ Quick winONNX fallback still doesn't verify
model.onnx.dataexists.The fallback only checks
ONNX_PATH. Ifmodel.onnxexists butmodel.onnx.datais missing (and the download at line 33 fails), this warns and continues, then crashes atInferenceSession(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
📒 Files selected for processing (3)
api/main.pyapp.pydetectors/bert_classifier.py
🚧 Files skipped from review as they are similar to previous changes (1)
- api/main.py
| 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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 winONNX fallback must verify both model files exist.
If
model.onnxexists butmodel.onnx.datais missing after a failed download, the code proceeds to line 56 and crashes whenInferenceSession(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 winNosec suppression doesn't resolve the underlying security concern.
This duplicates an unresolved past review: the hardcoded
0.0.0.0binding exposes all network interfaces by default. The# nosec B104suppression silences Bandit but doesn't address the security issue—Ruff S104 and SonarCloud still flag it. As recommended in the previous review, usehost=os.environ.get("HOST", "127.0.0.1")to default to loopback while allowing Docker/cloud override. This also makes use of the otherwise-unusedimport oson 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
📒 Files selected for processing (2)
app.pydetectors/bert_classifier.py
| from onnxruntime import InferenceSession | ||
|
|
||
| HF_MODEL = "Sandeep120205/agent-shield-distilbert" | ||
| HF_REVISION = "8d9339cfe468013da01a581f3399c1c19c4f51a3" # pin to verified commit |
There was a problem hiding this comment.
🧩 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:
- 1: https://d6108366.hf-mirror.com/Sandeep120205/agent-shield-distilbert/commit/8d9339cfe468013da01a581f3399c1c19c4f51a3
- 2: https://d6108366.hf-mirror.com/Sandeep120205/agent-shield-distilbert/tree/8d9339cfe468013da01a581f3399c1c19c4f51a3
🏁 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:
- 1: https://d6108366.hf-mirror.com/Sandeep120205/agent-shield-distilbert/commit/8d9339cfe468013da01a581f3399c1c19c4f51a3
- 2: https://d6108366.hf-mirror.com/Sandeep120205/agent-shield-distilbert/tree/8d9339cfe468013da01a581f3399c1c19c4f51a3
- 3: https://d6108366.hf-mirror.com/Sandeep120205/agent-shield-distilbert/tree/8d9339cfe468013da01a581f3399c1c19c4f51a3/data
🌐 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:
- 1: https://d6108366.hf-mirror.com/Sandeep120205/agent-shield-distilbert/commit/8d9339cfe468013da01a581f3399c1c19c4f51a3
- 2: https://d6108366.hf-mirror.com/Sandeep120205/agent-shield-distilbert/tree/8d9339cfe468013da01a581f3399c1c19c4f51a3
- 3: https://d6108366.hf-mirror.com/Sandeep120205/agent-shield-distilbert/blob/8d9339cfe468013da01a581f3399c1c19c4f51a3/tokenizer_config.json
- 4: https://d6108366.hf-mirror.com/Sandeep120205/agent-shield-distilbert/blob/8d9339cfe468013da01a581f3399c1c19c4f51a3/model.onnx
- 5: https://d6108366.hf-mirror.com/Sandeep120205/agent-shield-distilbert/blob/8d9339cfe468013da01a581f3399c1c19c4f51a3/README.md
🌐 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:
- 1: https://bandit.readthedocs.io/en/latest/plugins/b615_huggingface_unsafe_download.html
- 2: https://ericwbbandit.readthedocs.io/en/latest/plugins/b615_huggingface_unsafe_download.html
- 3: https://bandit.readthedocs.io/en/1.9.2/plugins/b615_huggingface_unsafe_download.html
- 4: Huggingface revision pinning PyCQA/bandit#1281
- 5: Add local_files_only parameter to pretrained items huggingface/transformers#2930
- 6: PyCQA/bandit@8f2f928
- 7: Fix B615 false positive when revision is set via variable PyCQA/bandit#1358
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 onlytokenizer_config.json(novocab.txt/tokenizer.json/special_tokens_map.json), soDistilBertTokenizer.from_pretrained(..., revision=HF_REVISION)will likely fail and depend entirely onLOCAL_TOKENIZER_PATHbeing populated with the full tokenizer files.- The blob-download exception handler only checks
ONNX_PATH(notONNX_DATA_PATH) before proceeding; ifmodel.onnxrelies on external data, missingmodel.onnx.datawill cause a later load failure with a less actionable error. # nosec B615on thelocal_files_only=Truetokenizer 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.
|



Summary by CodeRabbit
New Features
Bug Fixes / Reliability
Chores