Exemplo n.º 1
0
    def test_get_team(self):
        # No data at all
        ingestion_context, db_error, error_response = get_event_ingestion_context(
            HttpRequest(), {}, "")

        self.assertEqual(ingestion_context, None)
        self.assertEqual(db_error, None)
        self.assertEqual(type(error_response), JsonResponse)
        self.assertEqual(error_response.status_code,
                         status.HTTP_401_UNAUTHORIZED)  # type: ignore
        self.assertEqual("Project API key invalid"
                         in json.loads(error_response.getvalue())["detail"],
                         True)  # type: ignore

        # project_id exists but is invalid: should look for a personal API key and fail
        ingestion_context, db_error, error_response = get_event_ingestion_context(
            HttpRequest(), {"project_id": 438483483}, "")

        self.assertEqual(ingestion_context, None)
        self.assertEqual(db_error, None)
        self.assertEqual(type(error_response), JsonResponse)
        self.assertEqual(error_response.status_code,
                         status.HTTP_401_UNAUTHORIZED)  # type: ignore
        self.assertEqual(
            json.loads(error_response.getvalue())["detail"],
            "Invalid Personal API key.")  # type: ignore

        # Correct token
        ingestion_context, db_error, error_response = get_event_ingestion_context(
            HttpRequest(), {}, self.team.api_token)

        self.assertEqual(
            ingestion_context,
            EventIngestionContext(team_id=self.team.pk, anonymize_ips=False))
        self.assertEqual(db_error, None)
        self.assertEqual(error_response, None)

        get_team_from_token_patcher = patch(
            "posthog.api.utils.get_event_ingestion_context_for_token",
            side_effect=mocked_get_ingest_context_from_token)
        get_team_from_token_patcher.start()

        # Postgres fetch team error
        ingestion_context, db_error, error_response = get_event_ingestion_context(
            HttpRequest(), {}, self.team.api_token)

        self.assertEqual(ingestion_context, None)
        self.assertEqual(db_error, "Exception('test exception')")
        self.assertEqual(error_response, None)

        get_team_from_token_patcher.stop()
Exemplo n.º 2
0
def get_event(request):
    timer = statsd.timer("posthog_cloud_event_endpoint").start()
    now = timezone.now()

    data, error_response = get_data(request)

    if error_response:
        return error_response

    sent_at = _get_sent_at(data, request)

    token = get_token(data, request)

    if not token:
        return cors_response(
            request,
            generate_exception_response(
                "capture",
                "API key not provided. You can find your project API key in PostHog project settings.",
                type="authentication_error",
                code="missing_api_key",
                status_code=status.HTTP_401_UNAUTHORIZED,
            ),
        )

    ingestion_context, db_error, error_response = get_event_ingestion_context(request, data, token)

    if error_response:
        return error_response

    send_events_to_dead_letter_queue = False
    if db_error:
        send_events_to_dead_letter_queue = True

    if isinstance(data, dict):
        if data.get("batch"):  # posthog-python and posthog-ruby
            data = data["batch"]
            assert data is not None
        elif "engage" in request.path_info:  # JS identify call
            data["event"] = "$identify"  # make sure it has an event name

    if isinstance(data, list):
        events = data
    else:
        events = [data]

    try:
        events = preprocess_session_recording_events(events)
    except ValueError as e:
        return cors_response(
            request, generate_exception_response("capture", f"Invalid payload: {e}", code="invalid_payload")
        )

    site_url = request.build_absolute_uri("/")[:-1]

    ip = None if not ingestion_context or ingestion_context.anonymize_ips else get_ip_address(request)
    for event in events:
        event_uuid = UUIDT()
        distinct_id = get_distinct_id(event)
        if not distinct_id:
            continue

        payload_uuid = event.get("uuid", None)
        if payload_uuid:
            if UUIDT.is_valid_uuid(payload_uuid):
                event_uuid = UUIDT(uuid_str=payload_uuid)
            else:
                statsd.incr("invalid_event_uuid")

        event = parse_event(event, distinct_id, ingestion_context)
        if not event:
            continue

        if send_events_to_dead_letter_queue:
            kafka_event = parse_kafka_event_data(
                distinct_id=distinct_id,
                ip=None,
                site_url=site_url,
                team_id=None,
                now=now,
                event_uuid=event_uuid,
                data=event,
                sent_at=sent_at,
            )

            log_event_to_dead_letter_queue(
                data,
                event["event"],
                kafka_event,
                f"Unable to fetch team from Postgres. Error: {db_error}",
                "django_server_capture_endpoint",
            )
            continue

        try:
            capture_internal(event, distinct_id, ip, site_url, now, sent_at, ingestion_context.team_id, event_uuid)  # type: ignore
        except Exception as e:
            timer.stop()
            capture_exception(e, {"data": data})
            statsd.incr(
                "posthog_cloud_raw_endpoint_failure", tags={"endpoint": "capture",},
            )
            return cors_response(
                request,
                generate_exception_response(
                    "capture",
                    "Unable to store event. Please try again. If you are the owner of this app you can check the logs for further details.",
                    code="server_error",
                    type="server_error",
                    status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                ),
            )

    timer.stop()
    statsd.incr(
        "posthog_cloud_raw_endpoint_success", tags={"endpoint": "capture",},
    )
    return cors_response(request, JsonResponse({"status": 1}))
Exemplo n.º 3
0
    def test_determine_team_from_request_data_ch(self, _):
        team, db_error, _ = get_event_ingestion_context(HttpRequest(), {}, "")

        self.assertEqual(team, None)
        self.assertEqual(db_error, "Exception('test exception')")