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.

feat(billing): attach actor IP to billing activity logs (#71073)

Yasen39af9a9b7942
diff --git a/ee/api/billing.py b/ee/api/billing.py
index 16805675ba5e..d68d8deb0d54 100644
--- a/ee/api/billing.py
+++ b/ee/api/billing.py
@@ -21,7 +21,7 @@ from posthog.event_usage import groups
from posthog.exceptions_capture import capture_exception
from posthog.models import Organization, OrganizationIntegration, Team
from posthog.models.organization import OrganizationMembership
-from posthog.utils import relative_date_parse
+from posthog.utils import get_trusted_client_ip, relative_date_parse
from ee.billing.billing_manager import BillingManager
from ee.models import License
@@ -103,7 +103,7 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
user = (
self.request.user if isinstance(self.request.user, AbstractUser) and self.request.user.distinct_id else None
)
- return BillingManager(license, user)
+ return BillingManager(license, user, ip_address=get_trusted_client_ip(self.request))
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
license = get_cached_instance_license()
@@ -416,9 +416,10 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
license = License(key=serializer.validated_data["license"])
+ ip_address = get_trusted_client_ip(request)
res = requests.get(
f"{BILLING_SERVICE_URL}/api/billing",
- headers=BillingManager(license).get_auth_headers(organization),
+ headers=BillingManager(license, ip_address=ip_address).get_auth_headers(organization),
)
if res.status_code != 200:
@@ -428,7 +429,7 @@ class BillingViewset(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
}
)
data = res.json()
- BillingManager(license).update_license_details(data)
+ BillingManager(license, ip_address=ip_address).update_license_details(data)
return Response({"success": True})
@action(
diff --git a/ee/billing/billing_manager.py b/ee/billing/billing_manager.py
index b7d073a4cfa0..3a849ad7d057 100644
--- a/ee/billing/billing_manager.py
+++ b/ee/billing/billing_manager.py
@@ -169,10 +169,12 @@ def handle_billing_service_error(res: requests.Response, valid_codes=(200, 201,
class BillingManager:
license: License | None
user: User | None
+ ip_address: str | None
- def __init__(self, license, user: User | None = None):
+ def __init__(self, license, user: User | None = None, ip_address: str | None = None):
self.license = license or get_cached_instance_license()
self.user = user
+ self.ip_address = ip_address
def get_billing(
self,
@@ -534,7 +536,12 @@ class BillingManager:
billing_provider=billing_provider,
service_action=service_action,
)
- return {"Authorization": f"Bearer {billing_service_token}"}
+ headers = {"Authorization": f"Bearer {billing_service_token}"}
+ if self.ip_address:
+ # Billing is called server-to-server, so it only ever sees PostHog's egress IP.
+ # Forward the end-user's IP so billing can attach it to activity-log records.
+ headers["X-PostHog-Actor-IP"] = self.ip_address
+ return headers
def get_invoices(self, organization: Organization, status: str | None):
res = requests.get(
diff --git a/ee/billing/queue/BillingConsumer.py b/ee/billing/queue/BillingConsumer.py
index d063679b90fd..fb8a783e5e26 100644
--- a/ee/billing/queue/BillingConsumer.py
+++ b/ee/billing/queue/BillingConsumer.py
@@ -10,6 +10,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.models.organization import Organization
from posthog.models.user import User
+from posthog.utils import sanitize_ip_address
from products.customer_analytics.backend.facade.api import notify_managers_of_usage_spike
@@ -246,6 +247,14 @@ class BillingConsumer(SQSConsumer):
)
return
+ # Only attribute an IP when we resolved an org-scoped actor. Without this gate the
+ # actor IP and actor identity could drift apart: a system-origin message (no
+ # distinct_id) or one whose distinct_id doesn't map to a member of this org is logged
+ # as a system activity, and pinning an IP to an unattributed row is misleading audit data.
+ # Sanitize so a malformed/non-string value can't fail the IP column write and leave the
+ # message looping on redelivery forever.
+ ip_address = sanitize_ip_address(body.get("ip_address")) if user is not None else None
+
written = log_activity(
organization_id=organization.id,
team_id=None,
@@ -255,6 +264,7 @@ class BillingConsumer(SQSConsumer):
scope="Billing",
activity=activity,
detail=Detail(name=detail_data.get("name"), changes=changes),
+ ip_address=ip_address,
)
# This SQS message exists only to create the audit row. log_activity swallows write
diff --git a/ee/billing/test/test_billing_consumer.py b/ee/billing/test/test_billing_consumer.py
index 307e6a8aecc4..82aa9d7b6fe7 100644
--- a/ee/billing/test/test_billing_consumer.py
+++ b/ee/billing/test/test_billing_consumer.py
@@ -1,6 +1,8 @@
from posthog.test.base import BaseTest
from unittest.mock import patch
+from parameterized import parameterized
+
from posthog.models import Organization, User
from posthog.models.activity_logging.activity_log import ActivityLog
@@ -70,6 +72,7 @@ class TestBillingConsumerBillingActivity(BaseTest):
],
},
"event_id": "evt-1",
+ "ip_address": "203.0.113.7",
}
message.update(overrides)
return message
@@ -84,17 +87,20 @@ class TestBillingConsumerBillingActivity(BaseTest):
assert log.is_system is False
assert log.item_id == str(self.organization.id)
assert log.activity == "updated"
+ assert log.ip_address == "203.0.113.7"
assert log.detail is not None
assert log.detail["changes"][0]["field"] == "product_analytics"
assert log.detail["changes"][0]["after"] == 1000
def test_writes_system_activity_when_distinct_id_absent(self):
- # System-origin changes (Stripe webhooks, dunning) carry no actor.
+ # System-origin changes (Stripe webhooks, dunning) carry no actor. Even though the
+ # message carries an IP, it must not be pinned to an unattributed system row.
self._build_consumer()._process_billing_activity(self._message(distinct_id=None))
log = ActivityLog.objects.get(scope="Billing")
assert log.user_id is None
assert log.is_system is True
+ assert log.ip_address is None
def test_does_not_attribute_distinct_id_from_another_organization(self):
# distinct_id is globally unique; a user outside this org must never be
@@ -107,6 +113,24 @@ class TestBillingConsumerBillingActivity(BaseTest):
log = ActivityLog.objects.get(scope="Billing")
assert log.user_id is None
assert log.is_system is True
+ # A foreign actor is not attributed, so its IP must not be persisted either.
+ assert log.ip_address is None
+
+ @parameterized.expand(
+ [
+ ("empty_string", ""),
+ ("garbage", "not-an-ip"),
+ ("non_string", 12345),
+ ("missing", None),
+ ]
+ )
+ def test_malformed_ip_is_dropped_instead_of_blocking_the_queue(self, _name, bad_ip):
+ # A malformed IP must not reach the IP column and fail the write; otherwise the message
+ # would loop on redelivery forever. The row is still written, just without an IP.
+ self._build_consumer()._process_billing_activity(self._message(ip_address=bad_ip))
+
+ log = ActivityLog.objects.get(scope="Billing")
+ assert log.ip_address is None
@patch(f"{CONSUMER}.capture_exception")
def test_missing_organization_id_skips_and_captures(self, mock_capture):
diff --git a/ee/billing/test/test_billing_manager.py b/ee/billing/test/test_billing_manager.py
index b4060f296883..c221ef438713 100644
--- a/ee/billing/test/test_billing_manager.py
+++ b/ee/billing/test/test_billing_manager.py
@@ -74,6 +74,25 @@ class TestBillingManager(BaseTest):
"https://billing.posthog.com/api/products-v2", params={"plan": "standard"}, headers={}
)
+ @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.requests.patch",
return_value=MagicMock(status_code=200, json=MagicMock(return_value={"text": "ok"})),
diff --git a/posthog/utils.py b/posthog/utils.py
index 49bad398fb34..05fc0257fe8b 100644
--- a/posthog/utils.py
+++ b/posthog/utils.py
@@ -1077,6 +1077,17 @@ def get_ip_address(request: HttpRequest) -> str:
return ip
+def sanitize_ip_address(ip: Any) -> Optional[str]:
+ """Return the value only if it is a valid IP address string, otherwise None.
+
+ Use this before persisting an externally supplied IP so a malformed or non-string
+ value can't reach an IP database column and fail the write.
+ """
+ if not isinstance(ip, str):
+ return None
+ return _normalize_ip(ip)
+
+
def _normalize_ip(ip: str) -> Optional[str]:
"""Strip an optional port and validate; returns None if the result isn't a valid IP."""
if ip.startswith("["):