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

/api/events endpoint can be used to receive events not only from client #8799

Merged
merged 10 commits into from
Dec 18, 2024

Conversation

Eldies
Copy link
Contributor

@Eldies Eldies commented Dec 9, 2024

Motivation and context

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 a new permission scope for sending external events.
    • Added a method to log external events, accessible via a POST request.
  • Bug Fixes

    • Ensured existing event logging functionalities remain intact while integrating new features.

@Eldies Eldies requested a review from Marishka17 as a code owner December 9, 2024 12:24
Copy link
Contributor

coderabbitai bot commented Dec 9, 2024

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes introduce a new permission scope, SEND_EXTERNAL_EVENTS, to the EventsPermission class, enhancing the event handling model. This scope is mapped to the action external and the HTTP method POST. Additionally, a new method, external, is added to the EventsViewSet class, allowing for the logging of external events via a POST request. The method utilizes the EventSerializer for data validation and calls the record_server_event function, returning a 201 Created response. Existing methods remain unchanged, ensuring the overall structure is maintained.

Changes

File Change Summary
cvat/apps/events/permissions.py - Added new scope SEND_EXTERNAL_EVENTS to EventsPermission.Scopes.
- Updated get_scopes method to include mapping for ('external', 'POST').
cvat/apps/events/views.py - Added new method external to EventsViewSet for logging external events via POST.
- Updated imports for record_server_event and EventSerializer.

Poem

In the meadow, events do play,
New permissions hop and sway.
External calls now take their flight,
With data validated, all feels right.
A 201 cheer, let’s celebrate,
As rabbits dance, it’s truly great! 🐇✨


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 1

🧹 Outside diff range and nitpick comments (1)
cvat/apps/events/views.py (1)

50-54: Enhance OpenAPI documentation with error responses

The endpoint documentation should include possible error responses for better API understanding.

Add error responses to the @extend_schema decorator:

 @extend_schema(summary='Log external events',
     description='Sends logs to the Clickhouse if it is connected',
     parameters=ORGANIZATION_OPEN_API_PARAMETERS,
-    responses={'201': EventSerializer()})
+    responses={
+        '201': EventSerializer(),
+        '400': OpenApiResponse(description='Invalid event data'),
+        '403': OpenApiResponse(description='Permission denied'),
+        '429': OpenApiResponse(description='Too many requests'),
+    })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 094c62d and 014658f.

📒 Files selected for processing (2)
  • cvat/apps/events/permissions.py (2 hunks)
  • cvat/apps/events/views.py (3 hunks)
🔇 Additional comments (3)
cvat/apps/events/permissions.py (1)

18-18: LGTM! Permission scope addition is well-structured

The new SEND_EXTERNAL_EVENTS scope and its mapping are consistently implemented, following the existing patterns and naming conventions.

Also applies to: 54-54

cvat/apps/events/views.py (2)

10-10: LGTM! Clean import organization

The new imports are properly organized and necessary for the added functionality.

Also applies to: 19-19, 22-22


61-63: LGTM! Proper validation and event recording

The implementation correctly validates input data before recording the event.

Comment on lines 50 to 65
@extend_schema(summary='Log external events',
description='Sends logs to the Clickhouse if it is connected',
parameters=ORGANIZATION_OPEN_API_PARAMETERS,
responses={'201': EventSerializer()})
@action(
detail=False,
url_path='external',
methods=['POST'],
serializer_class=EventSerializer,
)
def external(self, request):
serializer = EventSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
record_server_event(**serializer.validated_data)

return Response(serializer.validated_data, status=status.HTTP_201_CREATED)
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Add rate limiting and request validation for external events endpoint

The external events endpoint currently lacks rate limiting and request size validation. While the system has some global settings, this endpoint needs specific protections:

  1. Add throttling class similar to ResendOrganizationInvitationThrottle but with appropriate rate for events
  2. Add request size validation (current global limit is 100MB which is too high for events)
  3. Consider adding field-level validation in the serializer

Example implementation:

class EventThrottleClass(UserRateThrottle):
    rate = '60/minute'  # Adjust based on requirements

@action(
    detail=False,
    url_path='external',
    methods=['POST'],
    throttle_classes=[EventThrottleClass],
    serializer_class=EventSerializer,
)
def external(self, request):
    # ... existing code
