Skip to content

Updated security för UserService, View and Graph#52

Draft
ehottinen wants to merge 3 commits into
mainfrom
user-security-view-graphql
Draft

Updated security för UserService, View and Graph#52
ehottinen wants to merge 3 commits into
mainfrom
user-security-view-graphql

Conversation

@ehottinen

@ehottinen ehottinen commented Apr 22, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Enhanced security for user-related actions, requiring authentication and appropriate roles for accessing or modifying user data.
    • Users can now only update or delete their own accounts unless they have admin privileges.
  • Bug Fixes

    • Improved session and security context handling after account deletion.
  • Refactor

    • Controller methods now explicitly declare public visibility for clarity.
  • Chores

    • Removed the user deletion confirmation form endpoint.

@coderabbitai

coderabbitai Bot commented Apr 22, 2025

Copy link
Copy Markdown

Walkthrough

This update strengthens security and access control in user management controllers. In UserGraphQLController, method-level security annotations are added, restricting certain queries and mutations to authenticated users or admins, and enforcing ownership or admin checks before sensitive operations. The UserViewController now explicitly declares public visibility for all handler methods and adds authorization checks to endpoints that modify or delete users. The service layer introduces a new method to centralize the logic for verifying if the current user is either the owner or an admin. Some unused or redundant controller methods are removed.

Changes

File(s) Change Summary
src/main/java/org/example/springboot25/controller/UserGraphQLController.java Added method-level security annotations (@PreAuthorize) to restrict access based on role and authentication. Introduced explicit ownership/admin checks before user modifications or deletions. Replaced previous createUser and updateUser methods with updated versions reflecting new security and validation. Added validation to input parameters. Imports updated for security and entity references.
src/main/java/org/example/springboot25/controller/UserViewController.java All handler methods now explicitly declared as public. Authorization checks added to user modification and deletion endpoints to ensure only the owner or an admin can perform these actions. Reactivated code for refreshing security context after updates. Removed showDeleteForm method. Session and security context are cleared after account deletion. Minor formatting cleanup performed.
src/main/java/org/example/springboot25/service/UserService.java Added checkIfOwnerOrAdmin(Long targetUserId, User currentUser) method to encapsulate access control logic for verifying ownership or admin status. Throws AccessDeniedException if checks fail. No other changes to business logic.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant UserGraphQLController
    participant SecurityContext
    participant UserService

    Client->>UserGraphQLController: updateUser(userId, input)
    UserGraphQLController->>SecurityContext: Get current authenticated user
    UserGraphQLController->>UserService: checkIfOwnerOrAdmin(userId, currentUser)
    UserService-->>UserGraphQLController: Access allowed or exception thrown
    UserGraphQLController->>UserService: Perform update
    UserService-->>UserGraphQLController: Updated user data
    UserGraphQLController-->>Client: Return updated user
Loading

Possibly related PRs

  • storkforge/catinder#25: Introduced the initial UserGraphQLController with its full set of GraphQL methods, which are directly modified in this PR.
  • storkforge/catinder#32: Refactored UserGraphQLController to use DTOs and centralized authorization logic, closely related to the security enhancements in this PR.

Suggested reviewers

  • Minhya
  • malvamalmgren

Poem

In the warren of code, security grew,
With checks for each user—are you admin, or you?
Controllers stand guard, with roles held tight,
Owner or admin, you must have the right.
The service now asks, “Are you sure you belong?”
With each hop of logic, our boundaries are strong.
🐇✨ Safe as a burrow, where nothing goes wrong!


📜 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 1e37bb5 and e6c51ce.

📒 Files selected for processing (2)
  • src/main/java/org/example/springboot25/controller/UserGraphQLController.java (2 hunks)
  • src/main/java/org/example/springboot25/service/UserService.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/java/org/example/springboot25/service/UserService.java
  • src/main/java/org/example/springboot25/controller/UserGraphQLController.java

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

