Skip to content

chore: updating the workspace slug when we the delete the workspace#6140

Closed
gurusainath wants to merge 2 commits intopreviewfrom
chore-workspace-delete
Closed

chore: updating the workspace slug when we the delete the workspace#6140
gurusainath wants to merge 2 commits intopreviewfrom
chore-workspace-delete

Conversation

@gurusainath
Copy link
Member

@gurusainath gurusainath commented Dec 3, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced workspace deletion process with improved identification and handling.
    • Added permission checks for listing and partially updating workspaces.
  • Bug Fixes

    • Clarified unpacking syntax in the create method for better readability.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 3, 2024

Walkthrough

The changes involve modifications to the WorkSpaceViewSet class in the apiserver/plane/app/views/workspace/base.py file. The create method's unpacking syntax has been clarified, while the destroy method has been significantly restructured to accept a slug parameter for workspace identification and deletion. Additionally, the list and partial_update methods have been updated with permission decorators to enhance access control. These changes improve method functionality, clarity, and permission handling.

Changes

File Path Change Summary
apiserver/plane/app/views/workspace/base.py - Updated create method for clearer unpacking of get_configuration_value.
- Modified destroy method to accept a slug parameter, retrieve the workspace, and handle deletion with a timestamped slug.
- Added @allow_permission decorator to list and partial_update methods for access control.

Possibly related PRs

  • minor improvements for workspace management #6099: The changes in the WorkspaceSerializer class regarding slug validation are related to the modifications in the destroy method of the WorkSpaceViewSet, as both involve handling workspace slugs and ensuring their uniqueness or proper identification.

Suggested reviewers

  • SatishGandham
  • sriramveeraghanta

Poem

In the workspace where bunnies play,
Changes hop in a bright array.
With slugs and timestamps, we now delete,
A clearer path, oh what a treat!
Permissions guard our joyful quest,
In this code, we surely invest! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between be9eec1 and f842b73.

📒 Files selected for processing (1)
  • apiserver/plane/app/views/workspace/base.py (3 hunks)
🔇 Additional comments (3)
apiserver/plane/app/views/workspace/base.py (3)

85-90: LGTM! Improved unpacking syntax.

The addition of parentheses around the unpacked variable makes it clearer that we're expecting a single value from get_configuration_value. This is a good readability improvement.


149-154: LGTM! Improved error handling.

The try-except block is the correct way to handle potential DoesNotExist exceptions when retrieving the workspace.


156-164: ⚠️ Potential issue

Add transaction management and improve slug handling.

Several improvements needed for robustness:

  1. The slug truncation might affect uniqueness by cutting off the epoch
  2. Operations should be atomic
  3. Should validate against restricted slugs

This issue was previously identified. Please refer to the existing solution that includes transaction management and better slug handling:

+from django.db import transaction
+from plane.utils.constants import RESTRICTED_WORKSPACE_SLUGS

-        # Trash the workspace by appending the epoch and `trash` to the slug
-        epoch = int(timezone.now().timestamp())
-        updated_workspace_slug = f"trash-{epoch}-{workspace.slug}"
-        if len(updated_workspace_slug) > 48:
-            updated_workspace_slug = updated_workspace_slug[:48]
-
-        workspace.slug = updated_workspace_slug
-        workspace.save()
-        workspace.delete()
+        with transaction.atomic():
+            epoch = int(timezone.now().timestamp())
+            base_slug = workspace.slug[:20]  # Preserve start of original slug
+            updated_workspace_slug = f"trash-{epoch}-{base_slug}"
+            
+            # Ensure the new slug isn't in restricted list
+            if updated_workspace_slug in RESTRICTED_WORKSPACE_SLUGS:
+                updated_workspace_slug = f"deleted-{updated_workspace_slug}"
+                
+            workspace.slug = updated_workspace_slug[:48]
+            workspace.save()
+            workspace.delete()

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

🧹 Outside diff range and nitpick comments (1)
apiserver/plane/app/views/workspace/base.py (1)

148-164: Consider adding audit logging for workspace deletion.

For better traceability, consider logging the workspace deletion event with relevant details like the original slug, actor, timestamp, etc.

Example implementation:

from django.contrib.admin.models import LogEntry, DELETION
from django.contrib.contenttypes.models import ContentType

def destroy(self, request, slug):
    # ... existing code ...
    
    # Add audit log
    LogEntry.objects.log_action(
        user_id=request.user.id,
        content_type_id=ContentType.objects.get_for_model(workspace).pk,
        object_id=workspace.id,
        object_repr=str(workspace),
        action_flag=DELETION,
        change_message=f"Workspace deleted. Original slug: {original_slug}"
    )
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 849d989 and be9eec1.

