Skip to content

migrated jwtAuth error response to problem JSON, added 'nbf' claim in jwtSign #1806

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

rrayst
Copy link
Member

@rrayst rrayst commented Apr 11, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced error reporting for authentication tokens with clear, detailed error codes.
    • Improved token signing with configurable expiration and clock skew settings for increased robustness.
  • Refactor

    • Overhauled error handling in token validation to deliver more structured and informative responses.
  • Tests

    • Updated and expanded tests to validate the improved error responses and handling of token anomalies.
  • Documentation

    • Revised migration guide to reflect new naming conventions and updated response formats.

@rrayst rrayst requested a review from predic8 April 11, 2025 15:03
Copy link
Contributor

coderabbitai bot commented Apr 11, 2025

Walkthrough

The changes update JWT error handling and token signing across multiple components. The JWTException class now carries an additional error identifier, and error handling in both JsonWebToken and JwtAuthInterceptor has been restructured to include error IDs and use ProblemDetails responses. In addition, the JWT signing process in JwtSignInterceptor has been refined with renamed expiration parameters and the introduction of a clock skew value. Test cases and migration documentation have been updated to reflect these modifications.

Changes

File(s) Change Summary
core/.../jwt/JWTException.java Added a new id field, updated the constructor from JWTException(String message) to JWTException(String message, String id), and introduced a getId() method.
core/.../jwt/JsonWebToken.java, core/.../jwt/JwtAuthInterceptor.java Updated error handling to throw JWTException with an extra error ID; removed or replaced static error message constants; restructured error responses using ProblemDetails; added new error constants.
core/.../jwt/JwtSignInterceptor.java Renamed expiryTime to expirySeconds; introduced clockSkewSeconds (defaulting to 120 seconds); updated JWT payload preparation to include the nbf claim; added corresponding getters and setters.
core/.../jwt/JwtAuthInterceptorTest.java, core/.../jwt/JwtAuthInterceptorUnitTests.java Changed test assertions to retrieve error details under the key detail instead of description; added new tests (e.g., for handling an invalid header) and updated error message references.
docs/MIGRATION-GUIDE.md Added a new jwtSign section documenting the renaming of expiryTime to expirySeconds and the switch to Problem JSON for error responses; updated notes on Internal API changes.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant JwtAuthInterceptor
    participant JWTException
    participant ProblemDetails

    Client->>JwtAuthInterceptor: Send request with JWT
    JwtAuthInterceptor->>JwtAuthInterceptor: Validate JWT header & parse token
    alt Missing or Invalid JWT
        JwtAuthInterceptor->>JWTException: Throw JWTException(message, id)
        JWTException-->>JwtAuthInterceptor: Exception raised
        JwtAuthInterceptor->>ProblemDetails: Build error response with error ID and detail
        ProblemDetails-->>Client: Return Problem JSON response
    else Valid JWT
        JwtAuthInterceptor->>Client: Process request normally
    end
Loading
sequenceDiagram
    participant JwtSignInterceptor
    participant PayloadGenerator

    JwtSignInterceptor->>PayloadGenerator: Prepare JWT payload using expirySeconds and clockSkewSeconds
    PayloadGenerator-->>JwtSignInterceptor: Return payload with nbf claim
    JwtSignInterceptor->>JwtSignInterceptor: Sign and generate JWT token
    JwtSignInterceptor-->>Client: Return signed JWT
Loading

Poem

I’m a rabbit hopping through the code,
With error IDs and claims all in a row.
I twirl through tokens, both new and refined,
Where expiry and skew have been redefined.
In every hop, improvements shine bright—
A playful patch to make our system just right.
Hop on and enjoy the digital delight! 🐇

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0b5977d and 90fad7e.

