Skip to content

Add C# JWT rules: enforce token verification and no hardcoded secrets #195

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 45 commits into from
Mar 31, 2025

Conversation

ESS-ENN
Copy link
Contributor

@ESS-ENN ESS-ENN commented Mar 31, 2025

Summary by CodeRabbit

  • New Features

    • Introduced security rules to enhance JWT token handling by flagging tokens decoded without proper verification and identifying hard-coded secrets.
  • Tests

    • Added a comprehensive suite of test cases to validate JWT processing under various scenarios, ensuring robust detection and prevention of potential vulnerabilities.

Sakshis and others added 30 commits December 16, 2024 13:09
@CLAassistant
Copy link

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ ESS-ENN
❌ Sakshis


Sakshis seems not to be a GitHub user. You need a GitHub account to be able to sign the CLA. If you have already a GitHub account, please add the email address used for this commit to your account.
You have signed the CLA already but the status is still pending? Let us recheck it.

Copy link

coderabbitai bot commented Mar 31, 2025

Walkthrough

This pull request introduces two new security rules for C# JWT handling. The first rule, defined in jwt-decode-without-verify-csharp.yml, detects cases where JWT tokens are decoded without a proper verification step. The second rule, in jwt-hardcoded-secret-csharp.yml, identifies the use of hardcoded secrets when encoding or decoding JWTs. In addition, several snapshot and direct test files have been added to verify the correct behavior of these rules using AST pattern matching, covering both valid and invalid JWT usage scenarios.

Changes

File(s) Change Summary
rules/csharp/security/jwt-decode-without-verify-csharp.yml
rules/csharp/security/jwt-hardcoded-secret-csharp.yml
Added two new security rules using AST pattern matching: one for detecting JWT decoding without verification and one for detecting hardcoded secrets in JWT operations.
tests/__snapshots__/jwt-decode-without-verify-csharp-snapshot.yml
tests/__snapshots__/jwt-hardcoded-secret-csharp-snapshot.yml
Introduced snapshot tests for both new rules with multiple test methods demonstrating various secure and insecure JWT handling patterns.
tests/csharp/jwt-decode-without-verify-csharp-test.yml
tests/csharp/jwt-hardcoded-secret-csharp-test.yml
Added direct test cases for validating proper JWT decoding and encoding behaviors, including both valid scenarios and those intended to trigger rule warnings.

Sequence Diagram(s)

sequenceDiagram
  participant Dev as Developer
  participant Analyzer as Static Analyzer
  participant DecodeRule as JWT Decode Rule

  Dev->>Analyzer: Submits C# code with JWT decoding call (missing verification)
  Analyzer->>DecodeRule: Analyze AST for verification flag
  DecodeRule-->>Analyzer: Return warning if verification is absent
  Analyzer-->>Dev: Report JWT decode without verification warning
Loading
sequenceDiagram
  participant Dev as Developer
  participant Analyzer as Static Analyzer
  participant HardcodedRule as JWT Hardcoded Secret Rule

  Dev->>Analyzer: Submits C# code with a hardcoded secret in JWT method
  Analyzer->>HardcodedRule: Analyze AST for hardcoded string usage
  HardcodedRule-->>Analyzer: Return warning for hardcoded secret
  Analyzer-->>Dev: Report hardcoded secret detection warning
Loading

Possibly related PRs

Suggested reviewers

  • ganeshpatro321

Poem

I'm a rabbit on a security spree,
Hopping through JWT code with glee,
Spotting tokens decoded without a check,
And secrets hardcoded by a sneaky tech.
With swift hops and keen eyes, I keep the code safe—🐰 all in a day's race!
Secure and merry, I celebrate our code's embrace!


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai bot changed the title @coderabbitai Add C# JWT rules: enforce token verification and no hardcoded secrets Mar 31, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (17)
rules/csharp/security/jwt-decode-without-verify-csharp.yml (2)

1-13: Metadata and YAML Structure
The rule’s metadata (ID, severity, language, message, and note) is clear and well structured. However, YAMLlint reported trailing spaces on line 8. Please remove the extra whitespace at the end of line 8 to ensure compliance with YAML style guidelines.


16-373: Comprehensive AST Pattern Definitions in the "utils" Block
The utils: section defines multiple AST pattern matchers to detect various invocations of JWT decoding without verification. The patterns cover method calls such as (IJwtDecoder $D).Decode($X,verify-false,.), ($D).Decode(false), and other variants. This comprehensive approach will help catch diverse coding styles.
Please verify that these patterns match all intended use cases in your C# codebase. Consider adding inline comments to explain non‑obvious pattern choices for future maintainability.

