Skip to content

Improve JWT error handling and logging#2970

Open
predic8 wants to merge 8 commits into
masterfrom
jwt-interceptor-log-messages
Open

Improve JWT error handling and logging#2970
predic8 wants to merge 8 commits into
masterfrom
jwt-interceptor-log-messages

Conversation

@predic8

@predic8 predic8 commented Jun 8, 2026

Copy link
Copy Markdown
Member

Summary by CodeRabbit

  • Bug Fixes

    • JWT authentication now returns HTTP 401 (Unauthorized) for validation failures.
    • Error responses give clearer, more specific messages for invalid signatures, malformed JWT headers, and missing tokens.
    • Logging for JWT retrieval and validation failures clarified to aid troubleshooting.
  • Tests

    • JWT-related tests updated to be resilient to message variations by using prefix-based assertions.

@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

JwtAuthInterceptor replaces wildcard imports with explicit ones, adds ERROR_JWT_INVALID_SIGNATURE, changes handleRequest to map JWT failures (parsing, invalid signature, validation, missing) to ProblemDetails.security(...) with HTTP 401 and updated logs, logs null JWTs in handleJwt, and updates tests to match these behaviors.

Changes

JWT Error Handling Improvements

Layer / File(s) Summary
Imports and new error constant
core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java (lines 15–38, 63)
Wildcard imports replaced with explicit imports; added public constant ERROR_JWT_INVALID_SIGNATURE.
JWT validation error response handling
core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java (lines 97–139)
handleRequest now distinguishes JsonProcessingException, InvalidJwtSignatureException, InvalidJwtException, and other exceptions, returning ProblemDetails.security(...) with HTTP 401 and specific detail/sub-see values; logging updated.
Null token diagnostic logging
core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java (lines 142–146)
handleJwt logs "JWT not found in request." before throwing JWTException when token is null.
Test imports and assertion adjustments
core/src/test/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptorTest.java (multiple ranges)
Replaced wildcard imports with explicit imports and changed several assertions to use startsWith(...) for error detail checks (invalid signature and validation-failed cases).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • membrane/api-gateway#1806: Also modifies JwtAuthInterceptor to produce ProblemDetails-style responses and extends JWT error handling/constants.

Suggested reviewers

  • rrayst
  • t-burch
  • christiangoerdes

Poem

🐰 I sniffed a header, small and slight,
Its signature failed in morning light.
I logged a hint, made errors bright,
Switched responses to one-oh-one right,
Now tokens hop straight into sight.

🚥 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 'Improve JWT error handling and logging' accurately summarizes the main changes: JWT exception handling was refactored to return proper security responses, error responses were standardized to 401 status, new error constants were added, and logging was updated.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch jwt-interceptor-log-messages

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 and usage tips.

@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: 1