📒 Files selected for processing (7)
  • core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JWTException.java (1 hunks)
  • core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JsonWebToken.java (3 hunks)
  • core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java (3 hunks)
  • core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtSignInterceptor.java (3 hunks)
  • core/src/test/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptorTest.java (8 hunks)
  • core/src/test/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptorUnitTests.java (4 hunks)
  • docs/MIGRATION-GUIDE.md (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
core/src/test/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptorUnitTests.java (1)
core/src/main/java/com/predic8/membrane/core/HttpRouter.java (1)
  • HttpRouter (24-65)
core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java (1)
core/src/main/java/com/predic8/membrane/core/exceptions/ProblemDetails.java (1)
  • ProblemDetails (38-435)
🔇 Additional comments (25)
docs/MIGRATION-GUIDE.md (1)

69-71: LGTM: Clear migration guide updates.

The migration guide properly documents the important changes to the JWT functionality:

  1. The parameter rename from expiryTime to expirySeconds
  2. The change to Problem JSON for JWT validation failure responses

This documentation is essential for users upgrading from v5 to v6.

core/src/test/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptorTest.java (8)

71-71: Test updated to check Problem JSON format.

The assertion has been correctly updated to verify the error message in the "detail" field instead of "description", which aligns with the move to Problem JSON format for error responses.


86-86: Test assertion updated for the new error format.

The assertion has been properly updated to match the Problem JSON format, checking the "detail" field where the error message is now stored.


100-100: Test assertion updated for the new error format.

The assertion has been properly updated to match the Problem JSON format, checking the "detail" field where the error message is now stored.


119-119: Test assertion updated for the new error format.

The assertion has been properly updated to match the Problem JSON format, checking the "detail" field where the error message is now stored.


137-137: Test assertion updated for the new error format.

The assertion has been properly updated to match the Problem JSON format, checking the "detail" field where the error message is now stored.


156-156: Test assertion updated for the new error format.

The assertion has been properly updated to match the Problem JSON format, checking the "detail" field where the error message is now stored.


171-171: Test assertion updated for the new error format.

The assertion has been properly updated to match the Problem JSON format, checking the "detail" field where the error message is now stored.


186-186: Test assertion updated for the new error format.

The assertion has been properly updated to match the Problem JSON format, checking the "detail" field where the error message is now stored.

core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JWTException.java (1)

18-27: Good enhancement to JWTException with error identifiers.

The addition of the id field and appropriate getter method enhances the exception to store a specific error identifier. This supports the migration to Problem JSON format for error responses, which typically include an identifier field for categorizing errors.

This change follows good Java practices with:

  • Using a final field for immutability
  • Adding a proper getter method
  • Storing the id in the constructor

This change is consistent with the stated PR objective of migrating JWT error responses to Problem JSON.

core/src/test/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptorUnitTests.java (4)

48-48: Test helper updated for Problem JSON format.

The getErrorResponse method has been updated to extract the error message from the "detail" field instead of "description", aligning with the Problem JSON format.


58-65: Improved test setup with realistic JWT keys.

The noJwtInHeader test has been enhanced with proper initialization of JWT keys, making the test more realistic and comprehensive. The test now sets up a mock RSA key that the interceptor would use in a real environment.


71-76: Good new test case for invalid JWT header.

This test case verifies the handling of malformed JWT headers, specifically a header with duplicate fields. It provides good coverage for an important edge case in JWT validation.


88-88: Updated error constant reference.

The assertion now directly uses the error constant from the JwtAuthInterceptor class rather than from JsonWebToken, indicating a refactoring of error constants to a more centralized location. This is a good practice for maintainability.

core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtSignInterceptor.java (4)

47-48: Field renames and additions look good

The change from expiryTime to expirySeconds improves clarity by specifying the unit of measurement. The addition of clockSkewSeconds is a good security enhancement to handle time differences between systems.


105-106: Excellent security enhancement with nbf claim

Adding the nbf (not before) claim with a clock skew adjustment is a great security improvement. This prevents token usage before its intended validity period while accounting for reasonable time synchronization differences between systems.


119-130: Renamed getter/setter methods match new field name

The getter and setter methods have been appropriately renamed to reflect the field name change from expiryTime to expirySeconds. The JavaDoc comment has been preserved, maintaining good documentation practice.


132-144: Well-documented accessor methods for clockSkewSeconds

The getter and setter methods for the new clockSkewSeconds parameter are appropriately implemented with clear JavaDoc documentation explaining the purpose of the clock skew parameter in relation to the JWT's validity period.

core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JsonWebToken.java (4)

22-24: Good use of static imports

The added static imports for Jackson features and JwtAuthInterceptor constants improve code readability and maintain a clean coding style.


39-39: Improved error handling with error ID

Adding an error ID to the JWTException provides better error categorization and makes debugging easier. This is a good enhancement to error handling.


61-64: Performance and security improvements

Moving the decoder and mapper initializations to static fields improves performance by creating these objects only once. Configuring the ObjectMapper to handle duplicate keys strictly is a security enhancement that prevents potential issues with malformed JSON input.


71-71: Consistent error handling with error IDs

The exceptions now include error IDs, which aligns with the overall error handling improvements in the JWT components. This consistency makes error handling more robust and traceable.

Also applies to: 78-78

core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java (3)

37-52: Well-structured error constants and helper method

The addition of descriptive error constants with their respective IDs improves error handling consistency and maintainability. The helper method for generating error messages for missing JWT values enhances the usability of error messages.


96-126: Enhanced error reporting with ProblemDetails

Replacing the previous error handling with ProblemDetails-based responses provides a more structured and standardized approach to error reporting. The detailed error information, including status codes and stacktrace configuration, improves the API's error communication.


131-131: Consistent exception throwing with error IDs

The exceptions now include error IDs that match the defined constants, which aligns with the overall error handling improvements. This consistency makes debugging and error tracing easier.

Also applies to: 137-137

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.

@membrane-ci-server
Copy link

This pull request needs "/ok-to-test" from an authorized committer.

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.

1 participant