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

minor improvements for workspace management #6099

Merged
merged 2 commits into from
Nov 29, 2024

Conversation

prateekshourya29
Copy link
Member

@prateekshourya29 prateekshourya29 commented Nov 27, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced slug validation to ensure uniqueness in a case-insensitive manner.
    • Improved slug matching logic for workspace checks, allowing case variations.
    • Accessibility improvements added to the Workspace Icon for better screen reader support.
  • Bug Fixes

    • Fixed potential issues with URL encoding for workspace slugs.
  • Refactor

    • Updated methods for better clarity and maintainability in URL construction.
  • Style

    • Improved formatting of SVG attributes for better readability.

Copy link
Contributor

coderabbitai bot commented Nov 27, 2024

Walkthrough

The changes in this pull request focus on improving the handling of workspace slugs across various components. Key modifications include the use of template literals and encodeURIComponent for URL encoding in the WorkspaceListItem, a shift to URLSearchParams for constructing API request URLs in the WorkspaceService, enhanced type safety in the WorkspaceStore, and improved slug validation in the WorkspaceSerializer. Additionally, the slug matching logic in API endpoints has been updated to be case-insensitive, ensuring better flexibility and error handling during workspace creation.

Changes

File Path Change Summary
admin/core/components/workspace/list-item.tsx Updated href attribute in Link component to use template literals and encodeURIComponent.
admin/core/services/workspace.service.ts Modified workspaceSlugCheck to use URLSearchParams for constructing API request URLs.
admin/core/store/workspace.store.ts Changed hydrate method parameter type from any to Record<string, IWorkspace> for type safety.
apiserver/plane/license/api/serializers/workspace.py Added case-insensitive uniqueness check in validate_slug method of WorkspaceSerializer.
apiserver/plane/license/api/views/workspace.py Updated slug existence check to be case-insensitive in InstanceWorkSpaceAvailabilityCheckEndpoint.
packages/ui/src/icons/workspace-icon.tsx Added accessibility attributes to <svg> in WorkspaceIcon component for improved screen reader support.

Possibly related PRs

Suggested labels

🌐frontend, 🧹chore, 🌟improvement

Suggested reviewers

  • SatishGandham
  • rahulramesha
  • pablohashescobar

🐰 In the workspace where we hop and play,
Slugs are now safe, come what may.
With URLs clear and cases bright,
Our paths are now a joyful sight!
So let’s celebrate with a little cheer,
For a workspace that’s better, let’s give a cheer! 🎉


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4b436dc and 45192c4.

📒 Files selected for processing (1)
  • packages/ui/src/icons/workspace-icon.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/ui/src/icons/workspace-icon.tsx

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

🧹 Outside diff range and nitpick comments (7)
apiserver/plane/license/api/serializers/workspace.py (2)

21-23: Consider adding a database index for performance.

The __iexact lookup might not efficiently use the default index. Consider adding a functional index for case-insensitive lookups if you expect a large number of workspaces.

Example migration:

from django.contrib.postgres.operations import CreateIndex
from django.db import migrations

class Migration(migrations.Migration):
    dependencies = [
        ('your_app', 'previous_migration'),
    ]

    operations = [
        migrations.AddIndex(
            model_name='workspace',
            index=models.Index(
                Lower('slug'),
                name='workspace_slug_lower_idx'
            ),
        ),
    ]

21-23: Consider adding transaction-level protection.

There's a potential race condition between validation and creation. Consider using select_for_update() or unique constraints at the database level.

Example implementation:

 def validate_slug(self, value):
     if value in RESTRICTED_WORKSPACE_SLUGS:
         raise serializers.ValidationError("Slug is not valid")
-    if Workspace.objects.filter(slug__iexact=value).exists():
+    # Use select_for_update() to prevent race conditions
+    with transaction.atomic():
+        if Workspace.objects.select_for_update().filter(slug__iexact=value).exists():
             raise serializers.ValidationError("Slug is already in use")
     return value
admin/core/components/workspace/list-item.tsx (1)

25-25: Consider extracting workspace URL construction to a helper function

Since workspace URL construction might be needed in multiple places, consider extracting this logic into a reusable helper function:

// helpers/workspace.helper.ts
export const getWorkspaceUrl = (slug: string): string => 
  `${WEB_BASE_URL}/${encodeURIComponent(slug)}`;