tests/__snapshots__/jwt-hardcoded-secret-csharp-snapshot.yml (1)

1-469: Snapshot Tests for Hardcoded JWT Secrets
The snapshot file contains detailed examples for various JWT encoding scenarios with hardcoded secrets. The snapshots include multiple labels and secondary source references that help verify both the payload and the secret values.
Overall, the snapshots are comprehensive. Consider reviewing and possibly consolidating duplicate label entries for improved clarity in future maintenance.

tests/__snapshots__/jwt-decode-without-verify-csharp-snapshot.yml (1)

1-908: Snapshot Tests for JWT Decoding Without Verification
This snapshot file is extensive and demonstrates a variety of JWT decode invocations with different parameter configurations—such as using verify: false, passing null for certain parameters, and leveraging builder patterns. The snapshots offer a solid baseline for verifying that tokens are not decoded without a proper verification step.
A couple of suggestions:

  • Ensure that the variables token (and key where applicable) are defined in your actual test harness so that these snapshots remain valid.
  • Consider adding inline comments within the snapshot code blocks to provide context for each distinct decoding pattern.
    Overall, these snapshots are comprehensive and align well with the new security rule requirements.
tests/csharp/jwt-decode-without-verify-csharp-test.yml (13)

1-20: Review Valid JWT Test Case:
The valid test case is structured correctly using JwtBuilder.Create() and enforcing signature verification via MustVerifySignature(). However, ensure that the placeholder variables (key and token) are defined in the test context to avoid runtime errors. Also, consider adding assertions to validate the decoded output rather than only printing to the console.


21-40: Review Invalid Test - JwtTest7:
This test accurately simulates disabled signature verification by calling decoder.Decode(token, verify: false). To enhance clarity and robustness, consider adding assertions that either check for an expected exception or log a warning when unsafe decoding is attempted. Additionally, a more descriptive test method name could help clarify the intent.


41-54: Review Invalid Test - JwtTest9:
JwtTest9 tests the scenario where a null secret is passed and signature verification is disabled. Confirm that this test scenario aligns with your security rules by either expecting a specific error or behavior. Adding a comment or assertion about the expected outcome would improve clarity.


71-86: Review Test - JwtTest11:
JwtTest11 explicitly disables signature verification using .Decode(token, verify: false), which correctly simulates unsafe usage. To further strengthen the test, add assertions that validate the resulting behavior (or failure) of the decoding operation.


87-104: Review Test - JwtTest13:
This test initializes ValidationParameters with several validations disabled (including signature validation) but does not actually use them in a decode or validate call. Completing the test by invoking a decode/validation method would fully exercise the security rule.


105-120: Review Test - JwtTest15:
JwtTest15 decodes a token without explicitly specifying a signature verification flag. Clarify whether this scenario is intended to rely on default behavior (and if that default is insecure) by adding either an assertion or explanatory comment.


121-136: Review Test - JwtTest17:
JwtTest17 configures JwtAuthenticationOptions with VerifySignature set to false and simply logs a message. To leverage the new security rules, consider asserting that such a configuration is detected or flagged by your analyzer, ensuring that the test validates the intended security behavior.


137-156: Review Test - JwtTest18:
This test uses TokenValidationParameters with ValidateIssuerSigningKey disabled and then calls ValidateToken. While it effectively simulates an unsafe configuration, the test would be more robust if it included assertions to confirm that the operation either produces a warning or behaves in a predictable manner under the insecure setup.


157-174: Review Test - JwtTest19 (First Instance):
JwtTest19 creates TokenValidationParameters with signature validation turned off. This test correctly represents an unsafe configuration. Enhancing it with assertions to check for expected outcomes (e.g., a warning or error) could improve its effectiveness.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 167-167: trailing spaces

(trailing-spaces)


193-210: Review Test - JwtTest1 (First Instance):
This test decodes a token with verification disabled by using a custom decoder. While the structure is acceptable, adding assertions to validate the decoded output would enhance the test’s robustness. Also, ensure that any sensitive token data is handled appropriately.


230-245: Review Test - JwtTest2:
This test uses JwtBuilder.Create() to decode a token. To fully validate that unsafe decoding is being caught, include assertions checking the output or behavior against the expected security rule criteria.


