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
13 changes: 5 additions & 8 deletions src/sentry/api/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,10 @@
audit_logger = logging.getLogger("sentry.audit.api")
api_access_logger = logging.getLogger("sentry.access.api")

from sentry import analytics, features, tsdb
from sentry import analytics, tsdb
from sentry.analytics.events.release_set_commits import ReleaseSetCommitsLocalEvent
from sentry.api.api_owners import ApiOwner
from sentry.api.api_publish_status import ApiPublishStatus
from sentry.api.client_kind import FEATURE_FLAG as CLIENT_KIND_FEATURE_FLAG
from sentry.api.client_kind import set_client_kind_attributes
from sentry.api.exceptions import (
INSUFFICIENT_SCOPE_ATTR,
Expand Down Expand Up @@ -511,15 +510,13 @@ def dispatch(self, request: Request, *args, **kwargs) -> Response:
self.args = args
self.kwargs = kwargs

# Resolved solely to check the opt-in; everything else is
# derived from the request. Both sources are conventions rather
# than contracts, so the result is type-checked before use.
# Attribution is scoped to endpoints that resolve an organization;
# everything else is derived from the request. Both sources are
# conventions rather than contracts, so the result is type-checked.
organization = kwargs.get("organization") or getattr(
request, "organization", None
)
if isinstance(organization, (Organization, RpcOrganization)) and features.has(
CLIENT_KIND_FEATURE_FLAG, organization, actor=request.user
):
if isinstance(organization, (Organization, RpcOrganization)):
set_client_kind_attributes(request)
else:
handler = self.http_method_not_allowed
Expand Down
13 changes: 3 additions & 10 deletions src/sentry/api/client_kind.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@
from sentry.utils.sdk import get_transaction_name_from_request
from sentry.utils.tracing import set_span_data, start_span

FEATURE_FLAG = "organizations:api-client-kind-check"

ATTRIBUTION_SPAN_OP = "api.attribution"


Expand Down Expand Up @@ -105,11 +103,6 @@ def get_client_kind(request: Request) -> ClientKind:
"""Classify the caller of an API request.

Never raises; unrecognized callers fall back to ``UNKNOWN``.

Says nothing about whether the caller's organization opted in -- ``FEATURE_FLAG``
is checked by the caller, which is what holds the organization. Callers must
check it before reaching here, or a ``client_kind_scope`` declaration becomes a
way around the opt-in.
"""
declared = _client_kind_override.get()
if declared is not None:
Expand Down Expand Up @@ -187,9 +180,9 @@ def get_client_kind(request: Request) -> ClientKind:
def set_client_kind_attributes(request: Request) -> None:
"""Record who called the endpoint, on a span and on the enclosing transaction.

Called once from ``Endpoint.dispatch``, behind the opt-in check it makes for
whichever organization ``Endpoint.client_kind_organization`` resolves, so every
endpoint reports the same set of attributes without hand-wiring them per handler.
Called once from ``Endpoint.dispatch`` for every endpoint that resolves an
organization, so each one reports the same set of attributes without
hand-wiring them per handler.
"""
client_kind = get_client_kind(request)

Expand Down
2 changes: 1 addition & 1 deletion src/sentry/middleware/access_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def _create_api_access_log(
org_id = getattr(getattr(request, "organization", None), "id", None)
entity_id = getattr(request_auth, "entity_id", None)
status_code = getattr(response, "status_code", 500)
# Set during dispatch, for organizations opted into `client_kind`.
# Set during dispatch, for endpoints that resolve an organization.
client_kind = getattr(request, "client_kind", None)
log_metrics = dict(
method=request.method,
Expand Down
24 changes: 2 additions & 22 deletions tests/sentry/api/test_client_kind.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

from sentry.api.client_kind import (
ATTRIBUTION_SPAN_OP,
FEATURE_FLAG,
ClientKind,
client_kind_scope,
get_client_host,
Expand Down Expand Up @@ -493,11 +492,8 @@ def setUp(self) -> None:
super().setUp()
self.login_as(self.user)

def tags_for(self, url: str, *, enabled: bool = True) -> list[Any]:
with (
self.feature(FEATURE_FLAG if enabled else {FEATURE_FLAG: False}),
mock.patch("sentry.api.client_kind.sentry_sdk") as sdk,
):
def tags_for(self, url: str) -> list[Any]:
with mock.patch("sentry.api.client_kind.sentry_sdk") as sdk:
assert self.client.get(url).status_code == 200
return sdk.set_tag.call_args_list

Expand All @@ -519,19 +515,3 @@ def test_an_issue_endpoint_records_the_caller(self) -> None:
# likely to silently fall out of coverage.
url = f"/api/0/organizations/{self.organization.slug}/issues/{self.group.id}/"
assert mock.call("client_kind", "frontend") in self.tags_for(url)

def test_records_nothing_when_the_organization_has_not_opted_in(self) -> None:
url = f"/api/0/projects/{self.organization.slug}/{self.project.slug}/"
assert self.tags_for(url, enabled=False) == []

def test_a_declared_kind_does_not_bypass_the_opt_in(self) -> None:
"""A declared caller must not also grant the organization's opt-in.

The opt-in check moved out of `get_client_kind` and up to the dispatch call
site, so it is the ordering there -- not the function -- that now keeps a
`client_kind_scope` declaration from reporting for an org that never enabled
the feature.
"""
url = f"/api/0/projects/{self.organization.slug}/{self.project.slug}/"
with client_kind_scope(ClientKind.SEER):
assert self.tags_for(url, enabled=False) == []
17 changes: 3 additions & 14 deletions tests/sentry/middleware/test_access_log_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@

from sentry.api.base import Endpoint
from sentry.api.bases.organization import ControlSiloOrganizationEndpoint, OrganizationEndpoint
from sentry.api.client_kind import FEATURE_FLAG as CLIENT_KIND_FEATURE_FLAG
from sentry.api.endpoints.internal.rpc import InternalRpcServiceEndpoint
from sentry.api.permissions import SentryIsAuthenticated
from sentry.models.apitoken import ApiToken
Expand Down Expand Up @@ -207,7 +206,7 @@ def get(self, request, organization_context, organization):
"snuba_throttle_threshold",
"token_last_characters",
"gateway_proxy",
# Only present for organizations opted into `client_kind`.
# Only present for endpoints that resolve an organization.
"client_kind",
"client_host",
)
Expand Down Expand Up @@ -511,23 +510,13 @@ def request_stats(self) -> None:
},
)

def test_client_kind_logged_for_an_opted_in_org(self) -> None:
with self.feature(CLIENT_KIND_FEATURE_FLAG):
self.request_stats()
def test_client_kind_logged(self) -> None:
self.request_stats()

tested_log = self.get_tested_log(args=[self.organization.slug])
# A session cookie and no token is the web UI.
assert tested_log.client_kind == "frontend"

def test_absent_for_an_org_that_has_not_opted_in(self) -> None:
with self.feature({CLIENT_KIND_FEATURE_FLAG: False}):
self.request_stats()

tested_log = self.get_tested_log(args=[self.organization.slug])
# Absent rather than "unknown": a disabled org has to stay distinguishable
# from one whose traffic genuinely classifies as unknown.
assert not hasattr(tested_log, "client_kind")


@control_silo_test
class TestOrganizationIdPresentForControl(LogCaptureAPITestCase):
Expand Down
23 changes: 9 additions & 14 deletions tests/sentry/seer/endpoints/test_seer_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from rest_framework.test import APIRequestFactory
from sentry_protos.snuba.v1.endpoint_trace_item_details_pb2 import TraceItemDetailsResponse

from sentry.api.client_kind import FEATURE_FLAG as CLIENT_KIND_FEATURE_FLAG
from sentry.api.client_kind import ClientKind, get_client_kind
from sentry.constants import ObjectStatus
from sentry.integrations.models.integration import Integration
Expand Down Expand Up @@ -127,10 +126,7 @@ def fake_method(**kwargs: Any) -> dict[str, Any]:

path = self._get_path("get_organization_features")
data: dict[str, Any] = {"args": {"org_id": org.id}, "meta": {}}
with (
self.feature(CLIENT_KIND_FEATURE_FLAG),
patch.dict(seer_method_registry, {"get_organization_features": fake_method}),
):
with patch.dict(seer_method_registry, {"get_organization_features": fake_method}):
response = self.client.post(
path, data=data, HTTP_AUTHORIZATION=self.auth_header(path, data)
)
Expand All @@ -142,16 +138,15 @@ def test_client_kind_scope_does_not_outlive_the_dispatch(self) -> None:
org = self.create_organization()
path = self._get_path("get_organization_features")
data: dict[str, Any] = {"args": {"org_id": org.id}, "meta": {}}
with self.feature(CLIENT_KIND_FEATURE_FLAG):
response = self.client.post(
path, data=data, HTTP_AUTHORIZATION=self.auth_header(path, data)
)
assert response.status_code == 200
response = self.client.post(
path, data=data, HTTP_AUTHORIZATION=self.auth_header(path, data)
)
assert response.status_code == 200

nested = Request(APIRequestFactory().get("/"))
nested.user = AnonymousUser()
nested.auth = None
assert get_client_kind(nested) == ClientKind.UNKNOWN
nested = Request(APIRequestFactory().get("/"))
nested.user = AnonymousUser()
nested.auth = None
assert get_client_kind(nested) == ClientKind.UNKNOWN

def test_snuba_rate_limit_returns_429(self) -> None:
"""Test that SnubaRPCRateLimitExceeded returns 429 to Seer for retry."""
Expand Down
Loading