Skip to content
Open
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
2 changes: 1 addition & 1 deletion api/app/settings/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 0 additions & 2 deletions api/permissions/permission_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Comment thread
khvn26 marked this conversation as resolved.
Resolved
return user_organisation.role == OrganisationRole.ADMIN.name
return False

Expand Down
1 change: 0 additions & 1 deletion api/projects/code_references/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
)
Expand Down
4 changes: 4 additions & 0 deletions api/telemetry/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
19 changes: 19 additions & 0 deletions api/telemetry/mappers.py
Original file line number Diff line number Diff line change
@@ -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
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
return ids
6 changes: 2 additions & 4 deletions api/telemetry/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -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<version>[^\s/]+) \((?P<os>[^\s/()]+)/(?P<arch>[^\s/()]+)\)"
Expand Down Expand Up @@ -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
Expand Down
68 changes: 68 additions & 0 deletions api/telemetry/request_context.py
Original file line number Diff line number Diff line change
@@ -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),
)
52 changes: 52 additions & 0 deletions api/telemetry/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down Expand Up @@ -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
11 changes: 0 additions & 11 deletions api/telemetry/spans.py

This file was deleted.

11 changes: 11 additions & 0 deletions api/telemetry/types.py
Original file line number Diff line number Diff line change
@@ -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
11 changes: 11 additions & 0 deletions api/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading
Loading