📒 Files selected for processing (1)
  • apiserver/plane/app/views/workspace/base.py (3 hunks)
🔇 Additional comments (2)
apiserver/plane/app/views/workspace/base.py (2)

85-90: LGTM! Clearer unpacking syntax.

The parentheses make it more explicit that we're unpacking a single value from the configuration.


Line range hint 134-147: LGTM! Good security practice with role-based access control.

The permission decorators properly restrict access:

  • List endpoint accessible to all workspace roles (admin, member, guest)
  • Partial update endpoint restricted to admin role only

Comment on lines 149 to 153
workspace = Workspace.objects.get(slug=slug)
if workspace is None:
return Response(
{"error": "Workspace not found"}, status=status.HTTP_404_NOT_FOUND
)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the workspace existence check logic.

The current implementation is incorrect:

  • Workspace.objects.get() raises DoesNotExist exception if not found
  • The None check will never execute

Replace with:

-        workspace = Workspace.objects.get(slug=slug)
-        if workspace is None:
-            return Response(
-                {"error": "Workspace not found"}, status=status.HTTP_404_NOT_FOUND
-            )
+        try:
+            workspace = Workspace.objects.get(slug=slug)
+        except Workspace.DoesNotExist:
+            return Response(
+                {"error": "Workspace not found"}, status=status.HTTP_404_NOT_FOUND
+            )
📝 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.

Suggested change
workspace = Workspace.objects.get(slug=slug)
if workspace is None:
return Response(
{"error": "Workspace not found"}, status=status.HTTP_404_NOT_FOUND
)
try:
workspace = Workspace.objects.get(slug=slug)
except Workspace.DoesNotExist:
return Response(
{"error": "Workspace not found"}, status=status.HTTP_404_NOT_FOUND
)

Comment on lines +155 to +163
# Trash the workspace by appending the epoch and `trash` to the slug
epoch = int(timezone.now().timestamp())
updated_workspace_slug = f"trash-{epoch}-{workspace.slug}"
if len(updated_workspace_slug) > 48:
updated_workspace_slug = updated_workspace_slug[:48]

workspace.slug = updated_workspace_slug
workspace.save()
workspace.delete()
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add transaction management and improve slug handling.

Several improvements needed for robustness:

  1. The slug truncation might affect uniqueness by cutting off the epoch
  2. Operations should be atomic
  3. Should validate against restricted slugs

Consider this implementation:

+from django.db import transaction
+from plane.utils.constants import RESTRICTED_WORKSPACE_SLUGS

-        # Trash the workspace by appending the epoch and `trash` to the slug
-        epoch = int(timezone.now().timestamp())
-        updated_workspace_slug = f"trash-{epoch}-{workspace.slug}"
-        if len(updated_workspace_slug) > 48:
-            updated_workspace_slug = updated_workspace_slug[:48]
-
-        workspace.slug = updated_workspace_slug
-        workspace.save()
-        workspace.delete()
+        with transaction.atomic():
+            epoch = int(timezone.now().timestamp())
+            base_slug = workspace.slug[:20]  # Preserve start of original slug
+            updated_workspace_slug = f"trash-{epoch}-{base_slug}"
+            
+            # Ensure the new slug isn't in restricted list
+            if updated_workspace_slug in RESTRICTED_WORKSPACE_SLUGS:
+                updated_workspace_slug = f"deleted-{updated_workspace_slug}"
+                
+            workspace.slug = updated_workspace_slug[:48]
+            workspace.save()
+            workspace.delete()
📝 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.

Suggested change
# Trash the workspace by appending the epoch and `trash` to the slug
epoch = int(timezone.now().timestamp())
updated_workspace_slug = f"trash-{epoch}-{workspace.slug}"
if len(updated_workspace_slug) > 48:
updated_workspace_slug = updated_workspace_slug[:48]
workspace.slug = updated_workspace_slug
workspace.save()
workspace.delete()
from django.db import transaction
from plane.utils.constants import RESTRICTED_WORKSPACE_SLUGS
with transaction.atomic():
epoch = int(timezone.now().timestamp())
base_slug = workspace.slug[:20] # Preserve start of original slug
updated_workspace_slug = f"trash-{epoch}-{base_slug}"
# Ensure the new slug isn't in restricted list
if updated_workspace_slug in RESTRICTED_WORKSPACE_SLUGS:
updated_workspace_slug = f"deleted-{updated_workspace_slug}"
workspace.slug = updated_workspace_slug[:48]
workspace.save()
workspace.delete()

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.

3 participants