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(activity-logs): add ip address to activity logs (#59589)

Leon Daly61b2078aef24
diff --git a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
index 87108129a262..175c2bcef873 100644
--- a/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
+++ b/frontend/src/lib/components/ActivityLog/humanizeActivity.tsx
@@ -55,6 +55,8 @@ export type ActivityLogItem = {
was_impersonated?: boolean
/** SDK or integration that triggered this action (from x-posthog-client header). */
client?: string | null
+ /** Client IP address captured at request time. Null for non-HTTP activity (system, background jobs). */
+ ip_address?: string | null
}
// the description of a single activity log is a sentence describing one or more changes that makes up the entry
diff --git a/frontend/src/scenes/audit-logs/AuditLogTable.tsx b/frontend/src/scenes/audit-logs/AuditLogTable.tsx
index 809cc2bdfb66..1c037d5e7227 100644
--- a/frontend/src/scenes/audit-logs/AuditLogTable.tsx
+++ b/frontend/src/scenes/audit-logs/AuditLogTable.tsx
@@ -31,7 +31,7 @@ const baseColumns: LemonTableColumns<HumanizedActivityLogItem> = [
: (description as React.ReactNode) || 'No description'}
</span>
),
- width: '35%',
+ width: '30%',
},
{
title: 'User',
@@ -80,6 +80,17 @@ const baseColumns: LemonTableColumns<HumanizedActivityLogItem> = [
render: (_, logItem) => <TZLabel time={logItem.created_at} />,
width: '15%',
},
+ {
+ title: 'IP address',
+ key: 'ip_address',
+ render: (_, logItem) =>
+ logItem.unprocessed?.ip_address ? (
+ <span className="font-mono text-xs">{logItem.unprocessed.ip_address}</span>
+ ) : (
+ <span className="text-muted">—</span>
+ ),
+ width: '10%',
+ },
]
function buildColumns(teamsById?: Record<number, string>): LemonTableColumns<HumanizedActivityLogItem> {
diff --git a/frontend/src/scenes/audit-logs/BasicFiltersTab.tsx b/frontend/src/scenes/audit-logs/BasicFiltersTab.tsx
index a98970ab1a0a..e372ae8b7e74 100644
--- a/frontend/src/scenes/audit-logs/BasicFiltersTab.tsx
+++ b/frontend/src/scenes/audit-logs/BasicFiltersTab.tsx
@@ -7,10 +7,11 @@ import { humanizeActivity, humanizeScope } from 'lib/components/ActivityLog/huma
import { AnimatedCollapsible } from 'lib/components/AnimatedCollapsible'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { ActivityScope } from '~/types'
-import { advancedActivityLogsLogic } from './advancedActivityLogsLogic'
+import { advancedActivityLogsLogic, isValidIpFilterValue } from './advancedActivityLogsLogic'
import { DetailFilters } from './DetailFilters'
export const BasicFiltersTab = (): JSX.Element => {
@@ -268,6 +269,37 @@ export const BasicFiltersTab = (): JSX.Element => {
/>
</div>
)}
+
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center gap-1 mb-1">
+ <label className="block text-sm font-medium">IP address</label>
+ <Tooltip title="Filter by the client IP address captured at request time. Type a value and press enter to add it. Wildcards are supported, e.g. `203.0.113.*`.">
+ <IconInfo className="w-4 h-4 text-muted-alt cursor-help" />
+ </Tooltip>
+ </div>
+ <LemonInputSelect
+ mode="multiple"
+ displayMode="count"
+ bulkActions="select-and-clear-all"
+ value={filters.ip_addresses || []}
+ onChange={(ip_addresses) => {
+ const invalid = ip_addresses.filter((v) => !isValidIpFilterValue(v))
+ if (invalid.length) {
+ lemonToast.error(
+ `Invalid IP address format: ${invalid.join(', ')}. Use a full IPv4/IPv6 address or a wildcard like 192.168.1.*`
+ )
+ return
+ }
+ setFilters({ ip_addresses })
+ }}
+ options={[]}
+ placeholder="Enter IPs or patterns (e.g. 203.0.113.*)"
+ allowCustomValues={true}
+ data-attr="audit-logs-ip-address-filter"
+ size="small"
+ className="min-w-50"
+ />
+ </div>
</div>
<div className="py-4">
<DetailFilters />
diff --git a/frontend/src/scenes/audit-logs/ExportsListHelpers.tsx b/frontend/src/scenes/audit-logs/ExportsListHelpers.tsx
index c999a2f260bd..873a8414cd7d 100644
--- a/frontend/src/scenes/audit-logs/ExportsListHelpers.tsx
+++ b/frontend/src/scenes/audit-logs/ExportsListHelpers.tsx
@@ -64,6 +64,9 @@ export const getFilterSummary = (exportAsset: ExportedAsset): string => {
if (filters.clients && filters.clients.length > 0) {
activeFilters.push(`Clients: ${filters.clients.length}`)
}
+ if (filters.ip_addresses && filters.ip_addresses.length > 0) {
+ activeFilters.push(`IP addresses: ${filters.ip_addresses.length}`)
+ }
return activeFilters.length > 0 ? activeFilters.join(', ') : 'No filters'
}
@@ -190,6 +193,17 @@ export const getFilterTooltip = (exportAsset: ExportedAsset): JSX.Element => {
)
}
+ if (filters.ip_addresses && filters.ip_addresses.length > 0) {
+ filterSections.push(
+ <div key="ip_addresses">
+ <strong>IP addresses ({filters.ip_addresses.length}):</strong>
+ <br />
+ {filters.ip_addresses.slice(0, 5).join(', ')}
+ {filters.ip_addresses.length > 5 && `... and ${filters.ip_addresses.length - 5} more`}
+ </div>
+ )
+ }
+
if (filterSections.length === 0) {
return <div>No filters applied</div>
}
diff --git a/frontend/src/scenes/audit-logs/advancedActivityLogsLogic.tsx b/frontend/src/scenes/audit-logs/advancedActivityLogsLogic.tsx
index 15d93584dacb..2d8c549a2071 100644
--- a/frontend/src/scenes/audit-logs/advancedActivityLogsLogic.tsx
+++ b/frontend/src/scenes/audit-logs/advancedActivityLogsLogic.tsx
@@ -37,6 +37,7 @@ export interface AdvancedActivityLogFilters {
scopes?: ActivityScope[]
activities?: string[]
clients?: string[]
+ ip_addresses?: string[]
team_ids?: number[]
detail_filters?: Record<string, DetailFilter>
was_impersonated?: boolean
@@ -84,13 +85,21 @@ const DEFAULT_FILTERS: AdvancedActivityLogFilters = {
scopes: [],
activities: [],
clients: [],
+ ip_addresses: [],
team_ids: [],
detail_filters: {},
item_ids: [],
page: 1,
}
-const ADVANCED_FILTERS = ['was_impersonated', 'is_system', 'item_ids', 'clients', 'detail_filters'] as const
+const ADVANCED_FILTERS = [
+ 'was_impersonated',
+ 'is_system',
+ 'item_ids',
+ 'clients',
+ 'ip_addresses',
+ 'detail_filters',
+] as const
function parseListSearchParam(raw: unknown): string[] {
if (raw === undefined || raw === null || raw === '') {
@@ -105,6 +114,20 @@ function parseListSearchParam(raw: unknown): string[] {
return [String(raw)]
}
+export function isValidIpFilterValue(raw: string): boolean {
+ const v = raw.trim()
+ if (!v || !/^[0-9a-fA-F:.*]+$/.test(v)) {
+ return false
+ }
+ if (v.includes('*')) {
+ return true
+ }
+ if (/^\d{1,3}(\.\d{1,3}){3}$/.test(v)) {
+ return v.split('.').every((p) => Number(p) <= 255)
+ }
+ return v.includes(':')
+}
+
function parseBooleanSearchParam(raw: unknown): boolean | undefined {
if (raw === 'true') {
return true
@@ -234,6 +257,7 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
values.filters.scopes?.forEach((scope) => params.append('scopes', scope))
values.filters.activities?.forEach((activity) => params.append('activities', activity))
values.filters.clients?.forEach((client) => params.append('clients', client))
+ values.filters.ip_addresses?.forEach((ip) => params.append('ip_addresses', ip))
values.filters.item_ids?.forEach((item_id) => params.append('item_ids', item_id))
if (values.isOrganizationView) {
values.filters.team_ids?.forEach((team_id: number) =>
@@ -319,6 +343,7 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
filters.scopes?.length ||
filters.activities?.length ||
filters.clients?.length ||
+ filters.ip_addresses?.length ||
filters.item_ids?.length ||
(isOrganizationView && filters.team_ids?.length) ||
filters.was_impersonated !== undefined ||
@@ -357,6 +382,9 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
if (filters.clients && filters.clients.length > 0) {
count++
}
+ if (filters.ip_addresses && filters.ip_addresses.length > 0) {
+ count++
+ }
if (filters.detail_filters && Object.keys(filters.detail_filters).length > 0) {
count++
}
@@ -377,6 +405,7 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
scopes: filters.scopes?.length ? filters.scopes.join(',') : undefined,
activities: filters.activities?.length ? filters.activities.join(',') : undefined,
clients: filters.clients?.length ? filters.clients.join(',') : undefined,
+ ip_addresses: filters.ip_addresses?.length ? filters.ip_addresses.join(',') : undefined,
team_ids: isOrganizationView && filters.team_ids?.length ? filters.team_ids.join(',') : undefined,
item_ids: filters.item_ids?.length ? filters.item_ids.join(',') : undefined,
was_impersonated: filters.was_impersonated?.toString(),
@@ -551,6 +580,7 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
scopes: values.filters.scopes,
activities: values.filters.activities,
clients: values.filters.clients,
+ ip_addresses: values.filters.ip_addresses,
detail_filters: values.filters.detail_filters,
was_impersonated: values.filters.was_impersonated,
is_system: values.filters.is_system,
@@ -627,6 +657,10 @@ export const advancedActivityLogsLogic = kea<advancedActivityLogsLogicType>([
if (clients.length) {
urlFilters.clients = clients
}
+ const ipAddresses = parseListSearchParam(searchParams.ip_addresses)
+ if (ipAddresses.length) {
+ urlFilters.ip_addresses = ipAddresses
+ }
const itemIds = parseListSearchParam(searchParams.item_ids)
if (itemIds.length) {
urlFilters.item_ids = itemIds
diff --git a/posthog/api/advanced_activity_logs/filters.py b/posthog/api/advanced_activity_logs/filters.py
index a7c02ec0186a..258162bcd933 100644
--- a/posthog/api/advanced_activity_logs/filters.py
+++ b/posthog/api/advanced_activity_logs/filters.py
@@ -1,3 +1,4 @@
+import re
from typing import Any
from django.db.models import Q, QuerySet
@@ -20,6 +21,7 @@ class AdvancedActivityLogFilterManager:
queryset = self._apply_is_system_filter(queryset, filters)
queryset = self._apply_item_ids_filter(queryset, filters)
queryset = self._apply_clients_filter(queryset, filters)
+ queryset = self._apply_ip_addresses_filter(queryset, filters)
queryset = self._apply_team_ids_filter(queryset, filters)
return queryset
@@ -189,6 +191,26 @@ class AdvancedActivityLogFilterManager:
queryset = queryset.filter(client__in=filters["clients"])
return queryset
+ def _apply_ip_addresses_filter(
+ self, queryset: QuerySet[ActivityLog], filters: dict[str, Any]
+ ) -> QuerySet[ActivityLog]:
+ ip_filters = [ip for ip in (filters.get("ip_addresses") or []) if ip]
+ if not ip_filters:
+ return queryset
+
+ # Always go through __iregex so partial values (e.g. `192.168.1`) match no rows
+ # instead of triggering Django's GenericIPAddressField validation on __in lookups.
+ exact_values = [v for v in ip_filters if "*" not in v]
+ wildcard_values = [v for v in ip_filters if "*" in v]
+
+ q = Q()
+ if exact_values:
+ q |= Q(ip_address__in=exact_values)
+ for value in wildcard_values:
+ regex = "^" + "".join(".*" if c == "*" else re.escape(c) for c in value) + "$"
+ q |= Q(ip_address__iregex=regex)
+ return queryset.filter(q)
+
def _apply_team_ids_filter(self, queryset: QuerySet[ActivityLog], filters: dict[str, Any]) -> QuerySet[ActivityLog]:
if filters.get("team_ids"):
queryset = queryset.filter(team_id__in=filters["team_ids"])
diff --git a/posthog/api/advanced_activity_logs/test_filters.py b/posthog/api/advanced_activity_logs/test_filters.py
index 0b56838245a8..016a41aeb377 100644
--- a/posthog/api/advanced_activity_logs/test_filters.py
+++ b/posthog/api/advanced_activity_logs/test_filters.py
@@ -1,8 +1,13 @@
from posthog.test.base import BaseTest
+from django.http import QueryDict
+
+from parameterized import parameterized
+
from posthog.models.activity_logging.activity_log import ActivityLog
from .filters import AdvancedActivityLogFilterManager
+from .viewset import AdvancedActivityLogFiltersSerializer
class TestAdvancedActivityLogFilterManager(BaseTest):
@@ -224,6 +229,85 @@ class TestAdvancedActivityLogFilterManager(BaseTest):
self.assertEqual(filtered.count(), 1)
+class TestIpAddressFilter(BaseTest):
+ def setUp(self):
+ super().setUp()
+ self.filter_manager = AdvancedActivityLogFilterManager()
+
+ def _create_log(self, ip_address: str | None) -> ActivityLog:
+ return ActivityLog.objects.create(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ scope="TestScope",
+ activity="updated",
+ item_id="test-item",
+ detail={},
+ ip_address=ip_address,
+ )
+
+ def test_filters_by_single_ip(self):
+ match = self._create_log("203.0.113.42")
+ self._create_log("198.51.100.7")
+ self._create_log(None)
+
+ queryset = ActivityLog.objects.filter(team_id=self.team.id)
+ filtered = self.filter_manager.apply_filters(queryset, {"ip_addresses": ["203.0.113.42"]})
+ self.assertEqual(set(filtered.values_list("id", flat=True)), {match.id})
+
+ def test_filters_by_multiple_ips(self):
+ match1 = self._create_log("203.0.113.42")
+ match2 = self._create_log("198.51.100.7")
+ self._create_log("192.0.2.99")
+
+ queryset = ActivityLog.objects.filter(team_id=self.team.id)
+ filtered = self.filter_manager.apply_filters(queryset, {"ip_addresses": ["203.0.113.42", "198.51.100.7"]})
+ self.assertEqual(set(filtered.values_list("id", flat=True)), {match1.id, match2.id})
+
+ def test_no_ip_filter_returns_all(self):
+ log1 = self._create_log("203.0.113.42")
+ log2 = self._create_log(None)
+
+ queryset = ActivityLog.objects.filter(team_id=self.team.id)
+ filtered = self.filter_manager.apply_filters(queryset, {"ip_addresses": []})
+ self.assertEqual(set(filtered.values_list("id", flat=True)), {log1.id, log2.id})
+
+ def test_filters_by_wildcard_prefix(self):
+ match1 = self._create_log("203.0.113.42")
+ match2 = self._create_log("203.0.113.99")
+ self._create_log("198.51.100.7")
+ self._create_log(None)
+
+ queryset = ActivityLog.objects.filter(team_id=self.team.id)
+ filtered = self.filter_manager.apply_filters(queryset, {"ip_addresses": ["203.0.113.*"]})
+ self.assertEqual(set(filtered.values_list("id", flat=True)), {match1.id, match2.id})
+
+ def test_combines_exact_and_wildcard(self):
+ exact_match = self._create_log("198.51.100.7")
+ wildcard_match = self._create_log("203.0.113.42")
+ self._create_log("10.0.0.1")
+
+ queryset = ActivityLog.objects.filter(team_id=self.team.id)
+ filtered = self.filter_manager.apply_filters(queryset, {"ip_addresses": ["198.51.100.7", "203.0.*"]})
+ self.assertEqual(set(filtered.values_list("id", flat=True)), {exact_match.id, wildcard_match.id})
+
+ @parameterized.expand(
+ [
+ ("ipv4", "203.0.113.42", True),
+ ("ipv6", "2001:db8::1", True),
+ ("wildcard", "203.0.113.*", True),
+ ("text", "not-an-ip", False),
+ ("regex_metachar", "192.168.1.(0|1)", False),
+ ("empty", "", False),
+ ]
+ )
+ def test_serializer_validates_ip_filter_shape(self, _name: str, value: str, expected: bool) -> None:
+ query = QueryDict(mutable=True)
+ query.appendlist("ip_addresses", value)
+ serializer = AdvancedActivityLogFiltersSerializer(data=query)
+ self.assertEqual(serializer.is_valid(), expected, serializer.errors)
+
+
class TestTypeConversionIntegration(BaseTest):
def setUp(self):
super().setUp()
diff --git a/posthog/api/advanced_activity_logs/viewset.py b/posthog/api/advanced_activity_logs/viewset.py
index 2d0371fe88de..9283c87d88f7 100644
--- a/posthog/api/advanced_activity_logs/viewset.py
+++ b/posthog/api/advanced_activity_logs/viewset.py
@@ -1,3 +1,4 @@
+import re
import json
import hashlib
import logging
@@ -210,6 +211,30 @@ class JSONStringFilterField(serializers.JSONField):
pass
+_IP_FILTER_RE = re.compile(r"^[0-9a-fA-F:.*]+$")
+_IPV4_RE = re.compile(r"^\d{1,3}(\.\d{1,3}){3}$")
+
+
+def _validate_ip_or_wildcard(value: str) -> None:
+ v = (value or "").strip()
+ if not v or not _IP_FILTER_RE.match(v):
+ raise serializers.ValidationError(
+ "Invalid IP address format. Use a valid IPv4/IPv6 address or a wildcard like `203.0.113.*`."
+ )
+ if "*" in v:
+ return # wildcard patterns are accepted as-is
+ if _IPV4_RE.match(v):
+ if not all(int(octet) <= 255 for octet in v.split(".")):
+ raise serializers.ValidationError(
+ "Invalid IP address format. Use a valid IPv4/IPv6 address or a wildcard like `203.0.113.*`."
+ )
+ return
+ if ":" not in v:
+ raise serializers.ValidationError(
+ "Invalid IP address format. Use a valid IPv4/IPv6 address or a wildcard like `203.0.113.*`."
+ )
+
+
class AdvancedActivityLogFiltersSerializer(serializers.Serializer):
start_date = serializers.DateTimeField(
required=False,
@@ -243,6 +268,15 @@ class AdvancedActivityLogFiltersSerializer(serializers.Serializer):
default=[],
help_text="Filter by API clients that generated the activity (from x-posthog-client header).",
)
+ ip_addresses = serializers.ListField(
+ child=serializers.CharField(validators=[_validate_ip_or_wildcard]),
+ required=False,
+ default=[],
+ help_text=(
+ "Filter by client IP addresses. Accepts exact IPv4/IPv6 values or wildcard patterns "
+ "using `*` (e.g. `203.0.113.*`). Multiple entries are OR-combined."
+ ),
+ )
team_ids = serializers.ListField(
child=serializers.IntegerField(),
required=False,
@@ -319,6 +353,7 @@ class ActivityLogFlatExportSerializer(serializers.ModelSerializer):
"item_id",
"detail",
"client",
+ "ip_address",
"created_at",
]
diff --git a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
index ce69554a0439..42869ca7ee43 100644
--- a/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
+++ b/posthog/api/test/notebooks/__snapshots__/test_notebook.ambr
@@ -1460,6 +1460,7 @@
"posthog_activitylog"."was_impersonated",
"posthog_activitylog"."is_system",
"posthog_activitylog"."client",
+ "posthog_activitylog"."ip_address",
"posthog_activitylog"."activity",
"posthog_activitylog"."item_id",
"posthog_activitylog"."scope",
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index a09e4c543a7a..e65cf42136b8 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -440,6 +440,7 @@ def team_api_test_factory():
},
"client": None,
"created_at": ANY,
+ "ip_address": None,
},
{
"_state": ANY,
@@ -462,6 +463,7 @@ def team_api_test_factory():
"user_id": self.user.pk,
"was_impersonated": False,
"client": None,
+ "ip_address": "127.0.0.1",
},
]
if self.client_class is EnvironmentToProjectRewriteClient:
@@ -488,6 +490,7 @@ def team_api_test_factory():
"user_id": self.user.pk,
"was_impersonated": False,
"client": None,
+ "ip_address": "127.0.0.1",
},
)
assert activity == expected_activity
diff --git a/posthog/middleware.py b/posthog/middleware.py
index d637068d1e13..84730e7fba6c 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -50,7 +50,7 @@ from posthog.models.utils import generate_random_token
from posthog.rbac.user_access_control import UserAccessControl
from posthog.settings import PROJECT_SWITCHING_TOKEN_ALLOWLIST, SITE_URL
from posthog.user_permissions import UserPermissions
-from posthog.utils import _is_valid_ip_address
+from posthog.utils import _is_valid_ip_address, get_ip_address
from products.actions.backend.models.action import Action
from products.dashboards.backend.models.dashboard import Dashboard
@@ -972,6 +972,8 @@ class ActivityLoggingMiddleware:
if client_header:
activity_storage.set_client(client_header[:ACTIVITY_LOG_CLIENT_MAX_LENGTH])
+ activity_storage.set_ip_address(get_ip_address(request) or None)
+
try:
response = self.get_response(request)
finally:
diff --git a/posthog/migrations/1186_activitylog_ip_address.py b/posthog/migrations/1186_activitylog_ip_address.py
new file mode 100644
index 000000000000..be18238273a5
--- /dev/null
+++ b/posthog/migrations/1186_activitylog_ip_address.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1185_fix_non_list_test_account_filters"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="activitylog",
+ name="ip_address",
+ field=models.GenericIPAddressField(blank=True, null=True),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index fd0c44b6e724..555d8b7f07cf 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1185_fix_non_list_test_account_filters
+1186_activitylog_ip_address
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index bcc2c73a765c..977151b10436 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -198,6 +198,8 @@ class ActivityLog(UUIDTModel):
is_system = models.BooleanField(null=True)
# Value of the x-posthog-client request header captured when the activity was logged
client = models.CharField(max_length=ACTIVITY_LOG_CLIENT_MAX_LENGTH, null=True, blank=True)
+ # Client IP captured at request time. Null for non-HTTP activity (system, Celery).
+ ip_address = models.GenericIPAddressField(null=True, blank=True)
activity = models.fields.CharField(max_length=79, null=False)
# if scoped to a model this activity log holds the id of the model being logged
@@ -833,11 +835,14 @@ def log_activity(
detail: Detail,
was_impersonated: bool,
client: Optional[str] = None,
+ ip_address: Optional[str] = None,
force_save: bool = False,
instance_only: bool = False,
) -> ActivityLog | None:
if client is None:
client = activity_storage.get_client()
+ if ip_address is None:
+ ip_address = activity_storage.get_ip_address()
if was_impersonated and user is None:
logger.warn(
"activity_log.failed_to_write_to_activity_log",
@@ -871,6 +876,7 @@ def log_activity(
activity=activity,
detail=detail,
client=client,
+ ip_address=ip_address,
)
def _do_log_activity():
@@ -886,6 +892,7 @@ def log_activity(
activity=log.activity,
detail=log.detail,
client=log.client,
+ ip_address=log.ip_address,
)
if instance_only:
@@ -926,6 +933,7 @@ class LogActivityEntry(TypedDict, total=False):
detail: Required[Detail]
was_impersonated: Required[bool]
client: Optional[str]
+ ip_address: Optional[str]
force_save: bool
diff --git a/posthog/models/activity_logging/utils.py b/posthog/models/activity_logging/utils.py
index 073b477ca9f2..1aeffface4a7 100644
--- a/posthog/models/activity_logging/utils.py
+++ b/posthog/models/activity_logging/utils.py
@@ -54,10 +54,21 @@ class ActivityLoggingStorage:
if hasattr(self._local, "client"):
delattr(self._local, "client")
+ def set_ip_address(self, ip_address: Optional[str]) -> None:
+ self._local.ip_address = ip_address
+
+ def get_ip_address(self) -> Optional[str]:
+ return getattr(self._local, "ip_address", None)
+
+ def clear_ip_address(self) -> None:
+ if hasattr(self._local, "ip_address"):
+ delattr(self._local, "ip_address")
+
def clear_all(self) -> None:
self.clear_user()
self.clear_was_impersonated()
self.clear_client()
+ self.clear_ip_address()
activity_storage = ActivityLoggingStorage()
diff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.py
index e9657c2574b2..d1a23c4e7d42 100644
--- a/posthog/test/activity_logging/test_activity_logging.py
+++ b/posthog/test/activity_logging/test_activity_logging.py
@@ -108,6 +108,59 @@ class TestActivityLogModel(BaseTest):
log: ActivityLog = ActivityLog.objects.latest("id")
self.assertIsNone(log.client)
+ def test_ip_address_is_populated_from_activity_storage(self) -> None:
+ activity_storage.set_ip_address("203.0.113.42")
+ try:
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id=10,
+ scope="FeatureFlag",
+ activity="created",
+ detail=Detail(),
+ )
+ finally:
+ activity_storage.clear_ip_address()
+
+ log: ActivityLog = ActivityLog.objects.latest("id")
+ self.assertEqual(log.ip_address, "203.0.113.42")
+
+ def test_explicit_ip_address_overrides_storage(self) -> None:
+ activity_storage.set_ip_address("10.0.0.1")
+ try:
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id=11,
+ scope="FeatureFlag",
+ activity="created",
+ detail=Detail(),
+ ip_address="198.51.100.7",
+ )
+ finally:
+ activity_storage.clear_ip_address()
+
+ log: ActivityLog = ActivityLog.objects.latest("id")
+ self.assertEqual(log.ip_address, "198.51.100.7")
+
+ def test_ip_address_defaults_to_none_when_unset(self) -> None:
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=self.user,
+ was_impersonated=False,
+ item_id=12,
+ scope="FeatureFlag",
+ activity="created",
+ detail=Detail(),
+ )
+ log: ActivityLog = ActivityLog.objects.latest("id")
+ self.assertIsNone(log.ip_address)
+
def test_does_not_save_impersonated_activity_without_user(self) -> None:
log_activity(
organization_id=self.organization.id,
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 7914f0f1d72c..d901ded837fc 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -1695,6 +1695,7 @@ class TestActivityLoggingMiddleware(APIBaseTest):
def get_response(request):
self.captured["client"] = activity_storage.get_client()
self.captured["user"] = activity_storage.get_user()
+ self.captured["ip_address"] = activity_storage.get_ip_address()
from django.http import HttpResponse
return HttpResponse()
@@ -1724,6 +1725,31 @@ class TestActivityLoggingMiddleware(APIBaseTest):
self.middleware(request)
self.assertEqual(self.captured["client"], "x" * ACTIVITY_LOG_CLIENT_MAX_LENGTH)
+ def test_captures_ip_address_from_remote_addr(self):
+ request = self.factory.get("/", REMOTE_ADDR="203.0.113.42")
+ request.user = self.user
+ self.middleware(request)
+ self.assertEqual(self.captured["ip_address"], "203.0.113.42")
+ # Storage is cleared after the request finishes
+ self.assertIsNone(self.activity_storage.get_ip_address())
+
+ def test_captures_ip_address_from_x_forwarded_for(self):
+ request = self.factory.get(
+ "/",
+ HTTP_X_FORWARDED_FOR="198.51.100.7, 10.0.0.1",
+ REMOTE_ADDR="10.0.0.1",
+ )
+ request.user = self.user
+ self.middleware(request)
+ # leftmost XFF entry wins
+ self.assertEqual(self.captured["ip_address"], "198.51.100.7")
+
+ def test_invalid_ip_stored_as_none(self):
+ request = self.factory.get("/", REMOTE_ADDR="not-an-ip")
+ request.user = self.user
+ self.middleware(request)
+ self.assertIsNone(self.captured["ip_address"])
+
class TestCSPMiddleware(APIBaseTest):
def test_non_html_response_gets_strict_csp(self):
diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.ts
index 1d549bc7418e..2d49a2c28c21 100644
--- a/products/platform_features/frontend/generated/api.schemas.ts
+++ b/products/platform_features/frontend/generated/api.schemas.ts
@@ -586,6 +586,8 @@ export interface ActivityLogApi {
* @nullable
*/
client?: string | null
+ /** @nullable */
+ ip_address?: string | null
/** @maxLength 79 */
activity: string
/**
@@ -1149,6 +1151,10 @@ export type AdvancedActivityLogsListParams = {
* Reserved for future HogQL-based filtering.
*/
hogql_filter?: string
+ /**
+ * Filter by client IP addresses. Accepts exact IPv4/IPv6 values or wildcard patterns using `*` (e.g. `203.0.113.*`). Multiple entries are OR-combined.
+ */
+ ip_addresses?: string[]
/**
* When set, filters rows authored by the system (no user).
* @nullable
diff --git a/products/platform_features/frontend/generated/api.zod.ts b/products/platform_features/frontend/generated/api.zod.ts
index 818b49eabd1f..19cd6f914ea1 100644
--- a/products/platform_features/frontend/generated/api.zod.ts
+++ b/products/platform_features/frontend/generated/api.zod.ts
@@ -253,6 +253,7 @@ export const AdvancedActivityLogsExportCreateBody = /* @__PURE__ */ zod.object({
was_impersonated: zod.boolean().nullish(),
is_system: zod.boolean().nullish(),
client: zod.string().max(advancedActivityLogsExportCreateBodyClientMax).nullish(),
+ ip_address: zod.string().nullish(),
activity: zod.string().max(advancedActivityLogsExportCreateBodyActivityMax),
item_id: zod.string().max(advancedActivityLogsExportCreateBodyItemIdMax).nullish(),
scope: zod.string().max(advancedActivityLogsExportCreateBodyScopeMax),
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 5fc281cee302..5f15ba557346 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -1325,6 +1325,8 @@ export namespace Schemas {
* @nullable
*/
client?: string | null;
+ /** @nullable */
+ ip_address?: string | null;
/** @maxLength 79 */
activity: string;
/**
@@ -42307,6 +42309,10 @@ export namespace Schemas {
* Reserved for future HogQL-based filtering.
*/
hogql_filter?: string;
+ /**
+ * Filter by client IP addresses. Accepts exact IPv4/IPv6 values or wildcard patterns using `*` (e.g. `203.0.113.*`). Multiple entries are OR-combined.
+ */
+ ip_addresses?: string[];
/**
* When set, filters rows authored by the system (no user).
* @nullable
@@ -42965,6 +42971,10 @@ export namespace Schemas {
* Reserved for future HogQL-based filtering.
*/
hogql_filter?: string;
+ /**
+ * Filter by client IP addresses. Accepts exact IPv4/IPv6 values or wildcard patterns using `*` (e.g. `203.0.113.*`). Multiple entries are OR-combined.
+ */
+ ip_addresses?: string[];
/**
* When set, filters rows authored by the system (no user).
* @nullable
diff --git a/services/mcp/src/generated/platform_features/api.ts b/services/mcp/src/generated/platform_features/api.ts
index cb736d3231d4..6193fd947e7e 100644
--- a/services/mcp/src/generated/platform_features/api.ts
+++ b/services/mcp/src/generated/platform_features/api.ts
@@ -301,6 +301,7 @@ export const AdvancedActivityLogsListParams = /* @__PURE__ */ zod.object({
export const advancedActivityLogsListQueryActivitiesDefault = []
export const advancedActivityLogsListQueryClientsDefault = []
+export const advancedActivityLogsListQueryIpAddressesDefault = []
export const advancedActivityLogsListQueryItemIdsDefault = []
export const advancedActivityLogsListQueryPageSizeDefault = 100
export const advancedActivityLogsListQueryPageSizeMax = 1000
@@ -329,6 +330,12 @@ export const AdvancedActivityLogsListQueryParams = /* @__PURE__ */ zod.object({
.optional()
.describe('Upper bound on `created_at` (inclusive), ISO-8601.'),
hogql_filter: zod.string().optional().describe('Reserved for future HogQL-based filtering.'),
+ ip_addresses: zod
+ .array(zod.string())
+ .default(advancedActivityLogsListQueryIpAddressesDefault)
+ .describe(
+ 'Filter by client IP addresses. Accepts exact IPv4/IPv6 values or wildcard patterns using `*` (e.g. `203.0.113.*`). Multiple entries are OR-combined.'
+ ),
is_system: zod.boolean().nullish().describe('When set, filters rows authored by the system (no user).'),
item_ids: zod
.array(zod.string())
diff --git a/services/mcp/src/tools/generated/platform_features.ts b/services/mcp/src/tools/generated/platform_features.ts
index 8f496e8e09d3..e6434bd799c6 100644
--- a/services/mcp/src/tools/generated/platform_features.ts
+++ b/services/mcp/src/tools/generated/platform_features.ts
@@ -117,6 +117,7 @@ const advancedActivityLogsList = (): ToolBase<
detail_filters: params.detail_filters,
end_date: params.end_date,
hogql_filter: params.hogql_filter,
+ ip_addresses: params.ip_addresses,
is_system: params.is_system,
item_ids: params.item_ids,
page: params.page,
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/advanced-activity-logs-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/advanced-activity-logs-list.json
index 49ab0525f185..9164a582bef0 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/common/advanced-activity-logs-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/common/advanced-activity-logs-list.json
@@ -31,6 +31,14 @@
"description": "Reserved for future HogQL-based filtering.",
"type": "string"
},
+ "ip_addresses": {
+ "default": [],
+ "description": "Filter by client IP addresses. Accepts exact IPv4/IPv6 values or wildcard patterns using `*` (e.g. `203.0.113.*`). Multiple entries are OR-combined.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
"is_system": {
"anyOf": [
{