// Usage in component:
href={getWorkspaceUrl(workspace.slug)}

This would ensure consistent URL construction across the application and make it easier to modify the pattern if needed.

apiserver/plane/license/api/views/workspace.py (3)

Line range hint 89-91: Enhance error handling specificity for IntegrityError.

The current error message doesn't distinguish between different types of uniqueness violations. Consider extracting the specific field from the IntegrityError for more precise error messaging.

 except IntegrityError as e:
-    if "already exists" in str(e):
+    error_message = str(e)
+    if "slug" in error_message and "already exists" in error_message:
         return Response(
             {"slug": "The workspace with the slug already exists"},
             status=status.HTTP_410_GONE,
         )
+    return Response(
+        {"error": "An error occurred while creating the workspace"},
+        status=status.HTTP_400_BAD_REQUEST,
+    )

Line range hint 82-86: Consider using database transaction for atomic operations.

The workspace creation and member creation should be wrapped in a transaction to ensure both operations succeed or fail together.

+from django.db import transaction

     if serializer.is_valid(raise_exception=True):
+        with transaction.atomic():
             serializer.save(owner=request.user)
             # Create Workspace member
             _ = WorkspaceMember.objects.create(

Add validation for company_role field

The company_role field is defined as a TextField in the model with no constraints and is accepted without validation in the serializer. To maintain data quality, you should:

  • Add max_length validation in the model to prevent excessively long inputs
  • Add validation in the serializer using either CharField with max_length or custom validation method
  • Consider adding format validation if there's an expected structure for company roles

Example locations that need changes:

  • apiserver/plane/db/models/workspace.py: Update TextField definition with max_length
  • apiserver/plane/license/api/serializers/workspace.py: Add validation rules for company_role
🔗 Analysis chain

Line range hint 84-86: Validate company_role field.

The company_role field is accepted without validation. Consider adding length and format validation to prevent potential issues.


Let me check the serializer to see if there are any validations defined there.


Let me check the complete serializer definition to see all fields and their validations.


Let me check the model definition to understand the field constraints at the database level.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any existing validation on company_role field
rg -A 5 'company_role' --type py

Length of output: 2313


Script:

#!/bin/bash
# Check for workspace serializer definitions
rg -l "WorkspaceSerializer" --type py | xargs rg -A 10 "class WorkspaceSerializer"

Length of output: 1171


Script:

#!/bin/bash
# Get the complete workspace serializer definition
rg -A 30 "class WorkspaceSerializer" apiserver/plane/license/api/serializers/workspace.py

Length of output: 1032


Script:

#!/bin/bash
# Get the complete workspace model definition
rg -B 5 -A 10 "company_role = models\." apiserver/plane/db/models/workspace.py

Length of output: 756

admin/core/store/workspace.store.ts (1)

62-65: Consider adding input validation for better runtime safety.

While the type safety improvement is great, consider adding runtime validation since the data might come from external sources (API/storage). This would help catch malformed data early.

Here's a suggested implementation:

  hydrate = (data: Record<string, IWorkspace>) => {
-   if (data) this.workspaces = data;
+   if (!data) return;
+   
+   // Validate the structure of incoming data
+   Object.entries(data).forEach(([key, workspace]) => {
+     if (typeof key !== 'string' || !workspace?.id) {
+       console.warn('Invalid workspace data structure detected:', { key, workspace });
+       return;
+     }
+     this.workspaces[key] = workspace;
+   });
  };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 05d3e3a and 4b436dc.

📒 Files selected for processing (6)
  • admin/core/components/workspace/list-item.tsx (1 hunks)
  • admin/core/services/workspace.service.ts (1 hunks)
  • admin/core/store/workspace.store.ts (2 hunks)
  • apiserver/plane/license/api/serializers/workspace.py (1 hunks)
  • apiserver/plane/license/api/views/workspace.py (1 hunks)
  • packages/ui/src/icons/workspace-icon.tsx (1 hunks)
🔇 Additional comments (6)
apiserver/plane/license/api/serializers/workspace.py (2)

21-23: LGTM! Case-insensitive validation is a good addition.

This change prevents confusion and potential conflicts with similarly-cased workspace slugs.


21-23: Verify existing data for case-insensitive conflicts.

Let's check if there are any existing workspaces that might conflict with the new case-insensitive validation.

✅ Verification successful

Based on the model definition, I can now generate the final response:

Case-insensitive validation is safe to implement

The workspace model already has a unique constraint on the slug field (unique=True), and the migration history shows no conflicting constraints. The new case-insensitive validation in the serializer adds an extra layer of validation without risking data integrity since:

  • The database-level constraint prevents any duplicates (case-sensitive)
  • The new serializer validation prevents case-insensitive duplicates before reaching the database
  • The slug_validator only checks for restricted slugs, not case sensitivity
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for existing case-insensitive workspace slug conflicts
# Expected results: No output means no conflicts

# Search for workspace model definition to confirm the fields
rg -l "class Workspace\(" 

# Search for existing migrations to understand the current schema
fd -e py -p ".*migrations.*workspace.*"

Length of output: 586


Script:

#!/bin/bash
# Let's examine the workspace model and migrations to understand the current schema and constraints

# Check the workspace model definition
cat apiserver/plane/db/models/workspace.py

# Check the migration that alters workspace unique constraints
cat apiserver/plane/db/migrations/0017_alter_workspace_unique_together.py

Length of output: 11742

admin/core/services/workspace.service.ts (1)

33-34: LGTM! Good improvement using URLSearchParams

The switch to URLSearchParams is a better approach as it:

  • Handles URL encoding automatically and safely
  • Makes the code more maintainable
  • Follows modern JavaScript/TypeScript practices

Let's verify that workspace slugs are properly encoded throughout the codebase:

✅ Verification successful

URLSearchParams is correctly used, no other instances need updating

The codebase scan shows that URL parameter handling is done safely throughout the codebase. The instances found are either:

  1. Reading parameters from URLs using params.get() which is safe
  2. Using template literals in route definitions which don't require encoding
  3. Using URLSearchParams in API calls where needed

The original review comment's concern about workspace slug encoding has been properly addressed in the changed code, and no other unsafe URL parameter concatenation patterns were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential direct string concatenation with workspace slugs
# that might need similar URLSearchParams treatment

# Look for potential unencoded workspace slug usage in URL construction
rg -g '*.{ts,tsx,js,jsx}' -A 3 'workspace.*slug.*\?' --ignore-case

# Look for direct string concatenation in URL construction
ast-grep --pattern 'url + "?" + param'

Length of output: 101337

packages/ui/src/icons/workspace-icon.tsx (1)

6-13: Great addition of accessibility attributes!

The addition of role="img" and aria-label improves the accessibility of the icon for screen readers. The new formatting also enhances code readability.

apiserver/plane/license/api/views/workspace.py (1)

Line range hint 13-13: Verify InstanceAdminPermission implementation.

The endpoint is protected with InstanceAdminPermission. Let's verify its implementation to ensure proper access control.

✅ Verification successful

InstanceAdminPermission implementation is secure and properly configured

The permission class implements proper access control with the following security measures:

  • Blocks anonymous users
  • Validates against a single instance admin role (20 = "Admin")
  • Requires role >= 15 which ensures only admin users can access
  • Uses proper model relationships and existence checks
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the implementation of InstanceAdminPermission
rg -A 10 'class InstanceAdminPermission' --type py

Length of output: 847


Script:

#!/bin/bash
# Check the role field definition and possible values
rg -A 5 'class InstanceAdmin' --type py

Length of output: 4691


Script:

#!/bin/bash
# Check for role field definition and constants
rg -A 5 'role = models\.' --type py

Length of output: 3208


Script:

#!/bin/bash
# Check for ROLE_CHOICES definition in instance related files
rg 'ROLE_CHOICES.*=' apiserver/plane/license/models/instance.py -A 5

Length of output: 407

admin/core/store/workspace.store.ts (1)

17-17: LGTM! Great type safety improvement.

The change from any to Record<string, IWorkspace> enhances type safety by explicitly defining the expected data structure, which matches the store's workspaces property type.

xmlns="http://www.w3.org/2000/svg"
className={className}
role="img"
aria-abel="Workspace icon"
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 typo in aria-label attribute

There's a typo in the accessibility attribute: aria-abel should be aria-label.

-    aria-abel="Workspace icon"
+    aria-label="Workspace icon"
📝 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
aria-abel="Workspace icon"
aria-label="Workspace icon"

admin/core/components/workspace/list-item.tsx Show resolved Hide resolved
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