-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
feat(inbound-filters): Add custom inbound filters CRUD endpoint #117797
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
Draft
shellmayr
wants to merge
11
commits into
master
Choose a base branch
from
shellmayr/feat/inbound-filters-v2-add-endpoint
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 6 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
d17c591
feat(inbound-filters): add custom inbound filters endpoint
shellmayr 93dc7ae
Merge remote-tracking branch 'origin/master' into shellmayr/feat/inbo…
shellmayr 4452a85
:hammer_and_wrench: Sync API Urls to TypeScript
getsantry[bot] 118e47c
ref(inbound-filters): Move create to details endpoint and unify audit…
shellmayr 158f2de
Merge remote-tracking branch 'origin/shellmayr/feat/inbound-filters-v…
shellmayr 304fb7c
ref(inbound-filters): Map audit log operation to verb instead of if-c…
shellmayr 173ab0c
fix(inbound-filters): Move create back to the collection endpoint
shellmayr 8c1e635
Merge remote-tracking branch 'origin/master' into shellmayr/feat/inbo…
shellmayr bfa8c5f
feat(inbound-filters): Harden custom inbound filter endpoints
shellmayr a3e5794
ref(inbound-filters): Use DateTimeField for serialized timestamps
shellmayr e7ced48
ref(inbound-filters): Gate endpoints with shared has_feature base
shellmayr File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
349 changes: 349 additions & 0 deletions
349
src/sentry/api/endpoints/project_custom_inbound_filters.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,349 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from enum import StrEnum | ||
| from typing import Any, TypedDict | ||
|
|
||
| from drf_spectacular.utils import extend_schema | ||
| from rest_framework import serializers | ||
| from rest_framework.request import Request | ||
| from rest_framework.response import Response | ||
|
|
||
| from sentry import audit_log, features | ||
| from sentry.api.api_owners import ApiOwner | ||
| from sentry.api.api_publish_status import ApiPublishStatus | ||
| from sentry.api.base import cell_silo_endpoint | ||
| from sentry.api.bases.project import ProjectEndpoint, ProjectSettingPermission | ||
| from sentry.api.exceptions import ResourceDoesNotExist | ||
| from sentry.api.paginator import OffsetPaginator | ||
| from sentry.apidocs.constants import RESPONSE_BAD_REQUEST, RESPONSE_FORBIDDEN, RESPONSE_NOT_FOUND | ||
| from sentry.apidocs.parameters import GlobalParams | ||
| from sentry.models.custominboundfilter import CustomInboundFilter | ||
| from sentry.models.project import Project | ||
|
|
||
|
|
||
| class CustomInboundFilterConditionType(StrEnum): | ||
| ERROR_MESSAGE = "error_message" | ||
| LOG_MESSAGE = "log_message" | ||
| METRIC_NAME = "metric_name" | ||
| RELEASE = "release" | ||
|
|
||
|
|
||
| PRIMARY_CONDITION_TYPES = frozenset( | ||
| ( | ||
| CustomInboundFilterConditionType.ERROR_MESSAGE, | ||
| CustomInboundFilterConditionType.LOG_MESSAGE, | ||
| CustomInboundFilterConditionType.METRIC_NAME, | ||
| ) | ||
| ) | ||
|
|
||
|
|
||
| class CustomInboundFilterCondition(TypedDict): | ||
| type: str | ||
| value: list[str] | ||
|
|
||
|
|
||
| class CustomInboundFilterResponse(TypedDict): | ||
| id: str | ||
| name: str | None | ||
| active: bool | ||
| conditions: list[CustomInboundFilterCondition] | ||
| dateCreated: str | ||
| dateUpdated: str | ||
|
|
||
|
|
||
| class CustomInboundFilterConditionSerializer(serializers.Serializer): | ||
| type = serializers.ChoiceField( | ||
| choices=[condition_type.value for condition_type in CustomInboundFilterConditionType] | ||
| ) | ||
| value = serializers.ListField( | ||
| child=serializers.CharField(allow_blank=False, trim_whitespace=True), | ||
| allow_empty=False, | ||
| ) | ||
|
|
||
|
|
||
| class CustomInboundFilterSerializer(serializers.Serializer): | ||
| name = serializers.CharField( | ||
| max_length=256, allow_blank=True, allow_null=True, required=False, trim_whitespace=True | ||
| ) | ||
| active = serializers.BooleanField(required=False) | ||
| conditions = CustomInboundFilterConditionSerializer(many=True, allow_empty=False) | ||
|
|
||
| def validate_conditions(self, conditions: list[dict[str, Any]]) -> list[dict[str, Any]]: | ||
| condition_types = [condition["type"] for condition in conditions] | ||
|
|
||
| if len(condition_types) != len(set(condition_types)): | ||
| raise serializers.ValidationError("Condition types must be unique.") | ||
|
|
||
| primary_condition_types = PRIMARY_CONDITION_TYPES.intersection(condition_types) | ||
| if len(primary_condition_types) > 1: | ||
| raise serializers.ValidationError( | ||
| "Only one of error_message, log_message, or metric_name can be used in a filter." | ||
| ) | ||
|
|
||
| organization = self.context["project"].organization | ||
| request = self.context["request"] | ||
|
|
||
| if CustomInboundFilterConditionType.LOG_MESSAGE in condition_types and not features.has( | ||
| "organizations:ourlogs-ingestion", organization, actor=request.user | ||
| ): | ||
| raise serializers.ValidationError( | ||
| "Log message filters are not enabled for this organization." | ||
| ) | ||
|
|
||
| if CustomInboundFilterConditionType.METRIC_NAME in condition_types and not features.has( | ||
| "organizations:tracemetrics-ingestion", organization, actor=request.user | ||
| ): | ||
| raise serializers.ValidationError( | ||
| "Metric name filters are not enabled for this organization." | ||
| ) | ||
|
|
||
| return conditions | ||
|
|
||
|
|
||
| def serialize_project_custom_inbound_filter( | ||
| custom_filter: CustomInboundFilter, | ||
| ) -> CustomInboundFilterResponse: | ||
| return { | ||
| "id": str(custom_filter.id), | ||
| "name": custom_filter.name, | ||
| "active": custom_filter.active, | ||
| "conditions": custom_filter.conditions, | ||
| "dateCreated": custom_filter.date_added.isoformat(), | ||
| "dateUpdated": custom_filter.date_updated.isoformat(), | ||
| } | ||
|
|
||
|
|
||
| def get_custom_inbound_filter(project: Project, filter_id: str) -> CustomInboundFilter: | ||
| try: | ||
| return CustomInboundFilter.objects.get(id=filter_id, project_id=project.id) | ||
| except (CustomInboundFilter.DoesNotExist, ValueError): | ||
| raise ResourceDoesNotExist | ||
|
|
||
|
|
||
| def feature_access_denied(request: Request, project: Project) -> Response | None: | ||
| if not features.has( | ||
| "organizations:inbound-filters-v2", project.organization, actor=request.user | ||
| ): | ||
| raise ResourceDoesNotExist | ||
|
|
||
| if not features.has("projects:custom-inbound-filters", project, actor=request.user): | ||
| return Response({"detail": "You do not have that feature enabled"}, status=400) | ||
|
|
||
| return None | ||
|
|
||
|
|
||
| def get_audit_log_data( | ||
| project: Project, | ||
| custom_filter: CustomInboundFilter, | ||
| operation: str, | ||
| changes: dict[str, Any] | None = None, | ||
| ) -> dict[str, Any]: | ||
| data: dict[str, Any] = { | ||
| "project_slug": project.slug, | ||
| "filter_id": str(custom_filter.id), | ||
| "filter_name": custom_filter.name, | ||
| "active": custom_filter.active, | ||
| "conditions": custom_filter.conditions, | ||
| "operation": operation, | ||
| } | ||
|
|
||
| if changes: | ||
| data["changes"] = changes | ||
|
|
||
| return data | ||
|
|
||
|
|
||
| @cell_silo_endpoint | ||
| @extend_schema(tags=["Projects"]) | ||
| class CustomInboundFiltersEndpoint(ProjectEndpoint): | ||
| owner = ApiOwner.UNOWNED | ||
| permission_classes = (ProjectSettingPermission,) | ||
| publish_status = { | ||
| "GET": ApiPublishStatus.PRIVATE, | ||
| } | ||
|
|
||
| @extend_schema( | ||
| operation_id="List a Project's Custom Inbound Filters", | ||
| parameters=[ | ||
| GlobalParams.ORG_ID_OR_SLUG, | ||
| GlobalParams.PROJECT_ID_OR_SLUG, | ||
| ], | ||
| responses={ | ||
| 200: list[CustomInboundFilterResponse], | ||
| 400: RESPONSE_BAD_REQUEST, | ||
| 403: RESPONSE_FORBIDDEN, | ||
| 404: RESPONSE_NOT_FOUND, | ||
| }, | ||
| ) | ||
| def get(self, request: Request, project: Project) -> Response: | ||
| if denied := feature_access_denied(request, project): | ||
| return denied | ||
|
|
||
| filters = CustomInboundFilter.objects.filter(project_id=project.id) | ||
| return self.paginate( | ||
| request=request, | ||
| queryset=filters, | ||
| order_by="id", | ||
| paginator_cls=OffsetPaginator, | ||
| on_results=lambda results: [ | ||
| serialize_project_custom_inbound_filter(custom_filter) for custom_filter in results | ||
| ], | ||
| ) | ||
|
|
||
|
|
||
| @cell_silo_endpoint | ||
| @extend_schema(tags=["Projects"]) | ||
| class CustomInboundFilterDetailsEndpoint(ProjectEndpoint): | ||
| owner = ApiOwner.UNOWNED | ||
| permission_classes = (ProjectSettingPermission,) | ||
| publish_status = { | ||
| "GET": ApiPublishStatus.PRIVATE, | ||
| "POST": ApiPublishStatus.PRIVATE, | ||
| "PUT": ApiPublishStatus.PRIVATE, | ||
| "DELETE": ApiPublishStatus.PRIVATE, | ||
| } | ||
|
|
||
| @extend_schema( | ||
| operation_id="Create a Custom Inbound Filter", | ||
| parameters=[ | ||
| GlobalParams.ORG_ID_OR_SLUG, | ||
| GlobalParams.PROJECT_ID_OR_SLUG, | ||
| ], | ||
| request=CustomInboundFilterSerializer, | ||
| responses={ | ||
| 201: CustomInboundFilterResponse, | ||
| 400: RESPONSE_BAD_REQUEST, | ||
| 403: RESPONSE_FORBIDDEN, | ||
| 404: RESPONSE_NOT_FOUND, | ||
| }, | ||
| ) | ||
| def post(self, request: Request, project: Project, filter_id: str) -> Response: | ||
| if denied := feature_access_denied(request, project): | ||
| return denied | ||
|
Check warning on line 222 in src/sentry/api/endpoints/project_custom_inbound_filters.py
|
||
|
|
||
| serializer = CustomInboundFilterSerializer( | ||
| data=request.data, | ||
| context={"project": project, "request": request}, | ||
| ) | ||
| if not serializer.is_valid(): | ||
| return Response(serializer.errors, status=400) | ||
|
|
||
| custom_filter = CustomInboundFilter.objects.create( | ||
| project=project, | ||
| name=serializer.validated_data.get("name"), | ||
| active=serializer.validated_data.get("active", True), | ||
| conditions=serializer.validated_data["conditions"], | ||
| ) | ||
|
|
||
| self.create_audit_entry( | ||
| request=request, | ||
| organization=project.organization, | ||
| target_object=custom_filter.id, | ||
| event=audit_log.get_event_id("CUSTOM_INBOUND_FILTER"), | ||
| data=get_audit_log_data(project, custom_filter, "add"), | ||
| ) | ||
|
|
||
| return Response(serialize_project_custom_inbound_filter(custom_filter), status=201) | ||
|
|
||
| @extend_schema( | ||
| operation_id="Retrieve a Custom Inbound Filter", | ||
| parameters=[ | ||
| GlobalParams.ORG_ID_OR_SLUG, | ||
| GlobalParams.PROJECT_ID_OR_SLUG, | ||
| ], | ||
| responses={ | ||
| 200: CustomInboundFilterResponse, | ||
| 400: RESPONSE_BAD_REQUEST, | ||
| 403: RESPONSE_FORBIDDEN, | ||
| 404: RESPONSE_NOT_FOUND, | ||
| }, | ||
| ) | ||
| def get(self, request: Request, project: Project, filter_id: str) -> Response: | ||
| if denied := feature_access_denied(request, project): | ||
| return denied | ||
|
|
||
| custom_filter = get_custom_inbound_filter(project, filter_id) | ||
| return Response(serialize_project_custom_inbound_filter(custom_filter)) | ||
|
|
||
| @extend_schema( | ||
| operation_id="Update a Custom Inbound Filter", | ||
| parameters=[ | ||
| GlobalParams.ORG_ID_OR_SLUG, | ||
| GlobalParams.PROJECT_ID_OR_SLUG, | ||
| ], | ||
| request=CustomInboundFilterSerializer, | ||
| responses={ | ||
| 200: CustomInboundFilterResponse, | ||
| 400: RESPONSE_BAD_REQUEST, | ||
| 403: RESPONSE_FORBIDDEN, | ||
| 404: RESPONSE_NOT_FOUND, | ||
| }, | ||
| ) | ||
| def put(self, request: Request, project: Project, filter_id: str) -> Response: | ||
| if denied := feature_access_denied(request, project): | ||
| return denied | ||
|
|
||
| custom_filter = get_custom_inbound_filter(project, filter_id) | ||
| serializer = CustomInboundFilterSerializer( | ||
| custom_filter, | ||
| data=request.data, | ||
| partial=True, | ||
| context={"project": project, "request": request}, | ||
| ) | ||
| if not serializer.is_valid(): | ||
| return Response(serializer.errors, status=400) | ||
|
|
||
| changes = {} | ||
| for field in ("name", "active", "conditions"): | ||
| if field not in serializer.validated_data: | ||
| continue | ||
|
|
||
| previous_value = getattr(custom_filter, field) | ||
| new_value = serializer.validated_data[field] | ||
| if previous_value != new_value: | ||
| changes[field] = {"old": previous_value, "new": new_value} | ||
| setattr(custom_filter, field, new_value) | ||
|
|
||
| if changes: | ||
| custom_filter.save(update_fields=[*changes.keys(), "date_updated"]) | ||
| self.create_audit_entry( | ||
| request=request, | ||
| organization=project.organization, | ||
| target_object=custom_filter.id, | ||
| event=audit_log.get_event_id("CUSTOM_INBOUND_FILTER"), | ||
| data=get_audit_log_data(project, custom_filter, "edit", changes), | ||
| ) | ||
|
|
||
| return Response(serialize_project_custom_inbound_filter(custom_filter)) | ||
|
|
||
| @extend_schema( | ||
| operation_id="Delete a Custom Inbound Filter", | ||
| parameters=[ | ||
| GlobalParams.ORG_ID_OR_SLUG, | ||
| GlobalParams.PROJECT_ID_OR_SLUG, | ||
| ], | ||
| responses={ | ||
| 204: None, | ||
| 400: RESPONSE_BAD_REQUEST, | ||
| 403: RESPONSE_FORBIDDEN, | ||
| 404: RESPONSE_NOT_FOUND, | ||
| }, | ||
| ) | ||
| def delete(self, request: Request, project: Project, filter_id: str) -> Response: | ||
| if denied := feature_access_denied(request, project): | ||
| return denied | ||
|
|
||
| custom_filter = get_custom_inbound_filter(project, filter_id) | ||
| audit_log_data = get_audit_log_data(project, custom_filter, "remove") | ||
| target_object = custom_filter.id | ||
| custom_filter.delete() | ||
|
|
||
| self.create_audit_entry( | ||
| request=request, | ||
| organization=project.organization, | ||
| target_object=target_object, | ||
| event=audit_log.get_event_id("CUSTOM_INBOUND_FILTER"), | ||
| data=audit_log_data, | ||
| ) | ||
|
|
||
| return Response(status=204) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.