diff --git a/api/app/settings/common.py b/api/app/settings/common.py index 1fd243a2bd8a..348f780d42b3 100644 --- a/api/app/settings/common.py +++ b/api/app/settings/common.py @@ -402,8 +402,8 @@ "DEFAULT_SCHEMA_CLASS": "api.openapi.AutoSchema", } MIDDLEWARE = [ + "common.core.request_context.RequestContextMiddleware", # Must come first! "common.core.middleware.APIResponseVersionHeaderMiddleware", - "common.gunicorn.middleware.RouteLoggerMiddleware", "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", diff --git a/api/permissions/permission_service.py b/api/permissions/permission_service.py index 37ff8a937927..3d5bc1d9ae3d 100644 --- a/api/permissions/permission_service.py +++ b/api/permissions/permission_service.py @@ -6,7 +6,6 @@ from environments.models import Environment from organisations.models import Organisation, OrganisationRole from projects.models import Project -from telemetry.spans import set_span_attribute from .rbac_wrapper import ( # type: ignore[attr-defined] get_permitted_environments_for_master_api_key_using_roles, @@ -44,7 +43,6 @@ def is_user_organisation_admin( ) -> bool: user_organisation = user.get_user_organisation(organisation) if user_organisation is not None and user_organisation.is_active: - set_span_attribute("organisation.id", user_organisation.organisation_id) return user_organisation.role == OrganisationRole.ADMIN.name return False diff --git a/api/projects/code_references/views.py b/api/projects/code_references/views.py index 9666e573e62c..9b24fa95a927 100644 --- a/api/projects/code_references/views.py +++ b/api/projects/code_references/views.py @@ -60,7 +60,6 @@ def create(self, request: Request, *args: Any, **kwargs: Any) -> response.Respon feature_names = {ref["feature_name"] for ref in scan.code_references} logger.info( "scan.created", - organisation__id=scan.project.organisation_id, code_references__count=len(scan.code_references), feature__count=len(feature_names), ) diff --git a/api/telemetry/apps.py b/api/telemetry/apps.py index 8df74dd67211..a2935afc43ac 100644 --- a/api/telemetry/apps.py +++ b/api/telemetry/apps.py @@ -26,3 +26,7 @@ class TelemetryConfig(AppConfig): def ready(self): # type: ignore[no-untyped-def] post_migrate.connect(send_telemetry_callback, sender=self) + + from telemetry import request_context + + request_context.install() diff --git a/api/telemetry/mappers.py b/api/telemetry/mappers.py new file mode 100644 index 000000000000..c2a58792d4e7 --- /dev/null +++ b/api/telemetry/mappers.py @@ -0,0 +1,19 @@ +import typing + +from telemetry.types import ResolvedTelemetryAttributes + + +def map_view_kwargs_to_telemetry_attributes( + view_kwargs: dict[str, typing.Any], +) -> ResolvedTelemetryAttributes: + """Map the URL kwargs of a view to the IDs of the entities it acts on.""" + ids: ResolvedTelemetryAttributes = {} + if str(organisation_pk := view_kwargs.get("organisation_pk", "")).isdecimal(): + ids["organisation__id"] = int(organisation_pk) + if str(project_pk := view_kwargs.get("project_pk", "")).isdecimal(): + ids["project__id"] = int(project_pk) + if str(feature_pk := view_kwargs.get("feature_pk", "")).isdecimal(): + ids["feature__id"] = int(feature_pk) + if environment_api_key := view_kwargs.get("environment_api_key"): + ids["environment__key"] = environment_api_key + return ids diff --git a/api/telemetry/middleware.py b/api/telemetry/middleware.py index d2279e01a0d5..8f56978ed8f0 100644 --- a/api/telemetry/middleware.py +++ b/api/telemetry/middleware.py @@ -3,12 +3,11 @@ from typing import Literal import structlog +from common.core.request_context import get_request_context from django.http.request import HttpRequest from django.http.response import HttpResponse from opentelemetry import baggage -from telemetry.spans import get_span_attribute - # e.g. `flagsmith-cli/2.0.0 (darwin/arm64)` CLI_USER_AGENT_PATTERN = re.compile( r"^flagsmith-cli/(?P[^\s/]+) \((?P[^\s/()]+)/(?P[^\s/()]+)\)" @@ -80,8 +79,7 @@ def _get_organisation_id(self, request: HttpRequest) -> int | None: """Obtain the organisation ID from the request context.""" from organisations.models import Organisation - # Set by the permission layer for organisations the user belongs to - if isinstance(organisation_id := get_span_attribute("organisation.id"), int): + if isinstance(organisation_id := get_request_context("organisation__id"), int): return organisation_id assert request.user.is_authenticated # NOTE: protected upstream diff --git a/api/telemetry/request_context.py b/api/telemetry/request_context.py new file mode 100644 index 000000000000..04b5b52f8f9c --- /dev/null +++ b/api/telemetry/request_context.py @@ -0,0 +1,68 @@ +""" +Describe API requests with Flagsmith-specific request context. + +`common.core.request_context.RequestContextMiddleware` scopes request context +to the request, and binds its route. What the request acts on, and who makes +it, is only known once DRF has authenticated the request inside the view, so +it's bound from there. +""" + +import functools +import typing + +from common.core.request_context import bind_request_context +from rest_framework.request import Request +from rest_framework.views import APIView + +from api_keys.user import APIKeyUser +from telemetry.mappers import map_view_kwargs_to_telemetry_attributes +from telemetry.services import get_resolved_telemetry_attributes +from users.models import FFAdminUser + + +def bind_api_request_context(request: Request, view: APIView) -> None: + """Bind what's known about `request` once DRF has authenticated it.""" + user = request.user + if isinstance(user, FFAdminUser): + bind_request_context(user__id=str(user.uuid)) + elif getattr(user, "is_master_api_key_user", False): + # NOTE: `isinstance` can't tell `APIKeyUser`s apart, see `UserABC`. + # Master API keys aren't users, so don't identify them as such; but + # they belong to exactly one organisation. + api_key_user = typing.cast(APIKeyUser, user) + bind_request_context(organisation__id=api_key_user.key.organisation_id) + + resolved_ids = get_resolved_telemetry_attributes( + map_view_kwargs_to_telemetry_attributes(view.kwargs) + ) + bind_request_context(**resolved_ids) + + +_INSTALLED = "_binds_api_request_context" + + +def install() -> None: + """ + Bind API request context to every DRF view's request on authentication. + + API requests, e.g. authenticated by token or master API key, are + authenticated by DRF inside the view, so a middleware can't tell who makes + them. DRF has no hook for authenticated requests, and views extend + `APIView` directly, so wrap `APIView.perform_authentication`, which every + view runs before checking permissions. + """ + perform_authentication = APIView.perform_authentication + if getattr(perform_authentication, _INSTALLED, False): + return # e.g. Django set up its apps again + + @functools.wraps(perform_authentication) + def _perform_authentication(self: APIView, request: Request) -> None: + perform_authentication(self, request) + bind_api_request_context(request, self) + + setattr(_perform_authentication, _INSTALLED, True) + setattr( + APIView, + "perform_authentication", + typing.cast(typing.Any, _perform_authentication), + ) diff --git a/api/telemetry/services.py b/api/telemetry/services.py index b8b5e2e1da39..f29b10f830ad 100644 --- a/api/telemetry/services.py +++ b/api/telemetry/services.py @@ -7,9 +7,13 @@ from app_analytics.analytics_db_service import get_usage_data_for_window from app_analytics.dataclasses import UsageData +from environments.models import Environment +from features.models import Feature from organisations.models import Organisation +from projects.models import Project from telemetry.control_plane.client import post_usage_snapshot from telemetry.dataclasses import ApiCallBreakdown, ProjectUsage, UsageSnapshot +from telemetry.types import ResolvedTelemetryAttributes logger = structlog.get_logger("usage_reporting") @@ -104,3 +108,51 @@ def _get_usage_snapshot(organisation: Organisation) -> UsageSnapshot: instance_version=instance_version, project_usage=_map_to_top_project_usage(usage_data_by_project_id), ) + + +def get_resolved_telemetry_attributes( + ids: ResolvedTelemetryAttributes, +) -> ResolvedTelemetryAttributes: + """ + Resolve as many keys in `ids` as possible from the database. + + Makes at most one query, from the most specific key present. + """ + resolved_ids = ids.copy() + + if "environment__id" not in resolved_ids and ( + environment_api_key := resolved_ids.get("environment__key") + ): + if environment_ids := ( + Environment.objects.filter(api_key=environment_api_key) + .values_list("id", "project_id", "project__organisation_id") + .first() + ): + ( + resolved_ids["environment__id"], + resolved_ids["project__id"], + resolved_ids["organisation__id"], + ) = environment_ids + return resolved_ids + + if "project__id" not in resolved_ids and "feature__id" in resolved_ids: + if feature_ids := ( + Feature.objects.filter(id=resolved_ids["feature__id"]) + .values_list("project_id", "project__organisation_id") + .first() + ): + ( + resolved_ids["project__id"], + resolved_ids["organisation__id"], + ) = feature_ids + return resolved_ids + + if "organisation__id" not in resolved_ids and "project__id" in resolved_ids: + if ( + organisation_id := Project.objects.filter(pk=resolved_ids["project__id"]) + .values_list("organisation_id", flat=True) + .first() + ) is not None: + resolved_ids["organisation__id"] = organisation_id + + return resolved_ids diff --git a/api/telemetry/spans.py b/api/telemetry/spans.py deleted file mode 100644 index c4e60e1f4359..000000000000 --- a/api/telemetry/spans.py +++ /dev/null @@ -1,11 +0,0 @@ -from opentelemetry import trace -from opentelemetry.util.types import AttributeValue - - -def set_span_attribute(attribute: str, value: AttributeValue) -> None: - trace.get_current_span().set_attribute(attribute, value) - - -def get_span_attribute(attribute: str) -> AttributeValue | None: - attributes = getattr(trace.get_current_span(), "attributes", None) or {} - return attributes.get(attribute) diff --git a/api/telemetry/types.py b/api/telemetry/types.py new file mode 100644 index 000000000000..073226dfb1f2 --- /dev/null +++ b/api/telemetry/types.py @@ -0,0 +1,11 @@ +from typing import TypedDict + + +class ResolvedTelemetryAttributes(TypedDict, total=False): + """Telemetry-relevant attributes from objects an API request acts on""" + + organisation__id: int + project__id: int + feature__id: int + environment__id: int + environment__key: str diff --git a/api/tests/conftest.py b/api/tests/conftest.py index cfc3f05a3f42..a7849ecde527 100644 --- a/api/tests/conftest.py +++ b/api/tests/conftest.py @@ -1365,6 +1365,17 @@ def admin_client_new( return admin_client_original +@pytest.fixture +def admin_client_new_user_context( + admin_client_auth_type: AdminClientAuthType, + admin_user: FFAdminUser, +) -> dict[str, str]: + """Request context bound for the user making `admin_client_new`'s requests""" + if admin_client_auth_type == "master_api_key": + return {} # Master API keys aren't users + return {"user__id": str(admin_user.uuid)} + + @pytest.fixture() def superuser(): # type: ignore[no-untyped-def] return FFAdminUser.objects.create_superuser( # type: ignore[no-untyped-call] diff --git a/api/tests/integration/features/test_gitlab_external_resources.py b/api/tests/integration/features/test_gitlab_external_resources.py index 330afecd0cff..97c09fa30ddb 100644 --- a/api/tests/integration/features/test_gitlab_external_resources.py +++ b/api/tests/integration/features/test_gitlab_external_resources.py @@ -10,6 +10,7 @@ from integrations.github.models import GithubConfiguration from integrations.gitlab.models import GitLabConfiguration, GitLabWebhook from projects.models import Project +from users.models import FFAdminUser def test_create_external_resource__gitlab_issue__returns_201( @@ -17,6 +18,7 @@ def test_create_external_resource__gitlab_issue__returns_201( project: int, feature: int, log: StructuredLogCapture, + admin_user: FFAdminUser, ) -> None: # Given metadata = {"title": "Fix login bug", "state": "opened"} @@ -48,6 +50,7 @@ def test_create_external_resource__gitlab_issue__returns_201( "event": "resource.linked", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/", + "user__id": str(admin_user.uuid), "organisation__id": organisation_id, "project__id": project, "feature__id": feature, @@ -61,6 +64,7 @@ def test_create_external_resource__gitlab_merge_request__returns_201( project: int, feature: int, log: StructuredLogCapture, + admin_user: FFAdminUser, ) -> None: # Given metadata = {"title": "Add login button", "state": "opened"} @@ -93,6 +97,7 @@ def test_create_external_resource__gitlab_merge_request__returns_201( "event": "resource.linked", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/", + "user__id": str(admin_user.uuid), "organisation__id": organisation_id, "project__id": project, "feature__id": feature, @@ -155,6 +160,7 @@ def test_create_external_resource__gitlab_issue__registers_webhook_and_tags_feat project: int, feature: int, log: StructuredLogCapture, + admin_user: FFAdminUser, ) -> None: # Given expected_gitlab_hook_id = 42 @@ -222,8 +228,10 @@ def test_create_external_resource__gitlab_issue__registers_webhook_and_tags_feat "event": "webhook.registered", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/", + "user__id": str(admin_user.uuid), "organisation__id": organisation, "project__id": project, + "feature__id": feature, "gitlab__project__id": expected_gitlab_project_id, "gitlab__project__path": "testorg/testrepo", "gitlab__hook__id": expected_gitlab_hook_id, @@ -233,6 +241,7 @@ def test_create_external_resource__gitlab_issue__registers_webhook_and_tags_feat "event": "comment.posted", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/", + "user__id": str(admin_user.uuid), "organisation__id": organisation, "project__id": project, "feature__id": feature, @@ -244,6 +253,7 @@ def test_create_external_resource__gitlab_issue__registers_webhook_and_tags_feat "event": "resource.linked", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/", + "user__id": str(admin_user.uuid), "organisation__id": organisation, "project__id": project, "feature__id": feature, @@ -259,6 +269,7 @@ def test_create_external_resource__gitlab_mr__registers_webhook_and_tags_feature project: int, feature: int, log: StructuredLogCapture, + admin_user: FFAdminUser, ) -> None: # Given project_instance = Project.objects.get(id=project) @@ -309,8 +320,10 @@ def test_create_external_resource__gitlab_mr__registers_webhook_and_tags_feature "event": "webhook.registered", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/", + "user__id": str(admin_user.uuid), "organisation__id": organisation, "project__id": project, + "feature__id": feature, "gitlab__project__id": 777, "gitlab__project__path": "testorg/testrepo", "gitlab__hook__id": 77, @@ -320,6 +333,7 @@ def test_create_external_resource__gitlab_mr__registers_webhook_and_tags_feature "event": "comment.posted", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/", + "user__id": str(admin_user.uuid), "organisation__id": organisation, "project__id": project, "feature__id": feature, @@ -331,6 +345,7 @@ def test_create_external_resource__gitlab_mr__registers_webhook_and_tags_feature "event": "resource.linked", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/", + "user__id": str(admin_user.uuid), "organisation__id": organisation, "project__id": project, "feature__id": feature, @@ -346,6 +361,7 @@ def test_create_external_resource__second_link_same_gitlab_project__reuses_webho project: int, feature: int, log: StructuredLogCapture, + admin_user: FFAdminUser, ) -> None: # Given project_instance = Project.objects.get(id=project) @@ -394,6 +410,7 @@ def test_create_external_resource__second_link_same_gitlab_project__reuses_webho "event": "comment.posted", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/", + "user__id": str(admin_user.uuid), "organisation__id": organisation, "project__id": project, "feature__id": feature, @@ -405,6 +422,7 @@ def test_create_external_resource__second_link_same_gitlab_project__reuses_webho "event": "resource.linked", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/", + "user__id": str(admin_user.uuid), "organisation__id": organisation, "project__id": project, "feature__id": feature, @@ -450,6 +468,7 @@ def test_delete_external_resource__last_link_for_path__deregisters_webhook_and_p feature: int, feature_name: str, log: StructuredLogCapture, + admin_user: FFAdminUser, ) -> None: # Given project_instance = Project.objects.get(id=project) @@ -500,6 +519,7 @@ def test_delete_external_resource__last_link_for_path__deregisters_webhook_and_p "event": "comment.posted", "http__request__method": "DELETE", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/{id}/", + "user__id": str(admin_user.uuid), "organisation__id": organisation, "project__id": project, "feature__id": feature, @@ -511,8 +531,10 @@ def test_delete_external_resource__last_link_for_path__deregisters_webhook_and_p "event": "webhook.deregistered", "http__request__method": "DELETE", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/{id}/", + "user__id": str(admin_user.uuid), "organisation__id": organisation, "project__id": project, + "feature__id": feature, "gitlab__project__id": 777, "gitlab__hook__id": 42, }, @@ -521,6 +543,7 @@ def test_delete_external_resource__last_link_for_path__deregisters_webhook_and_p "event": "resource.unlinked", "http__request__method": "DELETE", "http__route": "/api/v1/projects/{project_pk}/features/{feature_pk}/feature-external-resources/{id}/", + "user__id": str(admin_user.uuid), "organisation__id": organisation, "project__id": project, "feature__id": feature, diff --git a/api/tests/integration/sentry/test_change_tracking_webhook_integration.py b/api/tests/integration/sentry/test_change_tracking_webhook_integration.py index 7fdf368580e9..03bef9844f37 100644 --- a/api/tests/integration/sentry/test_change_tracking_webhook_integration.py +++ b/api/tests/integration/sentry/test_change_tracking_webhook_integration.py @@ -44,6 +44,7 @@ def test_sentry_change_tracking__flag_created__sends_update_to_sentry( project: int, responses: RequestsMock, sentry_configuration: SentryChangeTrackingConfiguration, + organisation: int, ) -> None: # Given if use_v2_versioning: @@ -85,6 +86,9 @@ def test_sentry_change_tracking__flag_created__sends_update_to_sentry( "event": "sending", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/features/", + "user__id": str(admin_user.uuid), + "organisation__id": organisation, + "project__id": project, "feature_name": feature_name, "headers": ANY, "level": "debug", @@ -96,6 +100,9 @@ def test_sentry_change_tracking__flag_created__sends_update_to_sentry( "event": "success", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/features/", + "user__id": str(admin_user.uuid), + "organisation__id": organisation, + "project__id": project, "feature_name": feature_name, "level": "info", "sentry_action": "created", @@ -112,6 +119,9 @@ def test_sentry_change_tracking__flag_state_change__sends_update_to_sentry( log: StructuredLogCapture, responses: RequestsMock, sentry_configuration: SentryChangeTrackingConfiguration, + organisation: int, + environment: int, + project: int, ) -> None: # Given responses.post(sentry_configuration.webhook_url, status=200, body="") @@ -148,6 +158,11 @@ def test_sentry_change_tracking__flag_state_change__sends_update_to_sentry( "event": "sending", "http__request__method": "PATCH", "http__route": "/api/v1/environments/{environment_api_key}/featurestates/{id}/", + "user__id": str(admin_user.uuid), + "organisation__id": organisation, + "project__id": project, + "environment__id": environment, + "environment__key": environment_api_key, "feature_name": feature_name, "headers": ANY, "level": "debug", @@ -159,6 +174,11 @@ def test_sentry_change_tracking__flag_state_change__sends_update_to_sentry( "event": "success", "http__request__method": "PATCH", "http__route": "/api/v1/environments/{environment_api_key}/featurestates/{id}/", + "user__id": str(admin_user.uuid), + "organisation__id": organisation, + "project__id": project, + "environment__id": environment, + "environment__key": environment_api_key, "feature_name": feature_name, "level": "info", "sentry_action": "updated", @@ -176,6 +196,8 @@ def test_sentry_change_tracking__flag_state_change_in_v2_environment__sends_upda responses: RequestsMock, sentry_configuration: SentryChangeTrackingConfiguration, environment_v2_versioning: int, + organisation: int, + project: int, ) -> None: # Given responses.post(sentry_configuration.webhook_url, status=200, body="") @@ -256,6 +278,10 @@ def test_sentry_change_tracking__flag_state_change_in_v2_environment__sends_upda "event": "sending", "http__request__method": "POST", "http__route": "/api/v1/environments/{environment_pk}/features/{feature_pk}/versions/{id}/publish/", + "user__id": str(admin_user.uuid), + "feature__id": feature, + "organisation__id": organisation, + "project__id": project, "feature_name": feature_name, "headers": ANY, "level": "debug", @@ -267,6 +293,10 @@ def test_sentry_change_tracking__flag_state_change_in_v2_environment__sends_upda "event": "success", "http__request__method": "POST", "http__route": "/api/v1/environments/{environment_pk}/features/{feature_pk}/versions/{id}/publish/", + "user__id": str(admin_user.uuid), + "feature__id": feature, + "organisation__id": organisation, + "project__id": project, "feature_name": feature_name, "level": "info", "sentry_action": "updated", @@ -431,6 +461,9 @@ def test_sentry_change_tracking__flag_deleted__sends_update_to_sentry( log: StructuredLogCapture, responses: RequestsMock, sentry_configuration: SentryChangeTrackingConfiguration, + organisation: int, + environment: int, + project: int, ) -> None: # Given responses.post(sentry_configuration.webhook_url, status=200, body="") @@ -464,6 +497,11 @@ def test_sentry_change_tracking__flag_deleted__sends_update_to_sentry( "event": "sending", "http__request__method": "DELETE", "http__route": "/api/v1/environments/{environment_api_key}/featurestates/{id}/", + "user__id": str(admin_user.uuid), + "organisation__id": organisation, + "project__id": project, + "environment__id": environment, + "environment__key": environment_api_key, "feature_name": feature_name, "headers": ANY, "level": "debug", @@ -475,6 +513,11 @@ def test_sentry_change_tracking__flag_deleted__sends_update_to_sentry( "event": "success", "http__request__method": "DELETE", "http__route": "/api/v1/environments/{environment_api_key}/featurestates/{id}/", + "user__id": str(admin_user.uuid), + "organisation__id": organisation, + "project__id": project, + "environment__id": environment, + "environment__key": environment_api_key, "feature_name": feature_name, "level": "info", "sentry_action": "deleted", @@ -512,6 +555,10 @@ def test_sentry_change_tracking__failing_integration__fails_gracefully( responses: RequestsMock, sentry_response: dict[str, Any], sentry_configuration: SentryChangeTrackingConfiguration, + admin_user: FFAdminUser, + organisation: int, + environment: int, + project: int, ) -> None: # Given responses.post(sentry_configuration.webhook_url, **sentry_response) @@ -531,6 +578,11 @@ def test_sentry_change_tracking__failing_integration__fails_gracefully( "event": "sending", "http__request__method": "PATCH", "http__route": "/api/v1/environments/{environment_api_key}/featurestates/{id}/", + "user__id": str(admin_user.uuid), + "organisation__id": organisation, + "project__id": project, + "environment__id": environment, + "environment__key": environment_api_key, "feature_name": feature_name, "headers": ANY, "level": "debug", @@ -542,6 +594,11 @@ def test_sentry_change_tracking__failing_integration__fails_gracefully( "feature_name": feature_name, "http__request__method": "PATCH", "http__route": "/api/v1/environments/{environment_api_key}/featurestates/{id}/", + "user__id": str(admin_user.uuid), + "organisation__id": organisation, + "project__id": project, + "environment__id": environment, + "environment__key": environment_api_key, "level": "warning", "sentry_action": "updated", **error_log, diff --git a/api/tests/unit/cohorts/test_views.py b/api/tests/unit/cohorts/test_views.py index f6ccc4af38d8..b3a0e538f5f2 100644 --- a/api/tests/unit/cohorts/test_views.py +++ b/api/tests/unit/cohorts/test_views.py @@ -232,7 +232,7 @@ def test_list_cohorts__multiple_cohorts_without_rbac__membership_counts_in_const edge_cohort, with_environment_permissions, django_assert_num_queries, - num_queries=10, + num_queries=11, ) @@ -255,7 +255,7 @@ def test_list_cohorts__multiple_cohorts_with_rbac__membership_counts_in_constant edge_cohort, with_environment_permissions, django_assert_num_queries, - num_queries=12, + num_queries=13, ) diff --git a/api/tests/unit/features/test_unit_features_views.py b/api/tests/unit/features/test_unit_features_views.py index 628b04d374d5..2d85e5ae7a2e 100644 --- a/api/tests/unit/features/test_unit_features_views.py +++ b/api/tests/unit/features/test_unit_features_views.py @@ -1957,7 +1957,7 @@ def test_list_feature_states__nested_environment_view_set__returns_expected_coun v2_feature_state.clone(env=environment, version=3, live_from=timezone.now()) # When - with django_assert_num_queries(8): + with django_assert_num_queries(9): response = admin_client_new.get(base_url) # Then @@ -4031,7 +4031,7 @@ def test_list_features__without_rbac__no_n_plus_1( with_project_permissions, django_assert_num_queries, environment, - num_queries=16, + num_queries=17, ) @@ -4056,7 +4056,7 @@ def test_list_features__with_rbac__no_n_plus_1( with_project_permissions, django_assert_num_queries, environment, - num_queries=17, + num_queries=18, ) @@ -4690,7 +4690,7 @@ def test_list_features__last_modified_without_rbac__returns_expected( feature, with_project_permissions, django_assert_num_queries, - num_queries=18, + num_queries=19, ) @@ -4718,7 +4718,7 @@ def test_list_features__last_modified_with_rbac__returns_expected( feature, with_project_permissions, django_assert_num_queries, - num_queries=19, + num_queries=20, ) diff --git a/api/tests/unit/features/versioning/test_unit_versioning_views.py b/api/tests/unit/features/versioning/test_unit_versioning_views.py index 01abf49ddfab..5943016b045f 100644 --- a/api/tests/unit/features/versioning/test_unit_versioning_views.py +++ b/api/tests/unit/features/versioning/test_unit_versioning_views.py @@ -385,6 +385,7 @@ def test_publish_feature_version__change_requests_enabled__responds_409( environment_v2_versioning: Environment, feature: Feature, log: StructuredLogCapture, + admin_client_new_user_context: dict[str, str], ) -> None: # Given environment_v2_versioning.minimum_change_request_approvals = 1 @@ -422,6 +423,7 @@ def test_publish_feature_version__change_requests_enabled__responds_409( "event": "version.publish_rejected", "http__request__method": "POST", "http__route": "/api/v1/environments/{environment_pk}/features/{feature_pk}/versions/{id}/publish/", + **admin_client_new_user_context, "level": "warning", "organisation__id": environment_v2_versioning.project.organisation_id, "project__id": environment_v2_versioning.project_id, @@ -944,6 +946,7 @@ def test_create_version__publish_immediately_with_change_requests_enabled__respo admin_client_new: APIClient, environment_v2_versioning: Environment, log: StructuredLogCapture, + admin_client_new_user_context: dict[str, str], ) -> None: # Given environment_v2_versioning.minimum_change_request_approvals = 1 @@ -1000,6 +1003,7 @@ def test_create_version__publish_immediately_with_change_requests_enabled__respo "event": "version.publish_rejected", "http__request__method": "POST", "http__route": "/api/v1/environments/{environment_pk}/features/{feature_pk}/versions/", + **admin_client_new_user_context, "level": "warning", "organisation__id": environment_v2_versioning.project.organisation_id, "project__id": environment_v2_versioning.project_id, diff --git a/api/tests/unit/integrations/github/test_unit_github_cleanup_issue.py b/api/tests/unit/integrations/github/test_unit_github_cleanup_issue.py index cc3e4bc87eb8..a88da3e0a27d 100644 --- a/api/tests/unit/integrations/github/test_unit_github_cleanup_issue.py +++ b/api/tests/unit/integrations/github/test_unit_github_cleanup_issue.py @@ -80,6 +80,7 @@ def test_create_cleanup_issue__valid_request__returns_204( organisation: Organisation, feature: Feature, log: StructuredLogCapture, + admin_client_new_user_context: dict[str, str], ) -> None: # Given github_issue_response_1: dict[str, Any] = { @@ -142,6 +143,7 @@ def test_create_cleanup_issue__valid_request__returns_204( "event": "cleanup_issues.created", "http__request__method": "POST", "http__route": "/api/v1/organisations/{organisation_pk}/github/create-cleanup-issue/", + **admin_client_new_user_context, "level": "info", "organisation__id": organisation.id, "issues_created__count": 2, diff --git a/api/tests/unit/integrations/gitlab/test_configuration.py b/api/tests/unit/integrations/gitlab/test_configuration.py index c3a8c39c7b18..5e3f242e3152 100644 --- a/api/tests/unit/integrations/gitlab/test_configuration.py +++ b/api/tests/unit/integrations/gitlab/test_configuration.py @@ -21,6 +21,7 @@ def test_create_configuration__valid_data__persists_and_masks_token( admin_client_new: APIClient, project: Project, log: StructuredLogCapture, + admin_client_new_user_context: dict[str, str], ) -> None: # Given / When response = admin_client_new.post( @@ -45,6 +46,7 @@ def test_create_configuration__valid_data__persists_and_masks_token( "event": "configuration.created", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/integrations/gitlab/", + **admin_client_new_user_context, "level": "info", "gitlab_instance_url": "https://gitlab.example.com", "project__id": project.id, @@ -77,6 +79,7 @@ def test_update_configuration__valid_data__persists_and_masks_token( project: Project, gitlab_configuration: GitLabConfiguration, log: StructuredLogCapture, + admin_client_new_user_context: dict[str, str], ) -> None: # Given / When response = admin_client_new.put( @@ -101,6 +104,7 @@ def test_update_configuration__valid_data__persists_and_masks_token( "event": "configuration.updated", "http__request__method": "PUT", "http__route": "/api/v1/projects/{project_pk}/integrations/gitlab/{id}/", + **admin_client_new_user_context, "level": "info", "gitlab_instance_url": "https://gitlab.updated.com", "project__id": project.id, @@ -114,6 +118,7 @@ def test_delete_configuration__existing__soft_deletes( project: Project, gitlab_configuration: GitLabConfiguration, log: StructuredLogCapture, + admin_client_new_user_context: dict[str, str], ) -> None: # Given / When response = admin_client_new.delete( @@ -129,6 +134,7 @@ def test_delete_configuration__existing__soft_deletes( "event": "configuration.deleted", "http__request__method": "DELETE", "http__route": "/api/v1/projects/{project_pk}/integrations/gitlab/{id}/", + **admin_client_new_user_context, "level": "info", "project__id": project.id, "organisation__id": project.organisation_id, diff --git a/api/tests/unit/integrations/gitlab/test_proxy_views.py b/api/tests/unit/integrations/gitlab/test_proxy_views.py index eec3323b195f..47d6236e7220 100644 --- a/api/tests/unit/integrations/gitlab/test_proxy_views.py +++ b/api/tests/unit/integrations/gitlab/test_proxy_views.py @@ -12,6 +12,7 @@ from rest_framework.test import APIClient from projects.models import Project + from users.models import FFAdminUser @pytest.mark.usefixtures("gitlab_config") @@ -20,6 +21,7 @@ def test_gitlab_project_list__valid_config__returns_paginated_response( project: Project, mocker: MockerFixture, log: StructuredLogCapture, + admin_user: FFAdminUser, ) -> None: # Given mocker.patch( @@ -52,6 +54,7 @@ def test_gitlab_project_list__valid_config__returns_paginated_response( "event": "projects.fetched", "http__request__method": "GET", "http__route": "/api/v1/projects/{project_pk}/gitlab/projects/", + "user__id": str(admin_user.uuid), "organisation__id": project.organisation_id, "project__id": project.id, }, @@ -77,6 +80,7 @@ def test_gitlab_issue_list__valid_config__returns_issues( project: Project, mocker: MockerFixture, log: StructuredLogCapture, + admin_user: FFAdminUser, ) -> None: # Given mocker.patch( @@ -113,6 +117,7 @@ def test_gitlab_issue_list__valid_config__returns_issues( "event": "issues.fetched", "http__request__method": "GET", "http__route": "/api/v1/projects/{project_pk}/gitlab/issues/", + "user__id": str(admin_user.uuid), "organisation__id": project.organisation_id, "project__id": project.id, "gitlab__project__id": 42, @@ -140,6 +145,7 @@ def test_gitlab_merge_request_list__valid_config__returns_merge_requests( project: Project, mocker: MockerFixture, log: StructuredLogCapture, + admin_user: FFAdminUser, ) -> None: # Given mocker.patch( @@ -178,6 +184,7 @@ def test_gitlab_merge_request_list__valid_config__returns_merge_requests( "event": "merge_requests.fetched", "http__request__method": "GET", "http__route": "/api/v1/projects/{project_pk}/gitlab/merge-requests/", + "user__id": str(admin_user.uuid), "organisation__id": project.organisation_id, "project__id": project.id, "gitlab__project__id": 42, @@ -219,6 +226,7 @@ def test_browse_gitlab__api_unreachable__returns_503( project: Project, mocker: MockerFixture, log: StructuredLogCapture, + admin_user: FFAdminUser, ) -> None: # Given mocker.patch( @@ -241,6 +249,7 @@ def test_browse_gitlab__api_unreachable__returns_503( "event": "api_call.failed", "http__request__method": "GET", "http__route": "/api/v1/projects/{project_pk}/gitlab/projects/", + "user__id": str(admin_user.uuid), "organisation__id": project.organisation_id, "project__id": project.id, "exc_info": mocker.ANY, diff --git a/api/tests/unit/projects/code_references/test_unit_projects_code_references_views.py b/api/tests/unit/projects/code_references/test_unit_projects_code_references_views.py index 7045bd6cf3d5..1b85b11ff610 100644 --- a/api/tests/unit/projects/code_references/test_unit_projects_code_references_views.py +++ b/api/tests/unit/projects/code_references/test_unit_projects_code_references_views.py @@ -13,6 +13,7 @@ def test_create_code_reference__valid_payload__returns_201_with_accepted_referen admin_client_new: APIClient, project: Project, log: StructuredLogCapture, + admin_client_new_user_context: dict[str, str], ) -> None: # Given Feature.objects.create(project=project, name="feature-1") @@ -70,8 +71,10 @@ def test_create_code_reference__valid_payload__returns_201_with_accepted_referen "event": "scan.created", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/code-references/", + **admin_client_new_user_context, "level": "info", "organisation__id": project.organisation_id, + "project__id": project.id, "code_references__count": 3, "feature__count": 2, }, @@ -83,6 +86,7 @@ def test_create_code_reference__empty_references__returns_201_and_clears_previou feature: Feature, project: Project, log: StructuredLogCapture, + admin_client_new_user_context: dict[str, str], ) -> None: # Given with freezegun.freeze_time("2099-06-01T12:00:00+00:00"): @@ -127,8 +131,10 @@ def test_create_code_reference__empty_references__returns_201_and_clears_previou "event": "scan.created", "http__request__method": "POST", "http__route": "/api/v1/projects/{project_pk}/code-references/", + **admin_client_new_user_context, "level": "info", "organisation__id": project.organisation_id, + "project__id": project.id, "code_references__count": 0, "feature__count": 0, } diff --git a/api/tests/unit/segments/test_unit_segments_views.py b/api/tests/unit/segments/test_unit_segments_views.py index b31f7d3839ca..fa73ad588835 100644 --- a/api/tests/unit/segments/test_unit_segments_views.py +++ b/api/tests/unit/segments/test_unit_segments_views.py @@ -748,8 +748,8 @@ def test_get_segment_by_uuid__existing_segment__returns_segment_data( # type: i @pytest.mark.parametrize( "client, num_queries", [ - (lazy_fixture("admin_master_api_key_client"), 14), - (lazy_fixture("admin_client"), 16), + (lazy_fixture("admin_master_api_key_client"), 15), + (lazy_fixture("admin_client"), 17), ], ) def test_list_segments__without_rbac__expected_num_queries( @@ -805,8 +805,8 @@ def test_list_segments__system_segment_exists__excludes_system_segment( @pytest.mark.parametrize( "client, num_queries", [ - (lazy_fixture("admin_master_api_key_client"), 14), - (lazy_fixture("admin_client"), 17), + (lazy_fixture("admin_master_api_key_client"), 15), + (lazy_fixture("admin_client"), 18), ], ) def test_list_segments__with_rbac__expected_num_queries( diff --git a/api/tests/unit/telemetry/conftest.py b/api/tests/unit/telemetry/conftest.py index 2d2eb39f5bf2..795266536575 100644 --- a/api/tests/unit/telemetry/conftest.py +++ b/api/tests/unit/telemetry/conftest.py @@ -3,8 +3,6 @@ import pytest from opentelemetry import baggage from opentelemetry import context as otel_context -from opentelemetry.sdk.trace import TracerProvider -from opentelemetry.trace import Span @pytest.fixture() @@ -13,10 +11,3 @@ def mcp_baggage() -> Generator[None, None, None]: token = otel_context.attach(ctx) yield otel_context.detach(token) - - -@pytest.fixture() -def recording_span() -> Generator[Span, None, None]: - tracer = TracerProvider().get_tracer("test") - with tracer.start_as_current_span("test") as span: - yield span diff --git a/api/tests/unit/telemetry/test_unit_telemetry_mappers.py b/api/tests/unit/telemetry/test_unit_telemetry_mappers.py new file mode 100644 index 000000000000..fedc6c32195b --- /dev/null +++ b/api/tests/unit/telemetry/test_unit_telemetry_mappers.py @@ -0,0 +1,37 @@ +import typing + +import pytest + +from telemetry.mappers import map_view_kwargs_to_telemetry_attributes +from telemetry.types import ResolvedTelemetryAttributes + + +@pytest.mark.parametrize( + "view_kwargs, expected_ids", + [ + ({}, {}), + ({"pk": "7"}, {}), + # Routers capture strings, path converters ints + ({"project_pk": "42"}, {"project__id": 42}), + ({"organisation_pk": "7"}, {"organisation__id": 7}), + ({"project_pk": 42, "feature_pk": 3}, {"project__id": 42, "feature__id": 3}), + ( + {"environment_api_key": "key", "feature_pk": "3"}, + {"environment__key": "key", "feature__id": 3}, + ), + ({"project_pk": "not-an-id", "feature_pk": "3"}, {"feature__id": 3}), + # Digits that `int` can't parse, e.g. captured by routers + ({"organisation_pk": "²", "project_pk": "²", "feature_pk": "²"}, {}), + ({"project_pk": None, "feature_pk": ""}, {}), + ], +) +def test_map_view_kwargs_to_telemetry_attributes__view_kwargs__returns_expected_ids( + view_kwargs: dict[str, typing.Any], + expected_ids: ResolvedTelemetryAttributes, +) -> None: + # Given / When + # NOTE: Without database access, any query would fail the test + ids = map_view_kwargs_to_telemetry_attributes(view_kwargs) + + # Then + assert ids == expected_ids diff --git a/api/tests/unit/telemetry/test_unit_telemetry_middleware.py b/api/tests/unit/telemetry/test_unit_telemetry_middleware.py index b0d71432b7d1..d8ead4dc156d 100644 --- a/api/tests/unit/telemetry/test_unit_telemetry_middleware.py +++ b/api/tests/unit/telemetry/test_unit_telemetry_middleware.py @@ -6,6 +6,7 @@ from environments.models import Environment from organisations.models import Organisation, OrganisationRole +from projects.models import Project from telemetry.middleware import ClientUsageLoggerMiddleware from users.models import FFAdminUser @@ -25,8 +26,8 @@ def test_client_usage_logger_middleware__no_mcp_baggage__logs_nothing( assert log.events == [] -@pytest.mark.usefixtures("mcp_baggage", "recording_span", "organisation") -def test_client_usage_logger_middleware__mcp_organisation_id_span_attribute__logs_span_organisation_id( +@pytest.mark.usefixtures("mcp_baggage", "organisation") +def test_client_usage_logger_middleware__mcp_organisation_id_in_request_context__logs_bound_organisation_id( staff_client: APIClient, staff_user: FFAdminUser, log: StructuredLogCapture, @@ -34,11 +35,12 @@ def test_client_usage_logger_middleware__mcp_organisation_id_span_attribute__log # Given other_organisation = Organisation.objects.create(name="Other Org") staff_user.add_organisation(other_organisation, role=OrganisationRole.ADMIN) + other_project = Project.objects.create( + name="Other Project", organisation=other_organisation + ) # When - response = staff_client.get( - f"/api/v1/organisations/{other_organisation.pk}/invites/" - ) + response = staff_client.get(f"/api/v1/projects/{other_project.pk}/features/") # Then assert response.status_code == 200 @@ -47,9 +49,11 @@ def test_client_usage_logger_middleware__mcp_organisation_id_span_attribute__log "level": "info", "event": "tool.called", "http__request__method": "GET", - "http__route": "/api/v1/organisations/{organisation_pk}/invites/", + "http__route": "/api/v1/projects/{project_pk}/features/", "organisation__id": other_organisation.pk, + "project__id": other_project.pk, "status": "success", + "user__id": str(staff_user.uuid), } ] @@ -57,6 +61,7 @@ def test_client_usage_logger_middleware__mcp_organisation_id_span_attribute__log @pytest.mark.usefixtures("mcp_baggage") def test_client_usage_logger_middleware__mcp_user_with_single_organisation__logs_user_organisation_id( staff_client: APIClient, + staff_user: FFAdminUser, organisation: Organisation, log: StructuredLogCapture, ) -> None: @@ -73,6 +78,7 @@ def test_client_usage_logger_middleware__mcp_user_with_single_organisation__logs "http__route": "/api/v1/projects/", "organisation__id": organisation.pk, "status": "success", + "user__id": str(staff_user.uuid), } ] @@ -99,6 +105,7 @@ def test_client_usage_logger_middleware__mcp_user_without_organisations__logs_wa "http__route": "/api/v1/projects/", "organisation__id": None, "status": "success", + "user__id": str(staff_user.uuid), } ] @@ -126,6 +133,7 @@ def test_client_usage_logger_middleware__mcp_user_with_multiple_organisations__l "http__route": "/api/v1/projects/", "organisation__id": None, "status": "success", + "user__id": str(staff_user.uuid), } ] @@ -146,6 +154,7 @@ def test_client_usage_logger_middleware__mcp_unauthenticated_request__logs_nothi @pytest.mark.usefixtures("mcp_baggage") def test_client_usage_logger_middleware__mcp_error_response__logs_error_status( staff_client: APIClient, + staff_user: FFAdminUser, organisation: Organisation, log: StructuredLogCapture, ) -> None: @@ -162,6 +171,7 @@ def test_client_usage_logger_middleware__mcp_error_response__logs_error_status( "http__route": "/api/v1/organisations/{organisation_pk}/invites/", "organisation__id": organisation.pk, "status": "error", + "user__id": str(staff_user.uuid), } ] @@ -224,8 +234,8 @@ def test_client_usage_logger_middleware__user_agent_not_matching_cli_pattern__lo assert log.events == [] -@pytest.mark.usefixtures("recording_span", "organisation") -def test_client_usage_logger_middleware__cli_organisation_id_span_attribute__logs_span_organisation_id( +@pytest.mark.usefixtures("organisation") +def test_client_usage_logger_middleware__cli_organisation_id_in_request_context__logs_bound_organisation_id( staff_client: APIClient, staff_user: FFAdminUser, log: StructuredLogCapture, @@ -233,10 +243,13 @@ def test_client_usage_logger_middleware__cli_organisation_id_span_attribute__log # Given other_organisation = Organisation.objects.create(name="Other Org") staff_user.add_organisation(other_organisation, role=OrganisationRole.ADMIN) + other_project = Project.objects.create( + name="Other Project", organisation=other_organisation + ) # When response = staff_client.get( - f"/api/v1/organisations/{other_organisation.pk}/invites/", + f"/api/v1/projects/{other_project.pk}/features/", HTTP_USER_AGENT=CLI_USER_AGENT, ) @@ -247,12 +260,14 @@ def test_client_usage_logger_middleware__cli_organisation_id_span_attribute__log "level": "info", "event": "request.made", "http__request__method": "GET", - "http__route": "/api/v1/organisations/{organisation_pk}/invites/", + "http__route": "/api/v1/projects/{project_pk}/features/", + "project__id": other_project.pk, "cli__version": "2.0.0", "cli__os": "darwin", "cli__arch": "arm64", "organisation__id": other_organisation.pk, "status": "success", + "user__id": str(staff_user.uuid), "amplitude__user_id": str(staff_user.uuid), } ] @@ -280,6 +295,7 @@ def test_client_usage_logger_middleware__cli_user_with_single_organisation__logs "cli__arch": "arm64", "organisation__id": organisation.pk, "status": "success", + "user__id": str(staff_user.uuid), "amplitude__user_id": str(staff_user.uuid), } ] @@ -309,6 +325,7 @@ def test_client_usage_logger_middleware__cli_user_without_organisations__logs_wa "cli__arch": "arm64", "organisation__id": None, "status": "success", + "user__id": str(staff_user.uuid), "amplitude__user_id": str(staff_user.uuid), } ] @@ -340,6 +357,7 @@ def test_client_usage_logger_middleware__cli_user_with_multiple_organisations__l "cli__arch": "arm64", "organisation__id": None, "status": "success", + "user__id": str(staff_user.uuid), "amplitude__user_id": str(staff_user.uuid), } ] @@ -410,6 +428,7 @@ def test_client_usage_logger_middleware__cli_error_response__logs_error_status( "cli__arch": "arm64", "organisation__id": organisation.pk, "status": "error", + "user__id": str(staff_user.uuid), "amplitude__user_id": str(staff_user.uuid), } ] @@ -496,6 +515,7 @@ def test_client_usage_logger_middleware__cli_user_agent__passes_version_through_ "cli__arch": expected_arch, "organisation__id": organisation.pk, "status": "success", + "user__id": str(staff_user.uuid), "amplitude__user_id": str(staff_user.uuid), } ] diff --git a/api/tests/unit/telemetry/test_unit_telemetry_request_context.py b/api/tests/unit/telemetry/test_unit_telemetry_request_context.py new file mode 100644 index 000000000000..c91408e95c88 --- /dev/null +++ b/api/tests/unit/telemetry/test_unit_telemetry_request_context.py @@ -0,0 +1,171 @@ +import typing +from collections.abc import Generator + +import pytest +import structlog.contextvars +from common.core.request_context import get_request_context +from django.contrib.auth.models import AnonymousUser +from rest_framework.request import Request +from rest_framework.response import Response +from rest_framework.test import APIRequestFactory, force_authenticate +from rest_framework.views import APIView + +from api_keys.authentication import MasterAPIKeyAuthentication +from api_keys.models import MasterAPIKey +from environments.models import Environment +from features.models import Feature +from organisations.models import Organisation +from projects.models import Project +from telemetry.request_context import install +from users.models import FFAdminUser + +REQUEST_CONTEXT_NAMES = ( + "environment__id", + "feature__id", + "organisation__id", + "project__id", + "user__id", +) + + +class RequestContextView(APIView): + """Respond with the request context bound by the time the view handles it""" + + authentication_classes = [MasterAPIKeyAuthentication] + permission_classes: list[type] = [] + + def get(self, request: Request, **kwargs: typing.Any) -> Response: + return Response( + {name: get_request_context(name) for name in REQUEST_CONTEXT_NAMES} + ) + + +@pytest.fixture(autouse=True) +def clear_request_context() -> Generator[None, None, None]: + # Bypassing `RequestContextMiddleware`, bindings would outlive the test + yield + structlog.contextvars.clear_contextvars() + + +@pytest.fixture() +def api_request_factory() -> APIRequestFactory: + return APIRequestFactory() + + +def test_api_view__ffadmin_user__binds_user( + api_request_factory: APIRequestFactory, + staff_user: FFAdminUser, +) -> None: + # Given + request = api_request_factory.get("/") + force_authenticate(request, user=staff_user) + + # When + response = RequestContextView.as_view()(request) + + # Then + assert response.data == { + "environment__id": None, + "feature__id": None, + "organisation__id": None, + "project__id": None, + "user__id": str(staff_user.uuid), + } + + +def test_api_view__master_api_key__binds_key_organisation_only( + api_request_factory: APIRequestFactory, + admin_master_api_key: tuple[MasterAPIKey, str], + organisation: Organisation, +) -> None: + # Given + _, key = admin_master_api_key + request = api_request_factory.get("/", HTTP_AUTHORIZATION=f"Api-Key {key}") + + # When + response = RequestContextView.as_view()(request) + + # Then + assert response.data == { + "environment__id": None, + "feature__id": None, + "organisation__id": organisation.id, + "project__id": None, + "user__id": None, + } + + +@pytest.mark.parametrize("user", [None, AnonymousUser()]) +def test_api_view__no_user__binds_nothing( + api_request_factory: APIRequestFactory, + user: AnonymousUser | None, +) -> None: + # Given + # e.g. `EnvironmentKeyAuthentication` authenticates SDK requests as `None` + request = api_request_factory.get("/") + force_authenticate(request, user=user) + + # When + response = RequestContextView.as_view()(request) + + # Then + assert response.data == {name: None for name in REQUEST_CONTEXT_NAMES} + + +def test_api_view__project_and_feature_route__binds_url_entities( + api_request_factory: APIRequestFactory, + staff_user: FFAdminUser, + project: Project, + feature: Feature, +) -> None: + # Given + request = api_request_factory.get("/") + force_authenticate(request, user=staff_user) + + # When + response = RequestContextView.as_view()( + request, + project_pk=str(project.id), + feature_pk=str(feature.id), + ) + + # Then + assert response.data == { + "environment__id": None, + "feature__id": feature.id, + "organisation__id": project.organisation_id, + "project__id": project.id, + "user__id": str(staff_user.uuid), + } + + +def test_api_view__environment_route__binds_environment_key_and_ids( + api_request_factory: APIRequestFactory, + environment: Environment, +) -> None: + # Given + request = api_request_factory.get("/") + force_authenticate(request, user=None) + + # When + RequestContextView.as_view()(request, environment_api_key=environment.api_key) + + # Then + assert structlog.contextvars.get_contextvars() == { + "environment__id": environment.id, + "environment__key": environment.api_key, + "organisation__id": environment.project.organisation_id, + "project__id": environment.project_id, + } + + +def test_install__installed_already__keeps_wrapper() -> None: + # Given + # NOTE: `TelemetryConfig.ready` installed it + perform_authentication = APIView.perform_authentication + + # When + install() + + # Then + assert APIView.perform_authentication is perform_authentication diff --git a/api/tests/unit/telemetry/test_unit_telemetry_services.py b/api/tests/unit/telemetry/test_unit_telemetry_services.py new file mode 100644 index 000000000000..4ad1d3f10871 --- /dev/null +++ b/api/tests/unit/telemetry/test_unit_telemetry_services.py @@ -0,0 +1,135 @@ +import typing + +import pytest + +from environments.models import Environment +from features.models import Feature +from projects.models import Project +from telemetry.services import get_resolved_telemetry_attributes +from telemetry.types import ResolvedTelemetryAttributes + + +def test_get_resolved_telemetry_attributes__project_id__resolves_organisation( + project: Project, + django_assert_num_queries: typing.Any, +) -> None: + # Given / When + with django_assert_num_queries(1): + resolved_ids = get_resolved_telemetry_attributes({"project__id": project.id}) + + # Then + assert resolved_ids == { + "organisation__id": project.organisation_id, + "project__id": project.id, + } + + +def test_get_resolved_telemetry_attributes__feature_id__resolves_project_and_organisation( + feature: Feature, + django_assert_num_queries: typing.Any, +) -> None: + # Given / When + with django_assert_num_queries(1): + resolved_ids = get_resolved_telemetry_attributes({"feature__id": feature.id}) + + # Then + assert resolved_ids == { + "feature__id": feature.id, + "organisation__id": feature.project.organisation_id, + "project__id": feature.project_id, + } + + +def test_get_resolved_telemetry_attributes__feature_and_project_ids__resolves_organisation_only( + feature: Feature, + django_assert_num_queries: typing.Any, +) -> None: + # Given / When + with django_assert_num_queries(1): + resolved_ids = get_resolved_telemetry_attributes( + {"feature__id": feature.id, "project__id": feature.project_id} + ) + + # Then + assert resolved_ids == { + "feature__id": feature.id, + "organisation__id": feature.project.organisation_id, + "project__id": feature.project_id, + } + + +def test_get_resolved_telemetry_attributes__environment_key__resolves_environment_project_and_organisation( + environment: Environment, + feature: Feature, + django_assert_num_queries: typing.Any, +) -> None: + # Given / When + with django_assert_num_queries(1): + resolved_ids = get_resolved_telemetry_attributes( + {"environment__key": environment.api_key, "feature__id": feature.id} + ) + + # Then + assert resolved_ids == { + "environment__key": environment.api_key, + "environment__id": environment.id, + "feature__id": feature.id, + "organisation__id": environment.project.organisation_id, + "project__id": environment.project_id, + } + + +@pytest.mark.parametrize( + "ids", + [ + {"environment__key": "unknown"}, + {"feature__id": 404}, + {"project__id": 404}, + ], +) +def test_get_resolved_telemetry_attributes__unknown_entities__resolves_nothing( + db: None, + ids: ResolvedTelemetryAttributes, +) -> None: + # Given / When + resolved_ids = get_resolved_telemetry_attributes(ids) + + # Then + assert resolved_ids == ids + + +def test_get_resolved_telemetry_attributes__complete_ids__queries_nothing() -> None: + # Given + ids: ResolvedTelemetryAttributes = { + "environment__key": "key", + "environment__id": 1, + "feature__id": 2, + "organisation__id": 3, + "project__id": 4, + } + + # When + # NOTE: Without database access, any query would fail the test + resolved_ids = get_resolved_telemetry_attributes(ids) + + # Then + assert resolved_ids == ids + assert resolved_ids is not ids + + +def test_get_resolved_telemetry_attributes__unknown_environment_key__skips_other_lookups( + feature: Feature, + django_assert_num_queries: typing.Any, +) -> None: + # Given + ids: ResolvedTelemetryAttributes = { + "environment__key": "unknown", + "feature__id": feature.id, + } + + # When + with django_assert_num_queries(1): + resolved_ids = get_resolved_telemetry_attributes(ids) + + # Then + assert resolved_ids == ids diff --git a/api/tests/unit/telemetry/test_unit_telemetry_spans.py b/api/tests/unit/telemetry/test_unit_telemetry_spans.py deleted file mode 100644 index 82b9d19037d2..000000000000 --- a/api/tests/unit/telemetry/test_unit_telemetry_spans.py +++ /dev/null @@ -1,37 +0,0 @@ -import pytest - -from telemetry.spans import get_span_attribute, set_span_attribute - - -@pytest.mark.usefixtures("recording_span") -def test_set_span_attribute__recording_span__attribute_round_trips() -> None: - # Given - attribute = "organisation.id" - - # When - set_span_attribute(attribute, 42) - - # Then - assert get_span_attribute(attribute) == 42 - - -def test_set_span_attribute__no_recording_span__silently_ignored() -> None: - # Given - attribute = "organisation.id" - - # When - set_span_attribute(attribute, 42) - - # Then - assert get_span_attribute(attribute) is None - - -def test_get_span_attribute__no_recording_span__returns_none() -> None: - # Given - attribute = "organisation.id" - - # When - value = get_span_attribute(attribute) - - # Then - assert value is None diff --git a/docs/docs/deployment-self-hosting/observability/_events-catalogue.md b/docs/docs/deployment-self-hosting/observability/_events-catalogue.md index 3d4a0eba6dba..81afc604ba5f 100644 --- a/docs/docs/deployment-self-hosting/observability/_events-catalogue.md +++ b/docs/docs/deployment-self-hosting/observability/_events-catalogue.md @@ -151,8 +151,8 @@ Attributes: ### `cli.request.made` Logged at `info` from: - - `api/telemetry/middleware.py:72` - - `api/telemetry/middleware.py:74` + - `api/telemetry/middleware.py:71` + - `api/telemetry/middleware.py:73` Attributes: - `amplitude.user_id` @@ -179,7 +179,6 @@ Logged at `info` from: Attributes: - `code_references.count` - `feature.count` - - `organisation.id` ### `cohorts.cohort.created` @@ -754,8 +753,8 @@ Attributes: ### `mcp.tool.called` Logged at `info` from: - - `api/telemetry/middleware.py:48` - - `api/telemetry/middleware.py:50` + - `api/telemetry/middleware.py:47` + - `api/telemetry/middleware.py:49` Attributes: - `organisation.id` @@ -1024,9 +1023,9 @@ Attributes: ### `usage_reporting.run.skipped` Logged at `debug` from: - - `api/telemetry/services.py:21` - - `api/telemetry/services.py:24` - - `api/telemetry/services.py:27` + - `api/telemetry/services.py:25` + - `api/telemetry/services.py:28` + - `api/telemetry/services.py:31` Attributes: - `reason` @@ -1034,7 +1033,7 @@ Attributes: ### `usage_reporting.snapshot.errored` Logged at `exception` from: - - `api/telemetry/services.py:39` + - `api/telemetry/services.py:43` Attributes: