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

*Permission.get_scopes: don't tolerate unknown actions #8426

Merged
merged 1 commit into from
Sep 10, 2024

Conversation

SpecLad
Copy link
Contributor

@SpecLad SpecLad commented Sep 10, 2024

Motivation and context

With almost all of the get_scopes methods, an unknown (action, method) combination will result in an array like [None] being returned (sometimes with other elements as well). If that happens, the OPA input will then have "scope": null, and so the policy evaluation will fail, unless the user is an admin.

Because of this, it's really easy to accidentally make a view admin-only, by forgetting to add/update an entry in get_scopes when making changes.

TaskPermission, MembershipPermission and WebhookPermission are even worse, because they will just return an empty list of scopes, which will later translate to an empty list of permissions, which means that everyone will be permitted to perform the action. This can lead to vulnerabilities like CVE-2024-45393.

Fix this by replacing all .get calls with indexing, which will cause a crash if the (action, method) combo is unknown. This breaks one endpoint (/api/webhooks/events), which is supposed to be publicly accessible; fix that by disabling authorization for it.

How has this been tested?

Checklist

  • I submit my changes into the develop branch
  • [ ] I have created a changelog fragment
  • [ ] I have updated the documentation accordingly
  • [ ] I have added tests to cover my changes
  • [ ] I have linked related issues (see GitHub docs)
  • [ ] I have increased versions of npm packages if it is necessary
    (cvat-canvas,
    cvat-core,
    cvat-data and
    cvat-ui)

License

  • I submit my code changes under the same MIT License that covers the project.
    Feel free to contact the maintainers if that's a concern.

Summary by CodeRabbit

  • New Features

    • Introduced stricter error handling in permission checks, ensuring only valid actions are processed.
    • Updated the events endpoint to allow unrestricted access by modifying permission requirements.
  • Bug Fixes

    • Enhanced robustness of permission handling logic across various modules by enforcing stricter key access.
  • Refactor

    • Simplified conditional logic in scope retrieval processes for clearer control flow.

With almost all of the `get_scopes` methods, an unknown (action, method)
combination will result in an array like `[None]` being returned (sometimes
with other elements as well). If that happens, the OPA input will then have
`"scope": null`, and so the policy evaluation will fail, unless the user is
an admin.

Because of this, it's really easy to accidentally make a view admin-only,
by forgetting to add/update an entry in `get_scopes` when making changes.

`TaskPermission`, `MembershipPermission` and `WebhookPermission` are even
worse, because they will just return an empty list of scopes, which will
later translate to an empty list of permissions, which means that everyone
will be permitted to perform the action. This can lead to vulnerabilities
like CVE-2024-45393.

Fix this by replacing all `.get` calls with indexing, which will cause
a crash if the (action, method) combo is unknown. This breaks one endpoint
(`/api/webhooks/events`), which is supposed to be publicly accessible;
fix that by disabling authorization for it.
@SpecLad SpecLad requested a review from Marishka17 as a code owner September 10, 2024 11:11
Copy link
Contributor

coderabbitai bot commented Sep 10, 2024

Walkthrough

The pull request introduces changes across multiple files in the CVAT codebase, primarily focusing on the get_scopes function within various permissions.py files. The modifications involve replacing the use of the .get() method for dictionary access with direct indexing, which raises a KeyError for undefined keys. This adjustment enforces stricter error handling for invalid actions and simplifies the control flow in scope retrieval. Additionally, a modification in views.py allows for unrestricted access to the events endpoint by specifying an empty list for permission_classes.

Changes

Files Change Summary
cvat/apps/analytics_report/permissions.py
cvat/apps/engine/permissions.py
cvat/apps/events/permissions.py
cvat/apps/lambda_manager/permissions.py
cvat/apps/log_viewer/permissions.py
cvat/apps/organizations/permissions.py
cvat/apps/quality_control/permissions.py
cvat/apps/webhooks/permissions.py
Modified the get_scopes function to replace .get() with direct indexing for dictionary access, enforcing stricter error handling for invalid actions.
cvat/apps/webhooks/views.py Added a permission_classes parameter set to an empty list in the @action decorator for the events method, allowing unrestricted access to this endpoint.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant Permissions

    Client->>Server: Request action
    Server->>Permissions: Check action validity
    alt Action valid
        Permissions-->>Server: Return scopes
        Server-->>Client: Respond with data
    else Action invalid
        Permissions-->>Server: Raise KeyError
        Server-->>Client: Respond with error
    end
