: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 at the edge (#64806)
Richard Solomou1c3f7da66b97
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex ec0d1a9fcbf2..d405eeaa7b2d 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -1792,6 +1792,7 @@ dependencies = ["flate2","futures","hex",+ "hmac","http-body-util","httparse","hyper 1.9.0",diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex 72f4f41240b9..dec2bda0c5b8 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -204,4 +204,5 @@ clickhouse = { version = "0.13.2", features = [fernet = "0.2"tiktoken-rs = "0.7.0"sha2 = "0.10"+hmac = "0.12"testcontainers = "0.27.2"diff --git a/rust/capture/Cargo.toml b/rust/capture/Cargo.tomlindex 02602138bbb5..7cdd3dfa2dd7 100644--- a/rust/capture/Cargo.toml+++ b/rust/capture/Cargo.toml@@ -61,6 +61,7 @@ lz4 = { workspace = true }multer = "3.0"futures = { workspace = true }sha2 = { workspace = true }+hmac = { workspace = true }[dev-dependencies]capture = { path = ".", features = ["test-utils"] }diff --git a/rust/capture/src/config.rs b/rust/capture/src/config.rsindex 69f1cd4615f6..9cd798a03ba8 100644--- a/rust/capture/src/config.rs+++ b/rust/capture/src/config.rs@@ -227,6 +227,12 @@ pub struct Config {pub ai_s3_access_key_id: Option<String>,pub ai_s3_secret_access_key: Option<String>,+ // HMAC-SHA256 key shared with the AI gateway. When set, $ai_generation events+ // carrying a valid PostHog-Ai-Gateway-* signature are stamped verified and+ // exempted from the llm_events quota limiter. Unset disables verification+ // (all $ai_gateway* props are stripped as untrusted).+ pub ai_gateway_signing_secret: Option<String>,+// HTTP/1 header read timeout in milliseconds - closes connections that don't// send complete headers within this duration (slow loris protection).// Set env var to enable; unset to disable.diff --git a/rust/capture/src/router.rs b/rust/capture/src/router.rsindex 5cf9ef7768b0..bcd089cf3658 100644--- a/rust/capture/src/router.rs+++ b/rust/capture/src/router.rs@@ -83,6 +83,7 @@ pub struct State {/// When present, the v1 analytics handler publishes events through this.pub v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,pub capture_v1_scatter_gather_min_batch: usize,+ pub ai_gateway_signing_secret: Option<String>,}#[derive(Clone, Copy)]@@ -151,6 +152,7 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +replay_overflow_limiter: Option<Arc<RedisLimiter>>,v1_sink_router: Option<Arc<crate::v1::sinks::Router>>,capture_v1_scatter_gather_min_batch: usize,+ ai_gateway_signing_secret: Option<String>,) -> Router {let state = State {sink,@@ -177,6 +179,7 @@ pub fn router<TZ: TimeSource + Send + Sync + 'static, R: Client + Send + Sync +replay_overflow_limiter,v1_sink_router,capture_v1_scatter_gather_min_batch,+ ai_gateway_signing_secret,};// Very permissive CORS policy, as old SDK versionsdiff --git a/rust/capture/src/setup.rs b/rust/capture/src/setup.rsindex c7984966d2a1..b0cb154a877c 100644--- a/rust/capture/src/setup.rs+++ b/rust/capture/src/setup.rs@@ -327,6 +327,7 @@ pub async fn build_components(replay_overflow_limiter,v1_sink_router.clone(),config.capture_v1_scatter_gather_min_batch,+ config.ai_gateway_signing_secret.clone(),);info!(diff --git a/rust/capture/src/v1/analytics/process.rs b/rust/capture/src/v1/analytics/process.rsindex e1a037c68cb9..f04ffa94ce6a 100644--- a/rust/capture/src/v1/analytics/process.rs+++ b/rust/capture/src/v1/analytics/process.rs@@ -63,6 +63,10 @@ pub async fn process_batch(return Ok(BatchResponse::build(context, &events));}+ // Verify gateway provenance before the quota limiter so verified events can+ // be exempted from the llm_events meter (they're wallet-billed, not AIO).+ apply_gateway_provenance(state, context, &mut events);+crate::v1::quota_limiter_shim::apply_quota_limits(&state.quota_limiter,&context.api_token,@@ -124,6 +128,85 @@ pub async fn process_batch(Ok(BatchResponse::build(context, &events))}+// Verify gateway provenance on each `$ai_*` event: a fresh, valid signature stamps+// the trusted marker and exempts it from the llm_events meter; anything else has its+// `$ai_gateway*` props stripped. The strip path skips the parse unless the raw bytes+// plausibly carry a gateway key, so ordinary traffic stays off the hot path.+fn apply_gateway_provenance(state: &router::State, context: &Context, events: &mut [WrappedEvent]) {+ use crate::v1::gateway_provenance as gp;++ let secret = state+ .ai_gateway_signing_secret+ .as_deref()+ .filter(|s| !s.is_empty());+ let now = context.server_received_at;++ for ev in events.iter_mut() {+ if ev.result != EventResult::Ok || !ev.event.event.starts_with("$ai_") {+ continue;+ }++ let sig = context.gateway_signature.as_ref();+ let outcome = match (secret, sig) {+ (Some(secret), Some(sig)) => gp::verify(+ secret.as_bytes(),+ &context.api_token,+ &ev.event.distinct_id,+ sig,+ now,+ ),+ // No secret or no signature — nothing to trust.+ _ => gp::Provenance::Invalid,+ };++ // Trust needs a non-empty request_id — billing dedups exemptions by it.+ let request_id = sig.map(|s| s.request_id.as_str()).unwrap_or_default();+ let trusted = outcome == gp::Provenance::Verified && !request_id.is_empty();++ if trusted {+ match gp::stamp_verified_raw(&ev.event.properties, request_id) {+ gp::StampOutcome::Stamped(props) => {+ ev.event.properties = props;+ ev.is_gateway_verified = true;+ metrics::counter!(gp::PROVENANCE_METRIC, "reason" => "verified").increment(1);+ }+ gp::StampOutcome::Unparseable => drop_unparseable_gateway_props(ev),+ }+ } else if gp::has_gateway_props(&ev.event.properties) {+ match gp::strip_gateway_raw(&ev.event.properties) {+ gp::StripOutcome::Stripped { props, forged } => {+ ev.event.properties = props;+ let reason = if forged {+ // A client-supplied $ai_gateway_verified — a real forgery.+ "forged"+ } else if outcome == gp::Provenance::Stale {+ "stale" // valid HMAC, outside the window — clock skew+ } else {+ "stripped" // leftover $ai_gateway* prop, no marker — benign+ };+ metrics::counter!(gp::PROVENANCE_METRIC, "reason" => reason).increment(1);+ }+ gp::StripOutcome::Unchanged => {}+ gp::StripOutcome::Unparseable => drop_unparseable_gateway_props(ev),+ }+ }+ }+}++/// Drop a `$ai_*` event whose properties carry a gateway key but can't be parsed to+/// strip or stamp it. `RawValue` and ClickHouse accept JSON the typed parse rejects,+/// so a forged marker we can't remove would otherwise survive to billing — fail closed.+fn drop_unparseable_gateway_props(ev: &mut WrappedEvent) {+ ev.result = EventResult::Drop;+ ev.destination = Destination::Drop;+ ev.details = Some("gateway_props_unparseable");+ metrics::counter!(+ crate::v1::gateway_provenance::PROVENANCE_METRIC,+ "reason" => "dropped_unparseable"+ )+ .increment(1);+}+// ---------------------------------------------------------------------------// SinkResult → WrappedEvent merge// ---------------------------------------------------------------------------@@ -222,6 +305,7 @@ fn validate_events(context: &RequestContext, batch: Batch) -> Result<Vec<Wrapped},destination,force_disable_person_processing: illegal,+ is_gateway_verified: false,});}Err(err) => {@@ -233,6 +317,7 @@ fn validate_events(context: &RequestContext, batch: Batch) -> Result<Vec<Wrappeddetails: Some(err.tag()),destination,force_disable_person_processing: false,+ is_gateway_verified: false,});}}@@ -1013,6 +1098,7 @@ mod tests {created_at: None,capture_internal: false,historical_migration: false,+ gateway_signature: None,}}@@ -2298,6 +2384,299 @@ mod tests {assert_eq!(events[0].destination, Destination::AnalyticsMain);}+ // =========================================================================+ // apply_gateway_provenance tests — the verify→billing wiring+ // =========================================================================++ use crate::v1::gateway_provenance::{sign_for_test, GatewaySignature};+ use crate::v1::test_utils::TestStateBuilder;++ const GW_SECRET: &str = "test-signing-secret";++ /// Analytics context with `now` as the capture time, an api_token, and an+ /// optional gateway signature — the inputs `apply_gateway_provenance` reads.+ fn gateway_context(token: &str, now: DateTime<Utc>, sig: Option<GatewaySignature>) -> Context {+ let mut ctx = test_utils::test_analytics_context();+ ctx.req.api_token = token.to_string();+ ctx.req.server_received_at = now;+ ctx.req.gateway_signature = sig;+ ctx+ }++ fn ai_event(distinct_id: &str, properties: &str) -> WrappedEvent {+ wrapped_event("$ai_generation", distinct_id).with_properties(properties)+ }++ #[tokio::test]+ async fn gateway_provenance_leaves_non_ai_events_untouched() {+ let token = "phc_test_token";+ let now = Utc::now();+ let state = TestStateBuilder::new()+ .with_ai_gateway_signing_secret(GW_SECRET)+ .build()+ .state;+ let signed_at = now.to_rfc3339();+ let sig = GatewaySignature {+ signature: sign_for_test(GW_SECRET.as_bytes(), token, "user-1", "req-1", &signed_at),+ signed_at,+ request_id: "req-1".to_string(),+ };+ let ctx = gateway_context(token, now, Some(sig));++ // A valid signature is present, but a non-$ai_ event must be skipped: its+ // client `$ai_gateway*` props are neither stamped nor stripped.+ let mut events =+ vec![wrapped_event("$pageview", "user-1").with_properties(r#"{"$ai_gateway": true}"#)];+ apply_gateway_provenance(&state, &ctx, &mut events);++ assert!(!events[0].is_gateway_verified);+ assert!(events[0].event.properties.get().contains("$ai_gateway"));+ }++ #[tokio::test]+ async fn gateway_provenance_verifies_and_stamps_a_valid_signature() {+ let token = "phc_test_token";+ let distinct_id = "user-1";+ let now = Utc::now();+ let state = TestStateBuilder::new()+ .with_ai_gateway_signing_secret(GW_SECRET)+ .build()+ .state;+ let signed_at = now.to_rfc3339();+ let sig = GatewaySignature {+ signature: sign_for_test(+ GW_SECRET.as_bytes(),+ token,+ distinct_id,+ "req-1",+ &signed_at,+ ),+ signed_at,+ request_id: "req-1".to_string(),+ };+ let ctx = gateway_context(token, now, Some(sig));++ // Client supplies its own request_id — the signed one must win.+ let mut events = vec![ai_event(+ distinct_id,+ r#"{"$ai_model": "claude", "$ai_gateway_request_id": "client-fake"}"#,+ )];+ apply_gateway_provenance(&state, &ctx, &mut events);++ assert!(events[0].is_gateway_verified);+ let props: serde_json::Value =+ serde_json::from_str(events[0].event.properties.get()).unwrap();+ assert_eq!(props["$ai_gateway_verified"], serde_json::Value::Bool(true));+ assert_eq!(+ props["$ai_gateway_request_id"],+ serde_json::Value::String("req-1".to_string()),+ "the signed request_id must overwrite the client value"+ );+ }++ #[tokio::test]+ async fn gateway_provenance_strips_forged_props_and_does_not_verify() {+ let token = "phc_test_token";+ let distinct_id = "user-1";+ let now = Utc::now();+ let state = TestStateBuilder::new()+ .with_ai_gateway_signing_secret(GW_SECRET)+ .build()+ .state;+ // No signature on the request: a client-set `$ai_gateway_verified` must be+ // stripped and the event must not be marked verified.+ let ctx = gateway_context(token, now, None);++ let mut events = vec![ai_event(+ distinct_id,+ r#"{"$ai_gateway_verified": true, "$ai_gateway": "forged", "$ai_model": "claude"}"#,+ )];+ apply_gateway_provenance(&state, &ctx, &mut events);++ assert!(!events[0].is_gateway_verified);+ let raw = events[0].event.properties.get();+ assert!(+ !raw.contains("$ai_gateway"),+ "gateway props must be stripped"+ );+ assert!(raw.contains("$ai_model"), "non-gateway props must survive");+ }++ /// The signature binds `distinct_id`, so in a batch where it's signed for only+ /// one event, only that event is verified — the other's forged marker is+ /// stripped, even sharing one request-level signature.+ #[tokio::test]+ async fn gateway_provenance_verifies_only_the_signed_distinct_id_in_a_batch() {+ let token = "phc_test_token";+ let signed_id = "user-signed";+ let now = Utc::now();+ let state = TestStateBuilder::new()+ .with_ai_gateway_signing_secret(GW_SECRET)+ .build()+ .state;+ let signed_at = now.to_rfc3339();+ let sig = GatewaySignature {+ signature: sign_for_test(GW_SECRET.as_bytes(), token, signed_id, "req-1", &signed_at),+ signed_at,+ request_id: "req-1".to_string(),+ };+ let ctx = gateway_context(token, now, Some(sig));++ let mut events = vec![+ ai_event(signed_id, r#"{"$ai_model": "claude"}"#),+ // Different distinct_id, riding the same request signature, with a+ // forged marker — must not verify against a sig bound to `signed_id`.+ ai_event(+ "user-other",+ r#"{"$ai_gateway_verified": true, "$ai_model": "gpt"}"#,+ ),+ ];+ apply_gateway_provenance(&state, &ctx, &mut events);++ assert!(events[0].is_gateway_verified, "signed distinct_id verifies");+ assert!(+ !events[1].is_gateway_verified,+ "unsigned distinct_id must not verify"+ );+ assert!(+ !events[1].event.properties.get().contains("$ai_gateway"),+ "the other event's forged marker must be stripped"+ );+ }++ /// Fail closed: an unverified event whose props carry a forged marker but can't+ /// be parsed to strip it (RawValue accepts an out-of-range number serde rejects)+ /// is dropped, so the marker can't reach billing via ClickHouse's lenient reader.+ #[tokio::test]+ async fn gateway_provenance_drops_event_with_unparseable_forged_props() {+ let token = "phc_test_token";+ let now = Utc::now();+ let state = TestStateBuilder::new()+ .with_ai_gateway_signing_secret(GW_SECRET)+ .build()+ .state;+ let ctx = gateway_context(token, now, None);++ let mut events = vec![ai_event(+ "user-1",+ r#"{"$ai_gateway_verified": true, "x": 1e500}"#,+ )];+ apply_gateway_provenance(&state, &ctx, &mut events);++ assert_eq!(events[0].result, EventResult::Drop);+ assert_eq!(events[0].details, Some("gateway_props_unparseable"));+ assert!(!events[0].is_gateway_verified);+ }++ /// Fail closed on the verified path too: a valid signature can't excuse props we+ /// can't parse to stamp, since a forged marker hidden in them would survive.+ #[tokio::test]+ async fn gateway_provenance_drops_verified_event_with_unparseable_props() {+ let token = "phc_test_token";+ let distinct_id = "user-1";+ let now = Utc::now();+ let state = TestStateBuilder::new()+ .with_ai_gateway_signing_secret(GW_SECRET)+ .build()+ .state;+ let signed_at = now.to_rfc3339();+ let sig = GatewaySignature {+ signature: sign_for_test(+ GW_SECRET.as_bytes(),+ token,+ distinct_id,+ "req-1",+ &signed_at,+ ),+ signed_at,+ request_id: "req-1".to_string(),+ };+ let ctx = gateway_context(token, now, Some(sig));++ let mut events = vec![ai_event(distinct_id, r#"{"$ai_model": "x", "y": 1e500}"#)];+ apply_gateway_provenance(&state, &ctx, &mut events);++ assert_eq!(events[0].result, EventResult::Drop);+ assert_eq!(events[0].details, Some("gateway_props_unparseable"));+ assert!(!events[0].is_gateway_verified);+ }++ /// process_batch wiring: a valid signature is verified ahead of the limiter+ /// and the trusted marker survives serialization into the published payload.+ #[tokio::test]+ async fn process_batch_stamps_verified_gateway_event_into_published_payload() {+ let token = "phc_test_token";+ let distinct_id = "user-1";+ let now = Utc::now();+ let ts = TestStateBuilder::new()+ .with_ai_gateway_signing_secret(GW_SECRET)+ .build();+ let signed_at = now.to_rfc3339();+ let sig = GatewaySignature {+ signature: sign_for_test(+ GW_SECRET.as_bytes(),+ token,+ distinct_id,+ "req-1",+ &signed_at,+ ),+ signed_at,+ request_id: "req-1".to_string(),+ };+ let mut ctx = gateway_context(token, now, Some(sig));+ let batch = valid_batch(vec![Event {+ event: "$ai_generation".to_string(),+ distinct_id: distinct_id.to_string(),+ properties: test_utils::raw_obj(r#"{"$ai_model":"claude"}"#),+ ..valid_event()+ }]);++ process_batch(&ts.state, &mut ctx, batch).await.unwrap();++ ts.mock_producer.with_records(|records| {+ assert_eq!(records.len(), 1, "the verified event must be published");+ assert!(+ records[0].payload.contains("$ai_gateway_verified"),+ "verified marker must reach the published payload"+ );+ });+ }++ /// process_batch wiring: a client-set marker with no signature is stripped+ /// before the event is serialized, so it never reaches the meter as trusted.+ #[tokio::test]+ async fn process_batch_strips_forged_gateway_marker_from_published_payload() {+ let token = "phc_test_token";+ let now = Utc::now();+ let ts = TestStateBuilder::new()+ .with_ai_gateway_signing_secret(GW_SECRET)+ .build();+ let mut ctx = gateway_context(token, now, None);+ let batch = valid_batch(vec![Event {+ event: "$ai_generation".to_string(),+ distinct_id: "user-1".to_string(),+ properties: test_utils::raw_obj(+ r#"{"$ai_gateway_verified":true,"$ai_model":"claude"}"#,+ ),+ ..valid_event()+ }]);++ process_batch(&ts.state, &mut ctx, batch).await.unwrap();++ ts.mock_producer.with_records(|records| {+ assert_eq!(+ records.len(),+ 1,+ "the event is still published, just untrusted"+ );+ assert!(+ !records[0].payload.contains("$ai_gateway"),+ "forged marker must be stripped before publish"+ );+ assert!(records[0].payload.contains("$ai_model"));+ });+ }+// =========================================================================// merge_sink_results tests// =========================================================================diff --git a/rust/capture/src/v1/analytics/response.rs b/rust/capture/src/v1/analytics/response.rsindex f1a21e39d3ee..c1d77f86dcd7 100644--- a/rust/capture/src/v1/analytics/response.rs+++ b/rust/capture/src/v1/analytics/response.rs@@ -188,6 +188,7 @@ mod tests {details,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,}}diff --git a/rust/capture/src/v1/analytics/types.rs b/rust/capture/src/v1/analytics/types.rsindex b195d11a8a9b..a7f67c387deb 100644--- a/rust/capture/src/v1/analytics/types.rs+++ b/rust/capture/src/v1/analytics/types.rs@@ -110,6 +110,9 @@ pub struct WrappedEvent {pub details: Option<&'static str>,pub destination: Destination,pub force_disable_person_processing: bool,+ /// Set by the gateway-provenance step when a valid signature was verified;+ /// read by the quota shim to exempt the event from the llm_events limiter.+ pub is_gateway_verified: bool,}impl SinkEvent for WrappedEvent {@@ -1064,6 +1067,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,}}@@ -1244,6 +1248,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,};let ctx = serialize_ctx();@@ -1284,6 +1289,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,};let ctx = serialize_ctx();@@ -1323,6 +1329,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,};let ctx = serialize_ctx();@@ -1359,6 +1366,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,};let ctx = serialize_ctx();@@ -1398,6 +1406,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,};let ctx = serialize_ctx();@@ -1515,6 +1524,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: true,+ is_gateway_verified: false,};let ctx = serialize_ctx();@@ -1556,6 +1566,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,};let ctx = serialize_ctx();@@ -1595,6 +1606,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,};let ctx = serialize_ctx();@@ -1630,6 +1642,7 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,};let ctx = serialize_ctx();diff --git a/rust/capture/src/v1/constants.rs b/rust/capture/src/v1/constants.rsindex 800227970b0a..13a936c544d8 100644--- a/rust/capture/src/v1/constants.rs+++ b/rust/capture/src/v1/constants.rs@@ -21,6 +21,16 @@ pub const POSTHOG_REQUEST_ID: &str = "PostHog-Request-Id";/// Header carrying the SDK-side timestamp of the request.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";++/// AI-gateway provenance: RFC3339 timestamp the gateway signed at.+pub const POSTHOG_AI_GATEWAY_SIGNED_AT: &str = "PostHog-Ai-Gateway-Signed-At";++/// 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";+// ---------------------------------------------------------------------------// Supported content encodings// ---------------------------------------------------------------------------diff --git a/rust/capture/src/v1/context.rs b/rust/capture/src/v1/context.rsindex 0e8099664e8c..9777885cb2e1 100644--- a/rust/capture/src/v1/context.rs+++ b/rust/capture/src/v1/context.rs@@ -32,6 +32,8 @@ pub struct RequestContext {pub created_at: Option<String>,pub capture_internal: bool,pub historical_migration: bool,+ /// AI-gateway provenance signature parsed from the request headers, if present.+ pub gateway_signature: Option<super::gateway_provenance::GatewaySignature>,}/// Extracts a required header as &str, assuming presence was already checked.@@ -159,6 +161,8 @@ impl RequestContext {let user_agent = header_str(headers, "user-agent")?.to_string();let sdk_info = header_str(headers, POSTHOG_SDK_INFO)?.to_string();+ let gateway_signature = super::gateway_provenance::parse_signature(headers);+Ok(Self {api_token,user_agent,@@ -176,6 +180,7 @@ impl RequestContext {created_at: None,capture_internal: false,historical_migration: false,+ gateway_signature,})}diff --git a/rust/capture/src/v1/gateway_provenance.rs b/rust/capture/src/v1/gateway_provenance.rsnew file mode 100644index 000000000000..7946482acf0a--- /dev/null+++ b/rust/capture/src/v1/gateway_provenance.rs@@ -0,0 +1,694 @@+// AI-gateway provenance verification.+//+// The gateway bills a customer's LLM calls against a prepaid wallet and posts an+// `$ai_generation` per call through capture, so those events must be excluded from+// the team's billable AIO usage. The `$ai_gateway*` properties are client-settable+// and untrusted, so the gateway HMAC-signs each event and capture verifies here,+// before the llm_events limiter: a valid, fresh signature stamps a trusted+// `$ai_gateway_verified` and exempts the event; anything else has the whole+// `$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 serde_json::value::RawValue;+use serde_json::{Map, Value};+use sha2::Sha256;++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";+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";++/// Counter on every event-mutating provenance decision, labelled by `reason`+/// (`verified`/`stale`/`forged`) so forgery and clock skew are alertable.+pub const PROVENANCE_METRIC: &str = "capture_v1_gateway_provenance";++/// JSON-key form of `GATEWAY_PREFIX` (leading quote, no escapes) for the fast-path+/// scan. The static assert below pins it to `GATEWAY_PREFIX` so it can't drift.+const GATEWAY_KEY_NEEDLE: &str = "\"$ai_gateway";+const _: () = assert!(+ {+ let needle = GATEWAY_KEY_NEEDLE.as_bytes();+ let prefix = GATEWAY_PREFIX.as_bytes();+ let mut ok = needle.len() == prefix.len() + 1 && needle[0] == b'"';+ let mut i = 0;+ while i < prefix.len() {+ ok = ok && needle[i + 1] == prefix[i];+ i += 1;+ }+ ok+ },+ "GATEWAY_KEY_NEEDLE must be a quote followed by GATEWAY_PREFIX"+);++/// 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;++/// The provenance signature carried on the request headers.+#[derive(Debug, Clone)]+pub struct GatewaySignature {+ pub signature: String,+ pub signed_at: String,+ pub request_id: String,+}++/// Reads the provenance headers. `None` unless both signature and signed_at are+/// 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(),+ })+}++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],+ token: &str,+ distinct_id: &str,+ 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,+ }+}++/// Stamps the trusted marker and the signed request_id, overwriting client values.+/// Other `$ai_gateway*` props rode a valid signature, so they survive.+pub fn stamp_verified(props: &mut Map<String, Value>, request_id: &str) {+ props.insert(VERIFIED_PROPERTY.to_string(), Value::Bool(true));+ props.insert(+ REQUEST_ID_PROPERTY.to_string(),+ Value::String(request_id.to_owned()),+ );+}++/// 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));+}++/// Cheap raw-bytes pre-check: does the property object plausibly carry a+/// `$ai_gateway*` key? Lets the hot path skip the allocating parse for ordinary+/// `$ai_*` events. The literal prefix covers every legit event and unescaped client+/// value; only a JSON `\u` escape can hide the all-ASCII prefix, so with no `\u` the+/// substring scan is conclusive. With a `\u`, scan object keys only (never values),+/// so a value-side `\u` can't force the parse; a literal false-positive only wastes a parse.+pub fn has_gateway_props(properties: &RawValue) -> bool {+ let raw = properties.get();+ if raw.contains(GATEWAY_KEY_NEEDLE) {+ return true;+ }+ raw.contains("\\u") && scan_for_escaped_gateway_key(raw)+}++/// Single pass over a JSON object's bytes looking for an object key that decodes+/// to a string starting with `$ai_gateway`, without materializing any value. A+/// string token is a key iff the next non-whitespace byte is `:` — so a `\u`+/// escape inside a value is skipped over and never decoded.+fn scan_for_escaped_gateway_key(raw: &str) -> bool {+ let b = raw.as_bytes();+ let mut i = 0;+ while i < b.len() {+ if b[i] != b'"' {+ i += 1;+ continue;+ }+ // Find the closing quote, skipping escaped bytes (incl. `\uXXXX`).+ let start = i + 1;+ let mut j = start;+ let mut closed = false;+ while j < b.len() {+ match b[j] {+ b'\\' => j += 2,+ b'"' => {+ closed = true;+ break;+ }+ _ => j += 1,+ }+ }+ if !closed {+ return false; // unterminated string — malformed, nothing more to find+ }+ let mut k = j + 1;+ while k < b.len() && b[k].is_ascii_whitespace() {+ k += 1;+ }+ if k < b.len() && b[k] == b':' && key_starts_with_gateway(&b[start..j]) {+ return true;+ }+ i = j + 1;+ }+ false+}++/// Decodes the (possibly `\u`-escaped) key content just far enough to test the+/// `$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 mut ti = 0;+ let mut i = 0;+ while ti < target.len() {+ if i >= content.len() {+ return false;+ }+ let (ch, next) = if content[i] == b'\\' {+ if content.get(i + 1) != Some(&b'u') || i + 6 > content.len() {+ return false;+ }+ match parse_hex4(&content[i + 2..i + 6]) {+ Some(cp) if cp <= 0x7f => (cp as u8, i + 6),+ _ => return false,+ }+ } else {+ (content[i], i + 1)+ };+ if ch != target[ti] {+ return false;+ }+ ti += 1;+ i = next;+ }+ true+}++fn parse_hex4(b: &[u8]) -> Option<u32> {+ let mut v = 0u32;+ for &c in b {+ let d = match c {+ b'0'..=b'9' => c - b'0',+ b'a'..=b'f' => c - b'a' + 10,+ b'A'..=b'F' => c - b'A' + 10,+ _ => return None,+ };+ v = v * 16 + d as u32;+ }+ Some(v)+}++/// Outcome of stripping the `$ai_gateway*` namespace from raw properties.+#[derive(Debug)]+pub enum StripOutcome {+ /// Stripped at least one key. `forged` is true if the trusted marker+ /// `$ai_gateway_verified` was among them — a client-supplied marker, since the+ /// gateway never sends it (capture stamps it post-verify), so always a forgery.+ Stripped { props: Box<RawValue>, forged: bool },+ /// Parsed fine, no `$ai_gateway*` key to strip (the raw pre-check matched a value).+ Unchanged,+ /// Couldn't parse the properties as an object. `RawValue` accepts JSON that the+ /// typed parse rejects (out-of-range numbers, over-deep nesting) and ClickHouse's+ /// reader is more lenient still, so a forged marker we can't strip could survive+ /// to billing. The caller must fail closed (drop the event).+ Unparseable,+}++pub fn strip_gateway_raw(properties: &RawValue) -> StripOutcome {+ let Ok(mut map) = serde_json::from_str::<Map<String, Value>>(properties.get()) else {+ return StripOutcome::Unparseable;+ };+ let forged = map.contains_key(VERIFIED_PROPERTY);+ let before = map.len();+ strip_gateway(&mut map);+ if map.len() == before {+ return StripOutcome::Unchanged;+ }+ match reserialize(map) {+ Some(props) => StripOutcome::Stripped { props, forged },+ None => StripOutcome::Unparseable,+ }+}++/// Stamps the trusted marker and signed request_id onto raw properties.+/// `Unparseable` (see [`StripOutcome::Unparseable`]) when the typed parse fails, so+/// the caller fails closed rather than passing an unstrippable forged marker through.+#[derive(Debug)]+pub enum StampOutcome {+ Stamped(Box<RawValue>),+ Unparseable,+}++pub fn stamp_verified_raw(properties: &RawValue, request_id: &str) -> StampOutcome {+ let Ok(mut map) = serde_json::from_str::<Map<String, Value>>(properties.get()) else {+ return StampOutcome::Unparseable;+ };+ stamp_verified(&mut map, request_id);+ match reserialize(map) {+ Some(props) => StampOutcome::Stamped(props),+ None => StampOutcome::Unparseable,+ }+}++fn reserialize(map: Map<String, Value>) -> Option<Box<RawValue>> {+ RawValue::from_string(serde_json::to_string(&Value::Object(map)).ok()?).ok()+}++/// Test-only signer: produces the hex HMAC the gateway would emit for this tuple,+/// so other modules' (and integration) tests can build signatures `verify` accepts.+#[cfg(any(test, feature = "test-utils"))]+pub fn sign_for_test(+ secret: &[u8],+ token: &str,+ distinct_id: &str,+ 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())+}++#[cfg(test)]+mod tests {+ use super::*;++ const SECRET: &[u8] = b"test-signing-secret";+ const TOKEN: &str = "phc_test";+ const DISTINCT_ID: &str = "user-7";++ fn sign(token: &str, distinct_id: &str, request_id: &str, signed_at: &str) -> String {+ sign_for_test(SECRET, token, distinct_id, request_id, signed_at)+ }++ fn now() -> DateTime<Utc> {+ "2026-05-28T10:00:00Z".parse().unwrap()+ }++ fn valid_sig(request_id: &str) -> GatewaySignature {+ let signed_at = "2026-05-28T10:00:00Z".to_string();+ GatewaySignature {+ signature: sign(TOKEN, DISTINCT_ID, request_id, &signed_at),+ signed_at,+ request_id: request_id.to_string(),+ }+ }++ #[test]+ fn verifies_a_valid_fresh_signature() {+ assert_eq!(+ verify(SECRET, TOKEN, DISTINCT_ID, &valid_sig("req-1"), now()),+ Provenance::Verified+ );+ }++ #[test]+ fn verifies_with_an_empty_request_id() {+ assert_eq!(+ verify(SECRET, TOKEN, DISTINCT_ID, &valid_sig(""), now()),+ Provenance::Verified+ );+ }++ #[test]+ fn rejects_a_tampered_distinct_id() {+ assert_eq!(+ verify(SECRET, TOKEN, "user-8", &valid_sig("req-1"), now()),+ Provenance::Invalid+ );+ }++ #[test]+ fn rejects_a_tampered_token() {+ assert_eq!(+ verify(SECRET, "phc_other", DISTINCT_ID, &valid_sig("req-1"), now()),+ Provenance::Invalid+ );+ }++ #[test]+ fn rejects_a_garbage_signature() {+ let mut sig = valid_sig("req-1");+ sig.signature = "deadbeef".to_string();+ assert_eq!(+ verify(SECRET, TOKEN, DISTINCT_ID, &sig, now()),+ Provenance::Invalid+ );+ }++ #[test]+ fn rejects_a_non_hex_signature() {+ let mut sig = valid_sig("req-1");+ sig.signature = "not-hex".to_string();+ assert_eq!(+ verify(SECRET, TOKEN, DISTINCT_ID, &sig, now()),+ Provenance::Invalid+ );+ }++ #[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()),+ signed_at,+ request_id: "req-1".to_string(),+ };+ assert_eq!(+ verify(SECRET, TOKEN, DISTINCT_ID, &sig, now()),+ Provenance::Invalid+ );+ }++ #[test]+ fn distinct_id_cannot_shift_field_boundaries() {+ // A signature for (distinct_id="user", request_id="req") must NOT verify+ // when the boundary-shifting candidate (distinct_id="user\nreq",+ // request_id="") is presented. A delimiter join would collide here;+ // length-prefixing keeps the two encodings distinct.+ let signed_at = "2026-05-28T10:00:00Z".to_string();+ let signature = sign(TOKEN, "user", "req", &signed_at);+ let forged = GatewaySignature {+ signature,+ signed_at,+ request_id: String::new(),+ };+ assert_eq!(+ verify(SECRET, TOKEN, "user\nreq", &forged, now()),+ Provenance::Invalid+ );+ }++ #[test]+ fn rejects_a_stale_signature() {+ let stale = (now() - chrono::Duration::seconds(FRESHNESS_WINDOW_SECS + 1)).to_rfc3339();+ let sig = GatewaySignature {+ signature: sign(TOKEN, DISTINCT_ID, "req-1", &stale),+ signed_at: stale,+ request_id: "req-1".to_string(),+ };+ // Valid HMAC, but outside the window — clock skew, not forgery.+ assert_eq!(+ verify(SECRET, TOKEN, DISTINCT_ID, &sig, now()),+ Provenance::Stale+ );+ }++ #[test]+ fn accepts_a_signature_at_the_window_edge() {+ let edge = (now() - chrono::Duration::seconds(FRESHNESS_WINDOW_SECS)).to_rfc3339();+ let sig = GatewaySignature {+ signature: sign(TOKEN, DISTINCT_ID, "req-1", &edge),+ signed_at: edge,+ request_id: "req-1".to_string(),+ };+ assert_eq!(+ verify(SECRET, TOKEN, DISTINCT_ID, &sig, now()),+ Provenance::Verified+ );+ }++ #[test]+ fn accepts_a_future_signature_at_the_window_edge() {+ // Freshness is symmetric: a signed_at exactly +window in the future is+ // accepted, mirroring the past edge. Guards the `.abs()` on the skew.+ let edge = (now() + chrono::Duration::seconds(FRESHNESS_WINDOW_SECS)).to_rfc3339();+ let sig = GatewaySignature {+ signature: sign(TOKEN, DISTINCT_ID, "req-1", &edge),+ signed_at: edge,+ request_id: "req-1".to_string(),+ };+ assert_eq!(+ verify(SECRET, TOKEN, DISTINCT_ID, &sig, now()),+ Provenance::Verified+ );+ }++ #[test]+ fn rejects_a_future_signature_past_the_window() {+ // One second past the future edge is rejected.+ let beyond = (now() + chrono::Duration::seconds(FRESHNESS_WINDOW_SECS + 1)).to_rfc3339();+ let sig = GatewaySignature {+ signature: sign(TOKEN, DISTINCT_ID, "req-1", &beyond),+ signed_at: beyond,+ request_id: "req-1".to_string(),+ };+ // Valid HMAC, but past the future edge — skew, not forgery.+ assert_eq!(+ verify(SECRET, TOKEN, DISTINCT_ID, &sig, now()),+ Provenance::Stale+ );+ }++ #[test]+ fn rejects_an_unparseable_signed_at() {+ let sig = GatewaySignature {+ signature: sign(TOKEN, DISTINCT_ID, "req-1", "not-a-date"),+ signed_at: "not-a-date".to_string(),+ request_id: "req-1".to_string(),+ };+ // HMAC is valid (the gateway signed it), but the timestamp doesn't+ // parse, so freshness fails — never trusted.+ assert_eq!(+ verify(SECRET, TOKEN, DISTINCT_ID, &sig, now()),+ Provenance::Stale+ );+ }++ #[test]+ fn parse_requires_signature_and_signed_at() {+ let mut headers = HeaderMap::new();+ assert!(parse_signature(&headers).is_none());+ headers.insert(POSTHOG_AI_GATEWAY_SIGNATURE, "abc".parse().unwrap());+ assert!(parse_signature(&headers).is_none());+ headers.insert(+ POSTHOG_AI_GATEWAY_SIGNED_AT,+ "2026-05-28T10:00:00Z".parse().unwrap(),+ );+ let sig = parse_signature(&headers).unwrap();+ assert_eq!(sig.signature, "abc");+ assert_eq!(sig.request_id, "");+ }++ #[test]+ fn stamp_verified_overwrites_a_client_value_and_keeps_other_props() {+ let mut props: Map<String, Value> = serde_json::from_str(+ r#"{"$ai_gateway": true, "$ai_gateway_verified": false, "$ai_gateway_request_id": "client-fake", "$ai_model": "claude"}"#,+ )+ .unwrap();+ stamp_verified(&mut props, "signed-req");+ assert_eq!(props["$ai_gateway_verified"], Value::Bool(true));+ // request_id is overwritten with the signed value, not the client's.+ assert_eq!(+ props["$ai_gateway_request_id"],+ Value::String("signed-req".to_string())+ );+ assert_eq!(props["$ai_gateway"], Value::Bool(true));+ assert_eq!(props["$ai_model"], Value::String("claude".to_string()));+ }++ #[test]+ fn strip_gateway_removes_the_whole_namespace_including_a_forged_marker() {+ let mut props: Map<String, Value> = serde_json::from_str(+ r#"{"$ai_gateway": true, "$ai_gateway_verified": true, "$ai_model": "claude"}"#,+ )+ .unwrap();+ strip_gateway(&mut props);+ assert!(!props.contains_key("$ai_gateway"));+ assert!(!props.contains_key("$ai_gateway_verified"));+ assert_eq!(props["$ai_model"], Value::String("claude".to_string()));+ }++ fn raw(s: &str) -> Box<RawValue> {+ RawValue::from_string(s.to_string()).unwrap()+ }++ #[test]+ fn has_gateway_props_detects_a_key_but_not_a_bare_value() {+ assert!(has_gateway_props(&raw(r#"{"$ai_gateway_verified": true}"#)));+ assert!(!has_gateway_props(&raw(r#"{"$ai_model": "claude"}"#)));+ assert!(!has_gateway_props(&raw(+ r#"{"note": "mentions ai_gateway"}"#+ )));+ }++ #[test]+ fn has_gateway_props_catches_a_unicode_escaped_key() {+ // "\\u0024" decodes to "$", so this key parses to "$ai_gateway_verified"+ // even though the raw bytes lack the literal prefix. The \\u fallback must+ // catch it so the strip path isn't skipped on a forged escaped marker.+ assert!(has_gateway_props(&raw(+ r#"{"\u0024ai_gateway_verified": true}"#+ )));+ }++ #[test]+ fn strip_gateway_raw_returns_unchanged_when_nothing_to_strip() {+ assert!(matches!(+ strip_gateway_raw(&raw(r#"{"$ai_model": "claude"}"#)),+ StripOutcome::Unchanged+ ));+ match strip_gateway_raw(&raw(r#"{"$ai_gateway": true, "$ai_model": "x"}"#)) {+ StripOutcome::Stripped { props, forged } => {+ assert!(!forged, "no verified marker present");+ assert!(!props.get().contains("$ai_gateway"));+ assert!(props.get().contains("$ai_model"));+ }+ other => panic!("expected Stripped, got {other:?}"),+ }+ }++ #[test]+ fn strip_gateway_raw_flags_a_forged_verified_marker() {+ match strip_gateway_raw(&raw(r#"{"$ai_gateway_verified": true, "$ai_model": "x"}"#)) {+ StripOutcome::Stripped { forged, .. } => assert!(forged),+ other => panic!("expected Stripped, got {other:?}"),+ }+ }++ #[test]+ fn strip_gateway_raw_is_unparseable_for_objects_serde_rejects() {+ // RawValue accepts JSON the typed parse rejects (an out-of-range number);+ // a forged marker we can't strip must fail closed, not pass through.+ assert!(matches!(+ strip_gateway_raw(&raw(r#"{"$ai_gateway_verified": true, "x": 1e500}"#)),+ StripOutcome::Unparseable+ ));+ }++ #[test]+ fn has_gateway_props_ignores_a_unicode_escape_in_a_value() {+ // A \u escape inside a value must NOT trigger the parse — only keys are+ // scanned. This is the DoS guard: a value-side escape can't force a full+ // strip parse.+ assert!(!has_gateway_props(&raw(r#"{"$ai_model": "caf\u00e9"}"#)));+ }++ #[test]+ fn has_gateway_props_catches_a_mid_prefix_escaped_key() {+ // Escaping a char other than the leading $ evades the literal check, so+ // this exercises the key scanner: a decodes to 'a'.+ assert!(has_gateway_props(&raw(+ r#"{"$\u0061i_gateway_verified": true}"#+ )));+ }++ #[test]+ fn has_gateway_props_ignores_an_escaped_gateway_string_in_value_position() {+ // An escaped gateway-looking string in value position is not a property+ // key, so the scanner skips it and no parse is triggered.+ assert!(!has_gateway_props(&raw(+ r#"{"x": "\u0024ai_gateway_verified"}"#+ )));+ }++ #[test]+ fn strip_gateway_raw_strips_a_unicode_escaped_key() {+ // The escaped key decodes to "$ai_gateway_verified" on parse, so strip+ // (which matches decoded keys) removes it like any other gateway prop.+ match strip_gateway_raw(&raw(+ r#"{"\u0024ai_gateway_verified": true, "$ai_model": "x"}"#,+ )) {+ StripOutcome::Stripped { props, forged } => {+ assert!(forged, "the escaped key decodes to the verified marker");+ assert!(!props.get().contains("ai_gateway"));+ assert!(props.get().contains("$ai_model"));+ }+ other => panic!("expected Stripped, got {other:?}"),+ }+ }++ #[test]+ fn stamp_verified_raw_adds_the_marker() {+ let stamped = match stamp_verified_raw(&raw(r#"{"$ai_gateway": true}"#), "req-1") {+ StampOutcome::Stamped(p) => p,+ StampOutcome::Unparseable => panic!("expected Stamped"),+ };+ let map: Map<String, Value> = serde_json::from_str(stamped.get()).unwrap();+ assert_eq!(map["$ai_gateway_verified"], Value::Bool(true));+ assert_eq!(+ map["$ai_gateway_request_id"],+ Value::String("req-1".to_string())+ );+ assert_eq!(map["$ai_gateway"], Value::Bool(true));+ }++ #[test]+ fn accepts_the_cross_language_known_answer() {+ // The exact hex the Go signer produces for this input (ai-gateway+ // internal/emitter/signer_test.go TestSigner_KnownAnswer). If either+ // side's length-prefixed canonical form drifts, this fails and real+ // gateway signatures stop verifying.+ let sig = GatewaySignature {+ signature: "a3de0bf6819919c28f6bf6e8b61f01d53d4f313bd57a67e4a31d3f4fc1161351"+ .to_string(),+ signed_at: "2026-05-28T10:00:00Z".to_string(),+ request_id: "req-123".to_string(),+ };+ let now: DateTime<Utc> = "2026-05-28T10:00:00Z".parse().unwrap();+ assert_eq!(+ verify(b"test-signing-secret", "phc_test", "user-7", &sig, now),+ Provenance::Verified+ );+ }+}diff --git a/rust/capture/src/v1/mod.rs b/rust/capture/src/v1/mod.rsindex 1bea9431ec7d..5c70253dc070 100644--- a/rust/capture/src/v1/mod.rs+++ b/rust/capture/src/v1/mod.rs@@ -2,6 +2,7 @@ pub mod analytics;pub mod constants;pub mod context;pub mod error;+pub mod gateway_provenance;pub mod middleware;pub mod quota_limiter_shim;pub mod router;diff --git a/rust/capture/src/v1/quota_limiter_shim.rs b/rust/capture/src/v1/quota_limiter_shim.rsindex 422abbf85680..5b23b19c8f59 100644--- a/rust/capture/src/v1/quota_limiter_shim.rs+++ b/rust/capture/src/v1/quota_limiter_shim.rs@@ -55,6 +55,11 @@ pub async fn apply_quota_limits(if ev.result != EventResult::Ok {continue;}+ // Gateway-verified events are wallet-billed, not AIO-billed, so they+ // must not be dropped by the llm_events quota.+ if *resource == QuotaResource::LLMEvents && ev.is_gateway_verified {+ continue;+ }let info = EventInfo {name: ev.event_name(),has_product_tour_id: ev.has_property("product_tour_id"),@@ -228,6 +233,7 @@ mod tests {ai_s3_region: "us-east-1".to_string(),ai_s3_access_key_id: None,ai_s3_secret_access_key: None,+ ai_gateway_signing_secret: None,http1_header_read_timeout_ms: Some(5000),body_chunk_read_timeout_ms: None,body_read_chunk_size_kb: 256,@@ -312,9 +318,16 @@ mod tests {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,}}+ fn make_verified_event(name: &str) -> WrappedEvent {+ let mut ev = make_event(name, None);+ ev.is_gateway_verified = true;+ ev+ }+fn ok_event_names(events: &[WrappedEvent]) -> Vec<&str> {let mut names: Vec<&str> = events.iter()@@ -557,6 +570,23 @@ mod tests {assert_eq!(quota_dropped_event_names(&events), vec!["$ai_generation"]);}+ #[tokio::test]+ async fn llm_limit_exempts_gateway_verified_events() {+ let limiter = build_limiter("tok", false, &[QuotaResource::LLMEvents]).await;+ let verified = make_verified_event("$ai_generation");+ let verified_uuid = verified.uuid;+ let mut events = vec![verified, make_event("$ai_generation", None)];++ let result = apply_quota_limits(&limiter, "tok", &mut events).await;+ assert!(result.is_ok());++ // Gateway-verified event survives (wallet-billed); the plain $ai_ one drops.+ let verified = events.iter().find(|e| e.uuid == verified_uuid).unwrap();+ assert_eq!(verified.result, EventResult::Ok);+ assert_eq!(verified.details, None);+ assert_eq!(quota_dropped_event_names(&events), vec!["$ai_generation"]);+ }+// -----------------------------------------------------------------------// Multiple scoped limits// -----------------------------------------------------------------------diff --git a/rust/capture/src/v1/test_utils.rs b/rust/capture/src/v1/test_utils.rsindex a9698901cf25..c57408c4a480 100644--- a/rust/capture/src/v1/test_utils.rs+++ b/rust/capture/src/v1/test_utils.rs@@ -63,6 +63,7 @@ pub fn test_context() -> RequestContext {created_at: Some("2026-03-19T14:30:00.000Z".to_string()),capture_internal: false,historical_migration: false,+ gateway_signature: None,}}@@ -111,6 +112,7 @@ pub fn wrapped_event(event_name: &str, distinct_id: &str) -> WrappedEvent {details: None,destination: Destination::default(),force_disable_person_processing: false,+ is_gateway_verified: false,}}@@ -133,6 +135,7 @@ pub fn wrapped_event_at(timestamp: DateTime<Utc>) -> WrappedEvent {details: None,destination: Destination::default(),force_disable_person_processing: false,+ is_gateway_verified: false,}}@@ -155,6 +158,7 @@ pub fn malformed_wrapped_event() -> WrappedEvent {details: Some("missing_event_name"),destination: Destination::default(),force_disable_person_processing: false,+ is_gateway_verified: false,}}@@ -217,6 +221,7 @@ pub fn realistic_pageview(distinct_id: &str) -> WrappedEvent {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,}}@@ -251,6 +256,7 @@ pub fn realistic_identify(distinct_id: &str) -> WrappedEvent {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,}}@@ -285,6 +291,7 @@ pub fn realistic_custom(distinct_id: &str, event_name: &str) -> WrappedEvent {details: None,destination: Destination::AnalyticsMain,force_disable_person_processing: false,+ is_gateway_verified: false,}}@@ -666,6 +673,7 @@ pub struct TestStateBuilder {restriction_service: Option<EventRestrictionService>,global_rate_limiter: Option<Arc<GlobalRateLimiter>>,mock_producer: Option<Arc<MockProducer>>,+ ai_gateway_signing_secret: Option<String>,}impl Default for TestStateBuilder {@@ -683,6 +691,7 @@ impl TestStateBuilder {restriction_service: None,global_rate_limiter: None,mock_producer: None,+ ai_gateway_signing_secret: None,}}@@ -692,6 +701,12 @@ impl TestStateBuilder {self}+ /// Set the AI-gateway HMAC signing secret used by provenance verification.+ pub fn with_ai_gateway_signing_secret(mut self, secret: impl Into<String>) -> Self {+ self.ai_gateway_signing_secret = Some(secret.into());+ self+ }+/// Add an in-process overflow limiter with the given rate and burst.pub fn with_overflow_limiter(mut self, per_second: u32, burst: u32) -> Self {self.overflow_limiter = Some((@@ -828,6 +843,7 @@ impl TestStateBuilder {replay_overflow_limiter: None,v1_sink_router: Some(Arc::new(v1_router)),capture_v1_scatter_gather_min_batch: 8,+ ai_gateway_signing_secret: self.ai_gateway_signing_secret,};TestState {diff --git a/rust/capture/tests/common/integration_utils.rs b/rust/capture/tests/common/integration_utils.rsindex 3b2493cc2041..49b0966f1952 100644--- a/rust/capture/tests/common/integration_utils.rs+++ b/rust/capture/tests/common/integration_utils.rs@@ -1110,6 +1110,7 @@ fn setup_capture_router(unit: &TestCase) -> (Router, MemorySink) {None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret),sink,)diff --git a/rust/capture/tests/common/utils.rs b/rust/capture/tests/common/utils.rsindex 3f8d2133b2cd..e5f676eee0e2 100644--- a/rust/capture/tests/common/utils.rs+++ b/rust/capture/tests/common/utils.rs@@ -149,6 +149,7 @@ pub static DEFAULT_CONFIG: Lazy<Config> = Lazy::new(|| Config {ai_s3_region: "us-east-1".to_string(),ai_s3_access_key_id: None,ai_s3_secret_access_key: None,+ ai_gateway_signing_secret: None,http1_header_read_timeout_ms: Some(5000), // 5 seconds defaultbody_chunk_read_timeout_ms: None, // disabled by default in testsbody_read_chunk_size_kb: 256, // 256KB default@@ -227,6 +228,16 @@ impl ServerHandle {Self::for_config_with_sink_env(config, sink_env).await}+ /// Like `for_v1_topic`, with the AI-gateway signing secret configured so the+ /// provenance check runs.+ pub async fn for_v1_topic_with_signing_secret(topic: &EphemeralTopic, secret: &str) -> Self {+ let mut config = DEFAULT_CONFIG.clone();+ config.capture_v1_sinks = "msk".to_string();+ config.ai_gateway_signing_secret = Some(secret.to_string());+ let sink_env = v1_sink_env_for_topic("msk", topic.topic_name());+ Self::for_config_with_sink_env(config, sink_env).await+ }+pub async fn for_config(config: Config) -> Self {Self::for_config_with_sink_env(config, std::env::vars().collect()).await}@@ -304,6 +315,34 @@ impl ServerHandle {.expect("failed to send request")}+ /// Like `capture_v1`, plus the AI-gateway provenance headers.+ #[allow(clippy::too_many_arguments)]+ pub async fn capture_v1_with_gateway_headers<T: Into<reqwest::Body>>(+ &self,+ token: &str,+ body: T,+ signature: &str,+ signed_at: &str,+ request_id: &str,+ ) -> reqwest::Response {+ self.client+ .post(format!("http://{:?}/i/v1/analytics/events", self.addr))+ .header("authorization", format!("Bearer {token}"))+ .header("PostHog-Sdk-Info", "posthog-rs/1.0.0")+ .header("PostHog-Attempt", "1")+ .header("PostHog-Request-Id", uuid::Uuid::new_v4().to_string())+ .header("PostHog-Request-Timestamp", "2026-03-19T14:30:00.000Z")+ .header("content-type", "application/json")+ .header("user-agent", "test-client/1.0")+ .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+ .expect("failed to send request")+ }+pub async fn capture_recording<T: Into<reqwest::Body>>(&self,body: T,diff --git a/rust/capture/tests/integration_ai_endpoint.rs b/rust/capture/tests/integration_ai_endpoint.rsindex 7d2cc31aaf8a..a394ac2ffc60 100644--- a/rust/capture/tests/integration_ai_endpoint.rs+++ b/rust/capture/tests/integration_ai_endpoint.rs@@ -196,6 +196,7 @@ fn setup_ai_test_router() -> Router {None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret)}@@ -1658,6 +1659,7 @@ fn setup_ai_test_router_with_capturing_sink() -> (Router, CapturingSink) {None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);(router, sink_clone)@@ -2572,6 +2574,7 @@ fn setup_ai_test_router_with_token_dropper(token_dropper: TokenDropper) -> (RoutNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);(router, sink_clone)@@ -2781,6 +2784,7 @@ fn setup_ai_test_router_with_llm_quota_limited(token: &str) -> (Router, CapturinNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);(router, sink_clone)@@ -2935,6 +2939,7 @@ fn setup_ai_test_router_with_overflow_limiter(None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);(router, sink_clone)diff --git a/rust/capture/tests/integration_ai_restrictions.rs b/rust/capture/tests/integration_ai_restrictions.rsindex 5a3d2ae9d038..80c7d16a1258 100644--- a/rust/capture/tests/integration_ai_restrictions.rs+++ b/rust/capture/tests/integration_ai_restrictions.rs@@ -194,6 +194,7 @@ async fn setup_ai_router_with_restriction(None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);(router, sink_clone)@@ -512,6 +513,7 @@ async fn setup_ai_router_with_redirect_to_topic(None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);(router, sink_clone)@@ -587,6 +589,7 @@ async fn setup_ai_router_with_force_overflow_and_limiter(None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);(router, sink_clone)diff --git a/rust/capture/tests/integration_analytics_restrictions.rs b/rust/capture/tests/integration_analytics_restrictions.rsindex 2d6bda4c2db9..f113ccd10ad4 100644--- a/rust/capture/tests/integration_analytics_restrictions.rs+++ b/rust/capture/tests/integration_analytics_restrictions.rs@@ -128,6 +128,7 @@ async fn setup_analytics_router_with_restriction(None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);(router, sink_clone)@@ -471,6 +472,7 @@ async fn setup_analytics_router_with_redirect_to_topic(None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);(router, sink_clone)diff --git a/rust/capture/tests/integration_otel_endpoint.rs b/rust/capture/tests/integration_otel_endpoint.rsindex 6eda5307011b..6d581e2150c5 100644--- a/rust/capture/tests/integration_otel_endpoint.rs+++ b/rust/capture/tests/integration_otel_endpoint.rs@@ -186,6 +186,7 @@ fn make_test_client_with_options(sink: &CapturingSink, options: TestClientOptionNone, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);TestClient::new(app)diff --git a/rust/capture/tests/integration_replay_restrictions.rs b/rust/capture/tests/integration_replay_restrictions.rsindex ab66d253c67e..4d3be7b2026b 100644--- a/rust/capture/tests/integration_replay_restrictions.rs+++ b/rust/capture/tests/integration_replay_restrictions.rs@@ -130,6 +130,7 @@ async fn setup_recordings_router_with_restriction(None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);(router, sink_clone)@@ -499,6 +500,7 @@ async fn setup_recordings_router_with_redirect_to_topic(None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);(router, sink_clone)diff --git a/rust/capture/tests/quota_limiters.rs b/rust/capture/tests/quota_limiters.rsindex 925a2e3c4358..4a044c2223e6 100644--- a/rust/capture/tests/quota_limiters.rs+++ b/rust/capture/tests/quota_limiters.rs@@ -152,6 +152,7 @@ async fn setup_router_with_limits(None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);(app, sink)@@ -1203,6 +1204,7 @@ async fn test_survey_quota_cross_batch_first_submission_allowed() {None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);let client = TestClient::new(app);@@ -1292,6 +1294,7 @@ async fn test_survey_quota_cross_batch_duplicate_submission_dropped() {None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);let client = TestClient::new(app);@@ -1385,6 +1388,7 @@ async fn test_survey_quota_cross_batch_redis_error_fail_open() {None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);let client = TestClient::new(app);@@ -1815,6 +1819,7 @@ async fn test_ai_quota_cross_batch_redis_error_fail_open() {None, // replay_overflow_limiterNone, // v1_sink_router8, // capture_v1_scatter_gather_min_batch+ None, // ai_gateway_signing_secret);let client = TestClient::new(app);diff --git a/rust/capture/tests/v1_http_integration.rs b/rust/capture/tests/v1_http_integration.rsindex 5931c49b5224..034642572227 100644--- a/rust/capture/tests/v1_http_integration.rs+++ b/rust/capture/tests/v1_http_integration.rs@@ -21,9 +21,11 @@ use common_types::CapturedEvent;use uuid::Uuid;use capture::v1::analytics::types::Event;-use capture::v1::test_utils::{batch_payload, valid_event};+use capture::v1::gateway_provenance::sign_for_test;+use capture::v1::test_utils::{batch_payload, raw_obj, valid_event};const TOKEN: &str = "phc_http_integration_token";+const GW_SECRET: &str = "test-signing-secret";/// A fresh `$pageview` event with a unique UUID and the given distinct_id.fn pageview(distinct_id: &str) -> Event {@@ -144,3 +146,80 @@ async fn v1_http_batch_to_kafka() -> Result<()> {topic.assert_empty();Ok(())}++// ---------------------------------------------------------------------------+// Gateway provenance: HTTP -> verified marker (and forged marker stripped) in Kafka+// ---------------------------------------------------------------------------++#[tokio::test]+async fn v1_http_gateway_signed_event_is_verified_in_kafka() -> Result<()> {+ setup_tracing();+ let topic = EphemeralTopic::new().await;+ let server = ServerHandle::for_v1_topic_with_signing_secret(&topic, GW_SECRET).await;++ let distinct_id = "gw-user-1";+ let request_id = "gw-req-1";+ let signed_at = chrono::Utc::now().to_rfc3339();+ let signature = sign_for_test(+ GW_SECRET.as_bytes(),+ TOKEN,+ distinct_id,+ request_id,+ &signed_at,+ );++ let mut ev = named(distinct_id, "$ai_generation");+ // Client supplies its own request_id — the signed one must overwrite it.+ ev.properties = raw_obj(r#"{"$ai_model":"claude","$ai_gateway_request_id":"client-fake"}"#);+ let uuid = ev.uuid.clone();+ let payload = batch_payload(std::slice::from_ref(&ev));++ let res = server+ .capture_v1_with_gateway_headers(TOKEN, payload, &signature, &signed_at, request_id)+ .await;+ assert_eq!(res.status(), reqwest::StatusCode::OK);++ let captured: CapturedEvent = serde_json::from_value(topic.next_event()?)?;+ assert_eq!(captured.uuid.to_string(), uuid);+ let data: serde_json::Value = serde_json::from_str(&captured.data)?;+ assert_eq!(+ data["properties"]["$ai_gateway_verified"],+ serde_json::json!(true),+ "a valid signature must stamp the verified marker: {data}"+ );+ assert_eq!(+ data["properties"]["$ai_gateway_request_id"],+ serde_json::json!("gw-req-1"),+ "the signed request_id must overwrite the client value: {data}"+ );++ topic.assert_empty();+ Ok(())+}++#[tokio::test]+async fn v1_http_forged_gateway_marker_is_stripped_in_kafka() -> Result<()> {+ setup_tracing();+ let topic = EphemeralTopic::new().await;+ let server = ServerHandle::for_v1_topic_with_signing_secret(&topic, GW_SECRET).await;++ // No gateway headers, but the client forges the trusted marker — it must not+ // survive to Kafka even with a signing secret configured.+ let mut ev = named("forged-user", "$ai_generation");+ ev.properties = raw_obj(r#"{"$ai_model":"claude","$ai_gateway_verified":true}"#);+ let payload = batch_payload(std::slice::from_ref(&ev));++ let res = server.capture_v1(TOKEN, payload).await;+ assert_eq!(res.status(), reqwest::StatusCode::OK);++ let captured: CapturedEvent = serde_json::from_value(topic.next_event()?)?;+ let data: serde_json::Value = serde_json::from_str(&captured.data)?;+ assert!(+ data["properties"].get("$ai_gateway_verified").is_none(),+ "a forged marker with no signature must be stripped: {data}"+ );+ assert_eq!(data["properties"]["$ai_model"], serde_json::json!("claude"));++ topic.assert_empty();+ Ok(())+}