Skip to content
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

[WEB-2778] chore: private project join restriction #6082

Merged
merged 5 commits into from
Nov 22, 2024

Conversation

NarayanBavisetti
Copy link
Collaborator

@NarayanBavisetti NarayanBavisetti commented Nov 21, 2024

chore:

  • added restriction on joining private projects for members and guest.
    Issue Link: WEB-2778

Summary by CodeRabbit

  • New Features

    • Enhanced project retrieval to only show projects associated with active members.
    • Improved error handling for project creation and updates, providing clearer feedback on issues like duplicate names and invalid email addresses.
    • Stricter permission checks for project deletion and invitation creation, ensuring only authorized users can perform these actions.
  • Bug Fixes

    • Adjusted rendering logic for the project wrapper component to simplify structure when a project is not found.

Copy link
Contributor

coderabbitai bot commented Nov 21, 2024

Walkthrough

The changes in this pull request enhance the ProjectViewSet class in apiserver/plane/app/views/project/base.py by modifying the retrieve, create, partial_update, and destroy methods. The retrieve method now filters projects to include only those associated with active members. The create and partial_update methods have improved error handling for specific exceptions, while the destroy method enforces stricter permission checks. Additionally, the ProjectAuthWrapper component in web/core/layouts/auth-layout/project-wrapper.tsx has been simplified in its rendering logic without altering its core functionality.

Changes

File Path Change Summary
apiserver/plane/app/views/project/base.py Enhanced retrieve to filter for active project members; improved error handling in create and partial_update; strengthened permission checks in destroy.
web/core/layouts/auth-layout/project-wrapper.tsx Simplified rendering logic for project not found state; retained existing data fetching logic.
apiserver/plane/app/views/project/invite.py Added permission check in create method of UserProjectInvitationsViewset; improved error handling for invalid emails in create method of ProjectInvitationsViewset.

Possibly related PRs

Suggested labels

⚙️backend, 🌟improvement

Suggested reviewers

  • pablohashescobar
  • sriramveeraghanta

🐰 In the fields where projects grow,
Active members help them flow.
With checks in place, and errors tamed,
Our work is safe, our goals are framed.
Hopping forward, we celebrate,
A brighter path we cultivate! 🌼✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c6ff747 and 3aee8fb.

📒 Files selected for processing (1)
  • apiserver/plane/app/views/project/invite.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apiserver/plane/app/views/project/invite.py

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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 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.

Copy link
Contributor

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

🧹 Outside diff range and nitpick comments (2)
web/core/layouts/auth-layout/project-wrapper.tsx (1)

Line range hint 165-178: Simplify the condition and improve error messaging

The empty state implementation looks good, but there are a few suggestions for improvement:

  1. The condition !!hasPermissionToCurrentProject === false can be simplified
  2. The error message could be more specific about private vs public projects to align with the PR objectives
  3. Consider adding error boundary protection for this component

Here's the suggested improvement:

-  if (!loader && !projectExists && projectId && !!hasPermissionToCurrentProject === false)
+  if (!loader && !projectExists && projectId && !hasPermissionToCurrentProject)
     return (
       <div className="grid h-screen place-items-center bg-custom-background-100">
         <EmptyState
-          title="No such project exists"
-          description="Try creating a new project"
+          title="Project not found or access restricted"
+          description="This project may be private or doesn't exist. You can try creating a new project."
           image={emptyProject}
           primaryButton={{
             text: "Create Project",
             onClick: () => {
               setTrackElement("Projects page empty state");
               toggleCreateProjectModal(true);
             },
           }}
         />
       </div>
     );

Also, consider wrapping the component with an error boundary:

import { ErrorBoundary } from "@/components/common";

export const ProjectAuthWrapper: FC<IProjectAuthWrapper> = observer((props) => {
  return (
    <ErrorBoundary>
      {/* existing component code */}
    </ErrorBoundary>
  );
});
apiserver/plane/app/views/project/base.py (1)

179-182: Security enhancement looks good, but consider public projects

The additional filtering ensures that only active project members can access project details, which is a good security measure. However, consider making this filter conditional based on the project's visibility/network settings to maintain accessibility for public projects.