🔗 Analysis chain

Consider adding rate limiting and validation safeguards

While the implementation is structurally sound, consider adding the following security measures:

  1. Rate limiting to prevent DoS attacks
  2. Maximum size validation for event data
  3. Input sanitization for sensitive fields

Consider implementing rate limiting using Django's built-in tools or a dedicated rate-limiting middleware.

Let's check if rate limiting is implemented elsewhere in the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for rate limiting implementations
rg -A 3 "ratelimit|rate_limit|RateLimit" 

Length of output: 42


Script:

#!/bin/bash
# Let's check for any throttling or rate limiting related code using broader patterns
rg -i "(throttle|limit.*request|request.*limit)" -A 3

# Also check Django settings and middleware configurations
fd "settings|middleware" --type f --extension py --exec rg -l "(throttle|rate|limit)"

# Check for DRF throttling configurations
rg "throttle" --type py -A 3

Length of output: 80865


Script:

#!/bin/bash
# Let's check Django REST framework throttling configurations in settings
rg -A 5 "REST_FRAMEWORK.*=.*{" cvat/settings/base.py

# Check for any rate limiting middleware
rg -l "class.*Throttle|class.*RateLimit" --type py

# Check for any rate limiting decorators or configurations
rg "@.*throttle|@.*rate_limit" --type py

Length of output: 475


Script:

#!/bin/bash
# Let's check the content of the throttle class and settings
rg -A 10 "REST_FRAMEWORK" cvat/settings/base.py

# Check the throttle implementation
cat cvat/apps/organizations/throttle.py

# Check if there are any size limits in request configurations
rg -A 3 "DATA_UPLOAD_MAX_MEMORY_SIZE|DATA_UPLOAD_MAX_NUMBER_FIELDS|MAX_" cvat/settings/base.py

Length of output: 1721

@Eldies Eldies requested a review from SpecLad as a code owner December 9, 2024 12:42
@codecov-commenter
Copy link

codecov-commenter commented Dec 9, 2024

Codecov Report

Attention: Patch coverage is 80.00000% with 1 line in your changes missing coverage. Please review.

Project coverage is 73.89%. Comparing base (289ad43) to head (f20c6af).
Report is 3 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #8799      +/-   ##
===========================================
- Coverage    73.93%   73.89%   -0.04%     
===========================================
  Files          409      409              
  Lines        43930    43930              
  Branches      3986     3986              
===========================================
- Hits         32478    32461      -17     
- Misses       11452    11469      +17     
Components Coverage Δ
cvat-ui 78.34% <ø> (+<0.01%) ⬆️
cvat-server 70.07% <80.00%> (-0.08%) ⬇️

@@ -44,6 +48,26 @@ def create(self, request):

return Response(serializer.validated_data, status=status.HTTP_201_CREATED)

@extend_schema(summary='Log external events',
Copy link
Contributor

Choose a reason for hiding this comment

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

Do we really need several end-points to send events (add a row into Clickhouse)?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

reused existing endpoint

class EventsPermission(OpenPolicyAgentPermission):
class Scopes(StrEnum):
SEND_EVENTS = 'send:events'
DUMP_EVENTS = 'dump:events'
SEND_EXTERNAL_EVENTS = 'send-external:events'
Copy link
Contributor

Choose a reason for hiding this comment

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

Please update the rego rules to reflect this change

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I planned it to be only accessible by admins, and rego rules do not need to be changed for it.
But due to comments above I will try to use the existing endpoint somehow, and just drop this scope

Copy link
Contributor Author

Choose a reason for hiding this comment

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

removed it

@azhavoro
Copy link
Contributor

Consider adding some tests for this endpoint

@Eldies Eldies changed the title endpoint for sending events not from client /api/events endpoint can be used to receive events not only from client Dec 12, 2024
@azhavoro
Copy link
Contributor

@Eldies LGTM, but please add a changelog entry

@Eldies
Copy link
Contributor Author

Eldies commented Dec 16, 2024

LGTM, but please add a changelog entry

done

@Eldies Eldies merged commit c99f8a4 into develop Dec 18, 2024
35 checks passed
@cvat-bot cvat-bot bot mentioned this pull request Dec 20, 2024
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.

4 participants