: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import copy
import hmac
import json
import math
import hashlib
import datetime
from email.message import Message
from types import SimpleNamespace
from typing import Any, cast
from urllib.request import Request as UrllibRequest
import time_machine
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from django.test import SimpleTestCase, override_settings
import jwt
import requests
from parameterized import parameterized
from rest_framework.exceptions import NotAuthenticated
from posthog.cloud_utils import TEST_clear_instance_license_cache
from posthog.models.oauth import OAuthApplication
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.team.team import Team
from posthog.models.user import User
from products.logs.backend.models import LogsRetentionRule
from ee.billing.billing_manager import (
BILLING_PROVIDER_WEBHOOK_SIGNATURE_HEADER,
BILLING_PROVIDER_WEBHOOK_SIGNATURE_VERSION,
BILLING_PROVIDER_WEBHOOK_TIMESTAMP_HEADER,
BillingManager,
BillingServiceRateLimited,
BillingServiceResponseError,
FundingStatusUnavailable,
OrganizationFundingStatus,
OrganizationHasNoOwnerError,
PrepaidCreditState,
_get_user_organization_role,
_parse_funding_status,
build_billing_token,
handle_billing_service_error,
http_session,
)
from ee.billing.billing_types import BillingProvider, BillingStatus, Product
from ee.billing.quota_limiting import QuotaLimitingCaches, QuotaResource, list_limited_team_attributes
from ee.models.license import License, LicenseManager
def create_default_products_response(**kwargs) -> dict[str, list[Product]]:
data: Any = {
"products": [
Product(
name="Product analytics",
headline="Product analytics with autocapture",
description="A comprehensive product analytics platform built to natively work with session replay, feature flags, experiments, and surveys.",
usage_key="events",
image_url="https://posthog.com/images/products/product-analytics/product-analytics.png",
docs_url="https://posthog.com/docs/product-analytics",
type="product_analytics",
unit="event",
contact_support=False,
inclusion_only=False,
icon_key="IconGraph",
plans=[],
addons=[],
)
]
}
data.update(kwargs)
return data
class TestFundingStatusParsing(SimpleTestCase):
@parameterized.expand(
[
(
"normal",
{"startup_program_label": None, "prepaid_credit_state": "none"},
OrganizationFundingStatus(
startup_program_label=None,
prepaid_credit_state=PrepaidCreditState.NONE,
),
),
(
"startup_active",
{"startup_program_label": "Startup", "prepaid_credit_state": "active"},
OrganizationFundingStatus(
startup_program_label="Startup",
prepaid_credit_state=PrepaidCreditState.ACTIVE,
),
),
(
"yc_expired",
{"startup_program_label": "YC", "prepaid_credit_state": "expired"},
OrganizationFundingStatus(
startup_program_label="YC",
prepaid_credit_state=PrepaidCreditState.EXPIRED,
),
),
]
)
def test_parses_funding_status(
self, _name: str, payload: dict[str, str | None], expected: OrganizationFundingStatus
) -> None:
self.assertEqual(_parse_funding_status(payload), expected)
@parameterized.expand(
[
("not_an_object", []),
(
"invalid_program_label",
{"startup_program_label": "Growth", "prepaid_credit_state": "none"},
),
("missing_program_label", {"prepaid_credit_state": "none"}),
("missing_credit_state", {"startup_program_label": None}),
(
"invalid_credit_state",
{"startup_program_label": None, "prepaid_credit_state": "paid"},
),
]
)
def test_rejects_invalid_funding_status(self, _name: str, payload: object) -> None:
with self.assertRaises(FundingStatusUnavailable):
_parse_funding_status(payload)
class TestBillingManager(BaseTest):
@patch(
"ee.billing.billing_manager.http_session.get",
return_value=MagicMock(
status_code=200, json=MagicMock(return_value={"products": create_default_products_response()})
),
)
def test_get_billing_unlicensed(self, billing_patch_request_mock):
organization = self.organization
TEST_clear_instance_license_cache()
BillingManager(license=None).get_billing(organization)
assert billing_patch_request_mock.call_count == 1
billing_patch_request_mock.assert_called_with(
"https://billing.posthog.com/api/products-v2", params={"plan": "standard"}, headers={}
)
def test_get_billing_adds_todays_usage_to_usage_summary(self):
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
self.organization.usage = {
"posthog_code_token_credits": {"usage": 1200, "todays_usage": 34, "limit": None},
"period": ["2022-10-07T11:12:48", "2022-11-07T11:12:48"],
}
manager = BillingManager(license)
billing_response = {
"customer": {
"products": [],
"usage_summary": {
"posthog_code_token_credits": {"usage": 1200, "limit": None},
"period": ["2022-10-07T11:12:48", "2022-11-07T11:12:48"],
},
}
}
with (
patch.object(manager, "_get_billing", return_value=billing_response),
patch.object(manager, "update_org_details"),
patch.object(manager, "get_default_products", return_value={"products": []}),
):
response = manager.get_billing(self.organization)
assert response["usage_summary"]["posthog_code_token_credits"] == {
"usage": 1200,
"limit": None,
"todays_usage": 34,
}
assert response["usage_summary"]["period"] == ["2022-10-07T11:12:48", "2022-11-07T11:12:48"]
@parameterized.expand(
[
("with_ip", "203.0.113.7", True),
("without_ip", None, False),
]
)
def test_get_auth_headers_forwards_actor_ip(self, _name, ip_address, expect_header):
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
headers = BillingManager(license, self.user, ip_address=ip_address).get_auth_headers(self.organization)
assert headers["Authorization"].startswith("Bearer ")
assert ("X-PostHog-Actor-IP" in headers) is expect_header
if expect_header:
assert headers["X-PostHog-Actor-IP"] == ip_address
@patch("ee.billing.billing_manager.BILLING_SERVICE_URL", "https://billing.posthog.com")
@patch("ee.billing.billing_manager.cache")
@patch("ee.billing.billing_manager.http_session.get")
def test_get_funding_status_uses_organization_scoped_billing_token(
self, mock_get: MagicMock, mock_cache: MagicMock
) -> None:
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
payload = {"startup_program_label": None, "prepaid_credit_state": "none"}
mock_cache.get.return_value = None
mock_get.return_value = MagicMock(status_code=200, json=MagicMock(return_value=payload))
result = BillingManager(license, self.user).get_funding_status(self.organization)
assert result == OrganizationFundingStatus(
startup_program_label=None,
prepaid_credit_state=PrepaidCreditState.NONE,
)
mock_get.assert_called_once()
call = mock_get.call_args
assert call.args[0] == "https://billing.posthog.com/api/billing/funding-status/"
assert call.kwargs["headers"]["Authorization"].startswith("Bearer ")
assert call.kwargs["timeout"] == 5
mock_cache.set.assert_called_once_with(
f"organization_funding_status:{self.organization.id}", payload, timeout=30
)
@patch("ee.billing.billing_manager.cache")
@patch("ee.billing.billing_manager.http_session.get")
def test_get_funding_status_uses_cached_value(self, mock_get: MagicMock, mock_cache: MagicMock) -> None:
mock_cache.get.return_value = {"startup_program_label": "YC", "prepaid_credit_state": "expired"}
result = BillingManager(MagicMock(), self.user).get_funding_status(self.organization)
assert result == OrganizationFundingStatus(
startup_program_label="YC",
prepaid_credit_state=PrepaidCreditState.EXPIRED,
)
mock_get.assert_not_called()
@patch("ee.billing.billing_manager.cache")
@patch("ee.billing.billing_manager.http_session.get")
def test_get_funding_status_ignores_cache_failure(self, mock_get: MagicMock, mock_cache: MagicMock) -> None:
payload = {"startup_program_label": None, "prepaid_credit_state": "active"}
mock_cache.get.side_effect = RuntimeError("cache unavailable")
mock_cache.set.side_effect = RuntimeError("cache unavailable")
mock_get.return_value = MagicMock(status_code=200, json=MagicMock(return_value=payload))
manager = BillingManager(MagicMock(), self.user)
with patch.object(manager, "get_auth_headers", return_value={}):
result = manager.get_funding_status(self.organization)
assert result.prepaid_credit_state == PrepaidCreditState.ACTIVE
@patch("ee.billing.billing_manager.cache")
@patch("ee.billing.billing_manager.http_session.get", side_effect=requests.Timeout)
def test_get_funding_status_caches_billing_failure(self, mock_get: MagicMock, mock_cache: MagicMock) -> None:
cached_values: list[object | None] = [None]
mock_cache.get.side_effect = lambda _key: cached_values[-1]
mock_cache.set.side_effect = lambda _key, value, timeout: cached_values.append(value)
manager = BillingManager(MagicMock(), self.user)
with patch.object(manager, "get_auth_headers", return_value={}):
with self.assertRaises(FundingStatusUnavailable):
manager.get_funding_status(self.organization)
with self.assertRaises(FundingStatusUnavailable):
manager.get_funding_status(self.organization)
mock_get.assert_called_once()
assert mock_cache.set.call_args.kwargs["timeout"] == 5
@patch(
"ee.billing.billing_manager.http_session.patch",
return_value=MagicMock(status_code=200, json=MagicMock(return_value={"text": "ok"})),
)
def test_update_billing_organization_users(self, billing_patch_request_mock: MagicMock):
organization = self.organization
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
y = User.objects.create_and_join(
organization=organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
organization.refresh_from_db()
assert len(organization.members.values_list("distinct_id", flat=True)) == 2 # one exists in the test base
BillingManager(license).update_billing_organization_users(organization)
assert billing_patch_request_mock.call_count == 1
assert len(billing_patch_request_mock.call_args[1]["json"]["distinct_ids"]) == 2
assert billing_patch_request_mock.call_args[1]["json"]["org_customer_email"] == "[email protected]"
assert billing_patch_request_mock.call_args[1]["json"]["org_admin_emails"] == ["[email protected]"]
assert billing_patch_request_mock.call_args[1]["json"]["org_users"] == [
{"email": "[email protected]", "distinct_id": y.distinct_id, "role": 15},
]
@patch(
"ee.billing.billing_manager.http_session.patch",
return_value=MagicMock(status_code=200, json=MagicMock(return_value={"text": "ok"})),
)
def test_update_billing_organization_users_with_multiple_members(self, billing_patch_request_mock: MagicMock):
organization = self.organization
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
User.objects.create_and_join(
organization=organization,
email="[email protected]",
first_name="y1",
last_name="y1",
password=None,
level=OrganizationMembership.Level.MEMBER,
)
y2 = User.objects.create_and_join(
organization=organization,
email="[email protected]",
first_name="y2",
last_name="y2",
password=None,
level=OrganizationMembership.Level.ADMIN,
)
y3 = User.objects.create_and_join(
organization=organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
organization.refresh_from_db()
BillingManager(license).update_billing_organization_users(organization)
assert billing_patch_request_mock.call_count == 1
assert len(billing_patch_request_mock.call_args[1]["json"]["distinct_ids"]) == 4
assert billing_patch_request_mock.call_args[1]["json"]["org_customer_email"] == "[email protected]"
assert sorted(billing_patch_request_mock.call_args[1]["json"]["org_admin_emails"]) == ["[email protected]", "[email protected]"]
assert billing_patch_request_mock.call_args[1]["json"]["org_users"] == [
{"email": "[email protected]", "distinct_id": y2.distinct_id, "role": 8},
{"email": "[email protected]", "distinct_id": y3.distinct_id, "role": 15},
]
@patch("posthoganalytics.capture")
def test_update_org_details_recomputes_existing_quota_limits(self, patch_capture):
organization = self.organization
organization.usage = {
"events": {
"usage": 90,
"limit": 1000,
"todays_usage": 10,
"quota_limited_until": 1612137599,
},
"exceptions": {
"usage": 10,
"limit": 100,
"todays_usage": 5,
"quota_limiting_suspended_until": 1611705600,
},
"recordings": {
"usage": 15,
"limit": 100,
"todays_usage": 5,
"quota_limiting_suspended_until": 1611705600,
},
"rows_synced": {"usage": 45, "limit": 500, "todays_usage": 5},
"rows_exported": {"usage": 10, "limit": 1000, "todays_usage": 5},
"feature_flag_requests": {"usage": 25, "limit": 300, "todays_usage": 5},
"api_queries_read_bytes": {"usage": 1000, "limit": 1000000, "todays_usage": 500},
"llm_events": {"usage": 50, "limit": 1000, "todays_usage": 2},
"ai_credits": {"usage": 1200, "limit": 20000, "todays_usage": 150},
"signals_credits": {},
"replay_vision_credits": {},
"cdp_trigger_events": {"usage": 10, "limit": 100, "todays_usage": 5},
"workflow_emails": {"usage": 100, "limit": 10000, "todays_usage": 10},
"workflow_destinations_dispatched": {"usage": 50, "limit": 10000, "todays_usage": 5},
"logs_mb_ingested": {"usage": 5500, "limit": 50000, "todays_usage": 500},
"period": ["2024-01-01T00:00:00Z", "2024-01-31T23:59:59Z"],
"survey_responses": {
"usage": 10,
"limit": 100,
"todays_usage": 5,
"quota_limiting_suspended_until": 1611705600,
},
}
organization.save()
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
billing_status = {
"customer": {
"usage_summary": {
"events": {"usage": 90, "limit": 1000},
"exceptions": {"usage": 10, "limit": 100},
"recordings": {"usage": 15, "limit": 100},
"rows_synced": {"usage": 45, "limit": 500},
"rows_exported": {"usage": 10, "limit": 1000},
"feature_flag_requests": {"usage": 25, "limit": 300},
"api_queries_read_bytes": {"usage": 1000, "limit": 1000000},
"llm_events": {"usage": 50, "limit": 1000},
"mcp_events": {"usage": 30, "limit": 500},
"ai_credits": {"usage": 1200, "limit": 20000, "todays_usage": 150},
"survey_responses": {"usage": 10, "limit": 100},
"cdp_trigger_events": {"usage": 10, "limit": 100},
"workflow_emails": {"usage": 100, "limit": 10000},
"workflow_destinations_dispatched": {"usage": 50, "limit": 10000},
"logs_mb_ingested": {"usage": 5500, "limit": 50000},
},
"billing_period": {
"current_period_start": "2024-01-01T00:00:00Z",
"current_period_end": "2024-01-31T23:59:59Z",
},
}
}
BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))
organization.refresh_from_db()
assert organization.usage == {
"events": {
"usage": 90,
"limit": 1000,
"todays_usage": 10,
},
"exceptions": {
"usage": 10,
"limit": 100,
"todays_usage": 5,
},
"recordings": {
"usage": 15,
"limit": 100,
"todays_usage": 5,
},
"rows_synced": {"usage": 45, "limit": 500, "todays_usage": 5},
"rows_exported": {"usage": 10, "limit": 1000, "todays_usage": 5},
"feature_flag_requests": {"usage": 25, "limit": 300, "todays_usage": 5},
"llm_events": {"usage": 50, "limit": 1000, "todays_usage": 2},
"mcp_events": {"usage": 30, "limit": 500, "todays_usage": 0},
"ai_credits": {"usage": 1200, "limit": 20000, "todays_usage": 150},
"signals_credits": {},
"signals_spend_credits": {},
"replay_vision_credits": {},
"posthog_code_credits": {},
"workflow_emails": {"usage": 100, "limit": 10000, "todays_usage": 10},
"workflow_push": {},
"workflow_destinations_dispatched": {"usage": 50, "limit": 10000, "todays_usage": 5},
"logs_mb_ingested": {"usage": 5500, "limit": 50000, "todays_usage": 500},
"period": ["2024-01-01T00:00:00Z", "2024-01-31T23:59:59Z"],
"api_queries_read_bytes": {"usage": 1000, "limit": 1000000, "todays_usage": 500},
"cdp_trigger_events": {"usage": 10, "limit": 100, "todays_usage": 5},
"survey_responses": {
"usage": 10,
"limit": 100,
"todays_usage": 5,
},
}
@patch("posthoganalytics.capture")
def test_update_org_details_applies_never_drop_data_before_recomputing_existing_quota_limits(self, patch_capture):
organization = self.organization
organization.usage = {
"events": {
"usage": 1_000,
"limit": 100,
"todays_usage": 0,
"quota_limited_until": 1612137599,
},
"recordings": {"usage": 0, "limit": 100, "todays_usage": 0},
"period": ["2024-01-01T00:00:00Z", "2024-01-31T23:59:59Z"],
}
organization.never_drop_data = False
organization.save()
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
billing_status = {
"customer": {
"usage_summary": {
"events": {"usage": 1_000, "limit": 100},
"recordings": {"usage": 0, "limit": 100},
},
"billing_period": {
"current_period_start": "2024-01-01T00:00:00Z",
"current_period_end": "2024-01-31T23:59:59Z",
},
"never_drop_data": True,
}
}
BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))
organization.refresh_from_db()
assert organization.never_drop_data is True
assert organization.usage["events"].get("quota_limited_until") is None
assert organization.usage["events"].get("quota_limiting_suspended_until") is None
def test_update_org_details_resets_logs_retention_when_entitlement_revoked(self):
organization = self.organization
organization.available_product_features = [{"key": "logs_retention_30d", "name": "30-day logs retention"}]
organization.save()
self.team.logs_settings = {"retention_days": 30, "json_parse_logs": True}
self.team.save()
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
billing_status = {"customer": {"available_product_features": [{"key": "surveys", "name": "Surveys"}]}}
BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))
self.team.refresh_from_db()
# Retention drops to the default; unrelated Logs settings survive.
assert self.team.logs_settings == {"retention_days": 14, "json_parse_logs": True}
def test_update_org_details_keeps_logs_retention_while_entitled(self):
organization = self.organization
organization.available_product_features = [{"key": "logs_retention_30d", "name": "30-day logs retention"}]
organization.save()
self.team.logs_settings = {"retention_days": 30}
self.team.save()
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
billing_status = {
"customer": {
"available_product_features": [
{"key": "logs_retention_30d", "name": "30-day logs retention"},
{"key": "surveys", "name": "Surveys"},
]
}
}
BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))
self.team.refresh_from_db()
assert self.team.logs_settings == {"retention_days": 30}
def test_update_org_details_ignores_empty_feature_list(self):
"""A partial or error-path billing response must not downgrade the org or reset retention."""
organization = self.organization
organization.available_product_features = [{"key": "logs_retention_30d", "name": "30-day logs retention"}]
organization.save()
self.team.logs_settings = {"retention_days": 30}
self.team.save()
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
billing_status: dict[str, Any] = {"customer": {"available_product_features": []}}
BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))
organization.refresh_from_db()
self.team.refresh_from_db()
assert organization.available_product_features == [
{"key": "logs_retention_30d", "name": "30-day logs retention"}
]
assert self.team.logs_settings == {"retention_days": 30}
@patch("ee.billing.billing_manager.http_session.get")
def test_update_available_product_features_resets_revoked_logs_retention(self, mock_get: MagicMock):
organization = self.organization
organization.available_product_features = [{"key": "logs_retention_30d", "name": "30-day logs retention"}]
organization.save()
self.team.logs_settings = {"retention_days": 30}
self.team.save()
rule = LogsRetentionRule.objects.create(
team=self.team,
name="keep api logs",
enabled=True,
config={"retention_days": 90, "filter_group": {"type": "AND", "values": []}},
)
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
# A cancellation lands the customer on free plans, which still carry (other) features.
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {
"available_product_features": [{"key": "surveys", "name": "Surveys"}]
}
BillingManager(license).update_available_product_features(organization)
organization.refresh_from_db()
self.team.refresh_from_db()
assert organization.available_product_features == [{"key": "surveys", "name": "Surveys"}]
assert self.team.logs_settings == {"retention_days": 14}
rule.refresh_from_db()
assert rule.config == {"retention_days": 14, "filter_group": {"type": "AND", "values": []}}
assert rule.enabled is True
assert rule.version == 2
@patch("ee.billing.billing_manager.http_session.get")
def test_update_available_product_features_reconciles_events_retention(self, mock_get: MagicMock):
organization = self.organization
Team.objects.filter(pk=self.team.pk).update(event_retention_months=84)
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = {
"available_product_features": [
{"key": "product_analytics_data_retention", "name": "Data retention", "limit": 1, "unit": "year"}
]
}
BillingManager(license).update_available_product_features(organization)
self.team.refresh_from_db()
assert self.team.event_retention_months == 12
@patch("ee.billing.billing_manager.update_org_billing_quotas", side_effect=Exception("Redis unavailable"))
def test_update_org_details_saves_org_fields_before_recomputing_existing_quota_limits(
self, update_org_billing_quotas_mock: MagicMock
):
organization = self.organization
organization.usage = {
"events": {
"usage": 1_000,
"limit": 100,
"todays_usage": 0,
"quota_limited_until": 1612137599,
},
"recordings": {"usage": 0, "limit": 100, "todays_usage": 0},
"period": ["2024-01-01T00:00:00Z", "2024-01-31T23:59:59Z"],
}
organization.never_drop_data = False
organization.save()
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
billing_status = {
"customer": {
"usage_summary": {
"events": {"usage": 1_000, "limit": 100},
"recordings": {"usage": 0, "limit": 100},
},
"billing_period": {
"current_period_start": "2024-01-01T00:00:00Z",
"current_period_end": "2024-01-31T23:59:59Z",
},
"never_drop_data": True,
}
}
with self.assertRaises(Exception) as context:
BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))
assert str(context.exception) == "Redis unavailable"
update_org_billing_quotas_mock.assert_called_once_with(organization)
organization.refresh_from_db()
assert organization.never_drop_data is True
@patch("ee.billing.billing_manager.BillingManager.get_default_products")
def test_update_org_details_skips_default_products_without_customer_trust_scores(
self, get_default_products_mock: MagicMock
):
organization = self.organization
organization.never_drop_data = False
organization.customer_trust_scores = {"events": 7}
organization.save()
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
billing_status = {
"customer": {
"never_drop_data": False,
"customer_trust_scores": {},
}
}
BillingManager(license).update_org_details(organization, cast(BillingStatus, billing_status))
get_default_products_mock.assert_not_called()
organization.refresh_from_db()
assert organization.customer_trust_scores == {"events": 7}
@patch(
"ee.billing.billing_manager.http_session.post",
return_value=MagicMock(status_code=200, json=MagicMock(return_value={"success": True})),
)
def test_deauthorize_calls_billing_service(self, billing_post_request_mock: MagicMock):
"""Deauthorize should call the billing service uninstall endpoint."""
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
result = BillingManager(license).deauthorize(self.organization, BillingProvider.VERCEL)
assert result == {"success": True}
billing_post_request_mock.assert_called_once()
call_args = billing_post_request_mock.call_args
assert call_args[0][0].endswith("/api/activate/authorize/uninstall")
assert call_args[1]["json"] == {"billing_provider": "vercel"}
assert "Authorization" in call_args[1]["headers"]
@patch(
"ee.billing.billing_manager.http_session.post",
return_value=MagicMock(
status_code=400,
json=MagicMock(return_value={"error": "Customer billing provider mismatch"}),
ok=False,
),
)
def test_deauthorize_handles_billing_service_error(self, billing_post_request_mock: MagicMock):
"""Deauthorize should raise an exception when billing service returns an error."""
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
with self.assertRaises(Exception) as context:
BillingManager(license).deauthorize(self.organization, BillingProvider.VERCEL)
assert "400" in str(context.exception)
@patch(
"ee.billing.billing_manager.http_session.post",
return_value=MagicMock(
status_code=404,
json=MagicMock(return_value={"detail": "Not found."}),
ok=False,
),
)
def test_deauthorize_raises_on_404(self, billing_post_request_mock: MagicMock):
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
with self.assertRaises(Exception) as context:
BillingManager(license).deauthorize(self.organization, BillingProvider.VERCEL)
assert "404" in str(context.exception)
@patch(
"ee.billing.billing_manager.http_session.post",
return_value=MagicMock(
status_code=409,
json=MagicMock(
return_value={
"success": False,
"error_message": "Cannot uninstall billing provider: 1 unpaid invoice must be resolved first.",
"code": "open_invoices_error",
}
),
ok=False,
),
)
def test_deauthorize_raises_open_invoices_error_on_409(self, billing_post_request_mock: MagicMock):
from ee.billing.billing_manager import BillingServiceOpenInvoicesError
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
with self.assertRaises(BillingServiceOpenInvoicesError) as context:
BillingManager(license).deauthorize(self.organization, BillingProvider.VERCEL)
assert "unpaid invoice" in str(context.exception)
@patch(
"ee.billing.billing_manager.http_session.post",
return_value=MagicMock(
status_code=409,
json=MagicMock(side_effect=requests.JSONDecodeError("", "", 0)),
text="Not JSON",
ok=False,
),
)
def test_deauthorize_409_no_json_falls_through_to_generic_error(self, billing_post_request_mock: MagicMock):
from ee.billing.billing_manager import BillingServiceOpenInvoicesError
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
with self.assertRaises(Exception) as context:
BillingManager(license).deauthorize(self.organization, BillingProvider.VERCEL)
assert not isinstance(context.exception, BillingServiceOpenInvoicesError)
assert "409" in str(context.exception)
@patch(
"ee.billing.billing_manager.http_session.post",
return_value=MagicMock(
status_code=409,
json=MagicMock(return_value={"code": "some_other_error", "error_message": "Something else"}),
text='{"code": "some_other_error"}',
ok=False,
),
)
def test_deauthorize_409_different_code_falls_through_to_generic_error(self, billing_post_request_mock: MagicMock):
from ee.billing.billing_manager import BillingServiceOpenInvoicesError
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
with self.assertRaises(Exception) as context:
BillingManager(license).deauthorize(self.organization, BillingProvider.VERCEL)
assert not isinstance(context.exception, BillingServiceOpenInvoicesError)
assert "409" in str(context.exception)
@patch(
"ee.billing.billing_manager.http_session.post",
return_value=MagicMock(
status_code=409,
json=MagicMock(return_value={"code": "open_invoices_error"}),
ok=False,
),
)
def test_deauthorize_409_open_invoices_missing_message_uses_default(self, billing_post_request_mock: MagicMock):
from ee.billing.billing_manager import BillingServiceOpenInvoicesError
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
with self.assertRaises(BillingServiceOpenInvoicesError) as context:
BillingManager(license).deauthorize(self.organization, BillingProvider.VERCEL)
assert "Open invoices must be resolved first" in str(context.exception)
def test_update_org_details_persists_has_active_subscription(self):
organization = self.organization
billing_status = {
"customer": {
"has_active_subscription": False,
"usage_summary": {
"events": {"usage": 1000, "limit": None},
"recordings": {"usage": 0, "limit": None},
},
"billing_period": {
"current_period_start": "2026-08-01T00:00:00Z",
"current_period_end": "2026-09-01T00:00:00Z",
},
}
}
BillingManager(license=None).update_org_details(organization, cast(BillingStatus, billing_status))
organization.refresh_from_db()
assert organization.has_active_subscription is False
def test_update_org_details_missing_key_keeps_existing_has_active_subscription(self):
organization = self.organization
organization.has_active_subscription = False
organization.save()
billing_status = {
"customer": {
"usage_summary": {
"events": {"usage": 1000, "limit": None},
"recordings": {"usage": 0, "limit": None},
},
"billing_period": {
"current_period_start": "2026-08-01T00:00:00Z",
"current_period_end": "2026-09-01T00:00:00Z",
},
}
}
BillingManager(license=None).update_org_details(organization, cast(BillingStatus, billing_status))
organization.refresh_from_db()
assert organization.has_active_subscription is False
@parameterized.expand(
[
("downgrade", True, False),
("upgrade", False, True),
]
)
def test_update_org_details_syncs_has_active_subscription_transition(self, _name, before, after):
organization = self.organization
organization.has_active_subscription = before
organization.save()
billing_status = {
"customer": {
"has_active_subscription": after,
"usage_summary": {
"events": {"usage": 1000, "limit": None},
"recordings": {"usage": 0, "limit": None},
},
"billing_period": {
"current_period_start": "2026-08-01T00:00:00Z",
"current_period_end": "2026-09-01T00:00:00Z",
},
}
}
BillingManager(license=None).update_org_details(organization, cast(BillingStatus, billing_status))
organization.refresh_from_db()
assert organization.has_active_subscription is after
@parameterized.expand(
[
("active_trial_counts_as_paid", "2027-01-01T00:00:00Z", True),
("expired_trial_counts_as_free", "2026-01-01T00:00:00Z", False),
("naive_timestamp_treated_as_utc", "2027-01-01T00:00:00", True),
]
)
def test_update_org_details_trial_handling(self, _name, free_trial_until, expected):
organization = self.organization
billing_status = {
"customer": {
"has_active_subscription": False,
"free_trial_until": free_trial_until,
"usage_summary": {
"events": {"usage": 1000, "limit": None},
"recordings": {"usage": 0, "limit": None},
},
"billing_period": {
"current_period_start": "2026-08-01T00:00:00Z",
"current_period_end": "2026-09-01T00:00:00Z",
},
}
}
with time_machine.travel("2026-08-13", tick=False):
BillingManager(license=None).update_org_details(organization, cast(BillingStatus, billing_status))
organization.refresh_from_db()
assert organization.has_active_subscription is expected
def _billing_status(
self,
computed_at: str | None,
events_usage: int,
*,
events_limit: int | None = None,
latest_usage_report_date: str = "2026-08-02",
) -> BillingStatus:
billing_status: dict[str, Any] = {
"customer": {
"usage_summary": {
"events": {"usage": events_usage, "limit": events_limit},
"recordings": {"usage": 0, "limit": None},
},
"billing_period": {
"current_period_start": "2026-08-01T00:00:00Z",
"current_period_end": "2026-09-01T00:00:00Z",
},
}
}
if computed_at:
billing_status["computed_at"] = computed_at
billing_status["latest_usage_report_date"] = latest_usage_report_date
return cast(BillingStatus, billing_status)
@time_machine.travel("2026-08-03T04:00:00Z", tick=False)
def test_status_after_a_report_keeps_todays_count_in_the_quota_check(self):
self.organization.usage = {
"events": {
"usage": 500,
"limit": 1000,
"todays_usage": 400,
"daily_usage": {"2026-08-02": 200, "2026-08-03": 400},
},
"recordings": {"usage": 0, "limit": None, "todays_usage": 0},
"period": ["2026-08-01T00:00:00Z", "2026-09-01T00:00:00Z"],
"billing_status_computed_at": "2026-08-02T04:00:00+00:00",
"billing_latest_usage_report_date": "2026-08-01",
}
self.organization.save()
# Billing's total now includes 2026-08-02, but not today.
BillingManager(license=None).update_org_details(
self.organization,
self._billing_status("2026-08-03T04:00:00Z", events_usage=700, events_limit=1000),
)
assert self.team.api_token in list_limited_team_attributes(
QuotaResource.EVENTS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY
)
@parameterized.expand(
[
("newer_status_applies", "2026-08-03T00:00:00Z", 1000, "2026-08-03T00:00:00+00:00", "2026-08-02"),
("redelivered_status_applies", "2026-08-02T00:00:00Z", 1000, "2026-08-02T00:00:00+00:00", "2026-08-02"),
("older_status_is_skipped", "2026-08-01T00:00:00Z", 500, "2026-08-02T00:00:00+00:00", None),
("status_without_stamp_applies_and_drops_the_stamps", None, 1000, None, None),
]
)
def test_update_org_details_skips_a_status_older_than_the_last_applied(
self, _name, status_computed_at, expected_events_usage, expected_computed_at, expected_report_date
):
organization = self.organization
organization.usage = {
"events": {"usage": 500, "limit": None, "todays_usage": 0},
"recordings": {"usage": 0, "limit": None, "todays_usage": 0},
"period": ["2026-08-01T00:00:00Z", "2026-09-01T00:00:00Z"],
"billing_status_computed_at": "2026-08-02T00:00:00+00:00",
}
organization.save()
BillingManager(license=None).update_org_details(
organization, self._billing_status(status_computed_at, events_usage=1000)
)
organization.refresh_from_db()
assert organization.usage is not None
assert organization.usage["events"]["usage"] == expected_events_usage
assert organization.usage.get("billing_status_computed_at") == expected_computed_at
assert organization.usage.get("billing_latest_usage_report_date") == expected_report_date
def test_update_org_details_writes_nothing_for_a_status_that_changes_only_the_stamp(self):
manager = BillingManager(license=None)
manager.update_org_details(self.organization, self._billing_status("2026-08-02T00:00:00Z", events_usage=1000))
assert self.organization.usage is not None
usage_written_by_quota_run = copy.deepcopy(self.organization.usage)
usage_written_by_quota_run["events"]["todays_usage"] = 25
Organization.objects.filter(id=self.organization.id).update(usage=usage_written_by_quota_run)
with patch("ee.billing.billing_manager.update_org_billing_quotas") as update_org_billing_quotas:
manager.update_org_details(
self.organization, self._billing_status("2026-08-03T00:00:00Z", events_usage=1000)
)
update_org_billing_quotas.assert_not_called()
self.organization.refresh_from_db()
assert self.organization.usage is not None
assert self.organization.usage["events"]["todays_usage"] == 25
@parameterized.expand(
[
("activate_trial", {"type": "autosubscribe", "target": "boost"}, 6, None),
("cancel_trial", {}, None, 6),
("switch_plan", {"from_product_key": "boost", "to_product_key": "scale"}, 6, None),
]
)
@patch("ee.billing.billing_manager.http_session.get")
@patch("ee.billing.billing_manager.http_session.post")
def test_plan_change_skips_a_status_queued_before_it(
self,
manager_method: str,
data: dict[str, Any],
limit_before: int | None,
limit_after: int | None,
mock_post: MagicMock,
mock_get: MagicMock,
):
license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
def features(projects_limit: int | None) -> list[dict[str, Any]]:
return [{"key": "organizations_projects", "name": "Projects", "limit": projects_limit}]
def status(computed_at: str, projects_limit: int | None) -> BillingStatus:
billing_status = cast(dict[str, Any], self._billing_status(computed_at, events_usage=500))
billing_status["customer"]["available_product_features"] = features(projects_limit)
return cast(BillingStatus, billing_status)
organization = self.organization
organization.usage = {
"events": {"usage": 500, "limit": None, "todays_usage": 0},
"recordings": {"usage": 0, "limit": None, "todays_usage": 0},
"period": ["2026-08-01T00:00:00Z", "2026-09-01T00:00:00Z"],
}
organization.available_product_features = features(limit_before)
organization.save()
mock_post.return_value.status_code = 200
mock_post.return_value.json.return_value = {}
mock_get.return_value.status_code = 200
mock_get.return_value.json.return_value = status("2026-08-03T00:00:00Z", projects_limit=limit_after)
manager = BillingManager(license)
getattr(manager, manager_method)(organization, data)
manager.update_org_details(organization, status("2026-08-02T00:00:00Z", projects_limit=limit_before))
organization.refresh_from_db()
assert organization.available_product_features == features(limit_after)
assert organization.usage is not None
assert organization.usage["billing_status_computed_at"] == "2026-08-03T00:00:00+00:00"
class TestBillingSession(SimpleTestCase):
def test_the_session_keeps_no_cookies(self):
# Every call to billing is server-to-server and carries a bearer token for one
# organization. A cookie set on one response must not ride along on the next request,
# which would be another organization's.
self.addCleanup(http_session.cookies.clear)
headers = Message()
headers["Set-Cookie"] = "sessionid=abc123; Path=/"
response = SimpleNamespace(info=lambda: headers)
http_session.cookies.extract_cookies(
cast(Any, response), UrllibRequest("https://billing.example/api/v2/billing/subscription/")
)
self.assertEqual(len(http_session.cookies), 0)
def _response(status_code: int, headers: dict[str, str] | None = None, body: Any = None) -> requests.Response:
response = requests.Response()
response.status_code = status_code
response.headers.update(headers or {})
response._content = b"" if body is None else json.dumps(body).encode()
response.raw = MagicMock()
return response
class TestHandleBillingServiceError(SimpleTestCase):
def test_handle_billing_service_error_raises_rate_limited_on_429(self):
res = _response(429, headers={"Retry-After": "30"}, body={"detail": "x"})
with self.assertRaises(BillingServiceRateLimited) as context:
handle_billing_service_error(res)
assert context.exception.status_code == 429
assert context.exception.wait == 30
assert context.exception.args == ()
def test_rate_limited_response_is_closed(self):
res = _response(429, headers={"Retry-After": "30"})
with patch.object(res, "close", wraps=res.close) as close, self.assertRaises(BillingServiceRateLimited):
handle_billing_service_error(res)
close.assert_called_once()
@parameterized.expand(
[
("missing", {}),
("not_a_number", {"Retry-After": "soon"}),
("nan", {"Retry-After": "nan"}),
("negative", {"Retry-After": "-5"}),
]
)
def test_rate_limited_without_retry_after_has_no_wait(self, _name, headers):
with self.assertRaises(BillingServiceRateLimited) as context:
handle_billing_service_error(_response(429, headers=headers))
assert context.exception.wait is None
def test_other_bad_statuses_still_raise_response_error(self):
res = _response(500, body={"detail": "boom"})
with self.assertRaises(BillingServiceResponseError) as context:
handle_billing_service_error(res)
assert context.exception.status_code == 500
assert context.exception.body == {"detail": "boom"}
class TestBillingProviderWebhookSigning(SimpleTestCase):
def setUp(self):
self.license = SimpleNamespace(key="license_id::license_secret")
self.organization = cast(Organization, SimpleNamespace(id="org_123", name="Test Org"))
self.enterContext(patch("ee.billing.billing_manager.get_billing_lock_partner", return_value=None))
@override_settings(BILLING_PROVIDER_WEBHOOK_SECRET="test_webhook_secret")
@patch("ee.billing.billing_manager.time.time", return_value=1700000000)
@patch(
"ee.billing.billing_manager.http_session.post",
return_value=MagicMock(status_code=200, ok=True, text="", json=MagicMock(return_value={"status": "ok"})),
)
def test_handle_billing_provider_webhook_signs_forwarded_body(
self, billing_post_request_mock: MagicMock, mock_time: MagicMock
):
BillingManager(self.license).handle_billing_provider_webhook(
event_type="marketplace.invoice.paid",
event_data={"installationId": "icfg_123", "invoiceId": "mi_123"},
organization=self.organization,
billing_provider="vercel",
)
billing_post_request_mock.assert_called_once()
call_kwargs = billing_post_request_mock.call_args.kwargs
body = call_kwargs["data"]
expected_body = (
b'{"event_type":"marketplace.invoice.paid",'
b'"event_data":{"installationId":"icfg_123","invoiceId":"mi_123"},'
b'"billing_provider":"vercel"}'
)
expected_signature = hmac.new(
b"test_webhook_secret",
b"1700000000." + expected_body,
hashlib.sha256,
).hexdigest()
assert body == expected_body
assert call_kwargs["headers"][BILLING_PROVIDER_WEBHOOK_TIMESTAMP_HEADER] == "1700000000"
assert (
call_kwargs["headers"][BILLING_PROVIDER_WEBHOOK_SIGNATURE_HEADER]
== f"{BILLING_PROVIDER_WEBHOOK_SIGNATURE_VERSION}={expected_signature}"
)
assert call_kwargs["headers"]["Content-Type"] == "application/json"
assert "Authorization" in call_kwargs["headers"]
@override_settings(BILLING_PROVIDER_WEBHOOK_SECRET="")
@patch("ee.billing.billing_manager.http_session.post")
def test_handle_billing_provider_webhook_requires_signature_secret(self, billing_post_request_mock: MagicMock):
with self.assertRaises(ValueError) as context:
BillingManager(self.license).handle_billing_provider_webhook(
event_type="marketplace.invoice.paid",
event_data={"installationId": "icfg_123", "invoiceId": "mi_123"},
organization=self.organization,
billing_provider="vercel",
)
assert "BILLING_PROVIDER_WEBHOOK_SECRET" in str(context.exception)
billing_post_request_mock.assert_not_called()
@parameterized.expand(
[
("nan", math.nan),
("infinity", math.inf),
("negative_infinity", -math.inf),
]
)
@override_settings(BILLING_PROVIDER_WEBHOOK_SECRET="test_webhook_secret")
@patch("ee.billing.billing_manager.http_session.post")
def test_handle_billing_provider_webhook_rejects_non_finite_numbers(
self, _name: str, non_finite_number: float, billing_post_request_mock: MagicMock
):
with self.assertRaises(ValueError) as context:
BillingManager(self.license).handle_billing_provider_webhook(
event_type="marketplace.invoice.paid",
event_data={"installationId": "icfg_123", "amount": non_finite_number},
organization=self.organization,
billing_provider="vercel",
)
assert "Out of range float values are not JSON compliant" in str(context.exception)
billing_post_request_mock.assert_not_called()
class TestBuildBillingToken(BaseTest):
def setUp(self):
super().setUp()
self.license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="license_id::license_secret",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
def test_build_billing_token_without_user(self):
"""Token without user should have basic organization info only"""
token = build_billing_token(self.license, self.organization)
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
assert decoded["id"] == "license_id"
assert decoded["organization_id"] == str(self.organization.id)
assert decoded["organization_name"] == self.organization.name
assert decoded["aud"] == "posthog:license-key"
assert "distinct_id" not in decoded
assert "email" not in decoded
assert "organization_role" not in decoded
assert "original_role" not in decoded
# Only service-to-service tokens carry service_action; billing uses its absence
# to reject user-minted tokens on service-only endpoints.
assert "service_action" not in decoded
def test_build_billing_token_with_service_action(self):
token = build_billing_token(self.license, self.organization, service_action="signals_pr_dispute")
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
assert decoded["service_action"] == "signals_pr_dispute"
assert "distinct_id" not in decoded
assert "email" not in decoded
assert "organization_role" not in decoded
@parameterized.expand([("paying_partner", True), ("no_partner", False)])
@patch("ee.billing.billing_manager.get_billing_lock_partner")
def test_build_billing_token_payer_partner_claim(
self, _name: str, has_partner: bool, mock_partner: MagicMock
) -> None:
application = (
OAuthApplication.objects.create(
client_id="example-partner",
name="Example Partner",
client_secret="",
client_type=OAuthApplication.CLIENT_PUBLIC,
authorization_grant_type=OAuthApplication.GRANT_AUTHORIZATION_CODE,
redirect_uris="https://partner.example.com/callback",
algorithm="RS256",
is_provisioning_partner=True,
)
if has_partner
else None
)
mock_partner.return_value = application
token = build_billing_token(self.license, self.organization)
mock_partner.assert_called_once_with(self.organization)
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
if application is not None:
assert decoded["payer_partner_id"] == str(application.id)
else:
assert "payer_partner_id" not in decoded
def test_build_billing_token_with_user_who_is_member(self):
"""Token with user should include distinct_id and organization_role as level display string"""
token = build_billing_token(self.license, self.organization, user=self.user)
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
assert decoded["id"] == "license_id"
assert decoded["organization_id"] == str(self.organization.id)
assert decoded["distinct_id"] == str(self.user.distinct_id)
assert decoded["email"] == self.user.email
# organization_role should be a level display string (e.g., "member", "administrator", "owner")
assert decoded["organization_role"] in ["member", "administrator", "owner"]
assert "original_role" not in decoded
def test_build_billing_token_raises_when_no_organization(self):
"""Should raise NotAuthenticated when organization is None"""
with self.assertRaises(NotAuthenticated):
build_billing_token(self.license, None)
def test_build_billing_token_raises_when_no_license(self):
"""Should raise NotAuthenticated when license is None"""
with self.assertRaises(NotAuthenticated):
build_billing_token(None, self.organization)
def test_build_billing_token_raises_when_user_not_in_organization(self):
"""Should raise NotAuthenticated when user (acting as authorizer) is not a member of the organization"""
other_org = Organization.objects.create(name="Other Org")
non_member_user = User.objects.create_and_join(
organization=other_org,
email="[email protected]",
password=None,
)
with self.assertRaises(NotAuthenticated) as ctx:
build_billing_token(self.license, self.organization, user=non_member_user)
# When user is provided without authorizer_actor, user becomes the authorizer
assert "Authorizer is not part of organization" in str(ctx.exception.detail)
@patch("posthog.event_usage.posthoganalytics.capture")
def test_build_billing_token_with_authorizer_actor_same_as_user(self, mock_capture):
"""When authorizer_actor equals user, no privilege escalation occurs"""
token = build_billing_token(self.license, self.organization, user=self.user, authorizer_actor=self.user)
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
assert decoded["distinct_id"] == str(self.user.distinct_id)
assert decoded["organization_role"] in ["member", "administrator", "owner"]
assert "original_role" not in decoded
mock_capture.assert_not_called()
@patch("posthog.event_usage.posthoganalytics.capture")
def test_build_billing_token_with_privilege_escalation(self, mock_capture):
"""When authorizer_actor differs from user, original_role is set and capture is called"""
member_user = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.MEMBER,
)
admin_authorizer = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.ADMIN,
)
token = build_billing_token(
self.license, self.organization, user=member_user, authorizer_actor=admin_authorizer
)
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
assert decoded["distinct_id"] == str(member_user.distinct_id)
# organization_role should be the authorizer's role (administrator)
assert decoded["organization_role"] == "administrator"
# original_role should be the user's actual role (member)
assert decoded["original_role"] == "member"
mock_capture.assert_called_once()
call_kwargs = mock_capture.call_args[1]
assert call_kwargs["event"] == "$billing_privilege_escalation"
assert call_kwargs["distinct_id"] == str(admin_authorizer.distinct_id)
assert call_kwargs["properties"]["target_user_id"] == member_user.id
assert call_kwargs["properties"]["target_distinct_id"] == str(member_user.distinct_id)
assert call_kwargs["properties"]["target_email"] == member_user.email
assert call_kwargs["properties"]["action"] == "update_billing"
def test_build_billing_token_raises_when_authorizer_actor_not_in_organization(self):
"""Should raise NotAuthenticated when authorizer_actor is not a member of the organization"""
other_org = Organization.objects.create(name="Other Org")
non_member_authorizer = User.objects.create_and_join(
organization=other_org,
email="[email protected]",
password=None,
)
with self.assertRaises(NotAuthenticated) as ctx:
build_billing_token(self.license, self.organization, user=self.user, authorizer_actor=non_member_authorizer)
assert "Authorizer is not part of organization" in str(ctx.exception.detail)
@patch("posthog.event_usage.posthoganalytics.capture")
def test_build_billing_token_privilege_escalation_user_not_member_allowed(self, mock_capture):
"""When authorizer_actor is valid but user is not a member, original_role should be None"""
other_org = Organization.objects.create(name="Other Org")
non_member_user = User.objects.create_and_join(
organization=other_org,
email="[email protected]",
password=None,
)
valid_authorizer = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.ADMIN,
)
token = build_billing_token(
self.license, self.organization, user=non_member_user, authorizer_actor=valid_authorizer
)
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
# Token should have non-member user's distinct_id
assert decoded["distinct_id"] == str(non_member_user.distinct_id)
# organization_role should be the authorizer's role
assert decoded["organization_role"] == "administrator"
# original_role should be None since user is not a member
assert decoded["original_role"] is None
# Privilege escalation capture should still be called
mock_capture.assert_called_once()
call_kwargs = mock_capture.call_args[1]
assert call_kwargs["event"] == "$billing_privilege_escalation"
assert call_kwargs["distinct_id"] == str(valid_authorizer.distinct_id)
assert call_kwargs["properties"]["target_user_id"] == non_member_user.id
assert call_kwargs["properties"]["target_distinct_id"] == str(non_member_user.distinct_id)
assert call_kwargs["properties"]["target_email"] == non_member_user.email
@parameterized.expand(
[
(OrganizationMembership.Level.MEMBER, "member"),
(OrganizationMembership.Level.ADMIN, "administrator"),
(OrganizationMembership.Level.OWNER, "owner"),
]
)
def test_build_billing_token_user_role_populated_for_all_levels(self, level, expected_role_display):
"""organization_role should be the correct level display string for each membership level"""
user_with_level = User.objects.create_and_join(
organization=self.organization,
email=f"user_level_{level}@example.com",
password=None,
level=level,
)
token = build_billing_token(self.license, self.organization, user=user_with_level)
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
assert decoded["organization_role"] == expected_role_display
def test_build_billing_token_without_user_but_with_authorizer_actor(self):
"""When user is None but authorizer_actor is provided, authorizer_actor should be ignored"""
admin_user = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.ADMIN,
)
token = build_billing_token(self.license, self.organization, user=None, authorizer_actor=admin_user)
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
# Without user, no user-related fields should be in the token
assert "distinct_id" not in decoded
assert "organization_role" not in decoded
assert "original_role" not in decoded
class TestGetUserOrganizationRole(BaseTest):
def test_returns_role_display_for_valid_member(self):
"""Should return the role display string for a user who is a member"""
role_display = _get_user_organization_role(self.user, self.organization)
# Should be a valid role display string
assert role_display in ["member", "administrator", "owner"]
@parameterized.expand(
[
(OrganizationMembership.Level.MEMBER, "member"),
(OrganizationMembership.Level.ADMIN, "administrator"),
(OrganizationMembership.Level.OWNER, "owner"),
]
)
def test_returns_correct_role_display_for_each_level(self, level, expected_display):
"""Should return the correct display string for each membership level"""
user_with_level = User.objects.create_and_join(
organization=self.organization,
email=f"user_level_{level}[email protected]",
password=None,
level=level,
)
role_display = _get_user_organization_role(user_with_level, self.organization)
assert role_display == expected_display
def test_returns_none_for_non_member(self):
"""Should return None for a user who is not a member"""
other_org = Organization.objects.create(name="Other Org")
non_member = User.objects.create_and_join(
organization=other_org,
email="[email protected]",
password=None,
)
role_display = _get_user_organization_role(non_member, self.organization)
assert role_display is None
class TestUpdateBillingOrganizationUsersPrivilegeEscalation(BaseTest):
"""Tests for update_billing_organization_users privilege escalation behavior"""
def setUp(self):
super().setUp()
self.license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="license_id::license_secret",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
@patch("ee.billing.billing_manager.http_session.patch")
@patch("posthog.event_usage.posthoganalytics.capture")
def test_update_billing_org_users_uses_owner_as_authorizer_actor(self, mock_capture, mock_patch):
"""
When BillingManager is initialized with a non-owner user but calls update_billing_organization_users,
the billing token should use the owner's role (privilege escalation) and capture the event.
"""
mock_patch.return_value = MagicMock(status_code=200, json=MagicMock(return_value={"text": "ok"}))
# Create an owner for the organization
owner = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
# Create a regular member - this will be the user in BillingManager
member = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.MEMBER,
)
# BillingManager is initialized with the member user
billing_manager = BillingManager(self.license, user=member)
billing_manager.update_billing_organization_users(self.organization)
# Verify the PATCH request was made
mock_patch.assert_called_once()
# Extract the Authorization header and decode the JWT
call_kwargs = mock_patch.call_args
auth_header = call_kwargs[1]["headers"]["Authorization"]
token = auth_header.replace("Bearer ", "")
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
# Token should have member's distinct_id
assert decoded["distinct_id"] == str(member.distinct_id)
# organization_role should be the owner's role (privilege escalation)
assert decoded["organization_role"] == "owner"
# original_role should be the member's actual role
assert decoded["original_role"] == "member"
# Verify posthoganalytics.capture was called for privilege escalation
mock_capture.assert_called_once()
capture_kwargs = mock_capture.call_args[1]
assert capture_kwargs["event"] == "$billing_privilege_escalation"
assert capture_kwargs["distinct_id"] == str(owner.distinct_id)
assert capture_kwargs["properties"]["target_user_id"] == member.id
assert capture_kwargs["properties"]["target_distinct_id"] == str(member.distinct_id)
assert capture_kwargs["properties"]["target_email"] == member.email
assert capture_kwargs["properties"]["action"] == "update_billing"
@patch("ee.billing.billing_manager.http_session.patch")
@patch("posthog.event_usage.posthoganalytics.capture")
def test_update_billing_org_users_no_escalation_when_user_is_owner(self, mock_capture, mock_patch):
"""
When BillingManager user is the owner, no privilege escalation should occur.
"""
mock_patch.return_value = MagicMock(status_code=200, json=MagicMock(return_value={"text": "ok"}))
# Create an owner for the organization
owner = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
# BillingManager is initialized with the owner user
billing_manager = BillingManager(self.license, user=owner)
billing_manager.update_billing_organization_users(self.organization)
mock_patch.assert_called_once()
# Extract and decode the JWT
call_kwargs = mock_patch.call_args
auth_header = call_kwargs[1]["headers"]["Authorization"]
token = auth_header.replace("Bearer ", "")
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
# Token should have owner's distinct_id
assert decoded["distinct_id"] == str(owner.distinct_id)
# organization_role should be owner
assert decoded["organization_role"] == "owner"
# original_role should NOT be present (no escalation)
assert "original_role" not in decoded
# No privilege escalation capture should occur
mock_capture.assert_not_called()
@patch("ee.billing.billing_manager.http_session.patch")
@patch("posthog.event_usage.posthoganalytics.capture")
def test_update_billing_org_users_uses_most_recent_owner(self, mock_capture, mock_patch):
"""
When multiple owners exist, should use the most recently joined owner as authorizer.
"""
mock_patch.return_value = MagicMock(status_code=200, json=MagicMock(return_value={"text": "ok"}))
# Create two owners with different join times
older_owner = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
# Update the joined_at to be older
membership = OrganizationMembership.objects.get(user=older_owner, organization=self.organization)
membership.joined_at = datetime.datetime(2020, 1, 1, tzinfo=datetime.UTC)
membership.save()
newer_owner = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
member = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.MEMBER,
)
billing_manager = BillingManager(self.license, user=member)
billing_manager.update_billing_organization_users(self.organization)
mock_patch.assert_called_once()
# Verify that the capture was called with the newer owner as authorizer
mock_capture.assert_called_once()
capture_kwargs = mock_capture.call_args[1]
assert capture_kwargs["distinct_id"] == str(newer_owner.distinct_id)
assert capture_kwargs["properties"]["target_user_id"] == member.id
assert capture_kwargs["properties"]["target_distinct_id"] == str(member.distinct_id)
assert capture_kwargs["properties"]["target_email"] == member.email
@patch("ee.billing.billing_manager.http_session.patch")
@patch("posthog.event_usage.posthoganalytics.capture")
def test_update_billing_org_users_admin_gets_escalated_to_owner(self, mock_capture, mock_patch):
"""
When BillingManager user is an admin, they should be escalated to owner role.
"""
mock_patch.return_value = MagicMock(status_code=200, json=MagicMock(return_value={"text": "ok"}))
owner = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
admin = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.ADMIN,
)
billing_manager = BillingManager(self.license, user=admin)
billing_manager.update_billing_organization_users(self.organization)
mock_patch.assert_called_once()
call_kwargs = mock_patch.call_args
auth_header = call_kwargs[1]["headers"]["Authorization"]
token = auth_header.replace("Bearer ", "")
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
assert decoded["distinct_id"] == str(admin.distinct_id)
assert decoded["organization_role"] == "owner"
assert decoded["original_role"] == "administrator"
mock_capture.assert_called_once()
capture_kwargs = mock_capture.call_args[1]
assert capture_kwargs["distinct_id"] == str(owner.distinct_id)
assert capture_kwargs["properties"]["target_user_id"] == admin.id
assert capture_kwargs["properties"]["target_distinct_id"] == str(admin.distinct_id)
assert capture_kwargs["properties"]["target_email"] == admin.email
@patch("ee.billing.billing_manager.capture_exception")
@patch("ee.billing.billing_manager.http_session.patch")
def test_update_billing_org_users_no_owner_captures_exception(self, mock_patch, mock_capture_exception):
"""
When organization has no owner, should capture exception and return early.
"""
# Remove the default user's ownership if any
OrganizationMembership.objects.filter(organization=self.organization).update(
level=OrganizationMembership.Level.MEMBER
)
billing_manager = BillingManager(self.license, user=self.user)
billing_manager.update_billing_organization_users(self.organization)
# Should not make any PATCH request
mock_patch.assert_not_called()
# Should capture exception about no owner
mock_capture_exception.assert_called_once()
exception, properties = mock_capture_exception.call_args[0]
assert str(exception) == "No owner membership found for organization"
assert properties == {"organization_id": self.organization.id}
@parameterized.expand(
[
("unauthorized", 401, None, False),
("not_found", 404, None, False),
("server_error", 500, None, True),
("connection_error", None, requests.ConnectionError("boom"), True),
]
)
@patch("ee.billing.billing_manager.capture_exception")
@patch("ee.billing.billing_manager.http_session.patch")
def test_update_billing_org_users_never_raises_and_captures_only_errors(
self, _name, status_code, side_effect, expect_capture, mock_patch, mock_capture_exception
):
User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
mock_patch.return_value = MagicMock(status_code=status_code, json=MagicMock(return_value={}))
mock_patch.side_effect = side_effect
BillingManager(self.license, user=self.user).update_billing_organization_users(self.organization)
mock_patch.assert_called_once()
if expect_capture:
mock_capture_exception.assert_called_once()
assert mock_capture_exception.call_args[0][1] == {"organization_id": self.organization.id}
else:
mock_capture_exception.assert_not_called()
@parameterized.expand([("ok", 200), ("unauthorized", 401), ("not_found", 404)])
@patch("ee.billing.billing_manager.http_session.patch")
def test_sync_organization_users_returns_billing_response(self, _name, status_code, mock_patch):
User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
mock_patch.return_value = MagicMock(status_code=status_code, json=MagicMock(return_value={}))
response = BillingManager(self.license, user=self.user).sync_organization_users(self.organization)
assert response.status_code == status_code
@patch("ee.billing.billing_manager.http_session.patch")
def test_sync_organization_users_raises_on_billing_error(self, mock_patch):
User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
mock_patch.return_value = MagicMock(status_code=500, json=MagicMock(return_value={}))
with self.assertRaises(BillingServiceResponseError) as ctx:
BillingManager(self.license, user=self.user).sync_organization_users(self.organization)
assert ctx.exception.status_code == 500
@patch("ee.billing.billing_manager.http_session.patch")
def test_sync_organization_users_raises_without_owner(self, mock_patch):
with self.assertRaises(OrganizationHasNoOwnerError):
BillingManager(self.license, user=self.user).sync_organization_users(self.organization)
mock_patch.assert_not_called()
@patch("ee.billing.billing_manager.http_session.patch")
def test_sync_organization_users_leaves_out_values_billing_rejects(self, mock_patch):
mock_patch.return_value = MagicMock(status_code=200, json=MagicMock(return_value={}))
owner = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
admin_without_distinct_id = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.ADMIN,
)
User.objects.filter(id=admin_without_distinct_id.id).update(distinct_id=None)
admin_with_invalid_email = User.objects.create_and_join(
organization=self.organization,
email="not-an-email",
password=None,
level=OrganizationMembership.Level.ADMIN,
)
BillingManager(self.license, user=owner).sync_organization_users(self.organization)
payload = mock_patch.call_args.kwargs["json"]
assert len(payload["distinct_ids"]) == 3
assert set(payload["distinct_ids"]) == {
self.user.distinct_id,
owner.distinct_id,
admin_with_invalid_email.distinct_id,
}
assert payload["org_customer_email"] == "[email protected]"
assert sorted(payload["org_admin_emails"]) == ["[email protected]", "[email protected]"]
assert payload["org_users"] == [
{"email": "not-an-email", "distinct_id": admin_with_invalid_email.distinct_id, "role": 8},
{"email": "[email protected]", "distinct_id": owner.distinct_id, "role": 15},
]
@patch("ee.billing.billing_manager.http_session.patch")
@patch("posthog.event_usage.posthoganalytics.capture")
def test_update_billing_org_users_without_billing_manager_user(self, mock_capture, mock_patch):
"""
When BillingManager has no user (user=None), no privilege escalation should occur
since there's no user to escalate.
"""
mock_patch.return_value = MagicMock(status_code=200, json=MagicMock(return_value={"text": "ok"}))
# Create an owner (required for the function to work)
User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
# BillingManager initialized without a user
billing_manager = BillingManager(self.license, user=None)
billing_manager.update_billing_organization_users(self.organization)
mock_patch.assert_called_once()
call_kwargs = mock_patch.call_args
auth_header = call_kwargs[1]["headers"]["Authorization"]
token = auth_header.replace("Bearer ", "")
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
# Without a user, there should be no user-related fields
assert "distinct_id" not in decoded
assert "organization_role" not in decoded
assert "original_role" not in decoded
# No privilege escalation capture should occur
mock_capture.assert_not_called()
class TestUserUpdateBillingOrganizationUsers(BaseTest):
"""Tests for User.update_billing_organization_users integration with BillingManager"""
def setUp(self):
super().setUp()
self.license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="license_id::license_secret",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
@patch("posthog.models.user.is_cloud", return_value=True)
@patch("posthog.models.user.get_cached_instance_license")
@patch("ee.billing.billing_manager.http_session.patch")
@patch("posthog.event_usage.posthoganalytics.capture")
def test_user_update_billing_organization_users_passes_self_to_billing_manager(
self, mock_capture, mock_patch, mock_get_license, mock_is_cloud
):
"""
User.update_billing_organization_users should pass self to BillingManager,
enabling privilege escalation to work correctly.
"""
mock_patch.return_value = MagicMock(status_code=200, json=MagicMock(return_value={"text": "ok"}))
mock_get_license.return_value = self.license
# Create an owner for the organization
owner = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.OWNER,
)
# Create a regular member who will call update_billing_organization_users
member = User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=None,
level=OrganizationMembership.Level.MEMBER,
)
# Reset mocks after user creation (create_and_join also calls update_billing_organization_users)
mock_patch.reset_mock()
mock_capture.reset_mock()
# Call the User method (not BillingManager directly)
member.update_billing_organization_users(self.organization)
# Verify the PATCH request was made
mock_patch.assert_called_once()
# Extract and decode the JWT token
call_kwargs = mock_patch.call_args
auth_header = call_kwargs[1]["headers"]["Authorization"]
token = auth_header.replace("Bearer ", "")
decoded = jwt.decode(token, "license_secret", algorithms=["HS256"], audience="posthog:license-key")
# Token should have member's distinct_id (the user who called the method)
assert decoded["distinct_id"] == str(member.distinct_id)
# organization_role should be the owner's role (privilege escalation)
assert decoded["organization_role"] == "owner"
# original_role should be the member's actual role
assert decoded["original_role"] == "member"
# Verify privilege escalation was captured
mock_capture.assert_called_once()
capture_kwargs = mock_capture.call_args[1]
assert capture_kwargs["event"] == "$billing_privilege_escalation"
assert capture_kwargs["distinct_id"] == str(owner.distinct_id)
assert capture_kwargs["properties"]["target_user_id"] == member.id
assert capture_kwargs["properties"]["target_distinct_id"] == str(member.distinct_id)
assert capture_kwargs["properties"]["target_email"] == member.email
class TestParamSerialization(SimpleTestCase):
@parameterized.expand(
[
("teams_map", {"1": "Team A", "2": "Team B"}, '{"1": "Team A", "2": "Team B"}'),
("usage_types", ["events", "recordings"], '["events", "recordings"]'),
("team_ids", [1, 2, 3], "[1, 2, 3]"),
("breakdowns", ["product"], '["product"]'),
]
)
def test_to_query_params_serializes_complex_types(self, field_name, native_value, expected_json):
params = {field_name: native_value}
result = BillingManager._to_query_params(params)
assert json.loads(result[field_name]) == json.loads(expected_json)
def test_to_query_params_passes_through_scalars(self):
params = {"start_date": "2025-01-01", "end_date": "2025-01-31"}
result = BillingManager._to_query_params(params)
assert result == {"start_date": "2025-01-01", "end_date": "2025-01-31"}
def test_to_query_params_stringifies_uuids(self):
from uuid import UUID
org_id = UUID("12345678-1234-5678-1234-567812345678")
result = BillingManager._to_query_params({"organization_id": org_id, "teams_map": {"1": "A"}})
assert result["organization_id"] == "12345678-1234-5678-1234-567812345678"
assert result["teams_map"] == '{"1": "A"}'
def test_to_post_body_converts_organization_id_to_string(self):
from uuid import UUID
org_id = UUID("12345678-1234-5678-1234-567812345678")
result = BillingManager._to_post_body({"organization_id": org_id, "teams_map": {"1": "A"}})
assert result["organization_id"] == str(org_id)
assert result["teams_map"] == {"1": "A"}
def test_to_post_body_preserves_native_types(self):
params = {"teams_map": {"1": "Team A"}, "start_date": "2025-01-01"}
result = BillingManager._to_post_body(params)
assert result == params
@parameterized.expand(
[
("json_list", '["event_count_in_period", "recordings"]', ["event_count_in_period", "recordings"]),
("json_int_list", "[1, 2, 3]", [1, 2, 3]),
("json_dict", '{"1": "Team A"}', {"1": "Team A"}),
("plain_string", "2025-01-01", "2025-01-01"),
("json_number_string", "42", "42"),
("json_bool_string", "true", "true"),
]
)
def test_to_post_body_parses_json_encoded_strings(self, _name, input_value, expected):
result = BillingManager._to_post_body({"field": input_value})
assert result["field"] == expected
class TestRequestWithPostFallback(BaseTest):
def setUp(self):
super().setUp()
self.license = super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
self.manager = BillingManager(self.license)
@parameterized.expand(
[
("get_usage_data", 414),
("get_usage_data", 431),
("get_spend_data", 414),
("get_spend_data", 431),
]
)
@patch("ee.billing.billing_manager.http_session.post")
@patch("ee.billing.billing_manager.http_session.get")
def test_falls_back_to_post_on_uri_too_large(self, method_name, status_code, mock_get, mock_post):
mock_get.return_value = MagicMock(status_code=status_code)
mock_post.return_value = MagicMock(status_code=200, json=MagicMock(return_value={"results": []}))
params = {
"start_date": "2025-01-01",
"teams_map": {"1": "Team A"},
}
result = getattr(self.manager, method_name)(self.organization, params)
assert result == {"results": []}
mock_get.assert_called_once()
assert mock_get.call_args.kwargs["timeout"] == (5, 30)
get_params = mock_get.call_args[1]["params"]
assert get_params["teams_map"] == '{"1": "Team A"}'
assert get_params["start_date"] == "2025-01-01"
mock_post.assert_called_once()
assert mock_post.call_args.kwargs["timeout"] == (5, 30)
post_json = mock_post.call_args[1]["json"]
assert post_json["teams_map"] == {"1": "Team A"}
assert post_json["start_date"] == "2025-01-01"
@parameterized.expand([("get_usage_data",), ("get_spend_data",)])
@patch("ee.billing.billing_manager.http_session.post")
@patch("ee.billing.billing_manager.http_session.get")
def test_post_fallback_parses_json_encoded_strings(self, method_name, mock_get, mock_post):
mock_get.return_value = MagicMock(status_code=414)
mock_post.return_value = MagicMock(status_code=200, json=MagicMock(return_value={"results": []}))
params = {
"start_date": "2025-01-01",
"usage_types": '["event_count_in_period", "recordings"]',
"team_ids": "[1, 2]",
"teams_map": {"1": "Team A"},
}
getattr(self.manager, method_name)(self.organization, params)
post_json = mock_post.call_args[1]["json"]
assert post_json["usage_types"] == ["event_count_in_period", "recordings"]
assert post_json["team_ids"] == [1, 2]
assert post_json["teams_map"] == {"1": "Team A"}
assert post_json["start_date"] == "2025-01-01"
@parameterized.expand([("get_usage_data",), ("get_spend_data",)])
@patch("ee.billing.billing_manager.http_session.post")
@patch("ee.billing.billing_manager.http_session.get")
def test_does_not_fall_back_on_success(self, method_name, mock_get, mock_post):
mock_get.return_value = MagicMock(status_code=200, json=MagicMock(return_value={"results": []}))
result = getattr(self.manager, method_name)(self.organization, {"start_date": "2025-01-01"})
assert result == {"results": []}
mock_get.assert_called_once()
mock_post.assert_not_called()
@parameterized.expand(
[
("get_usage_data", 400),
("get_usage_data", 500),
("get_spend_data", 400),
("get_spend_data", 500),
]
)
@patch("ee.billing.billing_manager.http_session.post")
@patch("ee.billing.billing_manager.http_session.get")
def test_does_not_fall_back_on_non_uri_errors(self, method_name, status_code, mock_get, mock_post):
mock_get.return_value = MagicMock(status_code=status_code, text="error")
with self.assertRaises(Exception):
getattr(self.manager, method_name)(self.organization, {"start_date": "2025-01-01"})
mock_get.assert_called_once()
mock_post.assert_not_called()
@parameterized.expand([("get_usage_data",), ("get_spend_data",)])
@patch("ee.billing.billing_manager.http_session.post")
@patch("ee.billing.billing_manager.http_session.get")
def test_post_fallback_error_propagates(self, method_name, mock_get, mock_post):
mock_get.return_value = MagicMock(status_code=414)
mock_post.return_value = MagicMock(status_code=500, text="internal error")
with self.assertRaises(Exception):
getattr(self.manager, method_name)(self.organization, {"teams_map": {"1": "A"}})
mock_get.assert_called_once()
mock_post.assert_called_once()
@parameterized.expand([("get_usage_data",), ("get_spend_data",)])
@patch("ee.billing.billing_manager.http_session.post")
@patch("ee.billing.billing_manager.http_session.get")
def test_with_empty_params(self, method_name, mock_get, mock_post):
mock_get.return_value = MagicMock(status_code=200, json=MagicMock(return_value={"results": []}))
result = getattr(self.manager, method_name)(self.organization, {})
assert result == {"results": []}
mock_get.assert_called_once()
mock_post.assert_not_called()
class TestDisputeSignalsPr(BaseTest):
def _license(self) -> License:
return super(LicenseManager, cast(LicenseManager, License.objects)).create(
key="key123::key123",
plan="enterprise",
valid_until=datetime.datetime(2038, 1, 19, 3, 14, 7),
)
@patch(
"ee.billing.billing_manager.http_session.post",
return_value=MagicMock(
status_code=200,
json=MagicMock(return_value={"credit_amount_usd": "15.00", "credit_id": "c1", "already_processed": False}),
),
)
def test_posts_to_dispute_endpoint_and_returns_body(self, billing_post_request_mock: MagicMock):
payload = {"refund_id": "r1", "credits": 1500, "metadata": {}}
result = BillingManager(self._license()).dispute_signals_pr(self.organization, payload)
assert result == {"credit_amount_usd": "15.00", "credit_id": "c1", "already_processed": False}
call_args = billing_post_request_mock.call_args
assert call_args[0][0].endswith("/api/signals/dispute-pr")
assert call_args[1]["json"] == payload
assert "Authorization" in call_args[1]["headers"]
# Billing only accepts dispute calls from tokens carrying the service_action
# claim; without it the request is rejected as a user-initiated token.
token = call_args[1]["headers"]["Authorization"].removeprefix("Bearer ")
decoded = jwt.decode(token, options={"verify_signature": False})
assert decoded["service_action"] == "signals_pr_dispute"
assert "organization_role" not in decoded
assert "distinct_id" not in decoded
@parameterized.expand([("missing_deploy", 404), ("auth_failure", 401)])
def test_raises_on_statuses_the_default_valid_codes_would_swallow(self, _name, status_code):
# handle_billing_service_error's default valid_codes includes 404/401 — treating a missing
# billing deploy or an auth failure as success would record an error body as a synced
# credit. Any non-200 must raise so the Celery caller retries.
response = MagicMock(status_code=status_code, json=MagicMock(return_value={"detail": "nope"}), ok=False)
with patch("ee.billing.billing_manager.http_session.post", return_value=response):
with self.assertRaises(Exception) as context:
BillingManager(self._license()).dispute_signals_pr(
self.organization, {"refund_id": "r1", "credits": 1500, "metadata": {}}
)
assert str(status_code) in str(context.exception)