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(aio): verify gateway-relayed OTLP traces (#71936)

Richard Solomouc4a9a4b47a05
diff --git a/docs/onboarding/ai-observability/convex.tsx b/docs/onboarding/ai-observability/convex.tsx
index 32329c71da5b..ab14ef406201 100644
--- a/docs/onboarding/ai-observability/convex.tsx
+++ b/docs/onboarding/ai-observability/convex.tsx
@@ -18,7 +18,7 @@ export const getConvexSteps = (ctx: OnboardingComponentsContext): StepDefinition
<CodeBlock
language="bash"
code={dedent`
- npm install @posthog/ai @ai-sdk/openai ai @opentelemetry/sdk-trace-base @opentelemetry/resources @opentelemetry/api
+ npm install @posthog/ai @ai-sdk/openai ai @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources @opentelemetry/api
`}
/>
</>
@@ -59,21 +59,21 @@ export const getConvexSteps = (ctx: OnboardingComponentsContext): StepDefinition
content: (
<>
<Markdown>
- Create a Convex action that initializes a `BasicTracerProvider` with PostHog's trace exporter
+ Create a Convex action that initializes a `BasicTracerProvider` with PostHog's span processor
and enables telemetry on your AI SDK calls. The provider is initialized at module scope so it
persists across warm V8 isolate invocations. Await `provider.forceFlush()` before returning
- because Convex may finish the action while the OTLP export is still pending.
+ because Convex may finish the action while the processor's batch is still pending.
</Markdown>
<CodeBlock
language="typescript"
code={dedent`
import { trace } from '@opentelemetry/api'
- import { BasicTracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'
+ import { BasicTracerProvider } from '@opentelemetry/sdk-trace-base'
import { resourceFromAttributes } from '@opentelemetry/resources'
import { generateText } from 'ai'
import { openai } from '@ai-sdk/openai'
- import { PostHogTraceExporter } from '@posthog/ai/otel'
+ import { PostHogSpanProcessor } from '@posthog/ai/otel'
import { action } from './_generated/server'
import { v } from 'convex/values'
@@ -82,12 +82,10 @@ export const getConvexSteps = (ctx: OnboardingComponentsContext): StepDefinition
'service.name': 'my-convex-app',
}),
spanProcessors: [
- new SimpleSpanProcessor(
- new PostHogTraceExporter({
- projectToken: process.env.POSTHOG_PROJECT_TOKEN!,
- host: process.env.POSTHOG_HOST,
- })
- ),
+ new PostHogSpanProcessor({
+ projectToken: process.env.POSTHOG_PROJECT_TOKEN!,
+ host: process.env.POSTHOG_HOST,
+ }),
],
})
trace.setGlobalTracerProvider(provider)
@@ -122,8 +120,9 @@ export const getConvexSteps = (ctx: OnboardingComponentsContext): StepDefinition
<CalloutBox type="fyi" icon="IconInfo" title="How this works">
<Markdown>
- The `PostHogTraceExporter` sends OpenTelemetry `gen_ai.*` spans to PostHog's OTLP ingestion
- endpoint. PostHog converts these into `$ai_generation` events automatically. The
+ The `PostHogSpanProcessor` sends AI-related OpenTelemetry spans to PostHog's OTLP ingestion
+ endpoint. `provider.forceFlush()` ensures its batch is sent before the Convex action
+ returns. PostHog converts these into `$ai_generation` events automatically. The
`posthog_distinct_id` metadata field links events to a specific user.
</Markdown>
</CalloutBox>
@@ -144,11 +143,11 @@ export const getConvexSteps = (ctx: OnboardingComponentsContext): StepDefinition
language="typescript"
code={dedent`
import { trace } from '@opentelemetry/api'
- import { BasicTracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'
+ import { BasicTracerProvider } from '@opentelemetry/sdk-trace-base'
import { resourceFromAttributes } from '@opentelemetry/resources'
import { Agent } from '@convex-dev/agent'
import { openai } from '@ai-sdk/openai'
- import { PostHogTraceExporter } from '@posthog/ai/otel'
+ import { PostHogSpanProcessor } from '@posthog/ai/otel'
import { components } from './_generated/api'
import { action } from './_generated/server'
import { v } from 'convex/values'
@@ -158,12 +157,10 @@ export const getConvexSteps = (ctx: OnboardingComponentsContext): StepDefinition
'service.name': 'my-convex-app',
}),
spanProcessors: [
- new SimpleSpanProcessor(
- new PostHogTraceExporter({
- projectToken: process.env.POSTHOG_PROJECT_TOKEN!,
- host: process.env.POSTHOG_HOST,
- })
- ),
+ new PostHogSpanProcessor({
+ projectToken: process.env.POSTHOG_PROJECT_TOKEN!,
+ host: process.env.POSTHOG_HOST,
+ }),
],
})
trace.setGlobalTracerProvider(provider)
diff --git a/posthog/tasks/test/__snapshots__/test_usage_report.ambr b/posthog/tasks/test/__snapshots__/test_usage_report.ambr
index 05a6ff89da32..d675781bbd37 100644
--- a/posthog/tasks/test/__snapshots__/test_usage_report.ambr
+++ b/posthog/tasks/test/__snapshots__/test_usage_report.ambr
@@ -1491,12 +1491,16 @@
SELECT team_id,
COUNT() - uniqExactIf(request_id, verified
- AND request_id != '') as count
+ AND NOT relay
+ AND request_id != '') AS count,
+ max(relay) AS has_verified_relay
FROM
(SELECT team_id,
replaceRegexpAll(JSONExtractRaw(properties, '$ai_gateway_verified'), '^"|"$', '') IN ('true',
- '1') as verified,
- if(verified, replaceRegexpAll(JSONExtractRaw(properties, '$ai_gateway_request_id'), '^"|"$', ''), '') as request_id
+ '1') AS verified,
+ if(verified, replaceRegexpAll(JSONExtractRaw(properties, '$ai_gateway_request_id'), '^"|"$', ''), '') AS request_id,
+ if(verified, replaceRegexpAll(JSONExtractRaw(properties, '$ai_gateway_relay'), '^"|"$', ''), '') IN ('true',
+ '1') AS relay
FROM events
WHERE event IN ['$ai_generation', '$ai_embedding', '$ai_span', '$ai_trace', '$ai_metric', '$ai_feedback', '$ai_evaluation', '$ai_tag', '$ai_trace_summary', '$ai_generation_summary', '$ai_trace_clusters', '$ai_generation_clusters']
AND timestamp >= '2022-01-10 00:00:00'
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index a060c1e6ec98..c9413171b013 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -1475,6 +1475,7 @@ class TestQueryUsageReportSQL:
assert params["end"] == end
assert params["event_time_end"] == end + timedelta(hours=6)
+ @patch("posthog.tasks.usage_report.use_new_events_schema", return_value=False)
@patch("posthog.tasks.usage_report._execute_split_query")
@patch("posthog.tasks.usage_report.sync_execute", return_value=[(1, 4)])
@patch("posthog.tasks.usage_report.get_property_string_expr")
@@ -1483,6 +1484,7 @@ class TestQueryUsageReportSQL:
mock_get_property_string_expr: MagicMock,
mock_sync_execute: MagicMock,
mock_execute_split_query: MagicMock,
+ _mock_use_new_events_schema: MagicMock,
) -> None:
mock_get_property_string_expr.side_effect = [("lib_expr", True), ("ai_lib_expr", True)]
# 1st _execute_split_query call is the main per-$lib scan (node_events over-counts every
@@ -1526,8 +1528,17 @@ class TestQueryUsageReportSQL:
assert result["openclaw_events"] == [(1, 3)]
assert result["node_events"] == [(1, 5)]
+ @patch("posthog.tasks.usage_report.events_read_table", return_value="events")
+ @patch("posthog.tasks.usage_report.get_property_string_expr", return_value=("property_expr", {}))
+ @patch("posthog.tasks.usage_report.use_new_events_schema", return_value=False)
@patch("posthog.tasks.usage_report.sync_execute", return_value=[])
- def test_get_teams_with_ai_event_count_excludes_conversations_loaded(self, mock_sync_execute: MagicMock) -> None:
+ def test_get_teams_with_ai_event_count_excludes_conversations_loaded(
+ self,
+ mock_sync_execute: MagicMock,
+ _mock_use_new_events_schema: MagicMock,
+ _mock_get_property_string_expr: MagicMock,
+ _mock_events_read_table: MagicMock,
+ ) -> None:
from posthog.tasks.usage_report import get_teams_with_ai_event_count_in_period
begin = datetime(2026, 6, 15, tzinfo=tzutc())
@@ -1539,6 +1550,87 @@ class TestQueryUsageReportSQL:
assert "$conversations_loaded" not in params["ai_events"]
assert "$conversations_widget_loaded" not in params["ai_events"]
+ @patch("posthog.tasks.usage_report.events_read_table", return_value="events")
+ @patch("posthog.tasks.usage_report.get_property_string_expr", return_value=("property_expr", {}))
+ @patch("posthog.tasks.usage_report.use_new_events_schema", return_value=False)
+ @patch("posthog.tasks.usage_report.sync_execute")
+ def test_get_teams_with_ai_event_count_skips_sponsorship_query_without_verified_relays(
+ self,
+ mock_sync_execute: MagicMock,
+ _mock_use_new_events_schema: MagicMock,
+ _mock_get_property_string_expr: MagicMock,
+ _mock_events_read_table: MagicMock,
+ ) -> None:
+ from posthog.tasks.usage_report import get_teams_with_ai_event_count_in_period
+
+ begin = datetime(2026, 6, 15, tzinfo=tzutc())
+ end = begin + timedelta(days=1)
+ mock_sync_execute.return_value = [(1, 150, 0), (2, 20, 0)]
+
+ result = get_teams_with_ai_event_count_in_period(begin, end)
+
+ assert result == [(1, 150), (2, 20)]
+ mock_sync_execute.assert_called_once()
+ base_query = mock_sync_execute.call_args.args[0]
+ assert "if(verified, property_expr, '') IN ('true', '1') AS relay" in base_query
+ assert "max(relay) AS has_verified_relay" in base_query
+
+ @patch("posthog.tasks.usage_report.events_read_table", return_value="events")
+ @patch("posthog.tasks.usage_report.get_property_string_expr", return_value=("property_expr", {}))
+ @patch("posthog.tasks.usage_report.use_new_events_schema", return_value=False)
+ @patch("posthog.tasks.usage_report.sync_execute")
+ def test_get_teams_with_ai_event_count_subtracts_bounded_gateway_sponsorship(
+ self,
+ mock_sync_execute: MagicMock,
+ _mock_use_new_events_schema: MagicMock,
+ _mock_get_property_string_expr: MagicMock,
+ _mock_events_read_table: MagicMock,
+ ) -> None:
+ from posthog.tasks.usage_report import (
+ GATEWAY_SPONSORED_EVALUATIONS_PER_TRACE,
+ GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE,
+ GATEWAY_SPONSORSHIP_BACKDATE,
+ GATEWAY_SPONSORSHIP_LOOKAROUND,
+ get_teams_with_ai_event_count_in_period,
+ )
+
+ begin = datetime(2026, 6, 15, tzinfo=tzutc())
+ end = begin + timedelta(days=1)
+ mock_sync_execute.side_effect = [[(1, 150, 1), (2, 20, 0)], [(1, 100)]]
+
+ result = get_teams_with_ai_event_count_in_period(begin, end)
+
+ assert result == [(1, 50), (2, 20)]
+ assert mock_sync_execute.call_count == 2
+ base_query = mock_sync_execute.call_args_list[0].args[0]
+ sponsor_query = mock_sync_execute.call_args_list[1].args[0]
+ sponsor_params = mock_sync_execute.call_args_list[1].args[1]
+ assert "max(relay) AS has_verified_relay" in base_query
+ assert "argMin(raw_trace_id, (raw_generation_timestamp, raw_trace_id)) AS trace_id" in sponsor_query
+ assert "GROUP BY team_id, trace_id" in sponsor_query
+ assert "PARTITION BY team_id, trace_id, allowance_kind" in sponsor_query
+ assert "ARRAY JOIN [0, 1] AS allowance_kind" in sponsor_query
+ assert "if(event = '$ai_evaluation', 1, 0) AS allowance_kind" in sponsor_query
+ assert "sponsor_timestamp - toIntervalSecond(%(backdate_seconds)s)" in sponsor_query
+ assert (
+ "if(\n allowance_kind = 0,\n sponsor_timestamp"
+ not in sponsor_query
+ )
+ assert sponsor_query.count("AND property_expr IN ('true', '1')") >= 3
+ assert "AND property_expr NOT IN ('true', '1')" in sponsor_query
+ assert "sum(balance_delta) OVER" in sponsor_query
+ assert "min(cumulative_balance) OVER" in sponsor_query
+ assert "cumulative_balance >= least(ifNull(previous_minimum, 0), 0)" in sponsor_query
+ assert "UNION ALL" in sponsor_query
+ assert sponsor_query.count("team_id IN %(relayed_team_ids)s") == 2
+ assert sponsor_params["trace_allowance"] == GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE
+ assert sponsor_params["evaluation_allowance"] == GATEWAY_SPONSORED_EVALUATIONS_PER_TRACE
+ assert sponsor_params["backdate_seconds"] == int(GATEWAY_SPONSORSHIP_BACKDATE.total_seconds())
+ assert sponsor_params["relayed_team_ids"] == [1]
+ assert sponsor_params["sponsor_begin"] == begin - GATEWAY_SPONSORSHIP_LOOKAROUND
+ assert sponsor_params["relay_begin"] == begin - GATEWAY_SPONSORSHIP_LOOKAROUND - GATEWAY_SPONSORSHIP_BACKDATE
+ assert sponsor_params["sponsor_end"] == end + GATEWAY_SPONSORSHIP_LOOKAROUND
+
@freeze_time("2022-01-10T00:01:00Z")
class TestFeatureFlagsUsageReport(ClickhouseDestroyTablesMixin, TestCase, ClickhouseTestMixin):
@@ -5960,6 +6052,441 @@ class TestQuerySplitting(ClickhouseDestroyTablesMixin, ClickhouseTestMixin, Test
"verified events with no request_id are not blanket-deduped; both stay counted",
)
+ def test_gateway_generation_sponsors_bounded_unique_relay_events(self) -> None:
+ from posthog.tasks.usage_report import (
+ GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE,
+ get_teams_with_ai_event_count_in_period,
+ )
+
+ def ai_count() -> int:
+ return dict(get_teams_with_ai_event_count_in_period(self.begin, self.end)).get(self.team.id, 0)
+
+ baseline_count = ai_count()
+ trace_id = "sponsored-trace"
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin - relativedelta(hours=1),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_request_id": "gateway-request",
+ "$ai_trace_id": trace_id,
+ },
+ )
+ for request_id in ("gateway-request-2", "gateway-request-2"):
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin - relativedelta(minutes=30),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_request_id": request_id,
+ "$ai_trace_id": trace_id,
+ },
+ )
+ for index in range(GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE + 1):
+ _create_event(
+ event="$ai_span",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin + relativedelta(hours=1),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_relay": True,
+ "$ai_gateway_request_id": f"relay-request-{index}",
+ "$ai_trace_id": trace_id,
+ "$ai_span_id": f"span-{index}",
+ },
+ )
+ for _ in range(2):
+ _create_event(
+ event="$ai_span",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin + relativedelta(hours=2),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_relay": True,
+ "$ai_gateway_request_id": "relay-request-0",
+ "$ai_trace_id": trace_id,
+ "$ai_span_id": "span-0",
+ },
+ )
+ _create_event(
+ event="$ai_span",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin + relativedelta(hours=3),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_relay": True,
+ "$ai_gateway_request_id": "unsponsored-relay-request",
+ "$ai_trace_id": "unsponsored-trace",
+ "$ai_span_id": "unsponsored-span",
+ },
+ )
+ flush_persons_and_events()
+
+ self.assertEqual(
+ ai_count(),
+ baseline_count + 4,
+ "one overage, two span replays, and one unmatched span stay billable",
+ )
+
+ def test_gateway_sponsorship_allowance_is_shared_across_adjacent_periods(self) -> None:
+ from posthog.tasks.usage_report import (
+ GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE,
+ get_teams_with_ai_event_count_in_period,
+ )
+
+ previous_begin = self.begin - relativedelta(days=1)
+
+ def ai_count(begin: datetime, end: datetime) -> int:
+ return dict(get_teams_with_ai_event_count_in_period(begin, end)).get(self.team.id, 0)
+
+ previous_baseline = ai_count(previous_begin, self.begin)
+ current_baseline = ai_count(self.begin, self.end)
+ trace_id = "cross-period-sponsored-trace"
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin - relativedelta(hours=2),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_request_id": "cross-period-request",
+ "$ai_trace_id": trace_id,
+ },
+ )
+ for index in range(GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE):
+ for timestamp in (
+ self.begin - relativedelta(hours=1),
+ self.begin + relativedelta(hours=1),
+ ):
+ _create_event(
+ event="$ai_span",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=timestamp,
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_relay": True,
+ "$ai_trace_id": trace_id,
+ "$ai_span_id": f"{timestamp.isoformat()}-{index}",
+ },
+ )
+ flush_persons_and_events()
+
+ self.assertEqual(ai_count(previous_begin, self.begin), previous_baseline)
+ self.assertEqual(
+ ai_count(self.begin, self.end),
+ current_baseline + GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE,
+ )
+
+ def test_gateway_request_sponsors_only_one_trace(self) -> None:
+ from posthog.tasks.usage_report import get_teams_with_ai_event_count_in_period
+
+ def ai_count() -> int:
+ return dict(get_teams_with_ai_event_count_in_period(self.begin, self.end)).get(self.team.id, 0)
+
+ baseline_count = ai_count()
+ for trace_id in ("first-trace", "second-trace"):
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin + relativedelta(hours=1),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_request_id": "replayed-request",
+ "$ai_trace_id": trace_id,
+ },
+ )
+ _create_event(
+ event="$ai_span",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin + relativedelta(hours=2),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_relay": True,
+ "$ai_trace_id": trace_id,
+ "$ai_span_id": f"{trace_id}-span",
+ },
+ )
+ flush_persons_and_events()
+
+ self.assertEqual(ai_count(), baseline_count + 2, "one generation replay and one unmatched span stay billable")
+
+ def test_gateway_sponsorship_is_isolated_by_team(self) -> None:
+ from posthog.tasks.usage_report import get_teams_with_ai_event_count_in_period
+
+ other_team = Team.objects.create(organization=self.team.organization, name="Other gateway team")
+ baseline_counts = dict(get_teams_with_ai_event_count_in_period(self.begin, self.end))
+ trace_id = "shared-across-teams"
+ for team, request_id in ((self.team, "first-request"), (other_team, "second-request")):
+ _create_event(
+ event="$ai_generation",
+ team=team,
+ distinct_id="gateway-user",
+ timestamp=self.begin + relativedelta(hours=1),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_request_id": request_id,
+ "$ai_trace_id": trace_id,
+ },
+ )
+ _create_event(
+ event="$ai_span",
+ team=team,
+ distinct_id="gateway-user",
+ timestamp=self.begin + relativedelta(hours=2),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_relay": True,
+ "$ai_trace_id": trace_id,
+ "$ai_span_id": "shared-span-id",
+ },
+ )
+ flush_persons_and_events()
+
+ counts = dict(get_teams_with_ai_event_count_in_period(self.begin, self.end))
+ self.assertEqual(counts.get(self.team.id, 0), baseline_counts.get(self.team.id, 0))
+ self.assertEqual(counts.get(other_team.id, 0), baseline_counts.get(other_team.id, 0))
+
+ def test_gateway_generation_does_not_sponsor_earlier_relay(self) -> None:
+ from posthog.tasks.usage_report import get_teams_with_ai_event_count_in_period
+
+ def ai_count() -> int:
+ return dict(get_teams_with_ai_event_count_in_period(self.begin, self.end)).get(self.team.id, 0)
+
+ baseline_count = ai_count()
+ trace_id = "future-sponsored-trace"
+ _create_event(
+ event="$ai_span",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin + relativedelta(hours=1),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_relay": True,
+ "$ai_trace_id": trace_id,
+ "$ai_span_id": "early-span",
+ },
+ )
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin + relativedelta(hours=2),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_request_id": "later-request",
+ "$ai_trace_id": trace_id,
+ },
+ )
+ flush_persons_and_events()
+
+ self.assertEqual(ai_count(), baseline_count + 1, "the later generation cannot sponsor the earlier span")
+
+ def test_gateway_generation_sponsors_relay_within_backdate_grace(self) -> None:
+ from posthog.tasks.usage_report import GATEWAY_SPONSORSHIP_BACKDATE, get_teams_with_ai_event_count_in_period
+
+ def ai_count() -> int:
+ return dict(get_teams_with_ai_event_count_in_period(self.begin, self.end)).get(self.team.id, 0)
+
+ baseline_count = ai_count()
+ trace_id = "backdated-sponsored-trace"
+ generation_timestamp = self.begin + relativedelta(hours=2)
+ _create_event(
+ event="$ai_span",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=generation_timestamp - GATEWAY_SPONSORSHIP_BACKDATE,
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_relay": True,
+ "$ai_trace_id": trace_id,
+ "$ai_span_id": "provider-parent-span",
+ },
+ )
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=generation_timestamp,
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_request_id": "completed-request",
+ "$ai_trace_id": trace_id,
+ },
+ )
+ flush_persons_and_events()
+
+ self.assertEqual(ai_count(), baseline_count, "provider-latency backdating keeps the parent span free")
+
+ def test_gateway_sponsorship_counts_grace_relay_before_lookaround(self) -> None:
+ from posthog.tasks.usage_report import (
+ GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE,
+ GATEWAY_SPONSORSHIP_BACKDATE,
+ GATEWAY_SPONSORSHIP_LOOKAROUND,
+ get_teams_with_ai_event_count_in_period,
+ )
+
+ def ai_count() -> int:
+ return dict(get_teams_with_ai_event_count_in_period(self.begin, self.end)).get(self.team.id, 0)
+
+ baseline_count = ai_count()
+ trace_id = "lookaround-boundary-trace"
+ sponsor_begin = self.begin - GATEWAY_SPONSORSHIP_LOOKAROUND
+ generation_timestamp = sponsor_begin + relativedelta(minutes=1)
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=generation_timestamp,
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_request_id": "lookaround-boundary-request",
+ "$ai_trace_id": trace_id,
+ },
+ )
+ _create_event(
+ event="$ai_span",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=generation_timestamp - GATEWAY_SPONSORSHIP_BACKDATE,
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_relay": True,
+ "$ai_trace_id": trace_id,
+ "$ai_span_id": "grace-window-span",
+ },
+ )
+ for index in range(GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE):
+ _create_event(
+ event="$ai_span",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin + relativedelta(hours=1),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_relay": True,
+ "$ai_trace_id": trace_id,
+ "$ai_span_id": f"period-span-{index}",
+ },
+ )
+ flush_persons_and_events()
+
+ self.assertEqual(ai_count(), baseline_count + 1, "the grace-window span consumes one trace allowance")
+
+ def test_gateway_sponsorship_has_independent_trace_and_evaluation_allowances(self) -> None:
+ from posthog.tasks.usage_report import (
+ GATEWAY_SPONSORED_EVALUATIONS_PER_TRACE,
+ GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE,
+ get_teams_with_ai_event_count_in_period,
+ )
+
+ def ai_count() -> int:
+ return dict(get_teams_with_ai_event_count_in_period(self.begin, self.end)).get(self.team.id, 0)
+
+ baseline_count = ai_count()
+ trace_id = "independent-allowance-trace"
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin + relativedelta(hours=1),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_request_id": "allowance-request",
+ "$ai_trace_id": trace_id,
+ },
+ )
+ for event, limit in (
+ ("$ai_span", GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE),
+ ("$ai_evaluation", GATEWAY_SPONSORED_EVALUATIONS_PER_TRACE),
+ ):
+ for index in range(limit + 1):
+ _create_event(
+ event=event,
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=self.begin + relativedelta(hours=2),
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_relay": True,
+ "$ai_trace_id": trace_id,
+ "$ai_span_id": f"{event}-{index}",
+ },
+ )
+ flush_persons_and_events()
+
+ self.assertEqual(ai_count(), baseline_count + 2, "each RFC allowance has one billable overage")
+
+ def test_gateway_sponsorship_does_not_carry_relay_debt_forward(self) -> None:
+ from posthog.tasks.usage_report import (
+ GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE,
+ get_teams_with_ai_event_count_in_period,
+ )
+
+ def ai_count() -> int:
+ return dict(get_teams_with_ai_event_count_in_period(self.begin, self.end)).get(self.team.id, 0)
+
+ baseline_count = ai_count()
+ trace_id = "chronological-sponsored-trace"
+
+ def create_generation(request_id: str, timestamp: datetime) -> None:
+ _create_event(
+ event="$ai_generation",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=timestamp,
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_request_id": request_id,
+ "$ai_trace_id": trace_id,
+ },
+ )
+
+ def create_relays(prefix: str, count: int, timestamp: datetime) -> None:
+ for index in range(count):
+ _create_event(
+ event="$ai_span",
+ team=self.team,
+ distinct_id="gateway-user",
+ timestamp=timestamp,
+ properties={
+ "$ai_gateway_verified": True,
+ "$ai_gateway_relay": True,
+ "$ai_trace_id": trace_id,
+ "$ai_span_id": f"{prefix}-{index}",
+ },
+ )
+
+ create_relays("before-sponsor", 1, self.begin + relativedelta(minutes=30))
+ create_generation("first-request", self.begin + relativedelta(hours=1))
+ create_relays(
+ "first-allowance",
+ GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE + 1,
+ self.begin + relativedelta(hours=2),
+ )
+ create_generation("second-request", self.begin + relativedelta(hours=3))
+ create_relays(
+ "second-allowance",
+ GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE,
+ self.begin + relativedelta(hours=4),
+ )
+ flush_persons_and_events()
+
+ self.assertEqual(
+ ai_count(),
+ baseline_count + GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE + 2,
+ "a later generation does not replenish the per-trace allowance",
+ )
+
def test_conversations_events_excluded_from_billable_count(self) -> None:
"""Test that Conversations widget events are excluded from billable event counts."""
from posthog.tasks.usage_report import get_teams_with_billable_event_count_in_period
diff --git a/posthog/tasks/usage_report.py b/posthog/tasks/usage_report.py
index 6ef6de695236..3f0ed700de9c 100644
--- a/posthog/tasks/usage_report.py
+++ b/posthog/tasks/usage_report.py
@@ -80,6 +80,12 @@ logging.getLogger(__name__).setLevel(logging.INFO)
# AI events dynamically generated from AIEventType TS enum
# Changes to the AIEventType enum will impact usage reporting
AI_EVENTS = [event.value for event in AIEventType]
+GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE = 20
+GATEWAY_SPONSORED_EVALUATIONS_PER_TRACE = 20
+# Gateway generations are emitted after provider completion. The default gateway
+# provider timeout bounds how far the caller's spans can precede that event.
+GATEWAY_SPONSORSHIP_BACKDATE = timedelta(minutes=5)
+GATEWAY_SPONSORSHIP_LOOKAROUND = timedelta(days=1)
# Conversations widget events (fired client-side by posthog-js on pageload).
# Excluded from billable counts because they're generated by PostHog's own
@@ -109,6 +115,11 @@ CH_BILLING_SETTINGS = {
"max_execution_time": 5 * 60, # 5 minutes
}
+GATEWAY_SPONSORSHIP_QUERY_SETTINGS = {
+ **CH_BILLING_SETTINGS,
+ "max_memory_usage": 4 * 1024 * 1024 * 1024,
+}
+
QUERY_RETRIES = 3
QUERY_RETRY_DELAY = 1
QUERY_RETRY_BACKOFF = 2
@@ -1390,26 +1401,50 @@ def get_teams_with_ai_event_count_in_period(
use_new_events_schema=use_new,
)
+ relay_expr, _ = get_property_string_expr(
+ "events",
+ "$ai_gateway_relay",
+ "'$ai_gateway_relay'",
+ "properties",
+ use_new_events_schema=use_new,
+ )
+ trace_id_expr, _ = get_property_string_expr(
+ "events",
+ "$ai_trace_id",
+ "'$ai_trace_id'",
+ "properties",
+ use_new_events_schema=use_new,
+ )
+ span_id_expr, _ = get_property_string_expr(
+ "events",
+ "$ai_span_id",
+ "'$ai_span_id'",
+ "properties",
+ use_new_events_schema=use_new,
+ )
+
with tags_context(product=Product.LLM_ANALYTICS, feature=Feature.USAGE_REPORT):
# nosemgrep: clickhouse-fstring-param-audit - property document/table expressions are internal fragments
- return sync_execute(
+ base_rows = sync_execute(
f"""
-- Gateway events are wallet-billed, so exempt them: subtract one per distinct
-- verified $ai_gateway_request_id (a replayed signature reuses one id, so it's
-- worth one exemption and the copies stay billable). Both markers are
-- capture-stamped (#64806), not client-settable; a non-empty request_id is
-- required so one without it stays billable.
- -- Perf: extract request_id only for verified rows (normally ≈0), so
- -- non-gateway rows pay just the verified-bool extraction, not a string
- -- extraction each, across the full AI event volume.
+ -- Perf: extract request_id and relay only for verified rows (normally ≈0),
+ -- so non-gateway rows pay just the verified-bool extraction, not string
+ -- extractions across the full AI event volume.
SELECT
team_id,
- COUNT() - uniqExactIf(request_id, verified AND request_id != '') as count
+ COUNT() - uniqExactIf(request_id, verified AND NOT relay AND request_id != '') AS count,
+ max(relay) AS has_verified_relay
FROM (
SELECT
team_id,
- {verified_expr} IN ('true', '1') as verified,
- if(verified, {request_id_expr}, '') as request_id
+ {verified_expr} IN ('true', '1') AS verified,
+ if(verified, {request_id_expr}, '') AS request_id,
+ if(verified, {relay_expr}, '') IN ('true', '1') AS relay
FROM {events_read_table(use_new)}
WHERE event IN %(ai_events)s AND timestamp >= %(begin)s AND timestamp < %(end)s
)
@@ -1421,6 +1456,136 @@ def get_teams_with_ai_event_count_in_period(
ch_user=ClickHouseUser.BILLING,
)
+ base_counts = [(team_id, count) for team_id, count, _ in base_rows]
+ relayed_team_ids = [team_id for team_id, _, has_verified_relay in base_rows if has_verified_relay]
+ if not relayed_team_ids:
+ return base_counts
+
+ # nosemgrep: clickhouse-fstring-param-audit - property document/table expressions are internal fragments
+ sponsored_counts = sync_execute(
+ f"""
+ SELECT
+ team_id,
+ countIf(
+ entry_kind = 1
+ AND ledger_timestamp >= %(begin)s
+ AND ledger_timestamp < %(end)s
+ AND cumulative_balance >= least(ifNull(previous_minimum, 0), 0)
+ ) AS sponsored_count
+ FROM (
+ SELECT
+ *,
+ min(cumulative_balance) OVER (
+ PARTITION BY team_id, trace_id, allowance_kind
+ ORDER BY ledger_timestamp, entry_kind, entry_id
+ ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING
+ ) AS previous_minimum
+ FROM (
+ SELECT
+ *,
+ sum(balance_delta) OVER (
+ PARTITION BY team_id, trace_id, allowance_kind
+ ORDER BY ledger_timestamp, entry_kind, entry_id
+ ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
+ ) AS cumulative_balance
+ FROM (
+ SELECT
+ team_id,
+ trace_id,
+ allowance_kind,
+ sponsor_timestamp - toIntervalSecond(%(backdate_seconds)s) AS ledger_timestamp,
+ 0 AS entry_kind,
+ request_id AS entry_id,
+ if(
+ allowance_kind = 0,
+ toInt64(%(trace_allowance)s),
+ toInt64(%(evaluation_allowance)s)
+ ) AS balance_delta
+ FROM (
+ SELECT
+ team_id,
+ trace_id,
+ min(request_id) AS request_id,
+ min(request_sponsor_timestamp) AS sponsor_timestamp
+ FROM (
+ SELECT
+ team_id,
+ request_id,
+ argMin(raw_trace_id, (raw_generation_timestamp, raw_trace_id)) AS trace_id,
+ min(raw_generation_timestamp) AS request_sponsor_timestamp
+ FROM (
+ SELECT
+ team_id,
+ timestamp AS raw_generation_timestamp,
+ {verified_expr} IN ('true', '1') AS verified,
+ {relay_expr} IN ('true', '1') AS relay,
+ if(verified AND NOT relay, {trace_id_expr}, '') AS raw_trace_id,
+ if(verified AND NOT relay, {request_id_expr}, '') AS request_id
+ FROM {events_read_table(use_new)}
+ WHERE team_id IN %(relayed_team_ids)s
+ AND event = '$ai_generation'
+ AND timestamp >= %(sponsor_begin)s AND timestamp < %(sponsor_end)s
+ AND {verified_expr} IN ('true', '1')
+ AND {relay_expr} NOT IN ('true', '1')
+ )
+ WHERE verified AND NOT relay AND raw_trace_id != '' AND request_id != ''
+ GROUP BY team_id, request_id
+ )
+ GROUP BY team_id, trace_id
+ )
+ ARRAY JOIN [0, 1] AS allowance_kind
+ UNION ALL
+ SELECT
+ team_id,
+ trace_id,
+ if(event = '$ai_evaluation', 1, 0) AS allowance_kind,
+ relay_timestamp AS ledger_timestamp,
+ 1 AS entry_kind,
+ concat(event, '\\0', span_id) AS entry_id,
+ toInt64(-1) AS balance_delta
+ FROM (
+ SELECT
+ team_id,
+ event,
+ min(timestamp) AS relay_timestamp,
+ {verified_expr} IN ('true', '1') AS verified,
+ {relay_expr} IN ('true', '1') AS relay,
+ if(verified AND relay, {trace_id_expr}, '') AS trace_id,
+ if(verified AND relay, {span_id_expr}, '') AS span_id
+ FROM {events_read_table(use_new)}
+ WHERE team_id IN %(relayed_team_ids)s
+ AND event IN %(ai_events)s
+ AND timestamp >= %(relay_begin)s AND timestamp < %(sponsor_end)s
+ AND {verified_expr} IN ('true', '1')
+ AND {relay_expr} IN ('true', '1')
+ GROUP BY team_id, event, verified, relay, trace_id, span_id
+ )
+ WHERE verified AND relay AND trace_id != '' AND span_id != ''
+ )
+ )
+ )
+ GROUP BY team_id
+ """,
+ {
+ "trace_allowance": GATEWAY_SPONSORED_TRACE_EVENTS_PER_TRACE,
+ "evaluation_allowance": GATEWAY_SPONSORED_EVALUATIONS_PER_TRACE,
+ "backdate_seconds": int(GATEWAY_SPONSORSHIP_BACKDATE.total_seconds()),
+ "relayed_team_ids": relayed_team_ids,
+ "ai_events": AI_EVENTS,
+ "begin": begin,
+ "end": end,
+ "sponsor_begin": begin - GATEWAY_SPONSORSHIP_LOOKAROUND,
+ "relay_begin": begin - GATEWAY_SPONSORSHIP_LOOKAROUND - GATEWAY_SPONSORSHIP_BACKDATE,
+ "sponsor_end": end + GATEWAY_SPONSORSHIP_LOOKAROUND,
+ },
+ workload=Workload.OFFLINE,
+ settings=GATEWAY_SPONSORSHIP_QUERY_SETTINGS,
+ ch_user=ClickHouseUser.BILLING,
+ )
+
+ sponsored_by_team = dict(sponsored_counts)
+ return [(team_id, max(0, count - sponsored_by_team.get(team_id, 0))) for team_id, count in base_counts]
+
# AI billing markup: 20% markup on top of cost
AI_COST_MARKUP_PERCENT = 0.2
diff --git a/rust/capture/Cargo.toml b/rust/capture/Cargo.toml
index a2073e435546..ef37a3edfdb2 100644
--- a/rust/capture/Cargo.toml
+++ b/rust/capture/Cargo.toml
@@ -43,7 +43,6 @@ opentelemetry_sdk = { workspace = true }
prost = { workspace = true }
rand = { workspace = true }
rdkafka = { workspace = true }
-redis = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
serde_urlencoded = { workspace = true }
@@ -83,4 +82,5 @@ rand = { workspace = true }
rstest = "0.26"
rdkafka = { workspace = true }
reqwest = { workspace = true, features = ["multipart"] }
+redis = { workspace = true }
serde_json = { workspace = true }
diff --git a/rust/capture/src/events/analytics.rs b/rust/capture/src/events/analytics.rs
index 9ad2a5045905..5080f336573f 100644
--- a/rust/capture/src/events/analytics.rs
+++ b/rust/capture/src/events/analytics.rs
@@ -342,6 +342,10 @@ async fn process_events_inner(
let raw_events = events;
let mut events: Vec<ProcessedEvent> = Vec::with_capacity(raw_events.len());
for mut raw in raw_events {
+ if raw.event.starts_with("$ai_") {
+ raw.properties
+ .retain(|key, _| !key.starts_with(crate::gateway_provenance::GATEWAY_PREFIX));
+ }
if raw.event == "$$heatmap" || !has_heatmap_data(&raw) {
events.push(process_single_event(
&raw,
diff --git a/rust/capture/src/gateway_provenance.rs b/rust/capture/src/gateway_provenance.rs
new file mode 100644
index 000000000000..e0152ab2658c
--- /dev/null
+++ b/rust/capture/src/gateway_provenance.rs
@@ -0,0 +1,68 @@
+use axum::http::HeaderMap;
+use chrono::{DateTime, Duration, Utc};
+use hmac::{Hmac, Mac};
+use sha2::Sha256;
+
+type HmacSha256 = Hmac<Sha256>;
+
+pub const SIGNATURE_HEADER: &str = "PostHog-Ai-Gateway-Signature";
+pub const SIGNED_AT_HEADER: &str = "PostHog-Ai-Gateway-Signed-At";
+pub const REQUEST_ID_HEADER: &str = "PostHog-Ai-Gateway-Request-Id";
+pub const GATEWAY_PREFIX: &str = "$ai_gateway";
+pub const VERIFIED_PROPERTY: &str = "$ai_gateway_verified";
+pub const FRESHNESS_WINDOW_SECS: i64 = 5 * 60;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Provenance {
+ Verified,
+ Stale,
+ Invalid,
+}
+
+pub fn header_str(headers: &HeaderMap, name: &str) -> Option<String> {
+ headers.get(name)?.to_str().ok().map(str::to_owned)
+}
+
+pub fn canonical(fields: &[&str]) -> Vec<u8> {
+ let mut buffer = Vec::with_capacity(fields.iter().map(|field| field.len() + 4).sum());
+ for field in fields {
+ buffer.extend_from_slice(&(field.len() as u32).to_be_bytes());
+ buffer.extend_from_slice(field.as_bytes());
+ }
+ buffer
+}
+
+pub fn verify(
+ secret: &[u8],
+ message: &[u8],
+ signature_hex: &str,
+ signed_at: &str,
+ now: DateTime<Utc>,
+) -> Provenance {
+ let Ok(expected) = hex::decode(signature_hex) else {
+ return Provenance::Invalid;
+ };
+ let Ok(mut mac) = HmacSha256::new_from_slice(secret) else {
+ return Provenance::Invalid;
+ };
+ mac.update(message);
+ if mac.verify_slice(&expected).is_err() {
+ return Provenance::Invalid;
+ }
+ match DateTime::parse_from_rfc3339(signed_at) {
+ Ok(value)
+ if (now - value.with_timezone(&Utc)).abs()
+ <= Duration::seconds(FRESHNESS_WINDOW_SECS) =>
+ {
+ Provenance::Verified
+ }
+ _ => Provenance::Stale,
+ }
+}
+
+#[cfg(any(test, feature = "test-utils"))]
+pub fn sign(secret: &[u8], fields: &[&str]) -> String {
+ let mut mac = HmacSha256::new_from_slice(secret).expect("hmac accepts any key length");
+ mac.update(&canonical(fields));
+ hex::encode(mac.finalize().into_bytes())
+}
diff --git a/rust/capture/src/lib.rs b/rust/capture/src/lib.rs
index 069db9750980..0905a1d5fbce 100644
--- a/rust/capture/src/lib.rs
+++ b/rust/capture/src/lib.rs
@@ -6,6 +6,7 @@ pub mod config;
pub mod event_restrictions;
pub mod events;
pub mod extractors;
+pub mod gateway_provenance;
pub mod global_rate_limiter;
pub mod ingestion_warnings;
pub mod log_util;
diff --git a/rust/capture/src/otel/filtering.rs b/rust/capture/src/otel/filtering.rs
index db1b8df71807..b2dc04331f88 100644
--- a/rust/capture/src/otel/filtering.rs
+++ b/rust/capture/src/otel/filtering.rs
@@ -1,5 +1,6 @@
use chrono::{DateTime, Utc};
use common_types::CapturedEvent;
+use limiters::redis::QuotaResource;
use serde_json::json;
use tracing::error;
use uuid::Uuid;
@@ -24,9 +25,22 @@ pub async fn check_quota(
limiter: &CaptureQuotaLimiter,
token: &str,
span_events: &[SpanEvent],
+ gateway_verified: bool,
) -> Result<(), QuotaOutcome> {
+ let count = span_events.len();
+
+ if gateway_verified {
+ if limiter
+ .is_quota_limited_v1(token, &QuotaResource::Events)
+ .await
+ {
+ report_dropped_events("otel_quota_drop", count as u64);
+ return Err(QuotaOutcome::Dropped);
+ }
+ return Ok(());
+ }
+
let refs: Vec<&SpanEvent> = span_events.iter().collect();
- let count = refs.len();
match limiter.check_and_filter(token, refs).await {
Ok(filtered) if filtered.len() == count => Ok(()),
diff --git a/rust/capture/src/otel/mod.rs b/rust/capture/src/otel/mod.rs
index 52a5b31ee269..9511164eed80 100644
--- a/rust/capture/src/otel/mod.rs
+++ b/rust/capture/src/otel/mod.rs
@@ -4,6 +4,7 @@ mod fan_out;
mod filtering;
mod identity;
mod ingestion;
+mod provenance;
mod providers;
use axum::body::Body;
@@ -104,6 +105,17 @@ pub async fn otel_handler(
} else {
"unknown"
};
+ let normalized_content_type = match format {
+ "protobuf" => "application/x-protobuf",
+ "json" => "application/json",
+ _ => "unknown",
+ };
+ let content_encoding = headers
+ .get("content-encoding")
+ .and_then(|value| value.to_str().ok())
+ .map(str::trim)
+ .unwrap_or("")
+ .to_ascii_lowercase();
counter!("capture_ai_otel_requests_total", "format" => format).increment(1);
let auth_header = headers
@@ -129,6 +141,16 @@ pub async fn otel_handler(
return Ok(Json(json!({})));
}
+ let gateway_provenance = provenance::verify(
+ &headers,
+ state.ai_gateway_signing_secret.as_deref(),
+ token,
+ normalized_content_type,
+ &content_encoding,
+ &body,
+ state.timesource.current_time(),
+ );
+
let request = ingestion::parse_request(&body, &headers, OTEL_BODY_SIZE).map_err(|e| {
report_internal_error_metrics(e.to_metric_tag(), "otel_parsing");
// No parsed request to attribute from: the SDK identity lives inside the
@@ -169,7 +191,15 @@ pub async fn otel_handler(
let received_at = Utc::now();
let request_fallback_distinct_id = identity::request_fallback_distinct_id();
- let span_events = fan_out::expand_into_events(&request, &request_fallback_distinct_id);
+ let mut span_events = fan_out::expand_into_events(&request, &request_fallback_distinct_id);
+ provenance::apply(
+ &mut span_events,
+ gateway_provenance,
+ headers.contains_key(crate::gateway_provenance::SIGNATURE_HEADER),
+ headers
+ .get(crate::gateway_provenance::REQUEST_ID_HEADER)
+ .and_then(|value| value.to_str().ok()),
+ );
let span_count = span_events.len();
let dropped_span_count = raw_span_count.saturating_sub(span_count);
@@ -216,7 +246,14 @@ pub async fn otel_handler(
let token = token.to_string();
// All-or-nothing quota check: reject the entire batch if any span is over quota
- if let Err(outcome) = filtering::check_quota(&state.quota_limiter, &token, &span_events).await {
+ if let Err(outcome) = filtering::check_quota(
+ &state.quota_limiter,
+ &token,
+ &span_events,
+ gateway_provenance == provenance::Provenance::Verified,
+ )
+ .await
+ {
return match outcome {
filtering::QuotaOutcome::Dropped => Err(non_retryable_rejection("quota exceeded")),
filtering::QuotaOutcome::Error(e) => {
diff --git a/rust/capture/src/otel/provenance.rs b/rust/capture/src/otel/provenance.rs
new file mode 100644
index 000000000000..352218fdd54c
--- /dev/null
+++ b/rust/capture/src/otel/provenance.rs
@@ -0,0 +1,205 @@
+use axum::http::HeaderMap;
+use chrono::{DateTime, Utc};
+use metrics::counter;
+use serde_json::Value;
+use sha2::{Digest, Sha256};
+
+use crate::gateway_provenance as shared;
+
+use super::fan_out::SpanEvent;
+
+const SIGNATURE_SCOPE: &str = "otel-v1";
+const RELAY_PROPERTY: &str = "$ai_gateway_relay";
+const REQUEST_ID_PROPERTY: &str = "$ai_gateway_request_id";
+const PROVENANCE_METRIC: &str = "capture_ai_otel_gateway_provenance";
+pub use crate::gateway_provenance::Provenance;
+
+pub fn verify(
+ headers: &HeaderMap,
+ secret: Option<&str>,
+ token: &str,
+ content_type: &str,
+ content_encoding: &str,
+ body: &[u8],
+ now: DateTime<Utc>,
+) -> Provenance {
+ let Some(secret) = secret.filter(|value| !value.is_empty()) else {
+ return Provenance::Invalid;
+ };
+ let Some(signature) = shared::header_str(headers, shared::SIGNATURE_HEADER) else {
+ return Provenance::Invalid;
+ };
+ let Some(signed_at) = shared::header_str(headers, shared::SIGNED_AT_HEADER) else {
+ return Provenance::Invalid;
+ };
+ let Some(request_id) =
+ shared::header_str(headers, shared::REQUEST_ID_HEADER).filter(|value| !value.is_empty())
+ else {
+ return Provenance::Invalid;
+ };
+
+ let body_digest = hex::encode(Sha256::digest(body));
+ let message = shared::canonical(&[
+ token,
+ SIGNATURE_SCOPE,
+ content_type,
+ content_encoding,
+ &body_digest,
+ &request_id,
+ &signed_at,
+ ]);
+ shared::verify(secret.as_bytes(), &message, &signature, &signed_at, now)
+}
+
+pub fn apply(
+ span_events: &mut [SpanEvent],
+ provenance: Provenance,
+ signature_present: bool,
+ request_id: Option<&str>,
+) {
+ let trusted = provenance == Provenance::Verified;
+ let reason = match provenance {
+ Provenance::Verified => "verified",
+ Provenance::Stale => "stale",
+ Provenance::Invalid if !signature_present => "unsigned",
+ Provenance::Invalid => "invalid",
+ };
+
+ for span_event in span_events {
+ let Some(properties) = span_event.properties.as_object_mut() else {
+ continue;
+ };
+ properties.retain(|key, _| !key.starts_with(shared::GATEWAY_PREFIX));
+ if trusted {
+ properties.insert(shared::VERIFIED_PROPERTY.to_string(), Value::Bool(true));
+ properties.insert(RELAY_PROPERTY.to_string(), Value::Bool(true));
+ if let Some(request_id) = request_id {
+ properties.insert(
+ REQUEST_ID_PROPERTY.to_string(),
+ Value::String(request_id.to_string()),
+ );
+ }
+ }
+ }
+ counter!(PROVENANCE_METRIC, "reason" => reason).increment(1);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ const SECRET: &str = "test-signing-secret";
+ const TOKEN: &str = "phc_test";
+ const SIGNED_AT: &str = "2026-07-16T12:34:56.12Z";
+ const REQUEST_ID: &str = "req-123";
+ const SIGNATURE: &str = "158b5ca0acb887eafbcfce9c871bfb6c11b0ccd58837f9f3346b88dd952ead89";
+ const BODY: &[u8] = &[0x0a, 0x02, 0x01, 0x02];
+
+ fn now() -> DateTime<Utc> {
+ DateTime::parse_from_rfc3339(SIGNED_AT)
+ .unwrap()
+ .with_timezone(&Utc)
+ }
+
+ fn signed_headers() -> HeaderMap {
+ let mut headers = HeaderMap::new();
+ headers.insert(shared::SIGNATURE_HEADER, SIGNATURE.parse().unwrap());
+ headers.insert(shared::SIGNED_AT_HEADER, SIGNED_AT.parse().unwrap());
+ headers.insert(shared::REQUEST_ID_HEADER, REQUEST_ID.parse().unwrap());
+ headers
+ }
+
+ #[test]
+ fn accepts_gateway_known_answer_vector() {
+ assert_eq!(
+ verify(
+ &signed_headers(),
+ Some(SECRET),
+ TOKEN,
+ "application/x-protobuf",
+ "gzip",
+ BODY,
+ now(),
+ ),
+ Provenance::Verified
+ );
+ }
+
+ #[test]
+ fn rejects_tampered_body() {
+ assert_eq!(
+ verify(
+ &signed_headers(),
+ Some(SECRET),
+ TOKEN,
+ "application/x-protobuf",
+ "gzip",
+ b"tampered",
+ now(),
+ ),
+ Provenance::Invalid
+ );
+ }
+
+ #[test]
+ fn rejects_stale_signature() {
+ assert_eq!(
+ verify(
+ &signed_headers(),
+ Some(SECRET),
+ TOKEN,
+ "application/x-protobuf",
+ "gzip",
+ BODY,
+ now() + chrono::Duration::seconds(shared::FRESHNESS_WINDOW_SECS + 1),
+ ),
+ Provenance::Stale
+ );
+ }
+
+ #[test]
+ fn strips_forged_properties_and_stamps_verified_batches() {
+ let mut events = vec![SpanEvent {
+ event_name: "$ai_span".to_string(),
+ distinct_id: "user-1".to_string(),
+ properties: json!({
+ "$ai_gateway_verified": true,
+ "$ai_gateway_request_id": "forged",
+ "$ai_trace_id": "trace-1",
+ }),
+ timestamp: None,
+ }];
+
+ apply(&mut events, Provenance::Verified, true, Some(REQUEST_ID));
+
+ let properties = events[0].properties.as_object().unwrap();
+ assert_eq!(
+ properties.get(shared::VERIFIED_PROPERTY),
+ Some(&Value::Bool(true))
+ );
+ assert_eq!(properties.get(RELAY_PROPERTY), Some(&Value::Bool(true)));
+ assert_eq!(
+ properties.get("$ai_gateway_request_id"),
+ Some(&json!(REQUEST_ID))
+ );
+ assert_eq!(properties.get("$ai_trace_id"), Some(&json!("trace-1")));
+ }
+
+ #[test]
+ fn strips_forged_properties_from_unsigned_batches() {
+ let mut events = vec![SpanEvent {
+ event_name: "$ai_span".to_string(),
+ distinct_id: "user-1".to_string(),
+ properties: json!({"$ai_gateway_verified": true, "$ai_trace_id": "trace-1"}),
+ timestamp: None,
+ }];
+
+ apply(&mut events, Provenance::Invalid, true, None);
+
+ let properties = events[0].properties.as_object().unwrap();
+ assert!(!properties.contains_key(shared::VERIFIED_PROPERTY));
+ assert!(!properties.contains_key(RELAY_PROPERTY));
+ assert_eq!(properties.get("$ai_trace_id"), Some(&json!("trace-1")));
+ }
+}
diff --git a/rust/capture/src/v1/constants.rs b/rust/capture/src/v1/constants.rs
index 13a936c544d8..adf25d680770 100644
--- a/rust/capture/src/v1/constants.rs
+++ b/rust/capture/src/v1/constants.rs
@@ -23,10 +23,10 @@ pub const POSTHOG_REQUEST_TIMESTAMP: &str = "PostHog-Request-Timestamp";
/// AI-gateway provenance: lowercase-hex HMAC-SHA256 over the canonical tuple
/// (token, distinct_id, request_id, signed_at). See `gateway_provenance::canonical`.
-pub const POSTHOG_AI_GATEWAY_SIGNATURE: &str = "PostHog-Ai-Gateway-Signature";
+pub const POSTHOG_AI_GATEWAY_SIGNATURE: &str = crate::gateway_provenance::SIGNATURE_HEADER;
/// AI-gateway provenance: RFC3339 timestamp the gateway signed at.
-pub const POSTHOG_AI_GATEWAY_SIGNED_AT: &str = "PostHog-Ai-Gateway-Signed-At";
+pub const POSTHOG_AI_GATEWAY_SIGNED_AT: &str = crate::gateway_provenance::SIGNED_AT_HEADER;
/// AI-gateway provenance: per-call request id; billing dedups exemptions by it.
pub const POSTHOG_AI_GATEWAY_REQUEST_ID: &str = "PostHog-Ai-Gateway-Request-Id";
diff --git a/rust/capture/src/v1/gateway_provenance.rs b/rust/capture/src/v1/gateway_provenance.rs
index 59cf76189c36..35d82489196d 100644
--- a/rust/capture/src/v1/gateway_provenance.rs
+++ b/rust/capture/src/v1/gateway_provenance.rs
@@ -9,21 +9,19 @@
// `$ai_gateway*` namespace stripped so a forged marker can't survive.
use axum::http::HeaderMap;
-use chrono::{DateTime, Duration, Utc};
-use hmac::{Hmac, Mac};
+use chrono::{DateTime, Utc};
use serde_json::value::RawValue;
use serde_json::{Map, Value};
-use sha2::Sha256;
+
+use crate::gateway_provenance as shared;
+
+pub use crate::gateway_provenance::Provenance;
+pub use crate::gateway_provenance::VERIFIED_PROPERTY;
use super::constants::{
POSTHOG_AI_GATEWAY_REQUEST_ID, POSTHOG_AI_GATEWAY_SIGNATURE, POSTHOG_AI_GATEWAY_SIGNED_AT,
};
-type HmacSha256 = Hmac<Sha256>;
-
-const GATEWAY_PREFIX: &str = "$ai_gateway";
-pub const VERIFIED_PROPERTY: &str = "$ai_gateway_verified";
-
/// Stamped from the signed header (not the client value) so billing can dedup
/// exemptions by it.
const REQUEST_ID_PROPERTY: &str = "$ai_gateway_request_id";
@@ -38,7 +36,7 @@ const GATEWAY_KEY_NEEDLE: &str = "\"$ai_gateway";
const _: () = assert!(
{
let needle = GATEWAY_KEY_NEEDLE.as_bytes();
- let prefix = GATEWAY_PREFIX.as_bytes();
+ let prefix = shared::GATEWAY_PREFIX.as_bytes();
let mut ok = needle.len() == prefix.len() + 1 && needle[0] == b'"';
let mut i = 0;
while i < prefix.len() {
@@ -52,7 +50,7 @@ const _: () = assert!(
/// How far `signed_at` may sit from capture's receive time. Capture stamps the
/// event (no ingestion lag), so the window only absorbs gateway/capture clock skew.
-pub const FRESHNESS_WINDOW_SECS: i64 = 5 * 60;
+pub use shared::FRESHNESS_WINDOW_SECS;
/// The provenance signature carried on the request headers.
#[derive(Debug, Clone)]
@@ -66,29 +64,12 @@ pub struct GatewaySignature {
/// present; `request_id` defaults to empty when absent (untrusted downstream).
pub fn parse_signature(headers: &HeaderMap) -> Option<GatewaySignature> {
Some(GatewaySignature {
- signature: header_str(headers, POSTHOG_AI_GATEWAY_SIGNATURE)?,
- signed_at: header_str(headers, POSTHOG_AI_GATEWAY_SIGNED_AT)?,
- request_id: header_str(headers, POSTHOG_AI_GATEWAY_REQUEST_ID).unwrap_or_default(),
+ signature: shared::header_str(headers, POSTHOG_AI_GATEWAY_SIGNATURE)?,
+ signed_at: shared::header_str(headers, POSTHOG_AI_GATEWAY_SIGNED_AT)?,
+ request_id: shared::header_str(headers, POSTHOG_AI_GATEWAY_REQUEST_ID).unwrap_or_default(),
})
}
-fn header_str(headers: &HeaderMap, name: &str) -> Option<String> {
- headers.get(name)?.to_str().ok().map(str::to_owned)
-}
-
-/// Outcome of checking a gateway signature, so callers can tell a forgery
-/// (`Invalid`) from clock skew (`Stale`) for metrics. Only `Verified` is trusted.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum Provenance {
- /// Valid HMAC, signed within the freshness window.
- Verified,
- /// Valid HMAC, but `signed_at` is outside the freshness window (clock skew, or
- /// a signature replayed past its lifetime).
- Stale,
- /// HMAC mismatch, unparseable signature, or no signature at all.
- Invalid,
-}
-
/// Verifies the HMAC over the gateway's canonical tuple, then checks freshness.
pub fn verify(
secret: &[u8],
@@ -97,48 +78,8 @@ pub fn verify(
sig: &GatewaySignature,
now: DateTime<Utc>,
) -> Provenance {
- let message = canonical(&[token, distinct_id, &sig.request_id, &sig.signed_at]);
- if !verify_hmac(secret, &message, &sig.signature) {
- return Provenance::Invalid;
- }
- if is_fresh(&sig.signed_at, now) {
- Provenance::Verified
- } else {
- Provenance::Stale
- }
-}
-
-// Length-prefixed encoding: each field is its big-endian u32 length then its bytes.
-// distinct_id is customer-controlled, so a delimiter wouldn't be injective;
-// length-prefixing stops any field's content from shifting another's boundary. Must
-// match the gateway signer byte-for-byte (ai-gateway internal/emitter/signer.go).
-fn canonical(fields: &[&str]) -> Vec<u8> {
- let mut buf = Vec::with_capacity(fields.iter().map(|f| f.len() + 4).sum());
- for f in fields {
- buf.extend_from_slice(&(f.len() as u32).to_be_bytes());
- buf.extend_from_slice(f.as_bytes());
- }
- buf
-}
-
-// HMAC-SHA256 over the canonical message, signature as lowercase hex. Compared
-// in constant time via `verify_slice`.
-fn verify_hmac(secret: &[u8], message: &[u8], signature_hex: &str) -> bool {
- let Ok(expected) = hex::decode(signature_hex) else {
- return false;
- };
- let Ok(mut mac) = HmacSha256::new_from_slice(secret) else {
- return false;
- };
- mac.update(message);
- mac.verify_slice(&expected).is_ok()
-}
-
-fn is_fresh(signed_at: &str, now: DateTime<Utc>) -> bool {
- match DateTime::parse_from_rfc3339(signed_at) {
- Ok(t) => (now - t.with_timezone(&Utc)).abs() <= Duration::seconds(FRESHNESS_WINDOW_SECS),
- Err(_) => false,
- }
+ let message = shared::canonical(&[token, distinct_id, &sig.request_id, &sig.signed_at]);
+ shared::verify(secret, &message, &sig.signature, &sig.signed_at, now)
}
/// Stamps the trusted marker and the signed request_id, overwriting client values.
@@ -153,7 +94,7 @@ pub fn stamp_verified(props: &mut Map<String, Value>, request_id: &str) {
/// Removes the whole `$ai_gateway*` namespace so a forged marker can't reach billing.
pub fn strip_gateway(props: &mut Map<String, Value>) {
- props.retain(|k, _| !k.starts_with(GATEWAY_PREFIX));
+ props.retain(|k, _| !k.starts_with(shared::GATEWAY_PREFIX));
}
/// Cheap raw-bytes pre-check: does the property object plausibly carry a
@@ -215,7 +156,7 @@ fn scan_for_escaped_gateway_key(raw: &str) -> bool {
/// `$ai_gateway` prefix. Any non-`\u` escape, or a `\u` codepoint outside ASCII,
/// can't be part of the all-ASCII prefix, so it's a mismatch.
fn key_starts_with_gateway(content: &[u8]) -> bool {
- let target = GATEWAY_PREFIX.as_bytes();
+ let target = shared::GATEWAY_PREFIX.as_bytes();
let mut ti = 0;
let mut i = 0;
while ti < target.len() {
@@ -322,9 +263,7 @@ pub fn sign_for_test(
request_id: &str,
signed_at: &str,
) -> String {
- let mut mac = HmacSha256::new_from_slice(secret).expect("hmac accepts any key length");
- mac.update(&canonical(&[token, distinct_id, request_id, signed_at]));
- hex::encode(mac.finalize().into_bytes())
+ shared::sign(secret, &[token, distinct_id, request_id, signed_at])
}
#[cfg(test)]
@@ -407,10 +346,8 @@ mod tests {
#[test]
fn rejects_a_wrong_secret() {
let signed_at = "2026-05-28T10:00:00Z".to_string();
- let mut mac = HmacSha256::new_from_slice(b"other-secret").unwrap();
- mac.update(&canonical(&[TOKEN, DISTINCT_ID, "req-1", &signed_at]));
let sig = GatewaySignature {
- signature: hex::encode(mac.finalize().into_bytes()),
+ signature: shared::sign(b"other-secret", &[TOKEN, DISTINCT_ID, "req-1", &signed_at]),
signed_at,
request_id: "req-1".to_string(),
};
diff --git a/rust/capture/tests/integration_analytics_ai_routing.rs b/rust/capture/tests/integration_analytics_ai_routing.rs
index ff85b8756fc4..aedf92514a8a 100644
--- a/rust/capture/tests/integration_analytics_ai_routing.rs
+++ b/rust/capture/tests/integration_analytics_ai_routing.rs
@@ -203,6 +203,52 @@ async fn post_batch(client: &TestClient, payload: String) {
assert_eq!(response.status(), StatusCode::OK);
}
+#[rstest]
+#[case("/e")]
+#[case("/batch")]
+#[tokio::test]
+async fn legacy_routes_strip_forged_gateway_properties(#[case] path: &str) {
+ let (router, sink) = setup_analytics_router(AiRouting::Primary, false, None, None);
+ let client = TestClient::new(router);
+ let event = json!({
+ "event": "$ai_span",
+ "distinct_id": DISTINCT_ID,
+ "properties": {
+ "$ai_gateway_verified": true,
+ "$ai_gateway_relay": true,
+ "$ai_gateway_request_id": "forged",
+ "$ai_trace_id": "trace-1"
+ }
+ });
+ let payload = if path == "/batch" {
+ json!({"api_key": TOKEN, "batch": [event]}).to_string()
+ } else {
+ json!({
+ "api_key": TOKEN,
+ "event": "$ai_span",
+ "distinct_id": DISTINCT_ID,
+ "properties": event["properties"].clone()
+ })
+ .to_string()
+ };
+
+ let response = client
+ .post(path)
+ .header("Content-Type", "application/json")
+ .header("X-Forwarded-For", "127.0.0.1")
+ .body(payload)
+ .send()
+ .await;
+
+ assert_eq!(response.status(), StatusCode::OK);
+ let events = sink.get_events().await;
+ let data: serde_json::Value = serde_json::from_str(&events[0].event.data).unwrap();
+ assert_eq!(data["properties"]["$ai_trace_id"], "trace-1");
+ assert!(data["properties"].get("$ai_gateway_verified").is_none());
+ assert!(data["properties"].get("$ai_gateway_relay").is_none());
+ assert!(data["properties"].get("$ai_gateway_request_id").is_none());
+}
+
fn allowlist(tokens: &[&str]) -> AiRouting {
AiRouting::SecondaryAllowlist(tokens.iter().map(|t| t.to_string()).collect::<HashSet<_>>())
}
diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rs
index 8e7c03d03597..d9b09dea81bc 100644
--- a/rust/capture/tests/integration_otel_endpoint.rs
+++ b/rust/capture/tests/integration_otel_endpoint.rs
@@ -19,6 +19,7 @@ use chrono::{DateTime, Utc};
use common_ingestion_warnings::test_support::CollectingEmitter;
use common_ingestion_warnings::{WarningEmitter, WarningType, CAPTURE_AI_OTEL};
use common_redis::MockRedisClient;
+use hmac::{Hmac, Mac};
use integration_utils::{test_lifecycle_handlers, DEFAULT_TEST_TIME};
use limiters::overflow::OverflowLimiter;
use limiters::redis::{QuotaResource, QUOTA_LIMITER_CACHE_KEY};
@@ -29,13 +30,17 @@ use opentelemetry_proto::tonic::resource::v1::Resource;
use opentelemetry_proto::tonic::trace::v1::{ResourceSpans, ScopeSpans, Span};
use prost::Message;
use serde_json::json;
+use sha2::{Digest, Sha256};
use std::collections::HashSet;
+use std::io::Write;
use std::num::NonZeroU32;
use std::sync::Arc;
use std::time::Duration;
use integration_utils::DEFAULT_CONFIG;
+const GATEWAY_REQUEST_ID: &str = "otel-request-1";
+
struct FixedTime {
pub time: DateTime<Utc>,
}
@@ -126,6 +131,7 @@ struct TestClientOptions {
redis: Option<Arc<MockRedisClient>>,
event_restriction_service: Option<EventRestrictionService>,
quota_limiter: Option<CaptureQuotaLimiter>,
+ ai_gateway_signing_secret: Option<String>,
// Opt-in OverflowLimiter wiring. `None` (default) matches production
// configs without `OVERFLOW_ENABLED=true` and exercises the no-op branch
// of `stamp_overflow_reason`.
@@ -192,9 +198,9 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOption
None, // replay_overflow_limiter
None, // v1_sink_router
8, // capture_v1_scatter_gather_min_batch
- None, // ai_gateway_signing_secret
- AiRouting::Primary, // ai_routing
- false, // ai_events_overflow_enabled
+ options.ai_gateway_signing_secret,
+ AiRouting::Primary, // ai_routing
+ false, // ai_events_overflow_enabled
options.ingestion_warning_emitter, // ingestion_warning_emitter
);
@@ -247,6 +253,71 @@ async fn send_request_with_client(client: &TestClient, request: &ExportTraceServ
resp.status().as_u16()
}
+async fn send_signed_request_with_client(
+ client: &TestClient,
+ request: &ExportTraceServiceRequest,
+ secret: &str,
+) -> u16 {
+ let body = request.encode_to_vec();
+ let signature = sign_gateway_body(
+ secret,
+ "application/x-protobuf",
+ "",
+ &body,
+ DEFAULT_TEST_TIME,
+ );
+
+ send_signed_body_with_client(client, body, "application/x-protobuf", signature).await
+}
+
+async fn send_signed_body_with_client(
+ client: &TestClient,
+ body: Vec<u8>,
+ content_type: &str,
+ signature: String,
+) -> u16 {
+ let resp = client
+ .post(ENDPOINT)
+ .header("Content-Type", content_type)
+ .header("Authorization", format!("Bearer {}", TOKEN))
+ .header("PostHog-Ai-Gateway-Signature", signature)
+ .header("PostHog-Ai-Gateway-Signed-At", DEFAULT_TEST_TIME)
+ .header("PostHog-Ai-Gateway-Request-Id", GATEWAY_REQUEST_ID)
+ .body(body)
+ .send()
+ .await;
+
+ resp.status().as_u16()
+}
+
+fn sign_gateway_body(
+ secret: &str,
+ content_type: &str,
+ content_encoding: &str,
+ body: &[u8],
+ signed_at: &str,
+) -> String {
+ let body_digest = hex::encode(Sha256::digest(body));
+ let fields = [
+ TOKEN,
+ "otel-v1",
+ content_type,
+ content_encoding,
+ body_digest.as_str(),
+ GATEWAY_REQUEST_ID,
+ signed_at,
+ ];
+ let mut message = Vec::new();
+ for field in fields {
+ message.extend_from_slice(&(field.len() as u32).to_be_bytes());
+ message.extend_from_slice(field.as_bytes());
+ }
+
+ let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).unwrap();
+ mac.update(&message);
+ hex::encode(mac.finalize().into_bytes())
+}
+
fn parse_event_data(event: &ProcessedEvent) -> serde_json::Value {
serde_json::from_str(&event.event.data).expect("event data is valid JSON")
}
@@ -359,6 +430,154 @@ async fn test_single_span_produces_one_event() {
assert_eq!(data["properties"]["$ai_ingestion_source"], "otel");
}
+#[tokio::test]
+async fn test_verified_gateway_batch_stamps_trusted_provenance() {
+ const SECRET: &str = "test-signing-secret";
+
+ let sink = CapturingSink::new();
+ let client = make_test_client_with_options(
+ &sink,
+ TestClientOptions {
+ ai_gateway_signing_secret: Some(SECRET.to_string()),
+ ..Default::default()
+ },
+ );
+
+ let status =
+ send_signed_request_with_client(&client, &make_single_span_request(), SECRET).await;
+ assert_eq!(status, 200);
+
+ let events = sink.get_events().await;
+ let data = parse_event_data(&events[0]);
+ assert_eq!(data["properties"]["$ai_gateway_verified"], true);
+ assert_eq!(data["properties"]["$ai_gateway_relay"], true);
+}
+
+#[tokio::test]
+async fn test_verified_gzip_gateway_batch_stamps_trusted_provenance() {
+ const SECRET: &str = "test-signing-secret";
+
+ let sink = CapturingSink::new();
+ let client = make_test_client_with_options(
+ &sink,
+ TestClientOptions {
+ ai_gateway_signing_secret: Some(SECRET.to_string()),
+ ..Default::default()
+ },
+ );
+ let body = make_single_span_request().encode_to_vec();
+ let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
+ encoder.write_all(&body).unwrap();
+ let body = encoder.finish().unwrap();
+ let signature = sign_gateway_body(
+ SECRET,
+ "application/x-protobuf",
+ "gzip",
+ &body,
+ DEFAULT_TEST_TIME,
+ );
+ let response = client
+ .post(ENDPOINT)
+ .header("Content-Type", "application/x-protobuf")
+ .header("Content-Encoding", "gzip")
+ .header("Authorization", format!("Bearer {}", TOKEN))
+ .header("PostHog-Ai-Gateway-Signature", signature)
+ .header("PostHog-Ai-Gateway-Signed-At", DEFAULT_TEST_TIME)
+ .header("PostHog-Ai-Gateway-Request-Id", GATEWAY_REQUEST_ID)
+ .body(body)
+ .send()
+ .await;
+
+ assert_eq!(response.status().as_u16(), 200);
+ let events = sink.get_events().await;
+ let data = parse_event_data(&events[0]);
+ assert_eq!(data["properties"]["$ai_gateway_verified"], true);
+ assert_eq!(data["properties"]["$ai_gateway_relay"], true);
+}
+
+#[tokio::test]
+async fn test_signed_json_batch_stamps_trusted_provenance() {
+ const SECRET: &str = "test-signing-secret";
+
+ let sink = CapturingSink::new();
+ let client = make_test_client_with_options(
+ &sink,
+ TestClientOptions {
+ ai_gateway_signing_secret: Some(SECRET.to_string()),
+ ..Default::default()
+ },
+ );
+ let body = serde_json::to_vec(&make_single_span_request()).unwrap();
+ let signature = sign_gateway_body(SECRET, "application/json", "", &body, DEFAULT_TEST_TIME);
+
+ let status = send_signed_body_with_client(&client, body, "application/json", signature).await;
+ assert_eq!(status, 200);
+
+ let events = sink.get_events().await;
+ let data = parse_event_data(&events[0]);
+ assert_eq!(data["properties"]["$ai_gateway_verified"], true);
+ assert_eq!(data["properties"]["$ai_gateway_relay"], true);
+}
+
+#[tokio::test]
+async fn test_signed_json_body_mismatch_rejects_trusted_provenance() {
+ const SECRET: &str = "test-signing-secret";
+
+ let sink = CapturingSink::new();
+ let client = make_test_client_with_options(
+ &sink,
+ TestClientOptions {
+ ai_gateway_signing_secret: Some(SECRET.to_string()),
+ ..Default::default()
+ },
+ );
+ let signed_body = serde_json::to_vec(&make_single_span_request()).unwrap();
+ let signature = sign_gateway_body(
+ SECRET,
+ "application/json",
+ "",
+ &signed_body,
+ DEFAULT_TEST_TIME,
+ );
+ let mut request = make_single_span_request();
+ request.resource_spans[0].schema_url = "tampered".to_string();
+ let body = serde_json::to_vec(&request).unwrap();
+
+ let status = send_signed_body_with_client(&client, body, "application/json", signature).await;
+ assert_eq!(status, 200);
+
+ let events = sink.get_events().await;
+ let data = parse_event_data(&events[0]);
+ let properties = data["properties"].as_object().unwrap();
+ assert!(!properties.contains_key("$ai_gateway_verified"));
+ assert!(!properties.contains_key("$ai_gateway_relay"));
+}
+
+#[tokio::test]
+async fn test_unsigned_batch_cannot_forge_gateway_provenance() {
+ let sink = CapturingSink::new();
+ let mut request = make_single_span_request();
+ let attributes = &mut request.resource_spans[0].scope_spans[0].spans[0].attributes;
+ attributes.extend([
+ make_kv("$ai_gateway_verified", any_value::Value::BoolValue(true)),
+ make_kv("$ai_gateway_relay", any_value::Value::BoolValue(true)),
+ make_kv(
+ "$ai_gateway_request_id",
+ any_value::Value::StringValue("forged".to_string()),
+ ),
+ ]);
+
+ let status = send_request(&sink, &request).await;
+ assert_eq!(status, 200);
+
+ let events = sink.get_events().await;
+ let data = parse_event_data(&events[0]);
+ let properties = data["properties"].as_object().unwrap();
+ assert!(!properties.contains_key("$ai_gateway_verified"));
+ assert!(!properties.contains_key("$ai_gateway_relay"));
+ assert!(!properties.contains_key("$ai_gateway_request_id"));
+}
+
#[tokio::test]
async fn test_multiple_spans_produce_multiple_events() {
let sink = CapturingSink::new();
@@ -1040,6 +1259,103 @@ async fn test_quota_limit_exceeded_returns_400_with_no_events() {
assert!(events.is_empty());
}
+#[tokio::test]
+async fn test_verified_gateway_batch_bypasses_scoped_llm_quota() {
+ const SECRET: &str = "test-signing-secret";
+
+ let llm_key = format!(
+ "{}{}",
+ QUOTA_LIMITER_CACHE_KEY,
+ QuotaResource::LLMEvents.as_str()
+ );
+ let redis =
+ Arc::new(MockRedisClient::new().zrangebyscore_ret(&llm_key, vec![TOKEN.to_string()]));
+ let sink = CapturingSink::new();
+ let client = make_test_client_with_options(
+ &sink,
+ TestClientOptions {
+ redis: Some(redis),
+ ai_gateway_signing_secret: Some(SECRET.to_string()),
+ ..Default::default()
+ },
+ );
+
+ let status =
+ send_signed_request_with_client(&client, &make_single_span_request(), SECRET).await;
+ assert_eq!(status, 200);
+ assert_eq!(sink.get_events().await.len(), 1);
+}
+
+#[tokio::test]
+async fn test_invalid_gateway_signature_does_not_bypass_scoped_llm_quota() {
+ const SECRET: &str = "test-signing-secret";
+
+ let llm_key = format!(
+ "{}{}",
+ QUOTA_LIMITER_CACHE_KEY,
+ QuotaResource::LLMEvents.as_str()
+ );
+ let redis =
+ Arc::new(MockRedisClient::new().zrangebyscore_ret(&llm_key, vec![TOKEN.to_string()]));
+ let sink = CapturingSink::new();
+ let client = make_test_client_with_options(
+ &sink,
+ TestClientOptions {
+ redis: Some(redis),
+ ai_gateway_signing_secret: Some(SECRET.to_string()),
+ ..Default::default()
+ },
+ );
+ let body = make_single_span_request().encode_to_vec();
+ let response = client
+ .post(ENDPOINT)
+ .header("Content-Type", "application/x-protobuf")
+ .header("Authorization", format!("Bearer {}", TOKEN))
+ .header("PostHog-Ai-Gateway-Signature", "00")
+ .header("PostHog-Ai-Gateway-Signed-At", DEFAULT_TEST_TIME)
+ .body(body)
+ .send()
+ .await;
+
+ assert_eq!(response.status().as_u16(), 400);
+ assert!(sink.get_events().await.is_empty());
+}
+
+#[tokio::test]
+async fn test_verified_gateway_batch_matches_direct_ai_global_quota_behavior() {
+ const SECRET: &str = "test-signing-secret";
+
+ let llm_key = format!(
+ "{}{}",
+ QUOTA_LIMITER_CACHE_KEY,
+ QuotaResource::LLMEvents.as_str()
+ );
+ let global_key = format!(
+ "{}{}",
+ QUOTA_LIMITER_CACHE_KEY,
+ QuotaResource::Events.as_str()
+ );
+ let redis = Arc::new(
+ MockRedisClient::new()
+ .zrangebyscore_ret(&llm_key, vec![TOKEN.to_string()])
+ .zrangebyscore_ret(&global_key, vec![TOKEN.to_string()]),
+ );
+ let sink = CapturingSink::new();
+ let client = make_test_client_with_options(
+ &sink,
+ TestClientOptions {
+ redis: Some(redis),
+ ai_gateway_signing_secret: Some(SECRET.to_string()),
+ ..Default::default()
+ },
+ );
+
+ let status =
+ send_signed_request_with_client(&client, &make_single_span_request(), SECRET).await;
+ assert_eq!(status, 400);
+ assert!(sink.get_events().await.is_empty());
+}
+
#[tokio::test]
async fn test_global_quota_exceeded_retains_scoped_llm_events() {
// When the global quota is exceeded but the scoped LLM limiter is not, the