Conversation
…tompJwtAuthInterceptor
…nd add tests for new behavior
…nce StompJwtAuthInterceptor with improved authentication handling
…ption handling in StompJwtAuthInterceptorTest
…unused tests from JwtAuthFilterTest and improve exception handling in StompJwtAuthInterceptorTest
📝 WalkthroughWalkthroughThis PR adds MongoDB integration and WebSocket JWT authentication to the application. MongoDB 7 service was added to Docker Compose with initialization support. The JWT authentication filter was refactored to extract reusable helper methods for bearer token parsing and token validation. Two new interceptor components ( Changes
Sequence Diagram(s)sequenceDiagram
actor Client
participant WebSocket as WebSocket<br/>Handshake Handler
participant Handshake as JwtHandshakeInterceptor
participant STOMP as STOMP Broker
participant StompAuth as StompJwtAuthInterceptor
participant JWT as JwtAuthFilter
participant SecurityCtx as SecurityContextHolder
Client->>WebSocket: Initiate WS connection<br/>(token in query param)
WebSocket->>Handshake: beforeHandshake()
Handshake->>Handshake: Extract token from URI
alt Token present and enabled
Handshake->>JWT: authenticateToken(token)
JWT-->>Handshake: UsernamePasswordAuthenticationToken
Handshake->>Handshake: Store token in session<br/>attributes
end
Handshake-->>WebSocket: Allow handshake
Client->>STOMP: STOMP CONNECT<br/>(token in header/session)
STOMP->>StompAuth: preSend() for CONNECT
StompAuth->>StompAuth: Extract token from<br/>headers or session
alt Token exists
StompAuth->>JWT: authenticateToken(token)
JWT-->>StompAuth: UsernamePasswordAuthenticationToken
StompAuth->>STOMP: Attach auth to<br/>message user
else Invalid token
StompAuth->>StompAuth: Throw BadCredentialsException
end
StompAuth-->>STOMP: Return processed message
Client->>STOMP: STOMP SUBSCRIBE
STOMP->>STOMP: RoomSubscriptionInterceptor<br/>validates principal
STOMP-->>Client: Allow subscription
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 1 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (1 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
|
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (7)
src/main/java/com/p2ps/config/RoomSubscriptionInterceptor.java (1)
47-49: Anonymous authentication is not currently enabled in this application; this defensive check is optional.Anonymous auth is explicitly disabled in SecurityConfig (no
.anonymous()call), and StompJwtAuthInterceptor returns null when no JWT is present, so the principal remains null. The existinginstanceofcheck on line 47 correctly rejects this case. However, adding an explicitAnonymousAuthenticationTokencheck is a reasonable defense-in-depth improvement to guard against future configuration changes that might enable anonymous auth without realizing the WebSocket impact.Optional defensive improvement
import org.springframework.security.core.Authentication; +import org.springframework.security.authentication.AnonymousAuthenticationToken; @@ - if (!(principal instanceof Authentication authentication) || !authentication.isAuthenticated()) { + if (!(principal instanceof Authentication authentication) + || !authentication.isAuthenticated() + || authentication instanceof AnonymousAuthenticationToken) { logger.warn("Security Alert: Blocked subscription attempt without authenticated principal"); return null; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/main/java/com/p2ps/config/RoomSubscriptionInterceptor.java` around lines 47 - 49, The subscription guard in RoomSubscriptionInterceptor currently checks that principal is an Authentication and authenticated but does not explicitly reject AnonymousAuthenticationToken; add an additional defensive check to treat AnonymousAuthenticationToken as unauthenticated by updating the conditional that inspects principal (used where principal and Authentication are referenced) to also return null if principal is an instance of org.springframework.security.authentication.AnonymousAuthenticationToken, ensuring the method (same block that previously returned null) continues to log the warning and exit when anonymous auth appears in the future.src/main/java/com/p2ps/config/StompJwtAuthInterceptor.java (2)
61-71: Consider simplifying header lookup with a loop.The sequential null checks for different header names can be simplified.
♻️ Suggested simplification
private String resolveToken(StompHeaderAccessor accessor) { - String headerToken = accessor.getFirstNativeHeader("Authorization"); - if (headerToken == null) { - headerToken = accessor.getFirstNativeHeader("authorization"); - } - if (headerToken == null) { - headerToken = accessor.getFirstNativeHeader("token"); - } - if (headerToken == null) { - headerToken = accessor.getFirstNativeHeader("access_token"); - } + String headerToken = Stream.of("Authorization", "authorization", "token", "access_token") + .map(accessor::getFirstNativeHeader) + .filter(Objects::nonNull) + .findFirst() + .orElse(null);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/main/java/com/p2ps/config/StompJwtAuthInterceptor.java` around lines 61 - 71, In resolveToken(StompHeaderAccessor), replace the repeated null-checks for different header names by iterating a list/array of candidate header keys (e.g., "Authorization", "authorization", "token", "access_token") and returning the first non-null value; update the method to loop through these keys calling accessor.getFirstNativeHeader(key) and return when a non-null token is found, otherwise continue to null return — this keeps the lookup concise and preserves current behavior while centralizing the header list for easy future changes.
86-97: DuplicateextractBearerTokenimplementation.This method duplicates
JwtAuthFilter.extractBearerToken(). Consider reusing the existing method to maintain consistency and reduce duplication.♻️ Proposed fix
- private String extractBearerToken(String authorizationHeader) { - if (authorizationHeader == null || authorizationHeader.isBlank()) { - return null; - } - - String token = authorizationHeader.trim(); - if (token.regionMatches(true, 0, "Bearer ", 0, 7)) { - return token.substring(7).trim(); - } - - return token; - }Then update
resolveTokento usejwtAuthFilter.extractBearerToken(headerToken):if (headerToken != null) { - return extractBearerToken(headerToken); + return jwtAuthFilter.extractBearerToken(headerToken); }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/main/java/com/p2ps/config/StompJwtAuthInterceptor.java` around lines 86 - 97, The extractBearerToken in StompJwtAuthInterceptor duplicates logic already present in JwtAuthFilter.extractBearerToken; remove the duplicate method and call the existing JwtAuthFilter.extractBearerToken(...) instead (inject or use the existing jwtAuthFilter instance) from StompJwtAuthInterceptor.resolveToken where headerToken is processed so token extraction is delegated to JwtAuthFilter.extractBearerToken and duplication is eliminated.src/main/java/com/p2ps/config/WebSocketConfig.java (1)
27-38: Javadoc is outdated.The constructor Javadoc only documents
subscriptionInterceptorbut now accepts three interceptors. Update it to reflect all parameters.📝 Suggested Javadoc update
/** - * Constructor injection for the subscription security interceptor. - * `@param` subscriptionInterceptor the interceptor validating inbound traffic + * Constructor injection for WebSocket interceptors. + * `@param` jwtHandshakeInterceptor validates JWT tokens during WebSocket handshake + * `@param` stompJwtAuthInterceptor authenticates STOMP CONNECT frames using JWT + * `@param` subscriptionInterceptor validates room subscription requests */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/main/java/com/p2ps/config/WebSocketConfig.java` around lines 27 - 38, The constructor Javadoc for WebSocketConfig is outdated and only documents subscriptionInterceptor; update the Javadoc block above the WebSocketConfig(...) constructor to list and describe all three parameters (JwtHandshakeInterceptor jwtHandshakeInterceptor, StompJwtAuthInterceptor stompJwtAuthInterceptor, and RoomSubscriptionInterceptor subscriptionInterceptor), ensuring each `@param` tag accurately describes the role of that interceptor in the constructor.src/test/java/com/p2ps/auth/security/SecurityConfigTest.java (1)
50-67: CORS test has hardcoded expected values.The test asserts specific CORS configuration values (e.g.,
http://localhost:5173). While this provides regression protection, consider adding a comment noting these values must stay in sync withSecurityConfig, or extract them as constants shared between production code and tests.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/test/java/com/p2ps/auth/security/SecurityConfigTest.java` around lines 50 - 67, The test corsConfigurationSource_ConfiguredCorrectly in SecurityConfigTest hardcodes CORS values that must match SecurityConfig.corsConfigurationSource; either add a concise comment in the test referencing SecurityConfig.corsConfigurationSource to warn future editors that these expected values must stay in sync, or better: extract the hardcoded values into public constants on SecurityConfig (e.g., ALLOWED_ORIGINS, ALLOWED_METHODS, ALLOWED_HEADERS, ALLOW_CREDENTIALS) and use those constants in the test when asserting (via SecurityConfig.ALLOWED_ORIGINS, etc.) so the production configuration and test expectations remain synchronized.src/test/java/com/p2ps/auth/security/JwtAuthFilterTest.java (1)
218-231: Assert filter-chain continuation in this path as well.Line 218-231 validates authentication state but does not assert that the request continues down the chain. Add
verify(filterChain).doFilter(request, response)for parity with the otherdoFilterInternaltests.Suggested assertion add-on
jwtAuthFilter.doFilterInternal(request, response, filterChain); assertNotNull(SecurityContextHolder.getContext().getAuthentication()); assertEquals("test@test.com", SecurityContextHolder.getContext().getAuthentication().getPrincipal()); + verify(filterChain).doFilter(request, response);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/test/java/com/p2ps/auth/security/JwtAuthFilterTest.java` around lines 218 - 231, The test method bareTokenWithoutBearerPrefix in JwtAuthFilterTest asserts authentication but doesn't verify the filter chain was continued; update this test to also verify the chain by adding a verification that filterChain.doFilter(request, response) was called (i.e., call verify(filterChain).doFilter(request, response)) after the existing assertions so this path mirrors the other doFilterInternal tests.src/test/java/com/p2ps/config/StompJwtAuthInterceptorTest.java (1)
45-60: Avoid stubbingauthenticateToken(null)in no-token cases; verify no auth call instead.These tests currently pass even if the interceptor incorrectly invokes authentication with
null. Prefer assertingverify(jwtAuthFilter, never()).authenticateToken(any())in no-token paths.Also applies to: 170-203
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/test/java/com/p2ps/config/StompJwtAuthInterceptorTest.java` around lines 45 - 60, Update the test preSend_ConnectWithoutTokenPassesThrough to assert that JwtAuthFilter.authenticateToken is never called rather than stubbing authenticateToken(null); specifically, remove the when(jwtAuthFilter.authenticateToken(null)) stub and add verify(jwtAuthFilter, never()).authenticateToken(any()) after calling StompJwtAuthInterceptor.preSend, referencing JwtAuthFilter.authenticateToken and StompJwtAuthInterceptor.preSend to locate the code; apply the same change pattern to the other tests noted (lines ~170-203) that handle "no-token" scenarios so they verify no authentication invocation instead of stubbing null.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In @.github/workflows/build.yml:
- Around line 16-20: CI JDK version (the "Set up JDK 21" step with java-version:
21) is mismatched with the Gradle toolchain target (Java 25 in
build.gradle.kts); either update the workflow step to use java-version: 25 to
match the Gradle toolchain, or change the Gradle toolchain JavaLanguageVersion
(the toolchain block / languageVersion.set(JavaLanguageVersion.of(25))) to 21 so
both match—pick one approach and make the corresponding change so the CI
java-version and Gradle toolchain value are identical.
In `@src/main/resources/application.properties`:
- Line 8: The property key spring.data.mongodb.uri in application.properties is
using the old Spring Boot namespace; update it to the Boot 4.0+ format by
replacing the key spring.data.mongodb.uri with spring.mongodb.uri while keeping
the same connection value (e.g.,
mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo}) so the app reads the
Mongo URI correctly under Spring Boot 4+.
In `@src/test/java/com/p2ps/auth/security/JwtAuthFilterTest.java`:
- Around line 79-81: The test currently asserts that
jwtAuthFilter.extractBearerToken("Bearer ") returns "Bearer", which accepts a
whitespace-only credential; change the test in JwtAuthFilterTest to assert that
extractBearerToken returns null for inputs like "Bearer " (use assertNull). Also
update the implementation of extractBearerToken in the JwtAuthFilter class so
that after stripping the "Bearer" prefix it trims the credential and returns
null when the remaining token is empty or only whitespace, ensuring malformed
"Bearer" headers are rejected.
In `@src/test/java/resources/application-test.properties`:
- Around line 14-15: Replace the legacy property key and env var usage by
updating occurrences of spring.data.mongodb.uri and SPRING_DATA_MONGODB_URI to
the Spring Boot 4.0 names: spring.mongodb.uri and SPRING_MONGODB_URI;
specifically, update the property key (spring.data.mongodb.uri ->
spring.mongodb.uri) and the environment variable placeholder
(SPRING_DATA_MONGODB_URI -> SPRING_MONGODB_URI) wherever they appear (including
the test and main application properties) so the MongoDB URI is read correctly
under Spring Boot 4.0.4.
---
Nitpick comments:
In `@src/main/java/com/p2ps/config/RoomSubscriptionInterceptor.java`:
- Around line 47-49: The subscription guard in RoomSubscriptionInterceptor
currently checks that principal is an Authentication and authenticated but does
not explicitly reject AnonymousAuthenticationToken; add an additional defensive
check to treat AnonymousAuthenticationToken as unauthenticated by updating the
conditional that inspects principal (used where principal and Authentication are
referenced) to also return null if principal is an instance of
org.springframework.security.authentication.AnonymousAuthenticationToken,
ensuring the method (same block that previously returned null) continues to log
the warning and exit when anonymous auth appears in the future.
In `@src/main/java/com/p2ps/config/StompJwtAuthInterceptor.java`:
- Around line 61-71: In resolveToken(StompHeaderAccessor), replace the repeated
null-checks for different header names by iterating a list/array of candidate
header keys (e.g., "Authorization", "authorization", "token", "access_token")
and returning the first non-null value; update the method to loop through these
keys calling accessor.getFirstNativeHeader(key) and return when a non-null token
is found, otherwise continue to null return — this keeps the lookup concise and
preserves current behavior while centralizing the header list for easy future
changes.
- Around line 86-97: The extractBearerToken in StompJwtAuthInterceptor
duplicates logic already present in JwtAuthFilter.extractBearerToken; remove the
duplicate method and call the existing JwtAuthFilter.extractBearerToken(...)
instead (inject or use the existing jwtAuthFilter instance) from
StompJwtAuthInterceptor.resolveToken where headerToken is processed so token
extraction is delegated to JwtAuthFilter.extractBearerToken and duplication is
eliminated.
In `@src/main/java/com/p2ps/config/WebSocketConfig.java`:
- Around line 27-38: The constructor Javadoc for WebSocketConfig is outdated and
only documents subscriptionInterceptor; update the Javadoc block above the
WebSocketConfig(...) constructor to list and describe all three parameters
(JwtHandshakeInterceptor jwtHandshakeInterceptor, StompJwtAuthInterceptor
stompJwtAuthInterceptor, and RoomSubscriptionInterceptor
subscriptionInterceptor), ensuring each `@param` tag accurately describes the role
of that interceptor in the constructor.
In `@src/test/java/com/p2ps/auth/security/JwtAuthFilterTest.java`:
- Around line 218-231: The test method bareTokenWithoutBearerPrefix in
JwtAuthFilterTest asserts authentication but doesn't verify the filter chain was
continued; update this test to also verify the chain by adding a verification
that filterChain.doFilter(request, response) was called (i.e., call
verify(filterChain).doFilter(request, response)) after the existing assertions
so this path mirrors the other doFilterInternal tests.
In `@src/test/java/com/p2ps/auth/security/SecurityConfigTest.java`:
- Around line 50-67: The test corsConfigurationSource_ConfiguredCorrectly in
SecurityConfigTest hardcodes CORS values that must match
SecurityConfig.corsConfigurationSource; either add a concise comment in the test
referencing SecurityConfig.corsConfigurationSource to warn future editors that
these expected values must stay in sync, or better: extract the hardcoded values
into public constants on SecurityConfig (e.g., ALLOWED_ORIGINS, ALLOWED_METHODS,
ALLOWED_HEADERS, ALLOW_CREDENTIALS) and use those constants in the test when
asserting (via SecurityConfig.ALLOWED_ORIGINS, etc.) so the production
configuration and test expectations remain synchronized.
In `@src/test/java/com/p2ps/config/StompJwtAuthInterceptorTest.java`:
- Around line 45-60: Update the test preSend_ConnectWithoutTokenPassesThrough to
assert that JwtAuthFilter.authenticateToken is never called rather than stubbing
authenticateToken(null); specifically, remove the
when(jwtAuthFilter.authenticateToken(null)) stub and add verify(jwtAuthFilter,
never()).authenticateToken(any()) after calling StompJwtAuthInterceptor.preSend,
referencing JwtAuthFilter.authenticateToken and StompJwtAuthInterceptor.preSend
to locate the code; apply the same change pattern to the other tests noted
(lines ~170-203) that handle "no-token" scenarios so they verify no
authentication invocation instead of stubbing null.
🪄 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
Run ID: e9007215-d55a-4c04-9b6f-c77e01056aac
📒 Files selected for processing (20)
.env.example.github/workflows/build.yml.github/workflows/test.ymlbuild.gradle.ktsdocker-compose.ymlsrc/main/java/com/p2ps/auth/security/JwtAuthFilter.javasrc/main/java/com/p2ps/auth/security/SecurityConfig.javasrc/main/java/com/p2ps/config/JwtHandshakeInterceptor.javasrc/main/java/com/p2ps/config/RoomSubscriptionInterceptor.javasrc/main/java/com/p2ps/config/StompJwtAuthInterceptor.javasrc/main/java/com/p2ps/config/WebSocketConfig.javasrc/main/resources/application.propertiessrc/test/java/com/p2ps/auth/JwtAuthFilterTest.javasrc/test/java/com/p2ps/auth/security/JwtAuthFilterTest.javasrc/test/java/com/p2ps/auth/security/SecurityConfigTest.javasrc/test/java/com/p2ps/config/JwtHandshakeInterceptorTest.javasrc/test/java/com/p2ps/config/RoomSubscriptionInterceptorTest.javasrc/test/java/com/p2ps/config/StompJwtAuthInterceptorTest.javasrc/test/java/com/p2ps/config/WebSocketConfigTest.javasrc/test/java/resources/application-test.properties
💤 Files with no reviewable changes (1)
- src/test/java/com/p2ps/auth/JwtAuthFilterTest.java
| - name: Set up JDK 21 | ||
| uses: actions/setup-java@v4 | ||
| with: | ||
| java-version: 17 | ||
| distribution: 'zulu' # Alternative distribution options are available | ||
| java-version: 21 | ||
| distribution: 'temurin' |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify Java version alignment between workflow and Gradle toolchain
rg -n 'java-version:\s*[0-9]+' .github/workflows/build.yml
rg -n 'JavaLanguageVersion\.of\([0-9]+\)' build.gradle.ktsRepository: P2P-Shopping/server
Length of output: 148
Align CI JDK version with Gradle toolchain target.
CI workflow uses Java 21 (line 19) but build.gradle.kts targets Java 25 (line 15). Update the workflow to use Java 25 or update the Gradle toolchain to match Java 21 to maintain consistency and avoid build inconsistencies.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In @.github/workflows/build.yml around lines 16 - 20, CI JDK version (the "Set
up JDK 21" step with java-version: 21) is mismatched with the Gradle toolchain
target (Java 25 in build.gradle.kts); either update the workflow step to use
java-version: 25 to match the Gradle toolchain, or change the Gradle toolchain
JavaLanguageVersion (the toolchain block /
languageVersion.set(JavaLanguageVersion.of(25))) to 21 so both match—pick one
approach and make the corresponding change so the CI java-version and Gradle
toolchain value are identical.
| spring.datasource.username=${POSTGRES_USER} | ||
| spring.datasource.password=${POSTGRES_PASSWORD} | ||
| spring.datasource.driver-class-name=org.postgresql.Driver | ||
| spring.data.mongodb.uri=mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo} |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find build files (pom.xml, build.gradle, etc.)
echo "=== Finding build configuration files ==="
find . -type f \( -name "pom.xml" -o -name "build.gradle" -o -name "build.gradle.kts" \) | head -20
# Check application.properties file
echo -e "\n=== Checking application.properties ==="
if [ -f "src/main/resources/application.properties" ]; then
cat -n src/main/resources/application.properties
else
echo "File not found at expected location"
find . -name "application.properties" -type f
fiRepository: P2P-Shopping/server
Length of output: 996
🏁 Script executed:
#!/bin/bash
# Check Spring Boot version in build.gradle.kts
echo "=== Checking Spring Boot version in build.gradle.kts ==="
cat -n build.gradle.kts | head -50
# Also search for specific Spring Boot version declaration
echo -e "\n=== Searching for Spring Boot version ==="
grep -n "spring.boot\|SpringBoot\|version" build.gradle.kts | head -20Repository: P2P-Shopping/server
Length of output: 3229
Update MongoDB connection property to Boot 4.0+ format.
Line 8 uses the legacy spring.data.mongodb.uri prefix. Spring Boot 4.0+ renamed this to spring.mongodb.uri without the .data segment.
Proposed fix
-spring.data.mongodb.uri=mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo}
+spring.mongodb.uri=mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo}📝 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.
| spring.data.mongodb.uri=mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo} | |
| spring.mongodb.uri=mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo} |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/main/resources/application.properties` at line 8, The property key
spring.data.mongodb.uri in application.properties is using the old Spring Boot
namespace; update it to the Boot 4.0+ format by replacing the key
spring.data.mongodb.uri with spring.mongodb.uri while keeping the same
connection value (e.g.,
mongodb://localhost:27017/${MONGO_DB:p2p_shopping_mongo}) so the app reads the
Mongo URI correctly under Spring Boot 4+.
| void bearerWithOnlyWhitespace_ReturnsBearer() { | ||
| assertEquals("Bearer", jwtAuthFilter.extractBearerToken("Bearer ")); | ||
| } |
There was a problem hiding this comment.
Bearer with no credentials should not be treated as a usable token.
Line 80 currently asserts "Bearer " becomes "Bearer", which bakes malformed header handling into the contract. Prefer returning null for empty Bearer credentials so malformed auth headers are rejected cleanly.
Suggested test adjustment
- void bearerWithOnlyWhitespace_ReturnsBearer() {
- assertEquals("Bearer", jwtAuthFilter.extractBearerToken("Bearer "));
+ void bearerWithOnlyWhitespace_ReturnsNull() {
+ assertNull(jwtAuthFilter.extractBearerToken("Bearer "));
}📝 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.
| void bearerWithOnlyWhitespace_ReturnsBearer() { | |
| assertEquals("Bearer", jwtAuthFilter.extractBearerToken("Bearer ")); | |
| } | |
| void bearerWithOnlyWhitespace_ReturnsNull() { | |
| assertNull(jwtAuthFilter.extractBearerToken("Bearer ")); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/test/java/com/p2ps/auth/security/JwtAuthFilterTest.java` around lines 79
- 81, The test currently asserts that jwtAuthFilter.extractBearerToken("Bearer
") returns "Bearer", which accepts a whitespace-only credential; change the test
in JwtAuthFilterTest to assert that extractBearerToken returns null for inputs
like "Bearer " (use assertNull). Also update the implementation of
extractBearerToken in the JwtAuthFilter class so that after stripping the
"Bearer" prefix it trims the credential and returns null when the remaining
token is empty or only whitespace, ensuring malformed "Bearer" headers are
rejected.
| # MongoDB - can be overridden via SPRING_DATA_MONGODB_URI env var for integration tests with real MongoDB | ||
| spring.data.mongodb.uri=${SPRING_DATA_MONGODB_URI:mongodb://mock-address:27017/test} |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# Find build configuration files to determine Spring Boot version
find . -maxdepth 3 -type f \( -name "pom.xml" -o -name "build.gradle*" \) | head -20Repository: P2P-Shopping/server
Length of output: 81
🏁 Script executed:
# Check the test properties file mentioned in the review
find . -type f -name "application-test.properties" -o -name "application.properties" | head -10Repository: P2P-Shopping/server
Length of output: 160
🏁 Script executed:
# Check Spring Boot version in build.gradle.kts
cat build.gradle.kts | grep -A 5 -B 5 -i "boot\|version"Repository: P2P-Shopping/server
Length of output: 2079
🏁 Script executed:
# Read both properties files to compare MongoDB property usage
echo "=== Main properties ===" && cat src/main/resources/application.properties
echo "" && echo "=== Test properties ===" && cat src/test/java/resources/application-test.propertiesRepository: P2P-Shopping/server
Length of output: 1477
🏁 Script executed:
# Search for all MongoDB property usages in the codebase
rg -i "spring\..*mongodb" --type properties -B 1 -A 1Repository: P2P-Shopping/server
Length of output: 97
🏁 Script executed:
# Search in Java code or other config files for MongoDB URI references
rg -i "mongodb|spring\.data\.mongodb|spring\.mongodb" --type-list | head -20Repository: P2P-Shopping/server
Length of output: 452
🏁 Script executed:
# Search for all MongoDB property usages in properties files
rg "spring\..*mongodb" . -g "*.properties"Repository: P2P-Shopping/server
Length of output: 326
🏁 Script executed:
# Search for MongoDB references in Java code to understand usage
rg -i "mongodb\|MongoTemplate\|MongoClient" . -t java | head -30Repository: P2P-Shopping/server
Length of output: 45
Test Mongo property uses outdated Spring Boot 4.0 prefix—must update to spring.mongodb.uri.
Line 15 uses the legacy spring.data.mongodb.uri key, which is not recognized in Spring Boot 4.0.4. Update to the new property prefix and corresponding environment variable name to ensure the MongoDB URI configuration is applied correctly.
Proposed fix
-# MongoDB - can be overridden via SPRING_DATA_MONGODB_URI env var for integration tests with real MongoDB
-spring.data.mongodb.uri=${SPRING_DATA_MONGODB_URI:mongodb://mock-address:27017/test}
+# MongoDB - can be overridden via SPRING_MONGODB_URI env var for integration tests with real MongoDB
+spring.mongodb.uri=${SPRING_MONGODB_URI:mongodb://mock-address:27017/test}Note: The same issue exists in src/main/resources/application.properties line 8 and should be corrected there as well.
📝 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.
| # MongoDB - can be overridden via SPRING_DATA_MONGODB_URI env var for integration tests with real MongoDB | |
| spring.data.mongodb.uri=${SPRING_DATA_MONGODB_URI:mongodb://mock-address:27017/test} | |
| # MongoDB - can be overridden via SPRING_MONGODB_URI env var for integration tests with real MongoDB | |
| spring.mongodb.uri=${SPRING_MONGODB_URI:mongodb://mock-address:27017/test} |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/test/java/resources/application-test.properties` around lines 14 - 15,
Replace the legacy property key and env var usage by updating occurrences of
spring.data.mongodb.uri and SPRING_DATA_MONGODB_URI to the Spring Boot 4.0
names: spring.mongodb.uri and SPRING_MONGODB_URI; specifically, update the
property key (spring.data.mongodb.uri -> spring.mongodb.uri) and the environment
variable placeholder (SPRING_DATA_MONGODB_URI -> SPRING_MONGODB_URI) wherever
they appear (including the test and main application properties) so the MongoDB
URI is read correctly under Spring Boot 4.0.4.



Summary by CodeRabbit
Release Notes
New Features
Improvements
Chores