: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
fix(surveys): reduce public config payload (#73443)
Manoel Aranda Neto82f3d608ff8d
diff --git a/posthog/models/remote_config.py b/posthog/models/remote_config.pyindex b669cd470659..429741e5d505 100644--- a/posthog/models/remote_config.py+++ b/posthog/models/remote_config.py@@ -129,6 +129,7 @@ class RemoteConfig(UUIDTModel):base_config = {"endpoint": "/s/","consoleLogRecordingEnabled": capture_console_logs,+ # Required by posthog-js <= 1.115.0 to select recorder-v2.js; >= 1.115.1 always uses v2 and no longer reads it."recorderVersion": "v2","minimumDurationMilliseconds": minimum_duration,"networkPayloadCapture": team.session_recording_network_payload_capture_config or None,@@ -206,7 +207,7 @@ class RemoteConfig(UUIDTModel):}@tracer.start_as_current_span("RemoteConfig.build_config")- def build_config(self, bypass_recordings_quota_cache: bool = False):+ def build_config(self, bypass_recordings_quota_cache: bool = False) -> dict[str, Any]:from posthog.models.team import Teamfrom posthog.plugins.site import get_decide_site_apps@@ -222,7 +223,6 @@ class RemoteConfig(UUIDTModel):# NOTE: Let's try and keep this tidy! Follow the styling of the values already here...config = {- "token": team.api_token,"supportedCompression": ["gzip", "gzip-js"],"hasFeatureFlags": FeatureFlag.objects.filter(team=team, active=True).exists(),"captureDeadClicks": bool(team.capture_dead_clicks),@@ -305,15 +305,8 @@ class RemoteConfig(UUIDTModel):surveys_opt_in = get_surveys_opt_in(team)if surveys_opt_in:- surveys_response = get_surveys_response(team)- surveys = surveys_response["surveys"]- if len(surveys) > 0:- config["surveys"] = surveys_response["surveys"]-- if surveys_response["survey_config"]:- config["survey_config"] = surveys_response["survey_config"]- else:- config["surveys"] = False+ surveys = get_surveys_response(team)["surveys"]+ config["surveys"] = surveys if len(surveys) > 0 else Falseelse:config["surveys"] = False@@ -329,7 +322,9 @@ class RemoteConfig(UUIDTModel):else:config["productTours"] = False- config["defaultIdentifiedOnly"] = True # Support old SDK versions with setting that is now the default+ # Required by posthog-js <= 1.207.1; without it those versions default to person_profiles="always".+ # posthog-js >= 1.207.2 always defaults to "identified_only" and no longer reads this field.+ config["defaultIdentifiedOnly"] = True# MARK: Site apps - we want to eventually inline the JS but that will come latersite_apps = []@@ -344,7 +339,9 @@ class RemoteConfig(UUIDTModel):# Array of JS objects to be included when building the final JSconfig["siteAppsJS"] = self._build_site_apps_js()- # MARK: Snippet versioning — store requested version, resolved at request time+ # MARK: Snippet versioning: store requested version, resolved at request time+ # Keep this internal metadata while snippet version pinning is enabled. posthog-js <= 1.369.1 read only+ # the sibling `resolved` field; >= 1.369.2 reads neither field.if settings.POSTHOG_JS_S3_BUCKET:snippet_config = get_or_create_team_extension(team, TeamJsSnippetConfig)config["sdkVersion"] = {"requested": snippet_config.js_snippet_version or DEFAULT_SNIPPET_VERSION}diff --git a/posthog/models/test/__snapshots__/test_remote_config.ambr b/posthog/models/test/__snapshots__/test_remote_config.ambrindex 88c6b9e0e5d9..f9bd34fd2a06 100644--- a/posthog/models/test/__snapshots__/test_remote_config.ambr+++ b/posthog/models/test/__snapshots__/test_remote_config.ambr@@ -62,6 +62,5 @@'gzip-js',]),'surveys': False,- 'token': 'phc_12345',})# ---diff --git a/posthog/models/test/test_remote_config.py b/posthog/models/test/test_remote_config.pyindex e4fdc6d24b71..afff307b97c0 100644--- a/posthog/models/test/test_remote_config.py+++ b/posthog/models/test/test_remote_config.py@@ -290,7 +290,7 @@ class TestRemoteConfigSurveys(_RemoteConfigBase):self.team.save()- def test_includes_survey_config(self):+ def test_excludes_survey_config(self):survey_appearance = {"thankYouMessageHeader": "Thanks for your feedback!","thankYouMessageDescription": "We'll use it to make notebooks better",@@ -309,12 +309,7 @@ class TestRemoteConfigSurveys(_RemoteConfigBase):self.team.save()self.sync_remote_config()- assert self.remote_config.config["survey_config"] == {- "appearance": {- "thankYouMessageHeader": "Thanks for your feedback!",- "thankYouMessageDescription": "We'll use it to make notebooks better",- }- }+ assert "survey_config" not in self.remote_config.configdef test_includes_range_of_survey_types(self):survey_basic = Survey.objects.create(@@ -390,7 +385,6 @@ class TestRemoteConfigSurveys(_RemoteConfigBase):"current_iteration_start_date": None,"schedule": "once","enable_partial_responses": False,- "base_language": "en",},{"id": str(survey_with_flags.id),@@ -418,7 +412,6 @@ class TestRemoteConfigSurveys(_RemoteConfigBase):"current_iteration_start_date": None,"schedule": "once","enable_partial_responses": False,- "base_language": "en",},{"id": str(survey_with_actions.id),@@ -467,7 +460,6 @@ class TestRemoteConfigSurveys(_RemoteConfigBase):"current_iteration_start_date": None,"schedule": "once","enable_partial_responses": False,- "base_language": "en",},],key=lambda s: str(s["id"]), # type: ignore@@ -516,7 +508,7 @@ class TestRemoteConfigCaching(_RemoteConfigBase):mock_get_client.return_value = mock_redis# Force a content change so sync() takes the change path.- self.remote_config.config["token"] = "FORCE_CHANGE"+ self.remote_config.config["surveys"] = Truewith (patch("posthog.storage.object_storage.write") as mock_s3_write,@@ -594,7 +586,7 @@ class TestRemoteConfigCaching(_RemoteConfigBase):REMOTE_CONFIG_CDN_PURGE_DOMAINS=["cdn.posthog.com", "https://cdn2.posthog.com"],):# Force a change to the config- self.remote_config.config["token"] = "NOT"+ self.remote_config.config["surveys"] = Trueself.remote_config.sync()mock_post.assert_called_once_with("https://api.cloudflare.com/client/v4/zones/MY_ZONE_ID/purge_cache",diff --git a/products/surveys/backend/api/survey.py b/products/surveys/backend/api/survey.pyindex 524b4069b4cd..edae32e11785 100644--- a/products/surveys/backend/api/survey.py+++ b/products/surveys/backend/api/survey.py@@ -3292,12 +3292,6 @@ class SurveyViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.)-class SurveyConfigSerializer(serializers.ModelSerializer):- class Meta:- model = Team- fields = ["survey_config"]--class SurveyAPIActionSerializer(serializers.ModelSerializer):steps = ActionStepJSONSerializer(many=True, required=False)@@ -3376,7 +3370,6 @@ class SurveyAPISerializer(serializers.ModelSerializer):internal_targeting_flag_key = serializers.CharField(source="internal_targeting_flag.key", read_only=True)conditions = serializers.SerializerMethodField(method_name="get_conditions")enable_partial_responses = serializers.BooleanField(read_only=True)- base_language = serializers.CharField(read_only=True)questions = serializers.SerializerMethodField(method_name="get_questions")translations = serializers.SerializerMethodField(method_name="get_translations")@@ -3403,7 +3396,6 @@ class SurveyAPISerializer(serializers.ModelSerializer):"current_iteration_start_date","schedule","enable_partial_responses",- "base_language","translations",]read_only_fields = fields@@ -3422,7 +3414,7 @@ class SurveyAPISerializer(serializers.ModelSerializer):@extend_schema_field(serializers.ListField(child=serializers.DictField(), allow_null=True))def get_questions(self, survey: Survey) -> list[dict[str, Any]] | None:- """Return questions with question-level translation keys filtered to what the SDK can match."""+ """Return only question fields used by SDKs, with translation keys normalized."""questions = survey.questionsif not isinstance(questions, list):return questions@@ -3434,16 +3426,15 @@ class SurveyAPISerializer(serializers.ModelSerializer):if not isinstance(question, dict):cleaned.append(question)continue- inline_translations = question.get("translations")- if not isinstance(inline_translations, dict):- cleaned.append(question)- continue- filtered = _strip_invalid_translation_keys(inline_translations, normalized_base)next_question = dict(question)- if filtered:- next_question["translations"] = filtered- else:- next_question.pop("translations", None)+ next_question.pop("isNpsQuestion", None)+ inline_translations = question.get("translations")+ if isinstance(inline_translations, dict):+ filtered = _strip_invalid_translation_keys(inline_translations, normalized_base)+ if filtered:+ next_question["translations"] = filtered+ else:+ next_question.pop("translations", None)cleaned.append(next_question)return cleaned@@ -3470,7 +3461,7 @@ def get_surveys_count(team: Team) -> int:)-def get_surveys_response(team: Team):+def get_surveys_response(team: Team) -> dict[str, Any]:surveys = SurveyAPISerializer(Survey.objects.db_manager(READ_DB_FOR_SURVEYS).filter(team__project_id=team.project_id)@@ -3480,14 +3471,7 @@ def get_surveys_response(team: Team):many=True,).data- serialized_survey_config: dict[str, Any] = {}- if team.survey_config is not None:- serialized_survey_config = SurveyConfigSerializer(team).data-- return {- "surveys": surveys,- "survey_config": serialized_survey_config.get("survey_config", None),- }+ return {"surveys": surveys}def _survey_page_site_url() -> str:diff --git a/products/surveys/backend/api/test/test_survey.py b/products/surveys/backend/api/test/test_survey.pyindex 731eb6759353..f86bcaec16ae 100644--- a/products/surveys/backend/api/test/test_survey.py+++ b/products/surveys/backend/api/test/test_survey.py@@ -32,7 +32,11 @@ from products.cohorts.backend.models.cohort import Cohortfrom products.feature_flags.backend.models.feature_flag import FeatureFlagfrom products.product_analytics.backend.models.insight import Insightfrom products.product_tours.backend.models import ProductTour-from products.surveys.backend.api.survey import nh3_clean_with_allow_list+from products.surveys.backend.api.survey import (+ get_survey_api_translations,+ get_surveys_response,+ nh3_clean_with_allow_list,+)from products.surveys.backend.models import MAX_ITERATION_COUNT, Survey, SurveyResponseArchivefrom ee.models.rbac.access_control import AccessControl@@ -453,10 +457,9 @@ class TestSurvey(APIBaseTest):assert response.status_code == status.HTTP_400_BAD_REQUEST, response.contentassert "base_language" in response.json() or "translation" in response.content.decode().lower()- def test_sdk_payload_strips_invalid_question_translation_keys(self) -> None:- """Question-level translation keys are stripped from the SDK payload, just like survey-level ones."""- from products.surveys.backend.api.survey import SurveyAPISerializer-+ def test_sdk_payload_strips_non_runtime_question_fields(self) -> None:+ self.team.survey_config = {"appearance": {"backgroundColor": "black"}}+ self.team.save(update_fields=["survey_config"])survey = Survey.objects.create(team=self.team,name="Q-level legacy",@@ -467,27 +470,39 @@ class TestSurvey(APIBaseTest):"id": "q1","type": "open","question": "How are you?",+ "isNpsQuestion": True,"translations": {"es": {"question": "¿Cómo estás?"},"default": {"question": "Should be dropped"},"english": {"question": "Should be dropped"},"EN-us": {"question": "Normalized to en-us"},},- }+ },+ {+ "id": "q2",+ "type": "open",+ "question": "Anything else?",+ "translations": {+ "default": {"question": "Should be dropped"},+ "en": {"question": "Same as base, should be dropped"},+ },+ },],)- payload = SurveyAPISerializer(survey).data+ response = get_surveys_response(self.team)+ assert set(response) == {"surveys"}+ payload = next(item for item in response["surveys"] if str(item["id"]) == str(survey.id))+ assert "base_language" not in payload+ assert "isNpsQuestion" not in payload["questions"][0]q_translations = payload["questions"][0]["translations"]assert "es" in q_translationsassert "en-us" in q_translationsassert "default" not in q_translationsassert "english" not in q_translations+ assert "translations" not in payload["questions"][1]def test_sdk_payload_strips_invalid_translation_keys(self) -> None:- """get_survey_api_translations drops keys the SDK matcher cannot resolve."""- from products.surveys.backend.api.survey import get_survey_api_translations-result = get_survey_api_translations({"es": {"name": "Hola"},diff --git a/rust/feature-flags/src/api/types.rs b/rust/feature-flags/src/api/types.rsindex 18787694e5c2..4edd820991c1 100644--- a/rust/feature-flags/src/api/types.rs+++ b/rust/feature-flags/src/api/types.rs@@ -154,9 +154,8 @@ impl ConfigResponse {////// This config disables optional features (session recording, surveys, heatmaps, etc.)/// to ensure safe degradation when the full config from Python's HyperCache is unavailable.- pub fn fallback(api_token: &str, has_feature_flags: bool) -> Self {+ pub fn fallback(has_feature_flags: bool) -> Self {let fallback = serde_json::json!({- "token": api_token,"hasFeatureFlags": has_feature_flags,"supportedCompression": ["gzip", "gzip-js"],"sessionRecording": false,@@ -1087,6 +1086,14 @@ mod tests {use rstest::rstest;use serde_json::json;+ #[test]+ fn test_fallback_config_excludes_request_token() {+ let config = serde_json::to_value(ConfigResponse::fallback(true)).unwrap();++ assert!(config.get("token").is_none());+ assert_eq!(config["hasFeatureFlags"], json!(true));+ }+#[rstest]#[case::condition_match(FeatureFlagMatch {diff --git a/rust/feature-flags/src/handler/config_response_builder.rs b/rust/feature-flags/src/handler/config_response_builder.rsindex 58f95a30cba0..1f565c9d51da 100644--- a/rust/feature-flags/src/handler/config_response_builder.rs+++ b/rust/feature-flags/src/handler/config_response_builder.rs@@ -59,7 +59,7 @@ pub async fn build_response_from_cache().increment(1);- return Ok(apply_fallback_config(response, team, is_recordings_limited));+ return Ok(apply_fallback_config(response, is_recordings_limited));}None => {// Cache miss - return minimal fallback config with quota info@@ -69,7 +69,7 @@ pub async fn build_response_from_cache("Config cache miss - returning fallback config");- return Ok(apply_fallback_config(response, team, is_recordings_limited));+ return Ok(apply_fallback_config(response, is_recordings_limited));}};@@ -99,11 +99,10 @@ pub async fn build_response_from_cache(/// Apply fallback config when cache is unavailable or returns unexpected data.fn apply_fallback_config(mut response: FlagsResponse,- team: &Team,is_recordings_limited: bool,) -> FlagsResponse {let has_flags = !response.flags.is_empty();- response.config = ConfigResponse::fallback(&team.api_token, has_flags);+ response.config = ConfigResponse::fallback(has_flags);if is_recordings_limited {response.quota_limited = Some(vec![QuotaResource::Recordings.as_str().to_string()]);@@ -159,13 +158,16 @@ fn set_cached_quota_limits_without_recordings(response: &mut FlagsResponse) {/// Sanitize cached config before returning to clients.////// Matches Python's `sanitize_config_for_public_cdn` behavior:+/// - Removes unused public config and survey fields/// - Removes `siteAppsJS` (raw JS only needed for array.js bundle, not JSON API)/// - Removes `sessionRecording.domains` (internal field, not needed by SDK)/// - Sets `sessionRecording` to `false` if request origin not in permitted domainsfn sanitize_config_for_client(cached_config: &mut Value, headers: &HeaderMap) {if let Some(obj) = cached_config.as_object_mut() {obj.remove("siteAppsJS");+ obj.remove("token");}+ sanitize_surveys_for_client(cached_config);let session_recording = match cached_config.get_mut("sessionRecording") {Some(sr) => sr,@@ -195,6 +197,49 @@ fn sanitize_config_for_client(cached_config: &mut Value, headers: &HeaderMap) {}}+fn sanitize_surveys_for_client(payload: &mut Value) {+ let Some(payload) = payload.as_object_mut() else {+ return;+ };+ payload.remove("survey_config");++ let Some(surveys) = payload.get_mut("surveys").and_then(Value::as_array_mut) else {+ return;+ };++ for survey in surveys {+ let Some(survey) = survey.as_object_mut() else {+ continue;+ };+ survey.remove("base_language");++ if let Some(questions) = survey.get_mut("questions").and_then(Value::as_array_mut) {+ for question in questions {+ if let Some(question) = question.as_object_mut() {+ question.remove("isNpsQuestion");+ }+ }+ }++ let Some(actions) = survey+ .get_mut("conditions")+ .and_then(Value::as_object_mut)+ .and_then(|conditions| conditions.get_mut("actions"))+ .and_then(Value::as_object_mut)+ .and_then(|actions| actions.get_mut("values"))+ .and_then(Value::as_array_mut)+ else {+ continue;+ };++ for action in actions {+ if let Some(action) = action.as_object_mut() {+ action.retain(|field, _| matches!(field.as_str(), "id" | "name" | "steps"));+ }+ }+ }+}+#[cfg(test)]mod tests {use super::*;@@ -339,6 +384,50 @@ mod tests {assert_eq!(cached.get("heatmaps"), Some(&json!(true)));}+ #[test]+ fn test_sanitize_removes_unused_cached_config_fields() {+ let mut cached = json!({+ "token": "phc_test",+ "survey_config": {"appearance": {"theme": "light"}},+ "surveys": [{+ "id": "survey-1",+ "base_language": "en",+ "questions": [{"type": "rating", "isNpsQuestion": true}],+ "conditions": {+ "actions": {+ "values": [{+ "id": 1,+ "name": "signed up",+ "steps": [{"event": "$pageview"}],+ "created_by": {"email": "[email protected]"}+ }]+ }+ }+ }]+ });++ sanitize_config_for_client(&mut cached, &HeaderMap::new());++ assert_eq!(+ cached,+ json!({+ "surveys": [{+ "id": "survey-1",+ "questions": [{"type": "rating"}],+ "conditions": {+ "actions": {+ "values": [{+ "id": 1,+ "name": "signed up",+ "steps": [{"event": "$pageview"}]+ }]+ }+ }+ }]+ })+ );+ }+#[test]fn test_session_recording_empty_domains_allowed() {// Empty domains list means "allow all" - recording should remain enableddiff --git a/rust/feature-flags/tests/test_flags.rs b/rust/feature-flags/tests/test_flags.rsindex b6179db38a28..0763c40ca4e0 100644--- a/rust/feature-flags/tests/test_flags.rs+++ b/rust/feature-flags/tests/test_flags.rs@@ -2224,7 +2224,7 @@ async fn test_config_cache_miss_returns_minimal_fallback() -> Result<()> {let json_data = res.json::<Value>().await?;// Verify minimal fallback config fields are present- assert_eq!(json_data.get("token"), Some(&json!(token)));+ assert!(json_data.get("token").is_none());assert_eq!(json_data.get("hasFeatureFlags"), Some(&json!(false))); // no flags configuredassert_eq!(json_data.get("sessionRecording"), Some(&json!(false)));assert_eq!(json_data.get("surveys"), Some(&json!(false)));@@ -2290,7 +2290,7 @@ async fn test_config_cache_miss_with_recordings_quota_limited() -> Result<()> {let json_data = res.json::<Value>().await?;// Verify fallback config fields are present (cache miss behavior)- assert_eq!(json_data.get("token"), Some(&json!(token)));+ assert!(json_data.get("token").is_none());assert_eq!(json_data.get("sessionRecording"), Some(&json!(false)));// Critical assertion: quota_limited must include "recordings"diff --git a/rust/hypercache-server/src/api/remote_config.rs b/rust/hypercache-server/src/api/remote_config.rsindex d40e7e94f511..a821f4ac6d1f 100644--- a/rust/hypercache-server/src/api/remote_config.rs+++ b/rust/hypercache-server/src/api/remote_config.rs@@ -330,7 +330,7 @@ mod tests {let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();assert_eq!(parsed["heatmaps"], json!(true));- assert_eq!(parsed["token"], json!(token));+ assert!(parsed.get("token").is_none());}#[tokio::test]diff --git a/rust/hypercache-server/src/api/surveys.rs b/rust/hypercache-server/src/api/surveys.rsindex 226e715c0918..d9811e58f26d 100644--- a/rust/hypercache-server/src/api/surveys.rs+++ b/rust/hypercache-server/src/api/surveys.rs@@ -1,6 +1,7 @@use crate::{config_cache::{get_cached_data, CacheNamespace},router::State as AppState,+ sanitize::sanitize_surveys_for_client,token::{Token, TokenError},};use axum::{@@ -27,11 +28,7 @@ struct SurveysFormBody {}fn empty_surveys_response() -> Response {- Json(serde_json::json!({- "surveys": [],- "survey_config": null- }))- .into_response()+ Json(serde_json::json!({"surveys": []})).into_response()}/// Surveys endpoint handler@@ -43,7 +40,7 @@ fn empty_surveys_response() -> Response {/// - Token from query param `token` or `api_key` (checked first)/// - For POST requests, falls back to form-encoded body (`token` or `api_key`)/// - No authentication beyond token validation-/// - Returns cached `{"surveys": [...], "survey_config": {...}}`+/// - Returns cached `{"surveys": [...]}`pub async fn surveys_endpoint(State(state): State<AppState>,Query(params): Query<SurveysQueryParams>,@@ -80,7 +77,7 @@ pub async fn surveys_endpoint(Err(r) => return r,};- let value = match get_cached_data(+ let mut value = match get_cached_data(&state.surveys_hypercache_reader,state.surveys_negative_cache.as_ref(),CacheNamespace::Surveys,@@ -92,6 +89,7 @@ pub async fn surveys_endpoint(None => return empty_surveys_response(),};+ sanitize_surveys_for_client(&mut value);Json(value).into_response()}@@ -199,8 +197,7 @@ mod tests {assert_eq!(status, StatusCode::OK);let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();- assert_eq!(parsed["surveys"], json!([]));- assert_eq!(parsed["survey_config"], json!(null));+ assert_eq!(parsed, json!({"surveys": []}));}#[tokio::test]@@ -209,7 +206,23 @@ mod tests {let key = cache_key("surveys", "surveys.json", token);let survey_data = json!({- "surveys": [{"id": "s1", "name": "NPS", "type": "popover"}],+ "surveys": [{+ "id": "s1",+ "name": "NPS",+ "type": "popover",+ "base_language": "en",+ "questions": [{"type": "rating", "isNpsQuestion": true}],+ "conditions": {+ "actions": {+ "values": [{+ "id": 1,+ "name": "signed up",+ "steps": [{"event": "$pageview"}],+ "created_by": {"email": "[email protected]"}+ }]+ }+ }+ }],"survey_config": {"appearance": {"theme": "light"}}});@@ -224,7 +237,26 @@ mod tests {assert_eq!(status, StatusCode::OK);let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();- assert_eq!(parsed, survey_data);+ assert_eq!(+ parsed,+ json!({+ "surveys": [{+ "id": "s1",+ "name": "NPS",+ "type": "popover",+ "questions": [{"type": "rating"}],+ "conditions": {+ "actions": {+ "values": [{+ "id": 1,+ "name": "signed up",+ "steps": [{"event": "$pageview"}]+ }]+ }+ }+ }]+ })+ );}#[tokio::test]@@ -232,7 +264,7 @@ mod tests {let token = "phc_apikey_test";let key = cache_key("surveys", "surveys.json", token);- let survey_data = json!({"surveys": [{"id": "s1"}], "survey_config": null});+ let survey_data = json!({"surveys": [{"id": "s1"}]});let mut mock = MockRedisClient::new();mock = mock.get_raw_bytes_ret(&key, Ok(pickle_json(&survey_data)));@@ -253,7 +285,7 @@ mod tests {let token = "phc_form_test";let key = cache_key("surveys", "surveys.json", token);- let survey_data = json!({"surveys": [{"id": "s2"}], "survey_config": null});+ let survey_data = json!({"surveys": [{"id": "s2"}]});let mut mock = MockRedisClient::new();mock = mock.get_raw_bytes_ret(&key, Ok(pickle_json(&survey_data)));@@ -274,7 +306,7 @@ mod tests {let token = "phc_form_apikey";let key = cache_key("surveys", "surveys.json", token);- let survey_data = json!({"surveys": [{"id": "s3"}], "survey_config": null});+ let survey_data = json!({"surveys": [{"id": "s3"}]});let mut mock = MockRedisClient::new();mock = mock.get_raw_bytes_ret(&key, Ok(pickle_json(&survey_data)));@@ -296,7 +328,7 @@ mod tests {let form_token = "phc_form_loses";let key = cache_key("surveys", "surveys.json", query_token);- let survey_data = json!({"surveys": [{"id": "query"}], "survey_config": null});+ let survey_data = json!({"surveys": [{"id": "query"}]});let mut mock = MockRedisClient::new();mock = mock.get_raw_bytes_ret(&key, Ok(pickle_json(&survey_data)));diff --git a/rust/hypercache-server/src/sanitize.rs b/rust/hypercache-server/src/sanitize.rsindex 174e3f5a68f1..be981e810ae6 100644--- a/rust/hypercache-server/src/sanitize.rs+++ b/rust/hypercache-server/src/sanitize.rs@@ -1,6 +1,7 @@//! Config sanitization for public-facing responses.//!//! Matches Python's `sanitize_config_for_public_cdn` behavior:+//! - Removes unused public config and survey fields//! - Removes `siteAppsJS` (raw JS only needed for array.js bundle, not JSON API)//! - Removes `sessionRecording.domains` (internal field, not needed by SDK)//! - Sets `sessionRecording` to `false` if request origin not in permitted domains@@ -19,7 +20,9 @@ const AUTHORIZED_MOBILE_CLIENTS: &[&str] = &[pub fn sanitize_config_for_client(cached_config: &mut Value, headers: &HeaderMap) {if let Some(obj) = cached_config.as_object_mut() {obj.remove("siteAppsJS");+ obj.remove("token");}+ sanitize_surveys_for_client(cached_config);let session_recording = match cached_config.get_mut("sessionRecording") {Some(sr) => sr,@@ -48,6 +51,49 @@ pub fn sanitize_config_for_client(cached_config: &mut Value, headers: &HeaderMap}}+pub fn sanitize_surveys_for_client(payload: &mut Value) {+ let Some(payload) = payload.as_object_mut() else {+ return;+ };+ payload.remove("survey_config");++ let Some(surveys) = payload.get_mut("surveys").and_then(Value::as_array_mut) else {+ return;+ };++ for survey in surveys {+ let Some(survey) = survey.as_object_mut() else {+ continue;+ };+ survey.remove("base_language");++ if let Some(questions) = survey.get_mut("questions").and_then(Value::as_array_mut) {+ for question in questions {+ if let Some(question) = question.as_object_mut() {+ question.remove("isNpsQuestion");+ }+ }+ }++ let Some(actions) = survey+ .get_mut("conditions")+ .and_then(Value::as_object_mut)+ .and_then(|conditions| conditions.get_mut("actions"))+ .and_then(Value::as_object_mut)+ .and_then(|actions| actions.get_mut("values"))+ .and_then(Value::as_array_mut)+ else {+ continue;+ };++ for action in actions {+ if let Some(action) = action.as_object_mut() {+ action.retain(|field, _| matches!(field.as_str(), "id" | "name" | "steps"));+ }+ }+ }+}+/// Checks if the request originates from a permitted recording domain.////// Returns true if:@@ -159,6 +205,7 @@ mod tests {#[test]fn test_removes_site_apps_js() {let mut config = json!({+ "token": "phc_test","siteApps": [{"id": 1}],"siteAppsJS": ["function() {}"],"heatmaps": true@@ -166,6 +213,7 @@ mod tests {sanitize_config_for_client(&mut config, &HeaderMap::new());+ assert!(config.get("token").is_none());assert!(config.get("siteAppsJS").is_none());assert!(config.get("siteApps").is_some());assert_eq!(config.get("heatmaps"), Some(&json!(true)));diff --git a/rust/hypercache-server/tests/integration_test.rs b/rust/hypercache-server/tests/integration_test.rsindex 38a60ad1601a..836d9159ae9b 100644--- a/rust/hypercache-server/tests/integration_test.rs+++ b/rust/hypercache-server/tests/integration_test.rs@@ -336,7 +336,7 @@ async fn test_surveys_redis_hit() -> anyhow::Result<()> {body["surveys"][0]["questions"][0]["question"],"What can we do to improve our product?");- assert_eq!(body["survey_config"], json!(null));+ assert!(body.get("survey_config").is_none());server.cleanup("surveys", "surveys.json", token).await?;Ok(())@@ -367,6 +367,7 @@ async fn test_surveys_s3_fallback() -> anyhow::Result<()> {body["surveys"][0]["appearance"]["backgroundColor"],"#ffffff");+ assert!(body.get("survey_config").is_none());server.cleanup("surveys", "surveys.json", token).await?;Ok(())@@ -385,8 +386,7 @@ async fn test_surveys_complete_miss_returns_empty() -> anyhow::Result<()> {assert_eq!(resp.status(), 200);let body: Value = resp.json().await?;- assert_eq!(body["surveys"], json!([]));- assert_eq!(body["survey_config"], json!(null));+ assert_eq!(body, json!({"surveys": []}));Ok(())}@@ -427,6 +427,7 @@ async fn test_config_redis_hit_with_headers() -> anyhow::Result<()> {assert_eq!(body["heatmaps"], json!(true));assert_eq!(body["analytics"]["endpoint"], "/i/v0/e/");assert_eq!(body["supportedCompression"], json!(["gzip", "gzip-js"]));+ assert!(body.get("token").is_none());// sessionRecording should be preserved as object (empty domains = allow all)assert!(body["sessionRecording"].is_object());// domains should be stripped from response@@ -457,6 +458,7 @@ async fn test_config_s3_fallback() -> anyhow::Result<()> {let body: Value = resp.json().await?;assert_eq!(body["heatmaps"], json!(true));assert_eq!(body["elementsChainAsString"], json!(true));+ assert!(body.get("token").is_none());server.cleanup("array", "config.json", token).await?;Ok(())