Loading

🐰 "In the code where actions play,
A change was made today!
No more get to softly fall,
Direct access stands tall.
With strictness in our scope,
We hop along with hope!" 🐇

Tip

Announcements
  • The review status is no longer posted as a separate comment when there are no actionable or nitpick comments. In such cases, the review status is included in the walkthrough comment.
  • We have updated our review workflow to use the Anthropic's Claude family of models. Please share any feedback in the discussion post on our Discord.
  • Possibly related PRs: Walkthrough comment now includes a list of potentially related PRs to help you recall past context. Please share any feedback in the discussion post on our Discord.
  • Suggested labels: CodeRabbit can now suggest labels by learning from your past PRs in the walkthrough comment. You can also provide custom labeling instructions in the UI or configuration file.
  • Possibly related PRs, automatic label suggestions based on past PRs, learnings, and possibly related issues require data opt-in (enabled by default).

Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 264e828 and c95fa3f.

Files selected for processing (9)
  • cvat/apps/analytics_report/permissions.py (1 hunks)
  • cvat/apps/engine/permissions.py (13 hunks)
  • cvat/apps/events/permissions.py (1 hunks)
  • cvat/apps/lambda_manager/permissions.py (1 hunks)
  • cvat/apps/log_viewer/permissions.py (1 hunks)
  • cvat/apps/organizations/permissions.py (3 hunks)
  • cvat/apps/quality_control/permissions.py (3 hunks)
  • cvat/apps/webhooks/permissions.py (1 hunks)
  • cvat/apps/webhooks/views.py (1 hunks)
Additional comments not posted (20)
cvat/apps/log_viewer/permissions.py (1)

33-33: Verify the impact of replacing .get with direct indexing.

The change enforces stricter error handling by raising a KeyError if view.action does not correspond to a valid key in the Scopes dictionary. This can potentially lead to runtime exceptions if this assumption is violated.

Verify that all possible values of view.action are handled and have a corresponding entry in the Scopes dictionary. Use the following script to search for all occurrences of view.action and ensure they are valid:

Verification successful

Verification successful: The change to direct indexing is consistent with usage patterns.

The change to use direct indexing instead of .get for view.action aligns with the codebase's usage patterns, where view.action is expected to match predefined keys in the Scopes dictionary. This ensures stricter error handling without introducing runtime exceptions, as long as view.action is set to one of these predefined keys.

  • The Scopes dictionary or enumeration includes mappings for actions like 'list', 'create', 'destroy', etc., which are consistent with the expected values of view.action.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all possible values of `view.action` are handled.

# Test: Search for all occurrences of `view.action`. Expect: Only valid values.
rg --type python -w $'view\.action'

Length of output: 67


Script:

#!/bin/bash
# Description: Verify all possible values of `view.action` are handled.

# Test: Search for all occurrences of `view.action`. Expect: Only valid values.
rg --type py -w $'view\.action'

Length of output: 2072


Script:

#!/bin/bash
# Description: Identify possible values of `view.action`.

# Search for assignments or definitions of `view.action`.
rg --type py -A 3 $'view\.action\s*='

Length of output: 1686


Script:

#!/bin/bash
# Description: Verify the definition of `Scopes` to ensure it includes all possible values of `view.action`.

# Search for the definition of `Scopes`.
rg --type py -A 5 $'Scopes\s*='

Length of output: 12037

cvat/apps/events/permissions.py (1)

53-53: Verify the impact of replacing .get with direct indexing.

The change makes the function less forgiving to invalid keys by raising a KeyError if the (view.action, request.method) tuple key is not found in the dictionary. This can potentially lead to unhandled exceptions if the provided action and method combination is not defined.

Verify that all possible combinations of view.action and request.method are handled and have a corresponding entry in the dictionary. Use the following script to search for all occurrences of view.action and request.method, and ensure they form valid tuple keys:

cvat/apps/lambda_manager/permissions.py (1)

52-52: Verify the impact of replacing .get with direct indexing.

The change affects the control flow by potentially introducing an exception handling scenario if an invalid (view.basename, view.action) tuple key is provided. This alters the error management strategy of the function.

Verify that all possible combinations of view.basename and view.action are handled and have a corresponding entry in the dictionary. Use the following script to search for all occurrences of view.basename and view.action, and ensure they form valid tuple keys:

