Skip to content

[BUG] Fix #510: validate_owasp crashes on malformed JWT tokens#523

Open
adityakryadav wants to merge 5 commits into
sreerevanth:mainfrom
adityakryadav:fix/510-owasp-jwt-validation
Open

[BUG] Fix #510: validate_owasp crashes on malformed JWT tokens#523
adityakryadav wants to merge 5 commits into
sreerevanth:mainfrom
adityakryadav:fix/510-owasp-jwt-validation

Conversation

@adityakryadav

@adityakryadav adityakryadav commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Summary

Closes #510.
Calling validate_owasp with a payload containing a malformed JWT token raised an unhandled ValueError (or jwt.DecodeError), crashing the caller with a raw traceback.

Changes

  • agentwatch/security/owasp.py — Added validate_owasp(payload: dict) -> dict:
    • Optionally decodes the token field in the payload using PyJWT (signature verification disabled — format-only check).
    • Catches ValueError and any other exception from the JWT library.
    • Returns a structured dict: {"status": "error", "error": "<message>"} on failure, {"status": "success"} on pass.
    • Never crashes; callers can inspect the returned dict.

How to test

from agentwatch.security.owasp import validate_owasp
# Malformed token — should NOT raise, should return {"status": "error", ...}
result = validate_owasp({"token": "not.a.valid.jwt"})
assert result["status"] == "error"
# No token — should succeed
result = validate_owasp({})
assert result["status"] == "success"

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **New Features**
  * Added detection for malformed JWT-like tokens in tool-call arguments.
  * Reports high-severity trust-boundary security findings when malformed tokens are identified.
  * Supports scanning nested argument structures.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

@coderabbitai

coderabbitai Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@adityakryadav, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 44 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 32045cdf-6bc7-446a-a54a-ee4cf64010dd

📥 Commits

Reviewing files that changed from the base of the PR and between 22b8002 and 5f103f4.

📒 Files selected for processing (2)
  • agentwatch/security/owasp.py
  • tests/test_owasp_security.py
📝 Walkthrough

Walkthrough

validate_owasp recursively inspects tool-call arguments for JWT-like values, suppresses decoding errors, and reports malformed tokens as high-severity trust-boundary findings. A regression test verifies detection of an invalid token.

Changes

JWT validation

Layer / File(s) Summary
Malformed JWT detection and regression coverage
agentwatch/security/owasp.py, tests/test_owasp_security.py
validate_owasp scans nested tool arguments, catches known JWT decoding failures, adds deduplicated trust-boundary findings, and verifies malformed-token detection with a regression test.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested labels: Medium, SSoC26

Poem

A bunny found a token askew,
With dots missing from its view.
The scanner caught the crooked trail,
And raised a finding without fail.
“No crash today!” the rabbit cheered.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main fix: preventing validate_owasp crashes on malformed JWT tokens.
Linked Issues check ✅ Passed The change addresses malformed JWT handling by catching decode errors and adding a validation finding instead of crashing.
Out of Scope Changes check ✅ Passed The changes stay focused on malformed JWT detection and the accompanying test, with no unrelated functional additions.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@github-actions

github-actions Bot commented Jul 4, 2026

Copy link
Copy Markdown
Contributor

🧪 PR Test Results

Check Result
Tests (pytest tests/) ❌ failure
Lint (ruff check .) ❌ failure
Coverage (agentwatch) 74.23%

Python 3.12 · commit 5f103f4

@vercel

vercel Bot commented Jul 6, 2026

Copy link
Copy Markdown

@adityakryadav is attempting to deploy a commit to the sreerevanth's projects Team on Vercel.

A member of the Team first needs to authorize it.

@sreerevanth sreerevanth left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Thanks for working on this! I think the fix should remain within the existing validate_owasp(events) API. This PR changes the function signature, mixes JWT validation with OWASP scanning, and changes the return type, which could break existing callers. Could you instead identify where malformed JWTs are causing the crash and handle that case while preserving the current API and return type?

@sreerevanth

Copy link
Copy Markdown
Owner

@adityakryadav

@sreerevanth

Copy link
Copy Markdown
Owner

@adityakryadav please reply bro either dc or here so i would know youre currently working

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🧹 Nitpick comments (2)
agentwatch/security/owasp.py (2)

136-136: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

DecodeError is a subclass of InvalidTokenError — catching both is redundant.

In PyJWT 2.8.0, DecodeError inherits from InvalidTokenError, so except (ValueError, jwt.exceptions.InvalidTokenError) already covers DecodeError. This is harmless but slightly misleading.

🤖 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 `@agentwatch/security/owasp.py` at line 136, Remove jwt.exceptions.DecodeError
from the exception tuple in the surrounding exception handler, leaving
ValueError and jwt.exceptions.InvalidTokenError handled by the existing except
clause. Preserve the current error-handling behavior.

127-150: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Nested function check_dict_keys is redefined on every loop iteration.