Consider updating the filter to handle public projects:

     .filter(
+        Q(network=2) |  # Public projects
+        Q(
             project_projectmember__member=self.request.user,
             project_projectmember__is_active=True,
+        )
     )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b72d180 and 64f22d5.

📒 Files selected for processing (2)
  • apiserver/plane/app/views/project/base.py (1 hunks)
  • web/core/layouts/auth-layout/project-wrapper.tsx (1 hunks)
🔇 Additional comments (2)
web/core/layouts/auth-layout/project-wrapper.tsx (1)

Line range hint 1-178: Verify permission handling for private projects

The implementation correctly checks permissions and shows appropriate UI states. However, let's verify if all permission-related code paths are properly tested.

Also, please ensure that:

  1. The JoinProject component properly handles private project scenarios
  2. Error messages clearly indicate when access is denied due to project privacy settings
  3. Permission checks are consistent with the backend changes in ProjectViewSet
✅ Verification successful

Based on the search results, I can now verify the permission handling implementation. Let me generate a final response:

Permission handling implementation is comprehensive and correct

The implementation properly handles project access permissions through:

  1. Correct usage of EUserPermissions enum with proper hierarchy (GUEST < MEMBER < ADMIN)
  2. Proper permission level checks using EUserPermissionsLevel.PROJECT
  3. Consistent permission validation using allowPermissions helper across components
  4. Appropriate UI states:
    • Loading spinner when checking permissions
    • JoinProject component for unauthorized access
    • Project not found state with proper messaging
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for comprehensive test coverage of permission-related scenarios

# Look for test files related to ProjectAuthWrapper
fd -e test.tsx -e spec.tsx "project.*wrapper"

# Check for permission-related test cases
rg -A 5 "test\(.*permission.*private.*project" 

# Look for related permission constants
rg "EUserPermissions|EUserPermissionsLevel" 

Length of output: 57293

apiserver/plane/app/views/project/base.py (1)

179-182: Consider API compatibility and caching implications

The new access restrictions might affect API clients and caching strategies:

  1. API clients should handle 404 responses appropriately when accessing restricted projects.
  2. Consider reviewing and updating any caching implementations to account for user-specific access restrictions.

Let's verify the API usage patterns:

@rahulramesha rahulramesha self-requested a review November 21, 2024 14:24
Copy link
Contributor

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

🧹 Outside diff range and nitpick comments (2)
apiserver/plane/app/views/project/invite.py (2)

139-144: Enhance error handling and improve error message clarity.

The current implementation has several areas for improvement:

  1. No handling for non-existent workspace_member
  2. Generic error message doesn't explain the required role
+        if not workspace_member:
+            return Response(
+                {"error": "You are not a member of this workspace"},
+                status=status.HTTP_403_FORBIDDEN,
+            )
+
         if workspace_member.role != 20:
             return Response(
-                {"error": "You do not have permission to join the project"},
+                {"error": "Only workspace admins can join projects directly. Please request an invitation from a project admin."},
                 status=status.HTTP_403_FORBIDDEN,
             )

139-144: Add docstring to explain the permission model.

The method lacks documentation about the role-based access control model being implemented.

     def create(self, request, slug):
+        """
+        Handle bulk project joining requests.
+        
+        This endpoint is restricted to workspace admins (role=20) only as part of
+        the private project access control system. Other members must be explicitly
+        invited to join projects.
+        
+        Args:
+            request: The HTTP request object containing project_ids in the data
+            slug: The workspace slug
+            
+        Returns:
+            Response: HTTP 201 if successful, HTTP 403 if permission denied
+        """
         project_ids = request.data.get("project_ids", [])
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 64f22d5 and c6ff747.

📒 Files selected for processing (1)
  • apiserver/plane/app/views/project/invite.py (1 hunks)

apiserver/plane/app/views/project/invite.py Outdated Show resolved Hide resolved
@pushya22 pushya22 requested a review from aaryan610 November 21, 2024 14:44
@sriramveeraghanta sriramveeraghanta merged commit 6ef6282 into preview Nov 22, 2024
13 of 15 checks passed
@sriramveeraghanta sriramveeraghanta deleted the chore/project-restriction branch November 22, 2024 10:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants