Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

7.4 KB
Raw Blame
import base64
import binascii
from collections.abc import Mapping
from datetime import timedelta
from typing import Any
from uuid import UUID

from drf_spectacular.utils import OpenApiResponse, extend_schema
from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import Throttled
from rest_framework.parsers import JSONParser
from rest_framework.permissions import AllowAny
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.throttling import SimpleRateThrottle
from rest_framework.views import APIView

from posthog.ingress.verify.schemes import VerificationOutcome, standard_webhooks_scheme
from posthog.rate_limit import IPThrottle

from products.account_audits.backend.facade import api as account_audits
from products.account_audits.backend.facade.contracts import AccountAuditRequest

MAX_BODY_BYTES = 4 * 1024
SIGNATURE_TOLERANCE = timedelta(minutes=5)


class AccountAuditStartThrottle(IPThrottle):
    scope = "account_audit_start"
    rate = "600/minute"


class AccountAuditCredentialThrottle(SimpleRateThrottle):
    scope = "account_audit_credential"
    rate = "60/minute"

    def get_cache_key(self, request: Request, view: APIView) -> str:
        return self.cache_format % {"scope": self.scope, "ident": str(UUID(request.headers["X-PostHog-Audit-Key"]))}


class AccountAuditStartRequestSerializer(serializers.Serializer):
    organization_id = serializers.UUIDField(help_text="Organization that owns the target team.")
    team_id = serializers.IntegerField(
        required=False,
        help_text="Target team ID. Defaults to the non-demo root project with the most distinct resource viewers in the last 30 days, excluding projects pending deletion. Ties use the oldest project.",
        min_value=1,
    )
    reason = serializers.CharField(max_length=500, help_text="Why the account audit is being requested.")
    skill_project = serializers.IntegerField(
        min_value=1,
        help_text="Project ID containing the skill in this region. Audit credentials authorize reading skills from any project.",
    )
    skill_name = serializers.CharField(
        max_length=64,
        help_text="Name of the single-file skill in skill_project. Uses its latest active version.",
    )

    def to_internal_value(self, data: Any) -> dict[str, Any]:
        field_types = {"organization_id": str, "team_id": int, "reason": str, "skill_project": int, "skill_name": str}
        if not isinstance(data, dict) or set(data) - field_types.keys():
            raise serializers.ValidationError(
                {"non_field_errors": ["Expected an object containing only supported audit parameters."]}
            )
        if any(type(value) is not field_types[key] for key, value in data.items()):
            raise serializers.ValidationError({"non_field_errors": ["Audit parameters have invalid types."]})
        return super().to_internal_value(data)


class AccountAuditStartResponseSerializer(serializers.Serializer):
    task_run_id = serializers.UUIDField(help_text="Native task run executing the account audit.")
    team_id = serializers.IntegerField(help_text="Resolved target team ID.")


class AccountAuditConflictSerializer(serializers.Serializer):
    detail = serializers.CharField(help_text="Why this audit did not start.")


class AccountAuditStartViewSet(viewsets.ViewSet):
    authentication_classes: list[type] = []
    permission_classes = [AllowAny]
    parser_classes = [JSONParser]
    scope_object = "INTERNAL"

    @extend_schema(
        request=AccountAuditStartRequestSerializer,
        responses={
            202: AccountAuditStartResponseSerializer,
            204: None,
            400: OpenApiResponse(
                description=(
                    "The request was rejected. A body that is not JSON or is too large, or a missing or ineligible "
                    "team, returns no body. Invalid fields return a validation error body. A missing "
                    "or unsupported skill returns a detail message."
                )
            ),
            401: None,
            403: None,
            409: AccountAuditConflictSerializer,
            503: None,
        },
    )
    @action(methods=["POST"], detail=False, throttle_classes=[AccountAuditStartThrottle])
    def start(self, request: Request) -> Response:
        if request.content_type != "application/json":
            return Response(status=status.HTTP_400_BAD_REQUEST)
        try:
            if int(request.META.get("CONTENT_LENGTH") or 0) > MAX_BODY_BYTES:
                return Response(status=status.HTTP_400_BAD_REQUEST)
        except ValueError:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        raw_body = request.body
        if len(raw_body) > MAX_BODY_BYTES:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        public_key_id = self._verified_credential_key_id(request, raw_body)
        if public_key_id is None:
            return Response(status=status.HTTP_401_UNAUTHORIZED)

        throttle = AccountAuditCredentialThrottle()
        if not throttle.allow_request(request, self):
            raise Throttled(wait=throttle.wait())

        serializer = AccountAuditStartRequestSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        payload = AccountAuditRequest(**serializer.validated_data)
        result = account_audits.start(payload, public_key_id, request.headers["webhook-id"])
        if result.status == "accepted":
            return Response(AccountAuditStartResponseSerializer(instance=result).data, status=202)
        if result.status == "skipped":
            return Response(status=204)
        if result.status == "skill_unavailable":
            return Response(
                {"detail": "Skill not found or unsupported. Check skill_project and skill_name."},
                status=400,
            )
        if result.status == "conflict":
            return Response({"detail": "This delivery ID has another audit request."}, status=409)
        return Response(
            status={"invalid": 400, "unauthorized": 401, "forbidden": 403, "unavailable": 503}[result.status]
        )

    @classmethod
    def _verified_credential_key_id(cls, request: Request, raw_body: bytes) -> UUID | None:
        key_id = request.headers.get("X-PostHog-Audit-Key")
        try:
            public_key_id = UUID(key_id or "")
        except (TypeError, ValueError, AttributeError):
            return None
        signing_secret = account_audits.signing_secret_for(public_key_id)
        webhook_id = request.headers.get("webhook-id")
        if (
            signing_secret is None
            or not webhook_id
            or len(webhook_id) > 255
            or not cls._valid_signature(signing_secret, raw_body, request.headers)
        ):
            return None
        return public_key_id

    @staticmethod
    def _valid_signature(signing_secret: str, raw_body: bytes, headers: Mapping[str, str]) -> bool:
        secret = signing_secret.removeprefix("whsec_")
        try:
            signing_key = base64.b64decode(secret, validate=True)
        except (ValueError, binascii.Error):
            return False
        scheme = standard_webhooks_scheme(
            lambda: signing_key, tolerance_seconds=int(SIGNATURE_TOLERANCE.total_seconds())
        )
        return scheme.verify(body=raw_body, headers=headers).outcome == VerificationOutcome.VERIFIED