check_dict_keys is defined inside the for event in events loop, so it's recreated on each iteration. Extract it to module level (or at least outside the loop) and pass event and scan as parameters.

♻️ Suggested refactor: extract check_dict_keys
 def validate_owasp(events: list[AgentEvent]) -> OwaspScan:
     scan = OwaspScan()
     for event in events:
         # Check for malformed JWT tokens in the event arguments
         if event.tool_call and event.tool_call.arguments:
-            def check_dict_keys(d: dict):
-                for k, v in d.items():
-                    if isinstance(v, str):
-                        is_token_key = any(tk in k.lower() for tk in ["token", "jwt", "auth", "credential"])
-                        is_jwt_structure = re.match(r"^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]*$", v) is not None
-                        if is_token_key or is_jwt_structure:
-                            try:
-                                import jwt
-                                jwt.decode(v, options={"verify_signature": False})
-                            except (ValueError, jwt.exceptions.DecodeError, jwt.exceptions.InvalidTokenError) as exc:
-                                if not any(f.event_id == event.event_id and f.detail.startswith("Malformed JWT token") for f in scan.findings):
-                                    scan.findings.append(
-                                        OwaspFinding(
-                                            vector=OwaspVector.TRUST_BOUNDARY,
-                                            severity="high",
-                                            detail=f"Malformed JWT token detected: {exc}",
-                                            event_id=event.event_id,
-                                        )
-                                    )
-                            except Exception:  # noqa: S110
-                                pass
-                    elif isinstance(v, dict):
-                        check_dict_keys(v)
-            check_dict_keys(event.tool_call.arguments)
+            _check_jwt_in_args(event.tool_call.arguments, event, scan)
+    return scan
+
+
+def _check_jwt_in_args(d: dict, event: AgentEvent, scan: OwaspScan) -> None:
+    for k, v in d.items():
+        if isinstance(v, str):
+            is_token_key = any(tk in k.lower() for tk in ["token", "jwt", "auth", "credential"])
+            is_jwt_structure = re.match(r"^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]*$", v) is not None
+            if is_token_key or is_jwt_structure:
+                try:
+                    import jwt
+                    jwt.decode(v, options={"verify_signature": False})
+                except (ValueError, jwt.exceptions.DecodeError, jwt.exceptions.InvalidTokenError) as exc:
+                    if not any(f.event_id == event.event_id and f.detail.startswith("Malformed JWT token") for f in scan.findings):
+                        scan.findings.append(
+                            OwaspFinding(
+                                vector=OwaspVector.TRUST_BOUNDARY,
+                                severity="high",
+                                detail=f"Malformed JWT token detected: {exc}",
+                                event_id=event.event_id,
+                            )
+                        )
+                except Exception:  # noqa: S110
+                    pass
+        elif isinstance(v, dict):
+            _check_jwt_in_args(v, event, scan)
+        elif isinstance(v, list):
+            for item in v:
+                if isinstance(item, dict):
+                    _check_jwt_in_args(item, event, scan)
🤖 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 `@agentwatch/security/owasp.py` around lines 127 - 150, Move the nested
check_dict_keys function outside the for event in events loop, then update its
signature to accept event and scan explicitly and pass those values through
recursive calls. Preserve its existing JWT detection, finding deduplication, and
nested-dictionary traversal behavior, and invoke it with each event’s tool-call
arguments.
🤖 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 `@agentwatch/security/owasp.py`:
- Around line 148-149: Update check_dict_keys to traverse list values in
addition to dict values, recursively invoking the existing dictionary inspection
for each dictionary item so JWTs nested in list-based structures such as headers
are detected.
- Around line 134-136: Update the JWT handling try/except around jwt.decode so
the exception tuple never references jwt when its inner import fails. Move the
jwt import outside the try that catches decode errors, or otherwise use guarded
exception handling, while preserving handling for ValueError, DecodeError, and
InvalidTokenError.

---

Nitpick comments:
In `@agentwatch/security/owasp.py`:
- Line 136: Remove jwt.exceptions.DecodeError from the exception tuple in the
surrounding exception handler, leaving ValueError and
jwt.exceptions.InvalidTokenError handled by the existing except clause. Preserve
the current error-handling behavior.
- Around line 127-150: Move the nested check_dict_keys function outside the for
event in events loop, then update its signature to accept event and scan
explicitly and pass those values through recursive calls. Preserve its existing
JWT detection, finding deduplication, and nested-dictionary traversal behavior,
and invoke it with each event’s tool-call arguments.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2793e0ee-57bb-449b-88b4-333ca1af725c

📥 Commits

Reviewing files that changed from the base of the PR and between 83dafb8 and 22b8002.

📒 Files selected for processing (2)
  • agentwatch/security/owasp.py
  • tests/test_owasp_security.py

Comment thread agentwatch/security/owasp.py Outdated
Comment thread agentwatch/security/owasp.py

@sreerevanth sreerevanth left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

fix the ci its good to merge

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.

[BUG] validate_owasp function crashes when processing malformed JWT tokens

2 participants