cvat/apps/analytics_report/permissions.py (1)

73-73: LGTM! The change from .get to direct indexing [] is a good improvement.

Using direct indexing }[view.action] instead of .get(view.action, None) enforces that only valid actions defined in the dictionary can be used. If an invalid action is provided, a KeyError will be raised immediately, making it easier to catch and handle the error.

This change makes the code stricter and less tolerant of invalid actions, which is a good practice to fail fast and avoid unexpected behavior.

cvat/apps/webhooks/permissions.py (2)

65-65: LGTM! The change from .get to direct indexing [] is a good improvement.

Using direct indexing }[(view.action, request.method)] instead of .get((view.action, request.method), None) enforces that only valid action-method combinations defined in the dictionary can be used. If an invalid combination is provided, a KeyError will be raised immediately, making it easier to catch and handle the error.

This change makes the code stricter and less tolerant of invalid action-method combinations, which is a good practice to fail fast and avoid unexpected behavior.


73-73: LGTM! The change from elif to else simplifies the code.

Using an else condition instead of an elif condition to append the scope to the scopes list when the scope is not Scopes.CREATE streamlines the code and makes it more readable.

This change simplifies the logic without altering the functionality, which is a good practice to keep the code concise and maintainable.

cvat/apps/organizations/permissions.py (3)

45-45: LGTM! The change from .get to direct indexing [] is a good improvement.

Using direct indexing }[view.action] instead of .get(view.action, None) enforces that only valid actions defined in the dictionary can be used. If an invalid action is provided, a KeyError will be raised immediately, making it easier to catch and handle the error.

This change makes the code stricter and less tolerant of invalid actions, which is a good practice to fail fast and avoid unexpected behavior.


175-175: LGTM! The change from .get to direct indexing [] is a good improvement.

Using direct indexing }[view.action] instead of .get(view.action, None) enforces that only valid actions defined in the dictionary can be used. If an invalid action is provided, a KeyError will be raised immediately, making it easier to catch and handle the error.

This change makes the code stricter and less tolerant of invalid actions, which is a good practice to fail fast and avoid unexpected behavior.


180-180: LGTM! The change from elif to else simplifies the code.

Using an else condition instead of an elif condition to append the scope to the scopes list when the scope is not Scopes.UPDATE streamlines the code and makes it more readable.

This change simplifies the logic without altering the functionality, which is a good practice to keep the code concise and maintainable.

cvat/apps/webhooks/views.py (1)

112-114: LGTM!

The changes to the events method are approved.

Setting permission_classes to an empty list disables authorization for the /api/webhooks/events endpoint, allowing unrestricted access. This aligns with the PR objective to make this endpoint publicly accessible.

cvat/apps/quality_control/permissions.py (3)

88-88: LGTM, but verify error handling for undefined actions.

The changes to the get_scopes function in the QualityReportPermission class are approved.

Replacing .get() with direct indexing enforces stricter handling of actions by raising a KeyError if view.action is not found in the dictionary. This removes the fallback mechanism for undefined actions.

Please verify that appropriate error handling is in place for scenarios where an undefined action is encountered. Ensure that the code gracefully handles the KeyError and returns a suitable error response.


161-161: LGTM, but verify error handling for undefined actions.

The changes to the get_scopes function in the AnnotationConflictPermission class are approved.

Replacing .get() with direct indexing enforces stricter handling of actions by raising a KeyError if view.action is not found in the dictionary. This removes the fallback mechanism for undefined actions.

Please verify that appropriate error handling is in place for scenarios where an undefined action is encountered. Ensure that the code gracefully handles the KeyError and returns a suitable error response.


228-228: LGTM, but verify error handling for undefined actions.

The changes to the get_scopes function in the QualitySettingPermission class are approved.

Replacing .get() with direct indexing enforces stricter handling of actions by raising a KeyError if view.action is not found in the dictionary. This removes the fallback mechanism for undefined actions.

Please verify that appropriate error handling is in place for scenarios where an undefined action is encountered. Ensure that the code gracefully handles the KeyError and returns a suitable error response.

cvat/apps/engine/permissions.py (7)

68-68: LGTM, but verify error handling for undefined action-method combinations.

The changes to the get_scopes function in the ServerPermission class are approved.

Replacing .get() with direct indexing enforces stricter handling by raising a KeyError if the tuple (view.action, request.method) is not found in the dictionary. This removes the fallback mechanism for undefined action-method combinations.