246-262: Review Test - JwtTest3:
Similar to JwtTest2, JwtTest3 decodes a token via a JWT builder setup but only prints the output. Enhancing this test with explicit assertions would help enforce the expected behavior and align with your security testing objectives.


167-167: Style Fix - Remove Trailing Whitespace:
Trailing whitespace detected on this line. Please remove any extra spaces to adhere to YAML formatting standards.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 167-167: trailing spaces

(trailing-spaces)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 289aa26 and d78f4c7.

📒 Files selected for processing (6)
  • rules/csharp/security/jwt-decode-without-verify-csharp.yml (1 hunks)
  • rules/csharp/security/jwt-hardcoded-secret-csharp.yml (1 hunks)
  • tests/__snapshots__/jwt-decode-without-verify-csharp-snapshot.yml (1 hunks)
  • tests/__snapshots__/jwt-hardcoded-secret-csharp-snapshot.yml (1 hunks)
  • tests/csharp/jwt-decode-without-verify-csharp-test.yml (1 hunks)
  • tests/csharp/jwt-hardcoded-secret-csharp-test.yml (1 hunks)
🧰 Additional context used
🪛 YAMLlint (1.35.1)
tests/csharp/jwt-hardcoded-secret-csharp-test.yml

[error] 8-8: trailing spaces

(trailing-spaces)

tests/csharp/jwt-decode-without-verify-csharp-test.yml

[error] 167-167: trailing spaces

(trailing-spaces)

🔇 Additional comments (6)
rules/csharp/security/jwt-decode-without-verify-csharp.yml (1)

714-728: Rule Consolidation and Match Conditions
The final rule: block aggregates the various match patterns identified earlier. The list of match patterns is logically organized and appears to cover the intended scenarios.
Ensure that the ordering and specificity of these patterns do not conflict with other rules in your suite.

tests/csharp/jwt-hardcoded-secret-csharp-test.yml (1)

1-106: JWT Hardcoded Secret Test Cases
This new test file effectively separates valid and invalid JWT secret usage scenarios. The valid test (OkJwtTest6) demonstrates token creation with a secret from an environment variable, while the invalid tests intentionally use hardcoded strings.
Make sure that these tests trigger the security rule detection as expected and that the console outputs are used only for debugging purposes.

🧰 Tools
🪛 YAMLlint (1.35.1)

[error] 8-8: trailing spaces

(trailing-spaces)

rules/csharp/security/jwt-hardcoded-secret-csharp.yml (2)

1-150: Rule for Hardcoded Secret Detection – Metadata and Utils Configuration
The rule’s metadata (ID, severity, language, message, and note) is clearly defined. The description appropriately highlights the risks of embedding secrets in source code.
The utils: block provides several AST patterns for detecting hardcoded secrets in JWT encoding/decoding operations (e.g. using literal strings via the $PASS placeholder). The patterns appear detailed and methodical.
Please ensure that these patterns continue to capture all common hardcoded secret scenarios in your projects.


673-683: Rule Definition Block Consolidation
The final rule: block here aggregates the various AST matchers defined earlier. It logically groups the conditions using the matches: keyword, and it is consistent with the structure in the other rule file.
Double-check that the defined patterns do not produce false positives when encountering acceptable secret management (e.g. environment variables).

tests/csharp/jwt-decode-without-verify-csharp-test.yml (2)

55-70: Review Test - JwtTest10:
This test invokes token decoding without an explicit verification flag. It is unclear whether the default behavior is secure or if it should be flagged by your new rules. Consider clarifying the expected outcome by either adding assertions or commenting on why this scenario is noteworthy.


175-192: Duplicate Test - JwtTest19 (Second Instance):
This test is identical to the previous JwtTest19. Duplicate definitions can lead to maintenance issues. Consider consolidating these two tests into one unless there is an intentional reason for their duplication.

@ganeshpatro321 ganeshpatro321 merged commit 7f42cbe into coderabbitai:main Mar 31, 2025
1 of 2 checks passed
gatsby003 pushed a commit that referenced this pull request Jul 24, 2025
…#195)

* removed missing-secure-java

* httponly-false-csharp

* use-of-md5-digest-utils-java

* removing use-of-md5-digest-utils and httponly-false-csharp

* jwt-hardcoded-secret-csharp

* jwt-decode-without-verify-csharp

---------

Co-authored-by: Sakshis <sakshil@abc.com>
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.

3 participants