:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(capture): verify AI-gateway provenance on the v0 AI endpoint (#66921)
Richard Solomou5062ea84124e
diff --git a/rust/capture/src/ai_endpoint.rs b/rust/capture/src/ai_endpoint.rsindex 2c5f6a197e4e..b5f250c9086c 100644--- a/rust/capture/src/ai_endpoint.rs+++ b/rust/capture/src/ai_endpoint.rs@@ -6,6 +6,7 @@ use axum_client_ip::InsecureClientIp;use bytes::Bytes;use common_types::{CapturedEvent, HasEventName};use futures::stream;+use limiters::redis::QuotaResource;use metrics::{counter, histogram};use multer::{parse_boundary, Multipart};use serde::{Deserialize, Serialize};@@ -34,6 +35,7 @@ use crate::router::State as AppState;use crate::timestamp;use crate::token::validate_token;use crate::v0_request::{DataType, ProcessedEvent, ProcessedEventMetadata};+use crate::v1::gateway_provenance as gp;#[derive(Debug, Clone, Serialize, Deserialize)]pub struct PartInfo {@@ -253,18 +255,50 @@ async fn ai_handler_inner(}));}- // Step 4: Check quota limiter - drop if over quota- // We pass a single-element vec and check if it's filtered out- let filtered = state- .quota_limiter- .check_and_filter(token, vec![event_metadata])- .await?;-- // If the event was filtered out by quota limiter, return billing limit error- let event_metadata = filtered- .into_iter()- .next()- .ok_or(CaptureError::BillingLimit)?;+ // AI-gateway provenance: a fresh, valid signature marks the event trusted.+ // Verify here, before the quota limiter, while distinct_id (in the signed tuple)+ // is known; the outcome gates the limiter below and the stamp/strip before Kafka.+ // sig + signed_at + request_id ride in headers.+ // TODO: relocate gateway_provenance out of v1/ now the v0 path uses it too.+ let gw_sig = gp::parse_signature(&headers);+ let gw_outcome = match (state.ai_gateway_signing_secret.as_deref(), gw_sig.as_ref()) {+ (Some(secret), Some(sig)) => gp::verify(+ secret.as_bytes(),+ token,+ &event_metadata.distinct_id,+ sig,+ state.timesource.current_time(),+ ),+ _ => gp::Provenance::Invalid,+ };+ let gw_request_id = gw_sig.map(|s| s.request_id).unwrap_or_default();+ let gw_trusted = gw_outcome == gp::Provenance::Verified && !gw_request_id.is_empty();++ // Step 4: quota limiter. Verified gateway events are wallet-billed, so they're+ // exempt from the scoped LLM-events quota but still subject to the team's global+ // Events quota (matching the v1 flow).+ let event_metadata = if gw_trusted {+ if state+ .quota_limiter+ .is_quota_limited_v1(token, &QuotaResource::Events)+ .await+ {+ return Err(CaptureError::BillingLimit);+ }+ event_metadata+ } else {+ // We pass a single-element vec and check if it's filtered out+ let filtered = state+ .quota_limiter+ .check_and_filter(token, vec![event_metadata])+ .await?;++ // If the event was filtered out by quota limiter, return billing limit error+ filtered+ .into_iter()+ .next()+ .ok_or(CaptureError::BillingLimit)?+ };// Step 5: Retrieve and validate remaining multipart parts (continues parsing from multipart)let parts = retrieve_multipart_parts(@@ -351,6 +385,46 @@ async fn ai_handler_inner(}}+ // AI-gateway provenance: stamp the trusted marker (overwriting client values) on a+ // verified event, else strip the whole $ai_gateway* namespace so a forged marker+ // can't reach billing. The verified metric always fires; the strip metric only fires+ // when a gateway prop was actually present, so ordinary $ai_* events stay silent.+ if let Some(event_obj) = parsed.event.as_object_mut() {+ if gw_trusted {+ // A verified event was exempted from the LLM-events quota, so it must carry+ // the stamp or billing would double-count it toward AIO. Guarantee a+ // properties object here rather than relying on validate_event_structure+ // having produced one, so the exemption and the stamp can't drift apart.+ let properties = event_obj+ .entry("properties")+ .or_insert_with(|| Value::Object(serde_json::Map::new()));+ if !properties.is_object() {+ *properties = Value::Object(serde_json::Map::new());+ }+ if let Some(properties) = properties.as_object_mut() {+ gp::stamp_verified(properties, &gw_request_id);+ counter!(gp::PROVENANCE_METRIC, "reason" => "verified").increment(1);+ }+ } else if let Some(properties) = event_obj+ .get_mut("properties")+ .and_then(|p| p.as_object_mut())+ {+ let before = properties.len();+ let forged = properties.contains_key(gp::VERIFIED_PROPERTY);+ gp::strip_gateway(properties);+ if properties.len() != before {+ let reason = if forged {+ "forged"+ } else if gw_outcome == gp::Provenance::Stale {+ "stale"+ } else {+ "stripped"+ };+ counter!(gp::PROVENANCE_METRIC, "reason" => reason).increment(1);+ }+ }+ }+// Step 8: Build Kafka event// Extract IP address, defaulting to 127.0.0.1 if not available (e.g., in tests)let client_ip = ipdiff --git a/rust/capture/src/v1/gateway_provenance.rs b/rust/capture/src/v1/gateway_provenance.rsindex 7946482acf0a..59cf76189c36 100644--- a/rust/capture/src/v1/gateway_provenance.rs+++ b/rust/capture/src/v1/gateway_provenance.rs@@ -22,7 +22,7 @@ use super::constants::{type HmacSha256 = Hmac<Sha256>;const GATEWAY_PREFIX: &str = "$ai_gateway";-const VERIFIED_PROPERTY: &str = "$ai_gateway_verified";+pub const VERIFIED_PROPERTY: &str = "$ai_gateway_verified";/// Stamped from the signed header (not the client value) so billing can dedup/// exemptions by it.diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rsindex a394ac2ffc60..69631e65d1ad 100644--- a/rust/capture/tests/integration_ai_endpoint.rs+++ b/rust/capture/tests/integration_ai_endpoint.rs@@ -3028,3 +3028,234 @@ async fn test_ai_endpoint_without_overflow_limiter_is_parity_with_pre_refactor()assert_eq!(events.len(), 1);assert_eq!(events[0].metadata.overflow_reason, None);}++// ============================================================================+// AI-gateway provenance on /i/v0/ai+// ============================================================================++const GW_SECRET: &str = "test-signing-secret";++// Shared router builder for the provenance tests, with the signing secret set;+// callers supply only what differs (the redis client and quota limiter).+fn ai_router(+ redis: Arc<MockRedisClient>,+ quota_limiter: CaptureQuotaLimiter,+) -> (Router, CapturingSink) {+ let (readiness, liveness, _monitor) = test_lifecycle_handlers();+ let sink = CapturingSink::new();+ let sink_clone = sink.clone();+ let timesource = FixedTime {+ time: DateTime::parse_from_rfc3339(DEFAULT_TEST_TIME)+ .unwrap()+ .with_timezone(&Utc),+ };+ let router = router(+ timesource,+ readiness,+ liveness,+ Arc::new(sink),+ redis,+ None,+ quota_limiter,+ TokenDropper::default(),+ None,+ false,+ CaptureMode::Events,+ String::from("capture-ai"),+ None,+ 25 * 1024 * 1024,+ false,+ 1_i64,+ false,+ 0.0_f32,+ 26_214_400,+ Some(create_mock_blob_storage()),+ None,+ 256,+ 10 * 1024 * 1024,+ 50 * 1024 * 1024,+ None,+ None,+ None,+ 8,+ Some(GW_SECRET.to_string()),+ );+ (router, sink_clone)+}++// LLM-quota-limited (the token reads as over quota) with the signing secret set,+// so a verified event can prove it bypasses the limiter.+fn setup_ai_router_quota_limited_with_secret(token: &str) -> (Router, CapturingSink) {+ 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 mut cfg = DEFAULT_CONFIG.clone();+ cfg.capture_mode = CaptureMode::Events;+ let quota_limiter = CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60))+ .add_scoped_limiter(QuotaResource::LLMEvents, is_llm_event);+ ai_router(redis, quota_limiter)+}++// Signing secret set, no quota limit, so the published event is observable+// (used to assert a forged marker is stripped).+fn setup_ai_router_with_secret() -> (Router, CapturingSink) {+ let redis = Arc::new(MockRedisClient::new());+ let mut cfg = DEFAULT_CONFIG.clone();+ cfg.capture_mode = CaptureMode::Events;+ let quota_limiter =+ CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60 * 60 * 24 * 7));+ ai_router(redis, quota_limiter)+}++// Sends an AI multipart request with the gateway provenance headers attached.+async fn send_signed_ai_request(+ client: &TestClient,+ form: Form,+ token: &str,+ signature: &str,+ signed_at: &str,+ request_id: &str,+) -> axum_test_helper::TestResponse {+ let boundary = form.boundary().to_string();+ let content_type = format!("multipart/form-data; boundary={boundary}");+ let mut stream = form.into_stream();+ let mut body = Vec::new();+ while let Some(chunk) = stream.next().await {+ body.extend_from_slice(&chunk.unwrap());+ }+ client+ .post("/i/v0/ai")+ .header("Content-Type", content_type)+ .header("Authorization", format!("Bearer {token}"))+ .header("PostHog-Ai-Gateway-Signature", signature)+ .header("PostHog-Ai-Gateway-Signed-At", signed_at)+ .header("PostHog-Ai-Gateway-Request-Id", request_id)+ .body(body)+ .send()+ .await+}++#[tokio::test]+async fn test_ai_endpoint_verified_gateway_event_bypasses_quota_and_is_stamped() {+ let token = "phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3";+ let (router, sink) = setup_ai_router_quota_limited_with_secret(token);+ let client = TestClient::new(router);++ let distinct_id = "user-7";+ let request_id = "req-verified-1";+ let sig = capture::v1::gateway_provenance::sign_for_test(+ GW_SECRET.as_bytes(),+ token,+ distinct_id,+ request_id,+ DEFAULT_TEST_TIME,+ );+ let form = create_ai_event_form(+ "$ai_generation",+ distinct_id,+ json!({"$ai_model": "claude"}),+ );+ let resp =+ send_signed_ai_request(&client, form, token, &sig, DEFAULT_TEST_TIME, request_id).await;+ assert_eq!(resp.status(), StatusCode::OK);++ // The token is LLM-quota-limited, so an unverified event would be dropped. A+ // verified gateway event must be exempt (published) and stamped.+ let events = sink.get_events().await;+ assert_eq!(+ events.len(),+ 1,+ "verified gateway event must bypass the LLM quota limiter"+ );+ let data: Value = serde_json::from_str(&events[0].event.data).unwrap();+ assert_eq!(data["properties"]["$ai_gateway_verified"], json!(true));+ assert_eq!(+ data["properties"]["$ai_gateway_request_id"],+ json!(request_id)+ );+}++#[tokio::test]+async fn test_ai_endpoint_forged_marker_is_stripped() {+ let token = "phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3";+ let (router, sink) = setup_ai_router_with_secret();+ let client = TestClient::new(router);++ // Client forges the verified marker and sends an invalid signature.+ let form = create_ai_event_form(+ "$ai_generation",+ "user-7",+ json!({"$ai_model": "claude", "$ai_gateway_verified": true}),+ );+ let resp = send_signed_ai_request(+ &client,+ form,+ token,+ "deadbeef",+ DEFAULT_TEST_TIME,+ "req-forged",+ )+ .await;+ assert_eq!(resp.status(), StatusCode::OK);++ let events = sink.get_events().await;+ assert_eq!(events.len(), 1);+ let data: Value = serde_json::from_str(&events[0].event.data).unwrap();+ assert!(+ data["properties"].get("$ai_gateway_verified").is_none(),+ "a forged $ai_gateway_verified with an invalid signature must be stripped"+ );+}++// Over the global Events quota (the team-wide cap, not the scoped LLM one), with+// the signing secret set.+fn setup_ai_router_global_quota_limited_with_secret(token: &str) -> (Router, CapturingSink) {+ let events_key = format!(+ "{}{}",+ QUOTA_LIMITER_CACHE_KEY,+ QuotaResource::Events.as_str()+ );+ let redis =+ Arc::new(MockRedisClient::new().zrangebyscore_ret(&events_key, vec![token.to_string()]));+ let mut cfg = DEFAULT_CONFIG.clone();+ cfg.capture_mode = CaptureMode::Events;+ let quota_limiter = CaptureQuotaLimiter::new(&cfg, redis.clone(), Duration::from_secs(60));+ ai_router(redis, quota_limiter)+}++#[tokio::test]+async fn test_ai_endpoint_verified_gateway_event_still_subject_to_global_quota() {+ let token = "phc_VXRzc3poSG9GZm1JenRianJ6TTJFZGh4OWY2QXzx9f3";+ let (router, sink) = setup_ai_router_global_quota_limited_with_secret(token);+ let client = TestClient::new(router);++ let distinct_id = "user-7";+ let request_id = "req-global-limited";+ let sig = capture::v1::gateway_provenance::sign_for_test(+ GW_SECRET.as_bytes(),+ token,+ distinct_id,+ request_id,+ DEFAULT_TEST_TIME,+ );+ let form = create_ai_event_form(+ "$ai_generation",+ distinct_id,+ json!({"$ai_model": "claude"}),+ );+ let resp =+ send_signed_ai_request(&client, form, token, &sig, DEFAULT_TEST_TIME, request_id).await;++ // Verified gateway events are exempt from the scoped LLM quota but not the+ // global Events quota, so an over-global-quota token is still rejected.+ assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);+ assert_eq!(+ sink.get_events().await.len(),+ 0,+ "verified gateway event must still obey the global Events quota"+ );+}