Please verify that appropriate error handling is in place for scenarios where an undefined action-method combination is encountered. Ensure that the code gracefully handles the KeyError and returns a suitable error response.


103-103: LGTM, but verify error handling for undefined actions.

The changes to the get_scopes function in the UserPermission class are approved.

Replacing .get() with direct indexing enforces stricter handling of actions by raising a KeyError if view.action is not found in the dictionary. This removes the fallback mechanism for undefined actions.

Please verify that appropriate error handling is in place for scenarios where an undefined action is encountered. Ensure that the code gracefully handles the KeyError and returns a suitable error response.


181-181: LGTM, but verify error handling for undefined actions.

The changes to the get_scopes function in the CloudStoragePermission class are approved.

Replacing .get() with direct indexing enforces stricter handling of actions by raising a KeyError if view.action is not found in the dictionary. This removes the fallback mechanism for undefined actions.

Please verify that appropriate error handling is in place for scenarios where an undefined action is encountered. Ensure that the code gracefully handles the KeyError and returns a suitable error response.


284-284: LGTM, but verify error handling for undefined action-method combinations.

The changes to the get_scopes function in the ProjectPermission class are approved.

Replacing .get() with direct indexing enforces stricter handling by raising a KeyError if the tuple (view.action, request.method) is not found in the dictionary. This removes the fallback mechanism for undefined action-method combinations.

Please verify that appropriate error handling is in place for scenarios where an undefined action-method combination is encountered. Ensure that the code gracefully handles the KeyError and returns a suitable error response.


501-501: LGTM, but verify error handling for undefined action-method combinations.

The changes to the get_scopes function in the TaskPermission class are approved.

Replacing .get() with direct indexing enforces stricter handling by raising a KeyError if the tuple (view.action, request.method) is not found in the dictionary. This removes the fallback mechanism for undefined action-method combinations.

Please verify that appropriate error handling is in place for scenarios where an undefined action-method combination is encountered. Ensure that the code gracefully handles the KeyError and returns a suitable error response.


727-727: LGTM, but verify error handling for undefined action-method combinations.

The changes to the get_scopes function in the JobPermission class are approved.

Replacing .get() with direct indexing enforces stricter handling by raising a KeyError if the tuple (view.action, request.method) is not found in the dictionary. This removes the fallback mechanism for undefined action-method combinations.

Please verify that appropriate error handling is in place for scenarios where an undefined action-method combination is encountered. Ensure that the code gracefully handles the KeyError and returns a suitable error response.


847-847: LGTM, but verify error handling for undefined actions.

The changes to the get_scopes function in the CommentPermission class are approved.

Replacing .get() with direct indexing enforces stricter handling of actions by raising a KeyError if view.action is not found in the dictionary. This removes the fallback mechanism for undefined actions.

Please verify that appropriate error handling is in place for scenarios where an


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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

Quality Gate Failed Quality Gate failed

Failed conditions
6.9% Duplication on New Code (required ≤ 3%)

See analysis details on SonarCloud

@SpecLad SpecLad requested a review from nmanovic September 10, 2024 12:05
Copy link
Contributor

@nmanovic nmanovic left a comment

Choose a reason for hiding this comment

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

LGTM

@SpecLad SpecLad merged commit 2a07b6c into cvat-ai:develop Sep 10, 2024
33 of 34 checks passed
@SpecLad SpecLad deleted the mandatory-scopes branch September 10, 2024 14:24
bschultz96 pushed a commit to bschultz96/cvat that referenced this pull request Sep 12, 2024
With almost all of the `get_scopes` methods, an unknown (action, method)
combination will result in an array like `[None]` being returned
(sometimes with other elements as well). If that happens, the OPA input
will then have `"scope": null`, and so the policy evaluation will fail,
unless the user is an admin.

Because of this, it's really easy to accidentally make a view
admin-only, by forgetting to add/update an entry in `get_scopes` when
making changes.

`TaskPermission`, `MembershipPermission` and `WebhookPermission` are
even worse, because they will just return an empty list of scopes, which
will later translate to an empty list of permissions, which means that
everyone will be permitted to perform the action. This can lead to
vulnerabilities like CVE-2024-45393.

Fix this by replacing all `.get` calls with indexing, which will cause a
crash if the (action, method) combo is unknown. This breaks one endpoint
(`/api/webhooks/events`), which is supposed to be publicly accessible;
fix that by disabling authorization for it.
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