🤖 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
`@core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java`:
- Line 131: The log call in JwtAuthInterceptor uses log.info("Could not retrieve
JWT: ", e.getMessage()) without a "{}" placeholder so the message is never
logged; update the log invocation in JwtAuthInterceptor (the log.info call) to
include a placeholder and/or pass the exception correctly, e.g. use
log.info("Could not retrieve JWT: {}", e.getMessage()) or log.info("Could not
retrieve JWT", e) to ensure the error message or stack trace is actually
recorded.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9e0edaa5-0999-49b6-a0f9-413924998e88

📥 Commits

Reviewing files that changed from the base of the PR and between ccef747 and f79fb77.

📒 Files selected for processing (1)
  • core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java

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

Caution

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

⚠️ Outside diff range comments (2)
core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java (2)

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

Avoid exposing raw JWT validation exception text to clients.

detail(ERROR_VALIDATION_FAILED + ": " + e.getMessage()) leaks internal validator output in the HTTP response. Keep client detail generic and retain specifics in logs only.

🔧 Proposed fix
         } catch (InvalidJwtException e) {
             log.info("JWT validation failed: {}", e.getErrorDetails());
             security(router.getConfiguration().isProduction(), "jwt-auth")
-                    .detail(ERROR_VALIDATION_FAILED + ": " + e.getMessage())
+                    .detail(ERROR_VALIDATION_FAILED)
                     .addSubSee(ERROR_VALIDATION_FAILED_ID)
                     .stacktrace(false)
                     .status(401)
                     .buildAndSetResponse(exc);
             return RETURN;

Based on learnings, HTTP ProblemDetails.detail(...) should avoid exposing internal implementation details to clients when a generic message is sufficient.

🤖 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
`@core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java`
around lines 123 - 125, In JwtAuthInterceptor, the
security(...).detail(ERROR_VALIDATION_FAILED + ": " + e.getMessage()) call
exposes internal validator text to clients; change it to set a generic
client-facing detail (e.g. ERROR_VALIDATION_FAILED or a short message) and move
the full exception message into a server log (use logger.error or similar)
referencing the exception (e) so the detailed error is recorded but not
returned; update the invocation around
security(router.getConfiguration().isProduction(), "jwt-auth").detail(...) and
keep addSubSee(ERROR_VALIDATION_FAILED_ID) as-is.

Source: Learnings


96-101: ⚠️ Potential issue | 🔴 Critical

Propagate JWTException’s structured id into ProblemDetails (addSubSee)
JWTException exposes the structured error id via getId(), but JwtAuthInterceptor’s catch (JWTException e) branch (lines 96-101) only sets .detail(e.getMessage()) and never calls .addSubSee(e.getId()); this drops the IDs from thrown new JWTException(..., ERROR_JWT_NOT_FOUND_ID) / new JWTException(..., ERROR_UNKNOWN_KEY_ID) paths.

🤖 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
`@core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java`
around lines 96 - 101, In JwtAuthInterceptor's catch (JWTException e) block,
include the exception's structured id into the ProblemDetails by calling
addSubSee(e.getId()) on the security(...) builder before
buildAndSetResponse(exc); specifically, after calling .detail(e.getMessage())
(and only if e.getId() is non-null/non-empty), invoke .addSubSee(e.getId()) on
the same builder chain so JWTException.getId() values (e.g.
ERROR_JWT_NOT_FOUND_ID / ERROR_UNKNOWN_KEY_ID) are propagated into the response.
🧹 Nitpick comments (1)
core/src/test/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptorTest.java (1)

117-121: ⚡ Quick win

Lock the new 401 contract with explicit status assertions.

These cases now validate detail prefixes but still only check isUserError(). Since this PR’s behavior change is specifically 401, assert status code explicitly to prevent silent regressions to other 4xx codes.

✅ Minimal test hardening
                     assertTrue(exc.getResponse().isUserError());
+                    assertEquals(401, exc.getResponse().getStatusCode());
                     assertNull(exc.getProperties().get("jwt"));
                     var detail = (String) unpackBody(exc).get("detail");
                     assertTrue(detail.startsWith(ERROR_JWT_INVALID_SIGNATURE));

Also applies to: 170-174, 186-190, 202-206

🤖 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
`@core/src/test/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptorTest.java`
around lines 117 - 121, The tests in JwtAuthInterceptorTest currently only
assert exc.getResponse().isUserError(); update them to lock the 401 contract by
asserting the explicit HTTP status instead (e.g. assertEquals(401,
exc.getResponse().getStatus())) wherever the test checks isUserError() —
specifically in the block that verifies ERROR_JWT_INVALID_SIGNATURE (uses
unpackBody(exc) and variable exc) and the other similar blocks noted (lines
referenced in the review: 170-174, 186-190, 202-206); keep the existing checks
for null jwt and detail prefix assertions (ERROR_JWT_INVALID_SIGNATURE) and just
add the explicit status assertion to prevent regressions.
🤖 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.

Outside diff comments:
In
`@core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java`:
- Around line 123-125: In JwtAuthInterceptor, the
security(...).detail(ERROR_VALIDATION_FAILED + ": " + e.getMessage()) call
exposes internal validator text to clients; change it to set a generic
client-facing detail (e.g. ERROR_VALIDATION_FAILED or a short message) and move
the full exception message into a server log (use logger.error or similar)
referencing the exception (e) so the detailed error is recorded but not
returned; update the invocation around
security(router.getConfiguration().isProduction(), "jwt-auth").detail(...) and
keep addSubSee(ERROR_VALIDATION_FAILED_ID) as-is.
- Around line 96-101: In JwtAuthInterceptor's catch (JWTException e) block,
include the exception's structured id into the ProblemDetails by calling
addSubSee(e.getId()) on the security(...) builder before
buildAndSetResponse(exc); specifically, after calling .detail(e.getMessage())
(and only if e.getId() is non-null/non-empty), invoke .addSubSee(e.getId()) on
the same builder chain so JWTException.getId() values (e.g.
ERROR_JWT_NOT_FOUND_ID / ERROR_UNKNOWN_KEY_ID) are propagated into the response.

---

Nitpick comments:
In
`@core/src/test/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptorTest.java`:
- Around line 117-121: The tests in JwtAuthInterceptorTest currently only assert
exc.getResponse().isUserError(); update them to lock the 401 contract by
asserting the explicit HTTP status instead (e.g. assertEquals(401,
exc.getResponse().getStatus())) wherever the test checks isUserError() —
specifically in the block that verifies ERROR_JWT_INVALID_SIGNATURE (uses
unpackBody(exc) and variable exc) and the other similar blocks noted (lines
referenced in the review: 170-174, 186-190, 202-206); keep the existing checks
for null jwt and detail prefix assertions (ERROR_JWT_INVALID_SIGNATURE) and just
add the explicit status assertion to prevent regressions.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 6ed5c6ae-5931-4dad-8d7e-aea9970c84af

📥 Commits

Reviewing files that changed from the base of the PR and between a5e6ccc and 67853a9.

📒 Files selected for processing (2)
  • core/src/main/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptor.java
  • core/src/test/java/com/predic8/membrane/core/interceptor/jwt/JwtAuthInterceptorTest.java

@predic8

predic8 commented Jun 9, 2026

Copy link
Copy Markdown
Member Author

/ok-to-test

1 similar comment
@predic8

predic8 commented Jun 9, 2026

Copy link
Copy Markdown
Member Author

/ok-to-test

@membrane-ci-server

Copy link
Copy Markdown

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

@rrayst

rrayst commented Jun 12, 2026

Copy link
Copy Markdown
Member

failing tests

@predic8 predic8 added this to the 7.3.0 milestone Jun 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants