Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/sentry/api/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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
# Origins that serve this endpoint, for the API docs; the schema build adds the base path.
Expand Down
1 change: 1 addition & 0 deletions src/sentry/api/endpoints/chunk.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/sentry/api/endpoints/dsn_lookup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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={
Expand Down
49 changes: 49 additions & 0 deletions src/sentry/apidocs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,55 @@ 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. |
| `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:<pointer>` | A `GET` that looks something up by ID alone. The numeric ID of the project it belongs to is at `<pointer>` in the response body, such as `response:/project/id`. |

`<pointer>` 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`.

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 OrganizationReleaseDetailsEndpoint(OrganizationReleasesBaseEndpoint):
publish_status = {
"DELETE": ApiPublishStatus.PUBLIC,
"GET": ApiPublishStatus.PUBLIC,
"PUT": ApiPublishStatus.PUBLIC,
}
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`, 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

Every field in a public operation's success (2xx) response needs a description
Expand Down
97 changes: 97 additions & 0 deletions src/sentry/apidocs/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,76 @@ 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:<JSON pointer>"'


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] = {}
Expand Down Expand Up @@ -203,6 +273,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]]] = {}
Expand Down Expand Up @@ -248,6 +319,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

Expand All @@ -256,6 +344,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:
Expand Down Expand Up @@ -354,6 +444,12 @@ 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]
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():
Expand Down Expand Up @@ -413,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",
Expand Down
1 change: 1 addition & 0 deletions src/sentry/core/endpoints/organization_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -1050,6 +1050,7 @@ class OrganizationDetailsEndpoint(OrganizationEndpoint):
"GET": ApiPublishStatus.PUBLIC,
"PUT": ApiPublishStatus.PUBLIC,
}
project_scope = {"GET": "org-metadata"}
idempotent_methods = frozenset()

@extend_schema(
Expand Down
1 change: 1 addition & 0 deletions src/sentry/core/endpoints/organization_environments.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ class OrganizationEnvironmentsEndpoint(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
project_scope = {"GET": "org-metadata"}

@extend_schema(
operation_id="listOrganizationEnvironments",
Expand Down
1 change: 1 addition & 0 deletions src/sentry/core/endpoints/organization_member_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,)
Expand Down
1 change: 1 addition & 0 deletions src/sentry/core/endpoints/organization_member_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ class OrganizationMemberIndexEndpoint(OrganizationEndpoint):
"GET": ApiPublishStatus.PUBLIC,
"POST": ApiPublishStatus.PUBLIC,
}
project_scope = {"GET": "org-metadata"}
idempotent_methods = frozenset()

rate_limits = RateLimitConfig(
Expand Down
1 change: 1 addition & 0 deletions src/sentry/core/endpoints/organization_projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/sentry/core/endpoints/organization_teams.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ class OrganizationTeamsEndpoint(OrganizationEndpoint):
"GET": ApiPublishStatus.PUBLIC,
"POST": ApiPublishStatus.PUBLIC,
}
project_scope = {"GET": "org-metadata"}
idempotent_methods = frozenset()
permission_classes = (OrganizationTeamsPermission,)

Expand Down
1 change: 1 addition & 0 deletions src/sentry/core/endpoints/organization_user_teams.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ class OrganizationUserTeamsEndpoint(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
project_scope = {"GET": "org-metadata"}
owner = ApiOwner.FOUNDATIONS

@extend_schema(
Expand Down
2 changes: 2 additions & 0 deletions src/sentry/core/endpoints/scim/teams.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/sentry/core/endpoints/team_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/sentry/core/endpoints/team_members.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ class TeamMembersEndpoint(TeamEndpoint):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
project_scope = {"GET": "org-metadata"}
owner = ApiOwner.FOUNDATIONS

@extend_schema(
Expand Down
1 change: 1 addition & 0 deletions src/sentry/core/endpoints/team_projects.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ class OrganizationDashboardDetailsEndpoint(OrganizationDashboardBase):
"GET": ApiPublishStatus.PUBLIC,
"PUT": ApiPublishStatus.PUBLIC,
}
project_scope = {"GET": "org-metadata"}
idempotent_methods = frozenset()

@extend_schema(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class OrganizationDashboardRevisionsEndpoint(OrganizationDashboardBase):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
project_scope = {"GET": "org-metadata"}
owner = ApiOwner.DASHBOARDS

@extend_schema(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,)
Expand Down
1 change: 1 addition & 0 deletions src/sentry/discover/endpoints/discover_saved_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class OrganizationConfigIntegrationsEndpoint(OrganizationEndpoint):
publish_status = {
"GET": ApiPublishStatus.PUBLIC,
}
project_scope = {"GET": "org-metadata"}

@extend_schema(
operation_id="getOrganizationConfigIntegrations",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,7 @@ class OrganizationIntegrationChannelsEndpoint(OrganizationIntegrationBaseEndpoin
publish_status = {
"GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL,
}
project_scope = {"GET": "org-metadata"}
owner = ApiOwner.TELEMETRY_EXPERIENCE

@extend_schema(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ class OrganizationIntegrationDetailsEndpoint(OrganizationIntegrationBaseEndpoint
"GET": ApiPublishStatus.PUBLIC,
"POST": ApiPublishStatus.PRIVATE,
}
project_scope = {"GET": "org-metadata"}
idempotent_methods = frozenset()

@extend_schema(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ class OrganizationIntegrationReposEndpoint(CellOrganizationIntegrationBaseEndpoi
publish_status = {
"GET": ApiPublishStatus.PUBLIC_EXPERIMENTAL,
}
project_scope = {"GET": "org-metadata"}
owner = ApiOwner.ISSUES

@extend_schema(
Expand Down
Loading
Loading