From 1d67e89cc4110a0530a619f2ac1501d5b1a69f72 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:22:59 +0000 Subject: [PATCH 1/3] feat(apidocs): Publish x-sentry-project-scope on operations Add a project_scope declaration to Endpoint, published as the x-sentry-project-scope operation extension. It says how a request names the projects whose data it returns or changes: "path" (stamped automatically on every path with {project_id_or_slug}), "filter" (the project query parameter), "org-metadata" (read-only organization metadata), or "response:" (a GET by ID whose project ID is at a JSON pointer in the response). The schema build validates declarations. Clients such as the Sentry CLI and MCP server can then enforce a project limit from the schema instead of a hand-written endpoint table. Refs getsentry/toolkit#2237 Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- .../organization_ai_conversations.py | 1 + src/sentry/api/base.py | 5 + src/sentry/api/endpoints/chunk.py | 1 + src/sentry/api/endpoints/dsn_lookup.py | 1 + .../api/endpoints/organization_events.py | 1 + .../endpoints/organization_events_dropped.py | 1 + .../organization_events_timeseries.py | 1 + .../api/endpoints/organization_releases.py | 1 + .../organization_trace_item_attributes.py | 1 + src/sentry/apidocs/README.md | 37 +++++ src/sentry/apidocs/hooks.py | 49 ++++++ .../core/endpoints/organization_details.py | 1 + .../endpoints/organization_environments.py | 1 + .../endpoints/organization_member_details.py | 1 + .../endpoints/organization_member_index.py | 1 + .../core/endpoints/organization_projects.py | 1 + .../core/endpoints/organization_teams.py | 1 + .../core/endpoints/organization_user_teams.py | 1 + src/sentry/core/endpoints/team_details.py | 1 + src/sentry/core/endpoints/team_members.py | 1 + src/sentry/core/endpoints/team_projects.py | 1 + .../organization_dashboard_details.py | 1 + .../organization_dashboard_revisions.py | 1 + .../endpoints/organization_dashboards.py | 1 + .../endpoints/discover_saved_queries.py | 1 + .../endpoints/discover_saved_query_detail.py | 1 + .../endpoints/organization_code_mappings.py | 1 + .../organization_config_integrations.py | 1 + ...ganization_integration_channel_validate.py | 1 + .../organization_integration_channels.py | 1 + .../organization_integration_details.py | 1 + .../organization_integration_repos.py | 1 + .../organization_integrations_index.py | 1 + .../endpoints/organization_repositories.py | 1 + .../organization_repository_commits.py | 1 + src/sentry/issues/endpoints/group_details.py | 1 + .../endpoints/organization_group_index.py | 1 + .../organization_group_search_views.py | 1 + .../endpoints/organization_monitor_details.py | 1 + .../endpoints/organization_monitor_index.py | 1 + .../endpoints/organization_release_details.py | 1 + .../endpoints/organization_replay_count.py | 1 + .../endpoints/organization_replay_details.py | 1 + .../endpoints/organization_replay_index.py | 1 + .../api/endpoints/organization_sentry_apps.py | 1 + .../api/endpoints/sentry_app_components.py | 1 + .../api/endpoints/sentry_app_installations.py | 1 + .../organization_available_action_index.py | 1 + .../organization_detector_details.py | 1 + .../endpoints/organization_detector_index.py | 1 + .../organization_workflow_details.py | 1 + .../endpoints/organization_workflow_index.py | 1 + tests/apidocs/test_hooks.py | 151 ++++++++++++++++++ 53 files changed, 291 insertions(+) diff --git a/src/sentry/ai_monitoring/endpoints/organization_ai_conversations.py b/src/sentry/ai_monitoring/endpoints/organization_ai_conversations.py index 3366efd1aefd..3e1fd8a5ff6b 100644 --- a/src/sentry/ai_monitoring/endpoints/organization_ai_conversations.py +++ b/src/sentry/ai_monitoring/endpoints/organization_ai_conversations.py @@ -163,6 +163,7 @@ class OrganizationAIConversationsEndpoint(OrganizationEventsEndpointBase): publish_status = { "GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL, } + project_scope = {"GET": "filter"} owner = ApiOwner.AGENT_TRACING @extend_schema( diff --git a/src/sentry/api/base.py b/src/sentry/api/base.py index fa187f8c4f1c..1e4839980772 100644 --- a/src/sentry/api/base.py +++ b/src/sentry/api/base.py @@ -305,6 +305,11 @@ class Endpoint(APIView): # changing the outcome. Published as `x-sentry-idempotent`; see apidocs/README.md. # None means undeclared, which the schema build rejects for published writes. idempotent_methods: frozenset[HTTP_METHOD_NAME] | None = None + # How each method's request names the projects whose data it returns or changes, + # for clients that limit a caller to some projects. Published as + # `x-sentry-project-scope`; see apidocs/README.md. Paths with `{project_id_or_slug}` + # get "path" automatically, so only organization-level endpoints declare it. + project_scope: dict[HTTP_METHOD_NAME, str] = {} rate_limits: RateLimitConfig | Callable[..., RateLimitConfig] = DEFAULT_RATE_LIMIT_CONFIG enforce_rate_limit: bool = settings.SENTRY_RATELIMITER_ENABLED # Origins that serve this endpoint, for the API docs; the schema build adds the base path. diff --git a/src/sentry/api/endpoints/chunk.py b/src/sentry/api/endpoints/chunk.py index 14752ae074bb..2bbf739fec00 100644 --- a/src/sentry/api/endpoints/chunk.py +++ b/src/sentry/api/endpoints/chunk.py @@ -241,6 +241,7 @@ class ChunkUploadEndpoint(OrganizationEndpoint): "GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL, "POST": ApiPublishStatus.PUBLIC_EXPERIMENTAL, } + project_scope = {"GET": "org-metadata"} # Blobs are unique per checksum, so resending a chunk leaves the same single blob. idempotent_methods = frozenset({"POST"}) owner = ApiOwner.OWNERS_INGEST diff --git a/src/sentry/api/endpoints/dsn_lookup.py b/src/sentry/api/endpoints/dsn_lookup.py index 83da4b28a938..17deeff123a8 100644 --- a/src/sentry/api/endpoints/dsn_lookup.py +++ b/src/sentry/api/endpoints/dsn_lookup.py @@ -51,6 +51,7 @@ class DsnLookupEndpoint(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} enforce_rate_limit = True rate_limits = RateLimitConfig( limit_overrides={ diff --git a/src/sentry/api/endpoints/organization_events.py b/src/sentry/api/endpoints/organization_events.py index 39e3326c8c5b..d048aacfa5c8 100644 --- a/src/sentry/api/endpoints/organization_events.py +++ b/src/sentry/api/endpoints/organization_events.py @@ -177,6 +177,7 @@ class OrganizationEventsEndpoint(OrganizationEventsEndpointBase): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "filter"} enforce_rate_limit = True diff --git a/src/sentry/api/endpoints/organization_events_dropped.py b/src/sentry/api/endpoints/organization_events_dropped.py index 6ff349943e60..27488bba62f9 100644 --- a/src/sentry/api/endpoints/organization_events_dropped.py +++ b/src/sentry/api/endpoints/organization_events_dropped.py @@ -123,6 +123,7 @@ class OrganizationEventsDroppedEndpoint(OrganizationEventsEndpointBase): publish_status = { "GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL, } + project_scope = {"GET": "filter"} @extend_schema( operation_id="listOrganizationEventsDropped", diff --git a/src/sentry/api/endpoints/organization_events_timeseries.py b/src/sentry/api/endpoints/organization_events_timeseries.py index ea2040ceb2d4..18207ce0450e 100644 --- a/src/sentry/api/endpoints/organization_events_timeseries.py +++ b/src/sentry/api/endpoints/organization_events_timeseries.py @@ -270,6 +270,7 @@ class OrganizationEventsTimeseriesEndpoint(OrganizationEventsEndpointBase): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "filter"} enforce_rate_limit = True diff --git a/src/sentry/api/endpoints/organization_releases.py b/src/sentry/api/endpoints/organization_releases.py index 8e12b6fb81e2..b7e3fc58da5d 100644 --- a/src/sentry/api/endpoints/organization_releases.py +++ b/src/sentry/api/endpoints/organization_releases.py @@ -357,6 +357,7 @@ class OrganizationReleasesEndpoint(OrganizationReleasesBaseEndpoint, ReleaseAnal "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "filter"} idempotent_methods = frozenset() rate_limits = RateLimitConfig( diff --git a/src/sentry/api/endpoints/organization_trace_item_attributes.py b/src/sentry/api/endpoints/organization_trace_item_attributes.py index 6ac6dca2a737..ba97150eb724 100644 --- a/src/sentry/api/endpoints/organization_trace_item_attributes.py +++ b/src/sentry/api/endpoints/organization_trace_item_attributes.py @@ -777,6 +777,7 @@ class OrganizationTraceItemAttributesEndpoint(OrganizationTraceItemAttributesEnd publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "filter"} @extend_schema( operation_id="listOrganizationTraceItemAttributes", diff --git a/src/sentry/apidocs/README.md b/src/sentry/apidocs/README.md index 74c959211ebc..a94e760a086a 100644 --- a/src/sentry/apidocs/README.md +++ b/src/sentry/apidocs/README.md @@ -71,6 +71,43 @@ qualify yet. Like routing, declarations are collected for every endpoint and reset on every build. The marker appears only on operations that are in the generated schema. +# Project scope + +`x-sentry-project-scope` says how an operation's request names the projects +whose data it returns or changes. Clients that limit a caller to some projects, +such as the Sentry CLI and MCP server, read it instead of keeping their own list +of endpoints. It is a string: + +| Value | Meaning | +| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `path` | The path names the project. Set automatically on every operation whose path contains `{project_id_or_slug}`. | +| `filter` | An organization endpoint that takes the `project` query parameter (numeric project IDs) and returns or changes only those projects' data. | +| `org-metadata` | A read-only organization endpoint whose response holds no project's issues, events, replays, or other telemetry, such as settings, members, integrations, and saved views. | +| `response:` | A `GET` that looks something up by ID alone. The numeric ID of the project it belongs to is at `` in the response body, such as `response:/project/id`. | + +`` is an RFC 6901 JSON pointer, plus a `*` segment that matches every +element of an array: `response:/projects/*/id`. The value at the pointer can be +a numeric string and, for objects that belong to no project, `null`. + +An organization-level endpoint declares it per method: + +```python +class OrganizationGroupIndexEndpoint(OrganizationEndpoint): + publish_status = { + "DELETE": ApiPublishStatus.PUBLIC, + "GET": ApiPublishStatus.PUBLIC, + "PUT": ApiPublishStatus.PUBLIC, + } + project_scope = {"GET": "filter", "PUT": "filter", "DELETE": "filter"} +``` + +The build fails for any other value, for `org-metadata` or `response:` on a +method other than `GET`, for a method the endpoint does not declare in +`publish_status`, and for a declaration on a path that contains +`{project_id_or_slug}`. A method without a value is not known to respect a +project limit. Subclasses inherit the declaration, like `idempotent_methods`. +Declarations are collected for every endpoint and reset on every build. + # Response fields Every field in a public operation's success (2xx) response needs a description diff --git a/src/sentry/apidocs/hooks.py b/src/sentry/apidocs/hooks.py index b320b3715ccb..68e376288d0f 100644 --- a/src/sentry/apidocs/hooks.py +++ b/src/sentry/apidocs/hooks.py @@ -170,6 +170,31 @@ class RoutingMetadata(TypedDict): # RFC 9110 9.2.1: these never change server state, so clients may always resend them. _SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "TRACE"}) +# (canonical path, lowercased method) -> the endpoint's `project_scope` value for the +# method. Collected for unpublished endpoints too, like silos. +_PROJECT_SCOPE_OPERATIONS: dict[tuple[str, str], str] = {} + +_PROJECT_PATH_PARAMETER = "{project_id_or_slug}" +_PROJECT_SCOPE_RESPONSE_PREFIX = "response:" +# RFC 6901: each segment escapes "~" as "~0" and "/" as "~1". A "*" segment is +# also allowed and matches every element of an array. +_JSON_POINTER = re.compile(r"(/([^/~]|~[01])*)+") + + +def _project_scope_error(method: str, value: str) -> str | None: + if value in ("filter", "org-metadata"): + if value == "org-metadata" and method != "GET": + return "org-metadata is only for GET" + return None + if value.startswith(_PROJECT_SCOPE_RESPONSE_PREFIX): + if method != "GET": + return "response: is only for GET" + if not _JSON_POINTER.fullmatch(value.removeprefix(_PROJECT_SCOPE_RESPONSE_PREFIX)): + return "response: must be followed by a JSON pointer such as /project/id" + return None + return 'the value must be "filter", "org-metadata", or "response:"' + + # Include non-spectacular endpoints so existing APPEND_PATHS operations can use # their backend declaration without changing which methods are published. _OPERATION_SILOS: dict[tuple[str, str], DeclaredSilo] = {} @@ -203,6 +228,7 @@ def custom_preprocessing_hook(endpoints: Any) -> Any: # TODO: organize method, _EXPERIMENTAL_OPERATIONS.clear() _OPERATION_SILOS.clear() _IDEMPOTENT_OPERATIONS.clear() + _PROJECT_SCOPE_OPERATIONS.clear() filtered = [] ownership_data: dict[ApiOwner, dict[ApiPublishStatus, set[str]]] = {} @@ -248,6 +274,23 @@ def custom_preprocessing_hook(endpoints: Any) -> Any: # TODO: organize method, f"Endpoint {callback.view_class} lists safe methods in idempotent_methods: {sorted(idempotent_methods & _SAFE_METHODS)}. Safe methods are always idempotent; only list non-safe methods such as POST.", ) + project_scope: Mapping[str, str] = getattr(callback.view_class, "project_scope", {}) + project_scope_value = project_scope.get(method) + if not project_scope.keys() <= callback.view_class.publish_status.keys(): + raise SentryApiBuildError( + f"Endpoint {callback.view_class} declares project_scope for methods that it does not implement: {sorted(project_scope.keys() - callback.view_class.publish_status.keys())}.", + ) + if project_scope_value is not None: + error = _project_scope_error(method, project_scope_value) + if error is not None: + raise SentryApiBuildError( + f"Endpoint {callback.view_class} declares project_scope {project_scope_value!r} for {method}: {error}. See src/sentry/apidocs/README.md.", + ) + if _PROJECT_PATH_PARAMETER in path: + raise SentryApiBuildError( + f'Endpoint {callback.view_class} declares project_scope for {method} {path}, which names the project in its path and gets project_scope "path" automatically.', + ) + if any(path.startswith(p) for p in EXCLUSION_PATH_PREFIXES): pass @@ -256,6 +299,8 @@ def custom_preprocessing_hook(endpoints: Any) -> Any: # TODO: organize method, _OPERATION_SILOS[operation_key] = _declared_silo(callback.view_class) if method in idempotent_methods: _IDEMPOTENT_OPERATIONS.add(operation_key) + if project_scope_value is not None: + _PROJECT_SCOPE_OPERATIONS[operation_key] = project_scope_value # endpoints that are documented via tooling status = callback.view_class.publish_status.get(method) if status is not None and status.is_published: @@ -354,6 +399,10 @@ def custom_postprocessing_hook( operation["x-sentry-routing"] = routing if operation_key in _IDEMPOTENT_OPERATIONS: operation["x-sentry-idempotent"] = True + if _PROJECT_PATH_PARAMETER in operation_key[0]: + operation["x-sentry-project-scope"] = "path" + elif operation_key in _PROJECT_SCOPE_OPERATIONS: + operation["x-sentry-project-scope"] = _PROJECT_SCOPE_OPERATIONS[operation_key] # Add servers override from endpoint class definitions for path, servers in _ENDPOINT_SERVERS.items(): diff --git a/src/sentry/core/endpoints/organization_details.py b/src/sentry/core/endpoints/organization_details.py index 9c343cc7eca4..3bb9bf233f3c 100644 --- a/src/sentry/core/endpoints/organization_details.py +++ b/src/sentry/core/endpoints/organization_details.py @@ -1050,6 +1050,7 @@ class OrganizationDetailsEndpoint(OrganizationEndpoint): "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() @extend_schema( diff --git a/src/sentry/core/endpoints/organization_environments.py b/src/sentry/core/endpoints/organization_environments.py index 1d0fc56f5d64..e9e4a016f3b5 100644 --- a/src/sentry/core/endpoints/organization_environments.py +++ b/src/sentry/core/endpoints/organization_environments.py @@ -31,6 +31,7 @@ class OrganizationEnvironmentsEndpoint(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} @extend_schema( operation_id="listOrganizationEnvironments", diff --git a/src/sentry/core/endpoints/organization_member_details.py b/src/sentry/core/endpoints/organization_member_details.py index 5dc59b07b156..27420aebe2c6 100644 --- a/src/sentry/core/endpoints/organization_member_details.py +++ b/src/sentry/core/endpoints/organization_member_details.py @@ -139,6 +139,7 @@ class OrganizationMemberDetailsEndpoint(OrganizationMemberEndpoint): "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() owner = ApiOwner.FOUNDATIONS permission_classes = (RelaxedMemberPermission,) diff --git a/src/sentry/core/endpoints/organization_member_index.py b/src/sentry/core/endpoints/organization_member_index.py index 866199553d89..fbdb2b339337 100644 --- a/src/sentry/core/endpoints/organization_member_index.py +++ b/src/sentry/core/endpoints/organization_member_index.py @@ -212,6 +212,7 @@ class OrganizationMemberIndexEndpoint(OrganizationEndpoint): "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() rate_limits = RateLimitConfig( diff --git a/src/sentry/core/endpoints/organization_projects.py b/src/sentry/core/endpoints/organization_projects.py index 9526cffce810..205fa26c339f 100644 --- a/src/sentry/core/endpoints/organization_projects.py +++ b/src/sentry/core/endpoints/organization_projects.py @@ -130,6 +130,7 @@ class OrganizationProjectsEndpoint(OrganizationEndpoint): "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() permission_classes = (OrganizationProjectsPermission,) owner = ApiOwner.FOUNDATIONS diff --git a/src/sentry/core/endpoints/organization_teams.py b/src/sentry/core/endpoints/organization_teams.py index c8bc1d978f16..3f267c9638b7 100644 --- a/src/sentry/core/endpoints/organization_teams.py +++ b/src/sentry/core/endpoints/organization_teams.py @@ -98,6 +98,7 @@ class OrganizationTeamsEndpoint(OrganizationEndpoint): "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() permission_classes = (OrganizationTeamsPermission,) diff --git a/src/sentry/core/endpoints/organization_user_teams.py b/src/sentry/core/endpoints/organization_user_teams.py index 719d7c0d8859..2bc68f8a14e9 100644 --- a/src/sentry/core/endpoints/organization_user_teams.py +++ b/src/sentry/core/endpoints/organization_user_teams.py @@ -26,6 +26,7 @@ class OrganizationUserTeamsEndpoint(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} owner = ApiOwner.FOUNDATIONS @extend_schema( diff --git a/src/sentry/core/endpoints/team_details.py b/src/sentry/core/endpoints/team_details.py index ed57ec89e280..aea1ee17ada1 100644 --- a/src/sentry/core/endpoints/team_details.py +++ b/src/sentry/core/endpoints/team_details.py @@ -68,6 +68,7 @@ class TeamDetailsEndpoint(TeamEndpoint): "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() # OrganizationSCIMTeamDetails inherits this endpoint, but toggles this setting _allow_idp_changes = False diff --git a/src/sentry/core/endpoints/team_members.py b/src/sentry/core/endpoints/team_members.py index b7bc6df15147..4d57f4ef7b9a 100644 --- a/src/sentry/core/endpoints/team_members.py +++ b/src/sentry/core/endpoints/team_members.py @@ -83,6 +83,7 @@ class TeamMembersEndpoint(TeamEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} owner = ApiOwner.FOUNDATIONS @extend_schema( diff --git a/src/sentry/core/endpoints/team_projects.py b/src/sentry/core/endpoints/team_projects.py index 6ead694bfa55..bf9b589ab9b6 100644 --- a/src/sentry/core/endpoints/team_projects.py +++ b/src/sentry/core/endpoints/team_projects.py @@ -190,6 +190,7 @@ class TeamProjectsEndpoint(TeamEndpoint): "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() permission_classes = (TeamProjectPermission,) owner = ApiOwner.FOUNDATIONS diff --git a/src/sentry/dashboards/endpoints/organization_dashboard_details.py b/src/sentry/dashboards/endpoints/organization_dashboard_details.py index 7ad91407585f..105cfb11031b 100644 --- a/src/sentry/dashboards/endpoints/organization_dashboard_details.py +++ b/src/sentry/dashboards/endpoints/organization_dashboard_details.py @@ -107,6 +107,7 @@ class OrganizationDashboardDetailsEndpoint(OrganizationDashboardBase): "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() @extend_schema( diff --git a/src/sentry/dashboards/endpoints/organization_dashboard_revisions.py b/src/sentry/dashboards/endpoints/organization_dashboard_revisions.py index b9e4f6ae2570..54a6d73243b2 100644 --- a/src/sentry/dashboards/endpoints/organization_dashboard_revisions.py +++ b/src/sentry/dashboards/endpoints/organization_dashboard_revisions.py @@ -34,6 +34,7 @@ class OrganizationDashboardRevisionsEndpoint(OrganizationDashboardBase): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} owner = ApiOwner.DASHBOARDS @extend_schema( diff --git a/src/sentry/dashboards/endpoints/organization_dashboards.py b/src/sentry/dashboards/endpoints/organization_dashboards.py index 885a10bdb0e4..7437081bb081 100644 --- a/src/sentry/dashboards/endpoints/organization_dashboards.py +++ b/src/sentry/dashboards/endpoints/organization_dashboards.py @@ -443,6 +443,7 @@ class OrganizationDashboardsEndpoint(OrganizationEndpoint): "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() owner = ApiOwner.DASHBOARDS permission_classes = (OrganizationDashboardsPermission,) diff --git a/src/sentry/discover/endpoints/discover_saved_queries.py b/src/sentry/discover/endpoints/discover_saved_queries.py index 7d933faa7815..274ccb7203cc 100644 --- a/src/sentry/discover/endpoints/discover_saved_queries.py +++ b/src/sentry/discover/endpoints/discover_saved_queries.py @@ -63,6 +63,7 @@ class DiscoverSavedQueriesEndpoint(OrganizationEndpoint): "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() owner = ApiOwner.DATA_BROWSING permission_classes = (DiscoverSavedQueryPermission,) diff --git a/src/sentry/discover/endpoints/discover_saved_query_detail.py b/src/sentry/discover/endpoints/discover_saved_query_detail.py index 51dd44664a24..fdbf4e5e7cf3 100644 --- a/src/sentry/discover/endpoints/discover_saved_query_detail.py +++ b/src/sentry/discover/endpoints/discover_saved_query_detail.py @@ -75,6 +75,7 @@ class DiscoverSavedQueryDetailEndpoint(DiscoverSavedQueryBase): "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset({"PUT"}) def has_feature(self, organization: Organization, request: Request) -> bool: diff --git a/src/sentry/integrations/api/endpoints/organization_code_mappings.py b/src/sentry/integrations/api/endpoints/organization_code_mappings.py index 5c3fbb458cc8..5824a92bd6ea 100644 --- a/src/sentry/integrations/api/endpoints/organization_code_mappings.py +++ b/src/sentry/integrations/api/endpoints/organization_code_mappings.py @@ -239,6 +239,7 @@ class OrganizationCodeMappingsEndpoint(OrganizationEndpoint, OrganizationIntegra "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() permission_classes = (OrganizationIntegrationsLoosePermission,) diff --git a/src/sentry/integrations/api/endpoints/organization_config_integrations.py b/src/sentry/integrations/api/endpoints/organization_config_integrations.py index 7fe8e5ecb91d..9470aa237f82 100644 --- a/src/sentry/integrations/api/endpoints/organization_config_integrations.py +++ b/src/sentry/integrations/api/endpoints/organization_config_integrations.py @@ -38,6 +38,7 @@ class OrganizationConfigIntegrationsEndpoint(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} @extend_schema( operation_id="getOrganizationConfigIntegrations", diff --git a/src/sentry/integrations/api/endpoints/organization_integration_channel_validate.py b/src/sentry/integrations/api/endpoints/organization_integration_channel_validate.py index 3684be821359..b326078d6771 100644 --- a/src/sentry/integrations/api/endpoints/organization_integration_channel_validate.py +++ b/src/sentry/integrations/api/endpoints/organization_integration_channel_validate.py @@ -57,6 +57,7 @@ class IntegrationChannelValidationResponse(DetailOptionalResponse): @control_silo_endpoint class OrganizationIntegrationChannelValidateEndpoint(OrganizationIntegrationBaseEndpoint): publish_status = {"GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL} + project_scope = {"GET": "org-metadata"} owner = ApiOwner.TELEMETRY_EXPERIENCE @extend_schema( diff --git a/src/sentry/integrations/api/endpoints/organization_integration_channels.py b/src/sentry/integrations/api/endpoints/organization_integration_channels.py index b8e3df83a5b3..11c34a1708ac 100644 --- a/src/sentry/integrations/api/endpoints/organization_integration_channels.py +++ b/src/sentry/integrations/api/endpoints/organization_integration_channels.py @@ -246,6 +246,7 @@ class OrganizationIntegrationChannelsEndpoint(OrganizationIntegrationBaseEndpoin publish_status = { "GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL, } + project_scope = {"GET": "org-metadata"} owner = ApiOwner.TELEMETRY_EXPERIENCE @extend_schema( diff --git a/src/sentry/integrations/api/endpoints/organization_integration_details.py b/src/sentry/integrations/api/endpoints/organization_integration_details.py index ec2282cb776b..b5e770f32730 100644 --- a/src/sentry/integrations/api/endpoints/organization_integration_details.py +++ b/src/sentry/integrations/api/endpoints/organization_integration_details.py @@ -60,6 +60,7 @@ class OrganizationIntegrationDetailsEndpoint(OrganizationIntegrationBaseEndpoint "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PRIVATE, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() @extend_schema( diff --git a/src/sentry/integrations/api/endpoints/organization_integration_repos.py b/src/sentry/integrations/api/endpoints/organization_integration_repos.py index 17f155e8d359..2eb08d1c797c 100644 --- a/src/sentry/integrations/api/endpoints/organization_integration_repos.py +++ b/src/sentry/integrations/api/endpoints/organization_integration_repos.py @@ -57,6 +57,7 @@ class OrganizationIntegrationReposEndpoint(CellOrganizationIntegrationBaseEndpoi publish_status = { "GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL, } + project_scope = {"GET": "org-metadata"} owner = ApiOwner.ISSUES @extend_schema( diff --git a/src/sentry/integrations/api/endpoints/organization_integrations_index.py b/src/sentry/integrations/api/endpoints/organization_integrations_index.py index 70d43447d3e8..a4006bbbd1be 100644 --- a/src/sentry/integrations/api/endpoints/organization_integrations_index.py +++ b/src/sentry/integrations/api/endpoints/organization_integrations_index.py @@ -64,6 +64,7 @@ class OrganizationIntegrationsEndpoint(OrganizationIntegrationBaseEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} permission_classes = (OrganizationIntegrationsPermission,) @extend_schema( diff --git a/src/sentry/integrations/api/endpoints/organization_repositories.py b/src/sentry/integrations/api/endpoints/organization_repositories.py index e448f89f8cc6..913ce6761d28 100644 --- a/src/sentry/integrations/api/endpoints/organization_repositories.py +++ b/src/sentry/integrations/api/endpoints/organization_repositories.py @@ -35,6 +35,7 @@ class OrganizationRepositoriesEndpoint(OrganizationEndpoint): "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PRIVATE, } + project_scope = {"GET": "org-metadata"} permission_classes = (OrganizationIntegrationsLoosePermission,) rate_limits = RateLimitConfig( group="CLI", limit_overrides={"POST": SENTRY_RATELIMITER_GROUP_DEFAULTS["default"]} diff --git a/src/sentry/integrations/api/endpoints/organization_repository_commits.py b/src/sentry/integrations/api/endpoints/organization_repository_commits.py index 9f1337782bcb..34e6cca3ac78 100644 --- a/src/sentry/integrations/api/endpoints/organization_repository_commits.py +++ b/src/sentry/integrations/api/endpoints/organization_repository_commits.py @@ -31,6 +31,7 @@ class OrganizationRepositoryCommitsEndpoint(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} @extend_schema( operation_id="listOrganizationRepoCommits", diff --git a/src/sentry/issues/endpoints/group_details.py b/src/sentry/issues/endpoints/group_details.py index a8f604ec8a1f..afebf8194ebc 100644 --- a/src/sentry/issues/endpoints/group_details.py +++ b/src/sentry/issues/endpoints/group_details.py @@ -120,6 +120,7 @@ class GroupDetailsEndpoint(GroupEndpoint): "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "response:/project/id"} idempotent_methods = frozenset() enforce_rate_limit = True rate_limits = RateLimitConfig( diff --git a/src/sentry/issues/endpoints/organization_group_index.py b/src/sentry/issues/endpoints/organization_group_index.py index d6910e16c6c9..59c452ef3ef1 100644 --- a/src/sentry/issues/endpoints/organization_group_index.py +++ b/src/sentry/issues/endpoints/organization_group_index.py @@ -272,6 +272,7 @@ class OrganizationGroupIndexEndpoint(OrganizationEndpoint): "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "filter", "PUT": "filter", "DELETE": "filter"} idempotent_methods = frozenset() owner = ApiOwner.ISSUES max_acceptable_duration = {"GET": DEFAULT_DURATION_BUDGET, "PUT": 10.0, "DELETE": 10.0} diff --git a/src/sentry/issues/endpoints/organization_group_search_views.py b/src/sentry/issues/endpoints/organization_group_search_views.py index 493f44e571f9..f9ef5cd02328 100644 --- a/src/sentry/issues/endpoints/organization_group_search_views.py +++ b/src/sentry/issues/endpoints/organization_group_search_views.py @@ -99,6 +99,7 @@ class OrganizationGroupSearchViewsEndpoint(OrganizationEndpoint): "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() owner = ApiOwner.ISSUES max_acceptable_duration = DEFAULT_DURATION_BUDGET diff --git a/src/sentry/monitors/endpoints/organization_monitor_details.py b/src/sentry/monitors/endpoints/organization_monitor_details.py index 8c9a5910239f..77c3b2dcec2d 100644 --- a/src/sentry/monitors/endpoints/organization_monitor_details.py +++ b/src/sentry/monitors/endpoints/organization_monitor_details.py @@ -35,6 +35,7 @@ class OrganizationMonitorDetailsEndpoint(MonitorEndpoint, MonitorDetailsMixin): "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "response:/project/id"} idempotent_methods = frozenset() owner = ApiOwner.CRONS diff --git a/src/sentry/monitors/endpoints/organization_monitor_index.py b/src/sentry/monitors/endpoints/organization_monitor_index.py index 900c901d9f6f..300914529693 100644 --- a/src/sentry/monitors/endpoints/organization_monitor_index.py +++ b/src/sentry/monitors/endpoints/organization_monitor_index.py @@ -92,6 +92,7 @@ class OrganizationMonitorIndexEndpoint(OrganizationEndpoint): # TODO(davidenwang): After this is merged and good to go, make this public "PUT": ApiPublishStatus.EXPERIMENTAL, } + project_scope = {"GET": "filter"} idempotent_methods = frozenset() owner = ApiOwner.CRONS permission_classes = (OrganizationAlertRulePermission,) diff --git a/src/sentry/releases/endpoints/organization_release_details.py b/src/sentry/releases/endpoints/organization_release_details.py index df191f228f75..955a88975a4f 100644 --- a/src/sentry/releases/endpoints/organization_release_details.py +++ b/src/sentry/releases/endpoints/organization_release_details.py @@ -351,6 +351,7 @@ class OrganizationReleaseDetailsEndpoint( "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "response:/projects/*/id"} idempotent_methods = frozenset() @extend_schema( diff --git a/src/sentry/replays/endpoints/organization_replay_count.py b/src/sentry/replays/endpoints/organization_replay_count.py index 5af991030acf..0c446d6ba1e6 100644 --- a/src/sentry/replays/endpoints/organization_replay_count.py +++ b/src/sentry/replays/endpoints/organization_replay_count.py @@ -84,6 +84,7 @@ class OrganizationReplayCountEndpoint(OrganizationEventsEndpointBase): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "filter"} enforce_rate_limit = True rate_limits = RateLimitConfig( diff --git a/src/sentry/replays/endpoints/organization_replay_details.py b/src/sentry/replays/endpoints/organization_replay_details.py index c29c1763db49..783fe4e5d6ad 100644 --- a/src/sentry/replays/endpoints/organization_replay_details.py +++ b/src/sentry/replays/endpoints/organization_replay_details.py @@ -236,6 +236,7 @@ class OrganizationReplayDetailsEndpoint(OrganizationReplayEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "response:/data/project_id"} @extend_schema( operation_id="getOrganizationReplay", diff --git a/src/sentry/replays/endpoints/organization_replay_index.py b/src/sentry/replays/endpoints/organization_replay_index.py index d780ac659a01..678b1699084e 100644 --- a/src/sentry/replays/endpoints/organization_replay_index.py +++ b/src/sentry/replays/endpoints/organization_replay_index.py @@ -39,6 +39,7 @@ class OrganizationReplayIndexEndpoint(OrganizationReplayEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "filter"} @extend_schema( operation_id="listOrganizationReplays", diff --git a/src/sentry/sentry_apps/api/endpoints/organization_sentry_apps.py b/src/sentry/sentry_apps/api/endpoints/organization_sentry_apps.py index 79b44fb3e26b..73d1d1383575 100644 --- a/src/sentry/sentry_apps/api/endpoints/organization_sentry_apps.py +++ b/src/sentry/sentry_apps/api/endpoints/organization_sentry_apps.py @@ -29,6 +29,7 @@ class OrganizationSentryAppsEndpoint(ControlSiloOrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} @extend_schema( operation_id="listOrganizationSentryApps", diff --git a/src/sentry/sentry_apps/api/endpoints/sentry_app_components.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_components.py index d4efe3460afe..23b459a800b2 100644 --- a/src/sentry/sentry_apps/api/endpoints/sentry_app_components.py +++ b/src/sentry/sentry_apps/api/endpoints/sentry_app_components.py @@ -61,6 +61,7 @@ class OrganizationSentryAppComponentsEndpoint(ControlSiloOrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL, } + project_scope = {"GET": "org-metadata"} @extend_schema( operation_id="listOrganizationSentryAppComponents", diff --git a/src/sentry/sentry_apps/api/endpoints/sentry_app_installations.py b/src/sentry/sentry_apps/api/endpoints/sentry_app_installations.py index 29dcf94fd046..cd42bbd2d334 100644 --- a/src/sentry/sentry_apps/api/endpoints/sentry_app_installations.py +++ b/src/sentry/sentry_apps/api/endpoints/sentry_app_installations.py @@ -42,6 +42,7 @@ class SentryAppInstallationsEndpoint(SentryAppInstallationsBaseEndpoint): "GET": ApiPublishStatus.PRIVATE, "POST": ApiPublishStatus.PRIVATE, } + project_scope = {"GET": "org-metadata"} @extend_schema( operation_id="List an Organization's Sentry App Installations", diff --git a/src/sentry/workflow_engine/endpoints/organization_available_action_index.py b/src/sentry/workflow_engine/endpoints/organization_available_action_index.py index be81e821d6da..cbdd20f05186 100644 --- a/src/sentry/workflow_engine/endpoints/organization_available_action_index.py +++ b/src/sentry/workflow_engine/endpoints/organization_available_action_index.py @@ -68,6 +68,7 @@ class OrganizationAvailableActionIndexEndpoint(OrganizationEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL, } + project_scope = {"GET": "org-metadata"} owner = ApiOwner.ISSUES @extend_schema( diff --git a/src/sentry/workflow_engine/endpoints/organization_detector_details.py b/src/sentry/workflow_engine/endpoints/organization_detector_details.py index af0d309e284b..61d4b4f36413 100644 --- a/src/sentry/workflow_engine/endpoints/organization_detector_details.py +++ b/src/sentry/workflow_engine/endpoints/organization_detector_details.py @@ -113,6 +113,7 @@ def convert_args( "PUT": ApiPublishStatus.PUBLIC, "DELETE": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "response:/projectId"} idempotent_methods = frozenset() owner = ApiOwner.ALERTS_MONITORS permission_classes = (OrganizationDetectorPermission,) diff --git a/src/sentry/workflow_engine/endpoints/organization_detector_index.py b/src/sentry/workflow_engine/endpoints/organization_detector_index.py index f39f2f8ca5b1..b833b8bce17f 100644 --- a/src/sentry/workflow_engine/endpoints/organization_detector_index.py +++ b/src/sentry/workflow_engine/endpoints/organization_detector_index.py @@ -208,6 +208,7 @@ class OrganizationDetectorIndexEndpoint(OrganizationEndpoint): "PUT": ApiPublishStatus.PUBLIC, "DELETE": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "filter"} idempotent_methods = frozenset({"PUT"}) owner = ApiOwner.ISSUES diff --git a/src/sentry/workflow_engine/endpoints/organization_workflow_details.py b/src/sentry/workflow_engine/endpoints/organization_workflow_details.py index b2f21b117541..9efacce1ce7b 100644 --- a/src/sentry/workflow_engine/endpoints/organization_workflow_details.py +++ b/src/sentry/workflow_engine/endpoints/organization_workflow_details.py @@ -44,6 +44,7 @@ class OrganizationWorkflowDetailsEndpoint(OrganizationWorkflowEndpoint): "PUT": ApiPublishStatus.PUBLIC, "DELETE": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "org-metadata"} idempotent_methods = frozenset() owner = ApiOwner.ALERTS_MONITORS diff --git a/src/sentry/workflow_engine/endpoints/organization_workflow_index.py b/src/sentry/workflow_engine/endpoints/organization_workflow_index.py index d9268ade99ba..56ebdfc50609 100644 --- a/src/sentry/workflow_engine/endpoints/organization_workflow_index.py +++ b/src/sentry/workflow_engine/endpoints/organization_workflow_index.py @@ -173,6 +173,7 @@ class OrganizationWorkflowIndexEndpoint(OrganizationEndpoint): "PUT": ApiPublishStatus.PUBLIC, "DELETE": ApiPublishStatus.PUBLIC, } + project_scope = {"GET": "filter"} idempotent_methods = frozenset({"PUT"}) owner = ApiOwner.ISSUES permission_classes = (OrganizationWorkflowPermission,) diff --git a/tests/apidocs/test_hooks.py b/tests/apidocs/test_hooks.py index 890e16eae5cc..a73215a5b7f1 100644 --- a/tests/apidocs/test_hooks.py +++ b/tests/apidocs/test_hooks.py @@ -16,6 +16,7 @@ _EXPERIMENTAL_OPERATIONS, _IDEMPOTENT_OPERATIONS, _OPERATION_SILOS, + _PROJECT_SCOPE_OPERATIONS, EXPERIMENTAL_NOTICE, CustomEndpointEnumerator, _fix_nullable_enums, @@ -351,6 +352,156 @@ def test_safe_method_raises(self, _write_ownership: Any) -> None: custom_preprocessing_hook(endpoints) +class TestProjectScopeOperations: + """Declared project scopes are collected per method; project paths get "path".""" + + @pytest.fixture(autouse=True) + def isolate_metadata(self) -> Iterator[None]: + _PROJECT_SCOPE_OPERATIONS.clear() + _OPERATION_SILOS.clear() + with patch("sentry.apidocs.hooks.__write_ownership_data"): + yield + _ENDPOINT_SERVERS.clear() + _EXPERIMENTAL_OPERATIONS.clear() + _IDEMPOTENT_OPERATIONS.clear() + _PROJECT_SCOPE_OPERATIONS.clear() + _OPERATION_SILOS.clear() + + def endpoints( + self, path: str, methods: dict[str, ApiPublishStatus], project_scope: dict[str, str] + ) -> list[tuple[Any, Any, str, Any]]: + view_class = type( + "FakeEndpoint", + (), + { + "owner": ApiOwner.CRONS, + "publish_status": methods, + "idempotent_methods": frozenset(), + "project_scope": project_scope, + "servers": None, + }, + ) + callback = type("FakeCallback", (), {"view_class": view_class}) + return [(path, path, method, callback) for method in methods] + + def operation(self, operation_id: str) -> dict[str, Any]: + return { + "tags": ["Events"], + "description": "An endpoint", + "operationId": operation_id, + "parameters": [], + } + + def process(self, paths: dict[str, Any]) -> dict[str, Any]: + return custom_postprocessing_hook({"components": {"schemas": {}}, "paths": paths}, None) + + def test_declared_values_are_stamped_per_method(self) -> None: + path = "/api/0/organizations/{organization_id_or_slug}/things/" + custom_preprocessing_hook( + self.endpoints( + path, + { + "GET": ApiPublishStatus.PUBLIC, + "PUT": ApiPublishStatus.PUBLIC, + "POST": ApiPublishStatus.PUBLIC, + }, + {"GET": "response:/projects/*/id", "PUT": "filter"}, + ) + ) + result = self.process( + { + path: { + "get": self.operation("get-thing"), + "put": self.operation("update-things"), + "post": self.operation("create-thing"), + } + } + ) + + operations = result["paths"][path] + assert operations["get"]["x-sentry-project-scope"] == "response:/projects/*/id" + assert operations["put"]["x-sentry-project-scope"] == "filter" + assert "x-sentry-project-scope" not in operations["post"] + + def test_project_paths_get_path_automatically(self) -> None: + path = "/api/0/projects/{organization_id_or_slug}/{project_id_or_slug}/things/" + custom_preprocessing_hook(self.endpoints(path, {"POST": ApiPublishStatus.PUBLIC}, {})) + result = self.process({path: {"post": self.operation("create-thing")}}) + + assert result["paths"][path]["post"]["x-sentry-project-scope"] == "path" + + def test_declaring_a_project_path_raises(self) -> None: + path = "/api/0/projects/{organization_id_or_slug}/{project_id_or_slug}/things/" + endpoints = self.endpoints(path, {"GET": ApiPublishStatus.PUBLIC}, {"GET": "filter"}) + + with pytest.raises(SentryApiBuildError, match="automatically"): + custom_preprocessing_hook(endpoints) + + @pytest.mark.parametrize( + "published_path", + [ + "/api/0/organizations/{organization_id_or_slug}/{var}/{issue_id}/", + "/api/0/organizations/{organization_id_or_slug}/issues/{issue_id}/", + ], + ) + def test_issue_alias_keeps_its_project_scope(self, published_path: str) -> None: + source_path = "/api/0/organizations/{organization_id_or_slug}/{var}/{issue_id}/" + custom_preprocessing_hook( + [(source_path, source_path, "GET", GroupDetailsEndpoint.as_view())] + ) + result = self.process({published_path: {"get": self.operation("get-issue")}}) + + canonical_path = "/api/0/organizations/{organization_id_or_slug}/issues/{issue_id}/" + operation = result["paths"][canonical_path]["get"] + assert operation["x-sentry-project-scope"] == "response:/project/id" + + def test_unpublished_methods_are_collected(self) -> None: + path = "/api/0/organizations/{organization_id_or_slug}/private-things/" + filtered = custom_preprocessing_hook( + self.endpoints(path, {"GET": ApiPublishStatus.PRIVATE}, {"GET": "org-metadata"}) + ) + + assert filtered == [] + assert _PROJECT_SCOPE_OPERATIONS == {(path, "get"): "org-metadata"} + + def test_next_build_does_not_reuse_previous_values(self) -> None: + _PROJECT_SCOPE_OPERATIONS[("/api/0/stale/", "get")] = "filter" + + custom_preprocessing_hook( + self.endpoints("/api/0/fresh/", {"GET": ApiPublishStatus.PUBLIC}, {}) + ) + + assert _PROJECT_SCOPE_OPERATIONS == {} + + def test_undeclared_method_raises(self) -> None: + endpoints = self.endpoints( + "/api/0/things/", {"GET": ApiPublishStatus.PUBLIC}, {"PUT": "filter"} + ) + + with pytest.raises(SentryApiBuildError, match="does not implement"): + custom_preprocessing_hook(endpoints) + + @pytest.mark.parametrize( + ("method", "value", "error"), + [ + ("GET", "path", "the value must be"), + ("GET", "projects", "the value must be"), + ("PUT", "org-metadata", "org-metadata is only for GET"), + ("PUT", "response:/project/id", "response: is only for GET"), + ("GET", "response:", "JSON pointer"), + ("GET", "response:project/id", "JSON pointer"), + ("GET", "response:/project~2/id", "JSON pointer"), + ], + ) + def test_invalid_value_raises(self, method: str, value: str, error: str) -> None: + endpoints = self.endpoints( + "/api/0/things/", {method: ApiPublishStatus.PUBLIC}, {method: value} + ) + + with pytest.raises(SentryApiBuildError, match=error): + custom_preprocessing_hook(endpoints) + + class SummaryUniquenessTest(TestCase): def _operation(self, summary: str) -> dict[str, Any]: return { From 1565da91b40123139632d630a36b347d3cf10427 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:25:25 +0000 Subject: [PATCH 2/3] ref(apidocs): Don't inherit project_scope on unchecked subclasses The SCIM team details endpoint and the private insights tree and trace item attribute details/merged endpoints inherit a project_scope that was not checked against their handlers. Clear it so only the declared endpoints publish a value. Co-Authored-By: BYK <126780+BYK@users.noreply.github.com> --- src/sentry/api/endpoints/organization_insights_tree.py | 2 ++ .../api/endpoints/organization_trace_item_attribute_details.py | 2 ++ .../api/endpoints/organization_trace_item_attributes_merged.py | 2 ++ src/sentry/apidocs/README.md | 3 ++- src/sentry/core/endpoints/scim/teams.py | 2 ++ 5 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/sentry/api/endpoints/organization_insights_tree.py b/src/sentry/api/endpoints/organization_insights_tree.py index 29a4498ec3bd..1dc8217af5ac 100644 --- a/src/sentry/api/endpoints/organization_insights_tree.py +++ b/src/sentry/api/endpoints/organization_insights_tree.py @@ -59,6 +59,8 @@ class OrganizationInsightsTreeEndpoint(OrganizationEventsEndpoint): publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } + # Not checked against this endpoint's handler, so don't inherit the parent's. + project_scope = {} def get(self, request: Request, organization: Organization) -> HttpResponseBase: if not request.GET.get("noPagination", False): diff --git a/src/sentry/api/endpoints/organization_trace_item_attribute_details.py b/src/sentry/api/endpoints/organization_trace_item_attribute_details.py index bc4fa6678b7b..ac4244ebeaeb 100644 --- a/src/sentry/api/endpoints/organization_trace_item_attribute_details.py +++ b/src/sentry/api/endpoints/organization_trace_item_attribute_details.py @@ -175,6 +175,8 @@ class OrganizationTraceItemAttributeDetailsEndpoint(OrganizationTraceItemAttribu publish_status = { "GET": ApiPublishStatus.PRIVATE, } + # Not checked against this endpoint's handler, so don't inherit the parent's. + project_scope = {} def get(self, request: Request, organization: Organization) -> Response: if not features.has( diff --git a/src/sentry/api/endpoints/organization_trace_item_attributes_merged.py b/src/sentry/api/endpoints/organization_trace_item_attributes_merged.py index b073e383806c..39a786b57ac5 100644 --- a/src/sentry/api/endpoints/organization_trace_item_attributes_merged.py +++ b/src/sentry/api/endpoints/organization_trace_item_attributes_merged.py @@ -271,6 +271,8 @@ class OrganizationTraceItemAttributesMergedEndpoint(OrganizationTraceItemAttribu publish_status = { "GET": ApiPublishStatus.PRIVATE, } + # Not checked against this endpoint's handler, so don't inherit the parent's. + project_scope = {} def get(self, request: Request, organization: Organization) -> Response: if not features.has( diff --git a/src/sentry/apidocs/README.md b/src/sentry/apidocs/README.md index a94e760a086a..32da56a50073 100644 --- a/src/sentry/apidocs/README.md +++ b/src/sentry/apidocs/README.md @@ -105,7 +105,8 @@ The build fails for any other value, for `org-metadata` or `response:` on a method other than `GET`, for a method the endpoint does not declare in `publish_status`, and for a declaration on a path that contains `{project_id_or_slug}`. A method without a value is not known to respect a -project limit. Subclasses inherit the declaration, like `idempotent_methods`. +project limit. Subclasses inherit the declaration, like `idempotent_methods`; +set `project_scope = {}` on a subclass whose handler it doesn't hold for. Declarations are collected for every endpoint and reset on every build. # Response fields diff --git a/src/sentry/core/endpoints/scim/teams.py b/src/sentry/core/endpoints/scim/teams.py index 938ae3cb29f1..24a226cf5a07 100644 --- a/src/sentry/core/endpoints/scim/teams.py +++ b/src/sentry/core/endpoints/scim/teams.py @@ -339,6 +339,8 @@ class OrganizationSCIMTeamDetails(SCIMEndpoint, TeamDetailsEndpoint): "PUT": ApiPublishStatus.EXPERIMENTAL, "PATCH": ApiPublishStatus.PUBLIC, } + # Not checked against this endpoint's handler, so don't inherit the parent's. + project_scope = {} idempotent_methods = frozenset() permission_classes = (OrganizationSCIMTeamPermission,) _allow_idp_changes = True From 647ebc4797f2b1b1079bb8702a11910e8d532f93 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 13:44:48 +0000 Subject: [PATCH 3/3] ref(apidocs): Derive project_scope filter and check response pointers Stamp "filter" on every non-project-path operation that documents the project query parameter, instead of declaring it per endpoint. A declared value still wins. Fail the schema build when a "response:" pointer does not reach a string or integer field in the operation's 200 response schema. Refs getsentry/toolkit#2237 --- .../organization_ai_conversations.py | 1 - src/sentry/api/base.py | 4 +- .../api/endpoints/organization_events.py | 1 - .../endpoints/organization_events_dropped.py | 1 - .../organization_events_timeseries.py | 1 - .../endpoints/organization_insights_tree.py | 2 - .../api/endpoints/organization_releases.py | 1 - ...ganization_trace_item_attribute_details.py | 2 - .../organization_trace_item_attributes.py | 1 - ...ganization_trace_item_attributes_merged.py | 2 - src/sentry/apidocs/README.md | 29 ++- src/sentry/apidocs/hooks.py | 48 +++++ .../endpoints/organization_group_index.py | 1 - .../endpoints/organization_monitor_index.py | 1 - .../endpoints/organization_replay_count.py | 1 - .../endpoints/organization_replay_index.py | 1 - .../endpoints/organization_detector_index.py | 1 - .../endpoints/organization_workflow_index.py | 1 - tests/apidocs/test_hooks.py | 185 ++++++++++++++++-- 19 files changed, 244 insertions(+), 40 deletions(-) diff --git a/src/sentry/ai_monitoring/endpoints/organization_ai_conversations.py b/src/sentry/ai_monitoring/endpoints/organization_ai_conversations.py index 3e1fd8a5ff6b..3366efd1aefd 100644 --- a/src/sentry/ai_monitoring/endpoints/organization_ai_conversations.py +++ b/src/sentry/ai_monitoring/endpoints/organization_ai_conversations.py @@ -163,7 +163,6 @@ class OrganizationAIConversationsEndpoint(OrganizationEventsEndpointBase): publish_status = { "GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL, } - project_scope = {"GET": "filter"} owner = ApiOwner.AGENT_TRACING @extend_schema( diff --git a/src/sentry/api/base.py b/src/sentry/api/base.py index 1e4839980772..dd7c81f765c7 100644 --- a/src/sentry/api/base.py +++ b/src/sentry/api/base.py @@ -307,8 +307,8 @@ class Endpoint(APIView): idempotent_methods: frozenset[HTTP_METHOD_NAME] | None = None # How each method's request names the projects whose data it returns or changes, # for clients that limit a caller to some projects. Published as - # `x-sentry-project-scope`; see apidocs/README.md. Paths with `{project_id_or_slug}` - # get "path" automatically, so only organization-level endpoints declare it. + # `x-sentry-project-scope`; see apidocs/README.md. The schema build derives "path" + # and "filter", so endpoints mostly declare "org-metadata" and "response:" values. project_scope: dict[HTTP_METHOD_NAME, str] = {} rate_limits: RateLimitConfig | Callable[..., RateLimitConfig] = DEFAULT_RATE_LIMIT_CONFIG enforce_rate_limit: bool = settings.SENTRY_RATELIMITER_ENABLED diff --git a/src/sentry/api/endpoints/organization_events.py b/src/sentry/api/endpoints/organization_events.py index d048aacfa5c8..39e3326c8c5b 100644 --- a/src/sentry/api/endpoints/organization_events.py +++ b/src/sentry/api/endpoints/organization_events.py @@ -177,7 +177,6 @@ class OrganizationEventsEndpoint(OrganizationEventsEndpointBase): publish_status = { "GET": ApiPublishStatus.PUBLIC, } - project_scope = {"GET": "filter"} enforce_rate_limit = True diff --git a/src/sentry/api/endpoints/organization_events_dropped.py b/src/sentry/api/endpoints/organization_events_dropped.py index 27488bba62f9..6ff349943e60 100644 --- a/src/sentry/api/endpoints/organization_events_dropped.py +++ b/src/sentry/api/endpoints/organization_events_dropped.py @@ -123,7 +123,6 @@ class OrganizationEventsDroppedEndpoint(OrganizationEventsEndpointBase): publish_status = { "GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL, } - project_scope = {"GET": "filter"} @extend_schema( operation_id="listOrganizationEventsDropped", diff --git a/src/sentry/api/endpoints/organization_events_timeseries.py b/src/sentry/api/endpoints/organization_events_timeseries.py index 18207ce0450e..ea2040ceb2d4 100644 --- a/src/sentry/api/endpoints/organization_events_timeseries.py +++ b/src/sentry/api/endpoints/organization_events_timeseries.py @@ -270,7 +270,6 @@ class OrganizationEventsTimeseriesEndpoint(OrganizationEventsEndpointBase): publish_status = { "GET": ApiPublishStatus.PUBLIC, } - project_scope = {"GET": "filter"} enforce_rate_limit = True diff --git a/src/sentry/api/endpoints/organization_insights_tree.py b/src/sentry/api/endpoints/organization_insights_tree.py index 1dc8217af5ac..29a4498ec3bd 100644 --- a/src/sentry/api/endpoints/organization_insights_tree.py +++ b/src/sentry/api/endpoints/organization_insights_tree.py @@ -59,8 +59,6 @@ class OrganizationInsightsTreeEndpoint(OrganizationEventsEndpoint): publish_status = { "GET": ApiPublishStatus.EXPERIMENTAL, } - # Not checked against this endpoint's handler, so don't inherit the parent's. - project_scope = {} def get(self, request: Request, organization: Organization) -> HttpResponseBase: if not request.GET.get("noPagination", False): diff --git a/src/sentry/api/endpoints/organization_releases.py b/src/sentry/api/endpoints/organization_releases.py index b7e3fc58da5d..8e12b6fb81e2 100644 --- a/src/sentry/api/endpoints/organization_releases.py +++ b/src/sentry/api/endpoints/organization_releases.py @@ -357,7 +357,6 @@ class OrganizationReleasesEndpoint(OrganizationReleasesBaseEndpoint, ReleaseAnal "GET": ApiPublishStatus.PUBLIC, "POST": ApiPublishStatus.PUBLIC, } - project_scope = {"GET": "filter"} idempotent_methods = frozenset() rate_limits = RateLimitConfig( diff --git a/src/sentry/api/endpoints/organization_trace_item_attribute_details.py b/src/sentry/api/endpoints/organization_trace_item_attribute_details.py index ac4244ebeaeb..bc4fa6678b7b 100644 --- a/src/sentry/api/endpoints/organization_trace_item_attribute_details.py +++ b/src/sentry/api/endpoints/organization_trace_item_attribute_details.py @@ -175,8 +175,6 @@ class OrganizationTraceItemAttributeDetailsEndpoint(OrganizationTraceItemAttribu publish_status = { "GET": ApiPublishStatus.PRIVATE, } - # Not checked against this endpoint's handler, so don't inherit the parent's. - project_scope = {} def get(self, request: Request, organization: Organization) -> Response: if not features.has( diff --git a/src/sentry/api/endpoints/organization_trace_item_attributes.py b/src/sentry/api/endpoints/organization_trace_item_attributes.py index ba97150eb724..6ac6dca2a737 100644 --- a/src/sentry/api/endpoints/organization_trace_item_attributes.py +++ b/src/sentry/api/endpoints/organization_trace_item_attributes.py @@ -777,7 +777,6 @@ class OrganizationTraceItemAttributesEndpoint(OrganizationTraceItemAttributesEnd publish_status = { "GET": ApiPublishStatus.PUBLIC, } - project_scope = {"GET": "filter"} @extend_schema( operation_id="listOrganizationTraceItemAttributes", diff --git a/src/sentry/api/endpoints/organization_trace_item_attributes_merged.py b/src/sentry/api/endpoints/organization_trace_item_attributes_merged.py index 39a786b57ac5..b073e383806c 100644 --- a/src/sentry/api/endpoints/organization_trace_item_attributes_merged.py +++ b/src/sentry/api/endpoints/organization_trace_item_attributes_merged.py @@ -271,8 +271,6 @@ class OrganizationTraceItemAttributesMergedEndpoint(OrganizationTraceItemAttribu publish_status = { "GET": ApiPublishStatus.PRIVATE, } - # Not checked against this endpoint's handler, so don't inherit the parent's. - project_scope = {} def get(self, request: Request, organization: Organization) -> Response: if not features.has( diff --git a/src/sentry/apidocs/README.md b/src/sentry/apidocs/README.md index 32da56a50073..6e0be547b3f6 100644 --- a/src/sentry/apidocs/README.md +++ b/src/sentry/apidocs/README.md @@ -80,7 +80,7 @@ of endpoints. It is a string: | Value | Meaning | | -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `path` | The path names the project. Set automatically on every operation whose path contains `{project_id_or_slug}`. | +| `path` | The path names the project. | | `filter` | An organization endpoint that takes the `project` query parameter (numeric project IDs) and returns or changes only those projects' data. | | `org-metadata` | A read-only organization endpoint whose response holds no project's issues, events, replays, or other telemetry, such as settings, members, integrations, and saved views. | | `response:` | A `GET` that looks something up by ID alone. The numeric ID of the project it belongs to is at `` in the response body, such as `response:/project/id`. | @@ -89,25 +89,36 @@ of endpoints. It is a string: element of an array: `response:/projects/*/id`. The value at the pointer can be a numeric string and, for objects that belong to no project, `null`. -An organization-level endpoint declares it per method: +Most operations get their value from the schema, so endpoints don't declare it: + +- `path` on every operation whose path contains `{project_id_or_slug}`. +- `filter` on every other operation that documents the `project` query + parameter, such as with `OrganizationParams.PROJECT` in `@extend_schema`. + Document it only when the handler limits its results to those projects, which + `get_projects`, `get_filter_params`, and `get_snuba_params` do. + +An organization-level endpoint declares the rest per method, and a declaration +wins over a derived `filter`: ```python -class OrganizationGroupIndexEndpoint(OrganizationEndpoint): +class OrganizationReleaseDetailsEndpoint(OrganizationReleasesBaseEndpoint): publish_status = { "DELETE": ApiPublishStatus.PUBLIC, "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } - project_scope = {"GET": "filter", "PUT": "filter", "DELETE": "filter"} + project_scope = {"GET": "response:/projects/*/id"} ``` The build fails for any other value, for `org-metadata` or `response:` on a method other than `GET`, for a method the endpoint does not declare in -`publish_status`, and for a declaration on a path that contains -`{project_id_or_slug}`. A method without a value is not known to respect a -project limit. Subclasses inherit the declaration, like `idempotent_methods`; -set `project_scope = {}` on a subclass whose handler it doesn't hold for. -Declarations are collected for every endpoint and reset on every build. +`publish_status`, for a declaration on a path that contains +`{project_id_or_slug}`, and for a `response:` pointer that does not reach a +string or integer field in the operation's 200 response schema. A method +without a value is not known to respect a project limit. Subclasses inherit the +declaration, like `idempotent_methods`; set `project_scope = {}` on a subclass +whose handler it doesn't hold for. Declarations are collected for every +endpoint and reset on every build. # Response fields diff --git a/src/sentry/apidocs/hooks.py b/src/sentry/apidocs/hooks.py index 68e376288d0f..83656dcb4576 100644 --- a/src/sentry/apidocs/hooks.py +++ b/src/sentry/apidocs/hooks.py @@ -195,6 +195,51 @@ def _project_scope_error(method: str, value: str) -> str | None: return 'the value must be "filter", "org-metadata", or "response:"' +def _takes_project_filter(operation: Mapping[str, Any]) -> bool: + return any( + param.get("in") == "query" and param.get("name") == "project" + for param in operation.get("parameters", []) + ) + + +def _schemas_at_pointer( + schema: Mapping[str, Any], segments: list[str], components: Mapping[str, Any] +) -> list[Mapping[str, Any]]: + """Every schema that a JSON pointer can reach, across $ref, allOf, oneOf, and anyOf.""" + while "$ref" in schema: + schema = components[schema["$ref"].split("/")[-1]] + found = [ + reached + for key in ("allOf", "oneOf", "anyOf") + for branch in schema.get(key, []) + for reached in _schemas_at_pointer(branch, segments, components) + ] + if not segments: + return [*found, schema] + head, *rest = segments + child = schema.get("items") if head == "*" else schema.get("properties", {}).get(head) + if child is not None: + found.extend(_schemas_at_pointer(child, rest, components)) + return found + + +def _check_project_scope_pointer( + operation: Mapping[str, Any], components: Mapping[str, Any], endpoint_name: str +) -> None: + scope = operation.get("x-sentry-project-scope", "") + if not scope.startswith(_PROJECT_SCOPE_RESPONSE_PREFIX): + return + pointer = scope.removeprefix(_PROJECT_SCOPE_RESPONSE_PREFIX) + segments = [s.replace("~1", "/").replace("~0", "~") for s in pointer.split("/")[1:]] + response = operation.get("responses", {}).get("200", {}) + schema = response.get("content", {}).get("application/json", {}).get("schema") + reached = _schemas_at_pointer(schema, segments, components) if schema else [] + if not any(s.get("type") in ("integer", "string") for s in reached): + raise SentryApiBuildError( + f"project_scope {scope!r} of endpoint {endpoint_name} does not point to a string or integer field in its 200 response." + ) + + # Include non-spectacular endpoints so existing APPEND_PATHS operations can use # their backend declaration without changing which methods are published. _OPERATION_SILOS: dict[tuple[str, str], DeclaredSilo] = {} @@ -403,6 +448,8 @@ def custom_postprocessing_hook( operation["x-sentry-project-scope"] = "path" elif operation_key in _PROJECT_SCOPE_OPERATIONS: operation["x-sentry-project-scope"] = _PROJECT_SCOPE_OPERATIONS[operation_key] + elif _takes_project_filter(operation): + operation["x-sentry-project-scope"] = "filter" # Add servers override from endpoint class definitions for path, servers in _ENDPOINT_SERVERS.items(): @@ -462,6 +509,7 @@ def custom_postprocessing_hook( summaries_seen[summary] = endpoint_name _check_tag(method_info, endpoint_name) + _check_project_scope_pointer(method_info, schema_components, endpoint_name) _check_description( method_info, f"Please add a description to your endpoint {endpoint_name} via docstring", diff --git a/src/sentry/issues/endpoints/organization_group_index.py b/src/sentry/issues/endpoints/organization_group_index.py index 59c452ef3ef1..d6910e16c6c9 100644 --- a/src/sentry/issues/endpoints/organization_group_index.py +++ b/src/sentry/issues/endpoints/organization_group_index.py @@ -272,7 +272,6 @@ class OrganizationGroupIndexEndpoint(OrganizationEndpoint): "GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC, } - project_scope = {"GET": "filter", "PUT": "filter", "DELETE": "filter"} idempotent_methods = frozenset() owner = ApiOwner.ISSUES max_acceptable_duration = {"GET": DEFAULT_DURATION_BUDGET, "PUT": 10.0, "DELETE": 10.0} diff --git a/src/sentry/monitors/endpoints/organization_monitor_index.py b/src/sentry/monitors/endpoints/organization_monitor_index.py index 300914529693..900c901d9f6f 100644 --- a/src/sentry/monitors/endpoints/organization_monitor_index.py +++ b/src/sentry/monitors/endpoints/organization_monitor_index.py @@ -92,7 +92,6 @@ class OrganizationMonitorIndexEndpoint(OrganizationEndpoint): # TODO(davidenwang): After this is merged and good to go, make this public "PUT": ApiPublishStatus.EXPERIMENTAL, } - project_scope = {"GET": "filter"} idempotent_methods = frozenset() owner = ApiOwner.CRONS permission_classes = (OrganizationAlertRulePermission,) diff --git a/src/sentry/replays/endpoints/organization_replay_count.py b/src/sentry/replays/endpoints/organization_replay_count.py index 0c446d6ba1e6..5af991030acf 100644 --- a/src/sentry/replays/endpoints/organization_replay_count.py +++ b/src/sentry/replays/endpoints/organization_replay_count.py @@ -84,7 +84,6 @@ class OrganizationReplayCountEndpoint(OrganizationEventsEndpointBase): publish_status = { "GET": ApiPublishStatus.PUBLIC, } - project_scope = {"GET": "filter"} enforce_rate_limit = True rate_limits = RateLimitConfig( diff --git a/src/sentry/replays/endpoints/organization_replay_index.py b/src/sentry/replays/endpoints/organization_replay_index.py index 678b1699084e..d780ac659a01 100644 --- a/src/sentry/replays/endpoints/organization_replay_index.py +++ b/src/sentry/replays/endpoints/organization_replay_index.py @@ -39,7 +39,6 @@ class OrganizationReplayIndexEndpoint(OrganizationReplayEndpoint): publish_status = { "GET": ApiPublishStatus.PUBLIC, } - project_scope = {"GET": "filter"} @extend_schema( operation_id="listOrganizationReplays", diff --git a/src/sentry/workflow_engine/endpoints/organization_detector_index.py b/src/sentry/workflow_engine/endpoints/organization_detector_index.py index b833b8bce17f..f39f2f8ca5b1 100644 --- a/src/sentry/workflow_engine/endpoints/organization_detector_index.py +++ b/src/sentry/workflow_engine/endpoints/organization_detector_index.py @@ -208,7 +208,6 @@ class OrganizationDetectorIndexEndpoint(OrganizationEndpoint): "PUT": ApiPublishStatus.PUBLIC, "DELETE": ApiPublishStatus.PUBLIC, } - project_scope = {"GET": "filter"} idempotent_methods = frozenset({"PUT"}) owner = ApiOwner.ISSUES diff --git a/src/sentry/workflow_engine/endpoints/organization_workflow_index.py b/src/sentry/workflow_engine/endpoints/organization_workflow_index.py index 56ebdfc50609..d9268ade99ba 100644 --- a/src/sentry/workflow_engine/endpoints/organization_workflow_index.py +++ b/src/sentry/workflow_engine/endpoints/organization_workflow_index.py @@ -173,7 +173,6 @@ class OrganizationWorkflowIndexEndpoint(OrganizationEndpoint): "PUT": ApiPublishStatus.PUBLIC, "DELETE": ApiPublishStatus.PUBLIC, } - project_scope = {"GET": "filter"} idempotent_methods = frozenset({"PUT"}) owner = ApiOwner.ISSUES permission_classes = (OrganizationWorkflowPermission,) diff --git a/tests/apidocs/test_hooks.py b/tests/apidocs/test_hooks.py index a73215a5b7f1..50791f8664ad 100644 --- a/tests/apidocs/test_hooks.py +++ b/tests/apidocs/test_hooks.py @@ -384,16 +384,36 @@ def endpoints( callback = type("FakeCallback", (), {"view_class": view_class}) return [(path, path, method, callback) for method in methods] - def operation(self, operation_id: str) -> dict[str, Any]: - return { + def operation( + self, + operation_id: str, + parameters: list[dict[str, Any]] | None = None, + response: dict[str, Any] | None = None, + ) -> dict[str, Any]: + operation: dict[str, Any] = { "tags": ["Events"], "description": "An endpoint", "operationId": operation_id, - "parameters": [], + "parameters": parameters or [], } + if response is not None: + operation["responses"] = { + "200": {"content": {"application/json": {"schema": response}}} + } + return operation - def process(self, paths: dict[str, Any]) -> dict[str, Any]: - return custom_postprocessing_hook({"components": {"schemas": {}}, "paths": paths}, None) + def process( + self, paths: dict[str, Any], components: dict[str, Any] | None = None + ) -> dict[str, Any]: + return custom_postprocessing_hook( + {"components": {"schemas": components or {}}, "paths": paths}, None + ) + + project_param = {"in": "query", "name": "project", "description": "Projects"} + project_id_response = { + "type": "object", + "properties": {"project": {"type": "object", "properties": {"id": {"type": "string"}}}}, + } def test_declared_values_are_stamped_per_method(self) -> None: path = "/api/0/organizations/{organization_id_or_slug}/things/" @@ -411,11 +431,24 @@ def test_declared_values_are_stamped_per_method(self) -> None: result = self.process( { path: { - "get": self.operation("get-thing"), + "get": self.operation( + "get-thing", response={"$ref": "#/components/schemas/Thing"} + ), "put": self.operation("update-things"), "post": self.operation("create-thing"), } - } + }, + components={ + "Thing": { + "type": "object", + "properties": { + "projects": { + "type": "array", + "items": {"type": "object", "properties": {"id": {"type": "integer"}}}, + } + }, + } + }, ) operations = result["paths"][path] @@ -449,7 +482,13 @@ def test_issue_alias_keeps_its_project_scope(self, published_path: str) -> None: custom_preprocessing_hook( [(source_path, source_path, "GET", GroupDetailsEndpoint.as_view())] ) - result = self.process({published_path: {"get": self.operation("get-issue")}}) + result = self.process( + { + published_path: { + "get": self.operation("get-issue", response=self.project_id_response) + } + } + ) canonical_path = "/api/0/organizations/{organization_id_or_slug}/issues/{issue_id}/" operation = result["paths"][canonical_path]["get"] @@ -501,6 +540,113 @@ def test_invalid_value_raises(self, method: str, value: str, error: str) -> None with pytest.raises(SentryApiBuildError, match=error): custom_preprocessing_hook(endpoints) + def test_documented_project_parameter_derives_filter(self) -> None: + path = "/api/0/organizations/{organization_id_or_slug}/things/" + custom_preprocessing_hook( + self.endpoints( + path, {"GET": ApiPublishStatus.PUBLIC, "PUT": ApiPublishStatus.PUBLIC}, {} + ) + ) + result = self.process( + { + path: { + "get": self.operation("list-things", [self.project_param]), + "put": self.operation("update-things"), + } + } + ) + + assert result["paths"][path]["get"]["x-sentry-project-scope"] == "filter" + assert "x-sentry-project-scope" not in result["paths"][path]["put"] + + def test_declaration_wins_over_derived_filter(self) -> None: + path = "/api/0/organizations/{organization_id_or_slug}/things/{thing_id}/" + custom_preprocessing_hook( + self.endpoints(path, {"GET": ApiPublishStatus.PUBLIC}, {"GET": "response:/project/id"}) + ) + result = self.process( + { + path: { + "get": self.operation( + "get-thing", [self.project_param], self.project_id_response + ) + } + } + ) + + assert result["paths"][path]["get"]["x-sentry-project-scope"] == "response:/project/id" + + def test_project_path_wins_over_derived_filter(self) -> None: + path = "/api/0/projects/{organization_id_or_slug}/{project_id_or_slug}/things/" + custom_preprocessing_hook(self.endpoints(path, {"GET": ApiPublishStatus.PUBLIC}, {})) + result = self.process({path: {"get": self.operation("list-things", [self.project_param])}}) + + assert result["paths"][path]["get"]["x-sentry-project-scope"] == "path" + + @pytest.mark.parametrize( + "pointer", + [ + "/project/id", + "/project/name", + "/project", + "/projects/*/id", + "/project/id/value", + ], + ) + def test_pointer_missing_from_response_raises(self, pointer: str) -> None: + path = "/api/0/organizations/{organization_id_or_slug}/things/{thing_id}/" + custom_preprocessing_hook( + self.endpoints(path, {"GET": ApiPublishStatus.PUBLIC}, {"GET": f"response:{pointer}"}) + ) + response = { + "type": "object", + "properties": { + "project": {"type": "object", "properties": {"slug": {"type": "string"}}} + }, + } + if pointer == "/project/id/value": + response = self.project_id_response + + with pytest.raises(SentryApiBuildError, match="does not point to a string or integer"): + self.process({path: {"get": self.operation("get-thing", response=response)}}) + + def test_pointer_follows_refs_and_union_branches(self) -> None: + path = "/api/0/organizations/{organization_id_or_slug}/things/{thing_id}/" + custom_preprocessing_hook( + self.endpoints( + path, {"GET": ApiPublishStatus.PUBLIC}, {"GET": "response:/data/project~1id"} + ) + ) + components = { + "Thing": { + "type": "object", + "properties": { + "data": { + "allOf": [{"$ref": "#/components/schemas/ThingData"}], + "nullable": True, + } + }, + }, + "ThingData": { + "type": "object", + "properties": {"project/id": {"oneOf": [{"type": "string"}, {"type": "integer"}]}}, + }, + } + result = self.process( + { + path: { + "get": self.operation( + "get-thing", response={"$ref": "#/components/schemas/Thing"} + ) + } + }, + components, + ) + + assert ( + result["paths"][path]["get"]["x-sentry-project-scope"] == "response:/data/project~1id" + ) + class SummaryUniquenessTest(TestCase): def _operation(self, summary: str) -> dict[str, Any]: @@ -817,9 +963,26 @@ def test_issue_alias_and_already_canonical_appended_operation_keep_routing( custom_preprocessing_hook( [(source_path, source_path, "GET", GroupDetailsEndpoint.as_view())] ) - result = self.process( - {published_path: {"get": self.operation([self.parameter("organization_id_or_slug")])}} - ) + operation = self.operation([self.parameter("organization_id_or_slug")]) + # GroupDetailsEndpoint's project_scope points into its response. + operation["responses"] = { + "200": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "project": { + "type": "object", + "properties": {"id": {"type": "string"}}, + } + }, + } + } + } + } + } + result = self.process({published_path: {"get": operation}}) canonical_path = "/api/0/organizations/{organization_id_or_slug}/issues/{issue_id}/" assert result["paths"][canonical_path]["get"]["x-sentry-routing"] == { "silo": "cell",