-
-
Notifications
You must be signed in to change notification settings - Fork 4.7k
feat(api): Add project ID-or-slug parser #117445
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
Merged
Merged
Changes from all commits
Commits
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
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,78 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from collections.abc import Iterable | ||
| from typing import NamedTuple, TypeAlias | ||
|
|
||
| from drf_spectacular.types import OpenApiTypes | ||
| from drf_spectacular.utils import extend_schema_field | ||
| from rest_framework import serializers | ||
|
|
||
| from sentry.constants import ALL_ACCESS_PROJECT_ID, ALL_ACCESS_PROJECTS_SLUG | ||
| from sentry.utils.slug import DEFAULT_SLUG_ERROR_MESSAGE, MIXED_SLUG_REGEX | ||
|
|
||
| ProjectIdOrSlug: TypeAlias = int | str | ||
|
|
||
|
|
||
| class ParsedProjectIdOrSlugParams(NamedTuple): | ||
| ids: set[int] | ||
| slugs: set[str] | ||
|
|
||
| @property | ||
| def has_values(self) -> bool: | ||
| return bool(self.ids or self.slugs) | ||
|
|
||
| @property | ||
| def has_all_projects_sentinel(self) -> bool: | ||
| return ALL_ACCESS_PROJECT_ID in self.ids or ALL_ACCESS_PROJECTS_SLUG in self.slugs | ||
|
|
||
|
|
||
| def parse_id_or_slug_params( | ||
| values: Iterable[ProjectIdOrSlug | None], | ||
| ) -> ParsedProjectIdOrSlugParams: | ||
| """ | ||
| Partition project identifier values into numeric IDs and slugs. | ||
|
|
||
| All-digit values and the ``-1`` all-access project sigil are treated as IDs. | ||
| Everything else is treated as a slug. | ||
| """ | ||
| ids: set[int] = set() | ||
| slugs: set[str] = set() | ||
| for value in values: | ||
| if value is None or value == "": | ||
| continue | ||
| if isinstance(value, int) and not isinstance(value, bool): | ||
| ids.add(value) | ||
| continue | ||
|
|
||
| value_str = str(value) | ||
| if value_str.isdecimal() or value_str == str(ALL_ACCESS_PROJECT_ID): | ||
| ids.add(int(value_str)) | ||
| else: | ||
| slugs.add(value_str) | ||
| return ParsedProjectIdOrSlugParams(ids=ids, slugs=slugs) | ||
|
|
||
|
|
||
| @extend_schema_field(field=OpenApiTypes.STR) | ||
| class ProjectIdOrSlugField(serializers.Field[ProjectIdOrSlug, object, ProjectIdOrSlug, object]): | ||
| default_error_messages = { | ||
| "invalid": "Expected a project ID or slug.", | ||
| "invalid_slug": DEFAULT_SLUG_ERROR_MESSAGE, | ||
| } | ||
|
|
||
| def to_internal_value(self, data: object) -> ProjectIdOrSlug: | ||
| if data is None or isinstance(data, bool): | ||
| self.fail("invalid") | ||
| if isinstance(data, int): | ||
| return data | ||
| if not isinstance(data, str) or data == "": | ||
| self.fail("invalid") | ||
| if data.isdecimal() or data == str(ALL_ACCESS_PROJECT_ID): | ||
| return int(data) | ||
| if data == ALL_ACCESS_PROJECTS_SLUG: | ||
| return data | ||
| if MIXED_SLUG_REGEX.match(data) is None: | ||
| self.fail("invalid_slug") | ||
| return data | ||
|
|
||
| def to_representation(self, value: ProjectIdOrSlug) -> ProjectIdOrSlug: | ||
| return value |
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
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,77 @@ | ||
| import pytest | ||
| from rest_framework import serializers | ||
|
|
||
| from sentry.api.helpers.projects import ProjectIdOrSlugField, parse_id_or_slug_params | ||
|
|
||
|
|
||
| class TestParseIdOrSlugParams: | ||
| def test_empty_input(self) -> None: | ||
| params = parse_id_or_slug_params([]) | ||
| assert params.ids == set() | ||
| assert params.slugs == set() | ||
|
|
||
| def test_numeric_values(self) -> None: | ||
| params = parse_id_or_slug_params(["1", "2", "3"]) | ||
| assert params.ids == {1, 2, 3} | ||
| assert params.slugs == set() | ||
|
|
||
| def test_slug_values(self) -> None: | ||
| params = parse_id_or_slug_params(["my-project", "another-proj"]) | ||
| assert params.ids == set() | ||
| assert params.slugs == {"my-project", "another-proj"} | ||
|
|
||
| def test_mixed_values(self) -> None: | ||
| params = parse_id_or_slug_params(["1", "my-project", 42]) | ||
| assert params.ids == {1, 42} | ||
| assert params.slugs == {"my-project"} | ||
|
|
||
| def test_empty_values_are_skipped(self) -> None: | ||
| params = parse_id_or_slug_params(["", None, "1", "foo"]) | ||
| assert params.ids == {1} | ||
| assert params.slugs == {"foo"} | ||
|
|
||
| def test_all_access_numeric_sentinel_is_id(self) -> None: | ||
| params = parse_id_or_slug_params(["-1"]) | ||
| assert params.ids == {-1} | ||
| assert params.slugs == set() | ||
|
|
||
| def test_negative_non_sentinel_is_slug(self) -> None: | ||
| params = parse_id_or_slug_params(["-2"]) | ||
| assert params.ids == set() | ||
| assert params.slugs == {"-2"} | ||
|
|
||
| def test_all_access_sigil_is_slug(self) -> None: | ||
| params = parse_id_or_slug_params(["$all"]) | ||
| assert params.ids == set() | ||
| assert params.slugs == {"$all"} | ||
|
|
||
| def test_detects_all_access_sentinels(self) -> None: | ||
| assert parse_id_or_slug_params(["-1"]).has_all_projects_sentinel | ||
| assert parse_id_or_slug_params(["$all"]).has_all_projects_sentinel | ||
| assert not parse_id_or_slug_params(["1", "my-project"]).has_all_projects_sentinel | ||
|
|
||
| def test_deduplication(self) -> None: | ||
| params = parse_id_or_slug_params(["1", "1", "foo", "foo"]) | ||
| assert params.ids == {1} | ||
| assert params.slugs == {"foo"} | ||
|
|
||
|
|
||
| class TestProjectIdOrSlugField: | ||
| def test_accepts_ids_and_slugs(self) -> None: | ||
| field = ProjectIdOrSlugField() | ||
| assert field.to_internal_value("1") == 1 | ||
| assert field.to_internal_value(2) == 2 | ||
| assert field.to_internal_value("-1") == -1 | ||
| assert field.to_internal_value("my-project") == "my-project" | ||
|
|
||
| def test_negative_non_sentinel_string_is_slug(self) -> None: | ||
| field = ProjectIdOrSlugField() | ||
| assert field.to_internal_value("-2") == "-2" | ||
|
|
||
| def test_rejects_invalid_slug(self) -> None: | ||
| field = ProjectIdOrSlugField() | ||
|
|
||
| with pytest.raises(serializers.ValidationError) as error: | ||
| field.to_internal_value("foo bar") | ||
|
|
||
| assert "Enter a valid slug" in str(error.value) |
40 changes: 40 additions & 0 deletions
40
tests/sentry/api/serializers/rest_framework/test_project.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,40 @@ | ||
| from unittest.mock import Mock | ||
|
|
||
| from rest_framework import serializers | ||
|
|
||
| from sentry.api.serializers.rest_framework.project import ProjectField | ||
| from sentry.testutils.cases import TestCase | ||
|
|
||
|
|
||
| class ProjectFieldTest(TestCase): | ||
| def test_id_allowed_accepts_project_id(self) -> None: | ||
| project = self.create_project() | ||
| access = Mock() | ||
| access.has_any_project_scope.return_value = True | ||
|
|
||
| class ProjectSerializer(serializers.Serializer): | ||
| project = ProjectField(scope="project:read", id_allowed=True) | ||
|
|
||
| serializer = ProjectSerializer( | ||
| data={"project": str(project.id)}, | ||
| context={"organization": project.organization, "access": access}, | ||
| ) | ||
|
|
||
| assert serializer.is_valid(), serializer.errors | ||
| assert serializer.validated_data["project"] == project | ||
|
|
||
| def test_default_rejects_project_id(self) -> None: | ||
| project = self.create_project() | ||
| access = Mock() | ||
| access.has_any_project_scope.return_value = True | ||
|
|
||
| class ProjectSerializer(serializers.Serializer): | ||
| project = ProjectField(scope="project:read") | ||
|
|
||
| serializer = ProjectSerializer( | ||
| data={"project": str(project.id)}, | ||
| context={"organization": project.organization, "access": access}, | ||
| ) | ||
|
|
||
| assert not serializer.is_valid() | ||
| assert serializer.errors == {"project": ["Invalid project"]} |
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.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bug: An invalid project slug raises a generic validation error instead of the intended "Invalid project" error because the specific
ValidationErroris not caught.Severity: LOW
Suggested Fix
Modify the
exceptblock inProjectField.to_internal_valueto also catchserializers.ValidationError. Inside the handler, raise a newserializers.ValidationErrorwith the intended 'Invalid project' message to ensure consistent error reporting for all invalid project identifiers.Prompt for AI Agent
Did we get this right? 👍 / 👎 to inform future reviews.