@ehottinen
ehottinen requested a review from a team April 22, 2025 09:57

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 (3)
src/main/java/org/example/springboot25/controller/UserGraphQLController.java (2)

28-31: Consider adding pagination to getAllUsers

Returning the full user list in one GraphQL response can quickly degrade performance and expose excessive data as the table grows. Expose page / size (or cursor‑based) arguments and delegate to a paginated service method.


34-40: Inject Authentication instead of querying SecurityContextHolder repeatedly

Every resolver re‑fetches the authentication and current user:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User currentUser = userService.findUserByUserName(auth.getName());
  1. This is duplicated across three methods.
  2. SecurityContextHolder.getContext() may return null in async execution unless @Async security context propagation is enabled.
  3. Spring will happily inject Authentication (or Principal) directly.

Suggested shape:

-@PreAuthorize("isAuthenticated()")
-public UserOutputDTO getUserById(@Argument Long userId) {
-    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
-    User currentUser = userService.findUserByUserName(auth.getName());
+@PreAuthorize("isAuthenticated()")
+public UserOutputDTO getUserById(@Argument Long userId, Authentication auth) {
+    User currentUser = userService.findUserByUserName(auth.getName());

Extract the currentUser lookup to a private helper or a dedicated @Component to DRY the code.

Also consider handling NotFoundException from findUserByUserName and converting it to a GraphQL‑friendly error.

Also applies to: 42-50, 51-59

src/main/java/org/example/springboot25/controller/UserViewController.java (1)

186-188: Deduplicate owner/admin verification & harden against missing authentication

The same three‑line block:

User current = userService.findUserByUserName(SecurityContextHolder.getContext().getAuthentication().getName());
userService.checkIfOwnerOrAdmin(userId, current);

is repeated four times. Besides breaching DRY, it assumes getAuthentication() is non‑null. A signed‑out user hitting these endpoints would cause NullPointerException before your AccessDeniedHandler gets a chance.

Refactor:

  1. Accept Authentication auth as a method parameter – Spring MVC will inject it.
  2. Create a private method:
private User resolveAndAuthorize(Long targetId, Authentication auth) {
    User current = userService.findUserByUserName(auth.getName());
    userService.checkIfOwnerOrAdmin(targetId, current);
    return current;
}
  1. Reuse it in all mutating handlers.

This removes duplication and provides a single place to null‑check auth.

Also applies to: 208-210, 251-253, 269-271

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0ff541b and 48508c5.

📒 Files selected for processing (3)
  • src/main/java/org/example/springboot25/controller/UserGraphQLController.java (2 hunks)
  • src/main/java/org/example/springboot25/controller/UserViewController.java (13 hunks)
  • src/main/java/org/example/springboot25/service/UserService.java (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/main/java/org/example/springboot25/controller/UserGraphQLController.java (1)
src/main/java/org/example/springboot25/controller/AdminController.java (1)
  • PreAuthorize (19-158)

Comment thread src/main/java/org/example/springboot25/service/UserService.java

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (1)
src/main/java/org/example/springboot25/controller/UserGraphQLController.java (1)

65-65: Always returning true might hide errors.

The deleteUser method always returns true regardless of the actual outcome of the deletion operation. Consider returning the actual result of the deletion operation or using exceptions consistently for error handling.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 48508c5 and 1e37bb5.

📒 Files selected for processing (1)
  • src/main/java/org/example/springboot25/controller/UserGraphQLController.java (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/main/java/org/example/springboot25/controller/UserGraphQLController.java (1)
src/main/java/org/example/springboot25/controller/AdminController.java (1)
  • PreAuthorize (19-158)
🪛 GitHub Actions: Java CI with Maven
src/main/java/org/example/springboot25/controller/UserGraphQLController.java

[error] 38-38: NullPointerException: Cannot invoke "org.springframework.security.core.Authentication.getName()" because "auth" is null in method getUserById.


[error] 62-62: NullPointerException: Cannot invoke "org.springframework.security.core.Authentication.getName()" because "auth" is null in method deleteUser.


[error] 53-53: NullPointerException: Cannot invoke "org.springframework.security.core.Authentication.getName()" because "auth" is null in method updateUser.


[error] 62-62: NullPointerException: Cannot invoke "org.springframework.security.core.Authentication.getName()" because "auth" is null in method deleteUser (error case).

🔇 Additional comments (4)
src/main/java/org/example/springboot25/controller/UserGraphQLController.java (4)

7-7: Appropriate security imports added.

The addition of necessary imports for User entity, PreAuthorize annotations, and SecurityContextHolder shows good preparation for implementing security controls throughout the controller.

Also applies to: 12-14


29-29: Good restriction of admin-only functionality.

Restricting the getAllUsers() operation to administrators only is an appropriate security measure as this prevents regular users from accessing the complete user database.


69-72:

Details

✅ Verification successful

Reconsider authentication requirement for createUser.

Requiring authentication to create a user might prevent new users from registering. Consider whether this endpoint should be public for registration purposes, or if there's a separate registration endpoint for new users.


🏁 Script executed:

#!/bin/bash
# Check if there's a separate registration endpoint without authentication
echo "Checking for public registration endpoints..."
rg -i "register|signup|sign.up|registration" --type java

Length of output: 1595


Clarify access for GraphQL createUser mutation

We’ve verified that a public registration endpoint already exists for UI sign‑ups:

  • In SecurityConfig.java, requestMatchers("/", "/about", "/register", …).permitAll() opens /register.
  • UserViewController.java handles GET/POST for /register.
  • Your GraphQL mutation createUser remains secured by @PreAuthorize("isAuthenticated()").

If your intent is to let end‑users self‑register via GraphQL, remove or relax the @PreAuthorize on createUser. Otherwise, it’s correct to keep this mutation authenticated and rely on the existing UI endpoint for new user sign‑up.


37-39:

Details

✅ Verification successful

Verify consistent ownership and admin checks.

The newly added owner/admin checks are good for security but need to be implemented consistently across endpoints. Please verify that the checkIfOwnerOrAdmin method in the UserService handles all edge cases properly, such as when checking ownership of a non-existent user.

Also applies to: 52-54, 61-63


🏁 Script executed:

#!/bin/bash
# Look for the implementation of checkIfOwnerOrAdmin to review its behavior
echo "Checking implementation of checkIfOwnerOrAdmin method..."
rg -A 15 "checkIfOwnerOrAdmin" --type java

Length of output: 13277


Ownership/Admin Guards Verified

  • The checkIfOwnerOrAdmin guard is consistently applied on the GraphQL endpoints
    getUserById (L37–39)
    updateUser (L52–54)
    deleteUser (L61–63)
  • checkIfOwnerOrAdmin properly throws AccessDeniedException for null or unauthorized inputs
  • Actual existence of the target user is validated downstream in the service (admins receive NotFoundException for missing users; non‑owners/non‑admins always get AccessDeniedException to avoid leaking existence)

This behavior aligns with our security requirements.

🧰 Tools
🪛 GitHub Actions: Java CI with Maven

[error] 38-38: NullPointerException: Cannot invoke "org.springframework.security.core.Authentication.getName()" because "auth" is null in method getUserById.

Comment on lines +44 to 47
@PreAuthorize("isAuthenticated()")
public UserOutputDTO getUserByUserName(@Argument String userName) {
return userService.getUserDtoByUserName(userName);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Authentication requirement for user lookup.

Good addition of the authentication requirement, but consider whether the same ownership check that exists in getUserById() should also be applied here to prevent users from looking up arbitrary usernames.

- Fix Authentication null pointer issue
- Fix Authentication null pointer in deleteUser
- Fix Authentication null pointer in updateUser.
@ehottinen
ehottinen marked this pull request as draft April 22, 2025 10:39
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