Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(flags): add per-team request/response body logging (#60179)

Phil Haacka54122d042b4
diff --git a/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts b/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts
index 4554585d3d46..19250330a75c 100644
--- a/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts
+++ b/frontend/src/scenes/instance/SystemStatus/systemStatusLogic.ts
@@ -58,6 +58,7 @@ const EDITABLE_INSTANCE_SETTINGS = [
'PARALLEL_DASHBOARD_ITEM_CACHE',
'RATE_LIMIT_ENABLED',
'RATE_LIMITING_ALLOW_LIST_TEAMS',
+ 'FLAGS_LOG_BODIES_TEAMS',
'CLICKHOUSE_KILL_SWITCH',
'CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS',
'CLICKHOUSE_KILL_SWITCH_FULL_TEAMS',
diff --git a/posthog/settings/dynamic_settings.py b/posthog/settings/dynamic_settings.py
index aca278bc6dfe..ec2ad5916a22 100644
--- a/posthog/settings/dynamic_settings.py
+++ b/posthog/settings/dynamic_settings.py
@@ -254,6 +254,11 @@ CONSTANCE_CONFIG = {
"Whether teams are on an allow list to bypass rate limiting. Comma separated list of team-ids",
str,
),
+ "FLAGS_LOG_BODIES_TEAMS": (
+ get_from_env("FLAGS_LOG_BODIES_TEAMS", "{}"),
+ 'Per-team /flags request and response body logging. JSON object mapping team_id (string) to a non-empty list of flag-key wildcard patterns; the response is filtered to flags matching any pattern. "{}" disables logging entirely. Examples: \'{"123": ["my-feature", "checkout-*"]}\' logs only matching flag keys for team 123. To capture every flag (rare, noisy), use [\\"*\\"] explicitly. The Rust feature-flags service polls this every ~60s. Limits: at most 100 teams, 50 patterns per team, 256 bytes per pattern.',
+ str,
+ ),
"REDIRECT_APP_TO_US": (
get_from_env("REDIRECT_APP_TO_US", False, type_cast=str_to_bool),
"Temporary option to redirect all app traffic from app.posthog.com to us.posthog.com.",
@@ -323,6 +328,7 @@ SETTINGS_ALLOWING_API_OVERRIDE = (
"ALLOW_EXPERIMENTAL_ASYNC_MIGRATIONS",
"RATE_LIMIT_ENABLED",
"RATE_LIMITING_ALLOW_LIST_TEAMS",
+ "FLAGS_LOG_BODIES_TEAMS",
"CLICKHOUSE_KILL_SWITCH",
"CLICKHOUSE_KILL_SWITCH_LIGHT_TEAMS",
"CLICKHOUSE_KILL_SWITCH_FULL_TEAMS",
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 2e1358663dd3..6bf6b7ff64a6 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -211,6 +211,15 @@ dependencies = [
"derive_arbitrary",
]
+[[package]]
+name = "arc-swap"
+version = "1.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6a3a1fd6f75306b68087b831f025c712524bcb19aad54e557b1129cfa0a2b207"
+dependencies = [
+ "rustversion",
+]
+
[[package]]
name = "arrayvec"
version = "0.7.6"
@@ -3336,6 +3345,7 @@ version = "0.1.0"
dependencies = [
"aho-corasick",
"anyhow",
+ "arc-swap",
"assert-json-diff",
"async-trait",
"aws-config",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 3052eac1e26a..56cd86af84d9 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -86,6 +86,7 @@ debug = "line-tables-only"
[workspace.dependencies]
aho-corasick = "1.1"
anyhow = "1.0"
+arc-swap = "1.7"
assert-json-diff = "2.0.2"
async-compression = { version = "0.4", features = [
"tokio",
diff --git a/rust/feature-flags/Cargo.toml b/rust/feature-flags/Cargo.toml
index 89d987f264df..d7abc6502474 100644
--- a/rust/feature-flags/Cargo.toml
+++ b/rust/feature-flags/Cargo.toml
@@ -9,6 +9,7 @@ publish = false
[dependencies]
aho-corasick = { workspace = true }
anyhow = { workspace = true }
+arc-swap = { workspace = true }
async-trait = { workspace = true }
aws-config = { workspace = true, optional = true }
aws-sdk-s3 = { workspace = true, optional = true }
diff --git a/rust/feature-flags/src/api/endpoint.rs b/rust/feature-flags/src/api/endpoint.rs
index 052e1678ab3d..330b5ccd69eb 100644
--- a/rust/feature-flags/src/api/endpoint.rs
+++ b/rust/feature-flags/src/api/endpoint.rs
@@ -29,6 +29,7 @@ use bytes::Bytes;
use serde_json;
use std::collections::HashMap;
use std::net::IpAddr;
+use std::sync::{Arc, OnceLock};
use tracing::Instrument;
use uuid::Uuid;
@@ -449,6 +450,17 @@ pub async fn flags(
.as_deref()
.map(|v| v.parse::<i32>().unwrap_or(1));
+ // Install a body-logging side channel only when at least one team is
+ // opted in. The OnceLock is filled inside the request decode flow with
+ // the post-gzip / post-base64 bytes, and read back here once the
+ // handler returns. This avoids decoding the body twice and ensures
+ // base64-wrapped bodies log as their decoded JSON. `Arc::clone` here is
+ // an O(1) refcount bump, paid only when at least one team is enabled.
+ let decoded_body_slot = state
+ .body_logger
+ .has_any_enabled()
+ .then(|| Arc::new(OnceLock::<Bytes>::new()));
+
let context = RequestContext {
request_id,
state: state.clone(),
@@ -456,6 +468,7 @@ pub async fn flags(
headers: headers.clone(),
meta: modified_query_params,
body,
+ decoded_body_for_logging: decoded_body_slot.clone(),
};
// Create debug span for detailed tracing when debugging
@@ -526,11 +539,24 @@ pub async fn flags(
match result {
Ok(response) => {
+ // Emit the body-log event before `response` is consumed by the
+ // versioning step. Skipped when the team isn't opted in. The
+ // request body bytes are the *decoded* form captured during
+ // `parse_and_authenticate` — we never decode the body twice,
+ // and base64-wrapped bodies log as JSON.
+ let decoded_body = decoded_body_slot
+ .as_ref()
+ .and_then(|slot| slot.get().cloned());
+ state
+ .body_logger
+ .log_response(request_id, log.team_id, decoded_body, &response);
+
// Determine the response format based on whether request is from decide and version
match get_versioned_response(is_from_legacy_decide, query_version, response) {
Ok((versioned_response, _response_format)) => {
log.http_status = 200;
log.emit();
+
let mut response = Json(versioned_response).into_response();
if log.rate_limit_warned {
response.headers_mut().insert(
diff --git a/rust/feature-flags/src/api/flag_definitions.rs b/rust/feature-flags/src/api/flag_definitions.rs
index e73db0755e79..e0d2094a867d 100644
--- a/rust/feature-flags/src/api/flag_definitions.rs
+++ b/rust/feature-flags/src/api/flag_definitions.rs
@@ -2,6 +2,7 @@ use crate::{
api::{
auth,
errors::{ClientFacingError, FlagError},
+ instance_setting::{constance_key, fetch_instance_setting_raw_value},
},
flags::{
flag_analytics::is_billable_flag_key, flag_request::FlagRequestType,
@@ -24,6 +25,7 @@ use axum::{
use common_hypercache::{HyperCacheError, KeyType};
use common_metrics::inc;
use common_types::TeamId;
+use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sqlx::PgPool;
@@ -32,7 +34,7 @@ use std::sync::Arc;
use tracing::{info, warn};
const ALLOWLIST_TTL_SECS: u64 = 60;
-const CONSTANCE_KEY: &str = "constance:posthog:RATE_LIMITING_ALLOW_LIST_TEAMS";
+static CONSTANCE_KEY: Lazy<String> = Lazy::new(|| constance_key("RATE_LIMITING_ALLOW_LIST_TEAMS"));
/// Refresh the rate limit allowlist from the database if stale, then update the limiter.
/// Matches Django's `get_team_allow_list(round(time.time() / 60))` pattern.
@@ -66,30 +68,15 @@ async fn refresh_rate_limit_allowlist_if_stale(state: &AppState) {
}
/// Query the posthog_instancesetting table for the rate limit allowlist.
-/// The key is stored with the constance prefix: "constance:posthog:RATE_LIMITING_ALLOW_LIST_TEAMS"
/// Returns None if the row doesn't exist (env var default should be kept),
/// Some(set) if the row exists (overrides the env var).
pub async fn fetch_allowlist_from_db(pool: &PgPool) -> Result<Option<HashSet<TeamId>>, String> {
- let row: Option<(String,)> =
- sqlx::query_as("SELECT raw_value FROM posthog_instancesetting WHERE key = $1")
- .bind(CONSTANCE_KEY)
- .fetch_optional(pool)
- .await
- .map_err(|e| format!("DB query failed: {e}"))?;
-
- let raw_value = match row {
- Some((val,)) => val,
+ let raw = match fetch_instance_setting_raw_value(pool, &CONSTANCE_KEY).await? {
+ Some(v) => v,
None => return Ok(None),
};
- // Match Django's InstanceSetting.value: try json.loads first, fall back to raw string.
- // Handles JSON strings ("\"23047,12345\""), null, and bare strings ("23047,12345").
- let value = match serde_json::from_str::<serde_json::Value>(&raw_value) {
- Ok(serde_json::Value::String(s)) => s,
- Ok(serde_json::Value::Null) => return Ok(Some(HashSet::new())),
- _ => raw_value, // non-string JSON or invalid JSON, treat as bare string (like Django)
- };
- let value = value.trim();
+ let value = raw.trim();
if value.is_empty() {
return Ok(Some(HashSet::new()));
}
diff --git a/rust/feature-flags/src/api/instance_setting.rs b/rust/feature-flags/src/api/instance_setting.rs
new file mode 100644
index 000000000000..96a29a8137ca
--- /dev/null
+++ b/rust/feature-flags/src/api/instance_setting.rs
@@ -0,0 +1,57 @@
+//! Shared helpers for reading Django Constance dynamic settings stored in
+//! `posthog_instancesetting`.
+//!
+//! Django writes settings under the key `constance:posthog:<NAME>` with one
+//! of three encodings, depending on history and value type:
+//! - JSON-encoded string (`"\"foo\""`) — the common case when `set_constance_value`
+//! went through Django's serializer.
+//! - JSON `null` — explicit "no value" written by some admin paths.
+//! - Bare string — older rows or values written outside the serializer.
+//!
+//! Callers want the unwrapped inner value to feed into their own parser
+//! (CSV, JSON, etc.). This helper consolidates that decoding so each caller
+//! only owns its parse step.
+use sqlx::PgPool;
+
+const CONSTANCE_PREFIX: &str = "constance:posthog:";
+
+/// Build the full Postgres key for a Constance setting name.
+pub fn constance_key(setting_name: &str) -> String {
+ format!("{CONSTANCE_PREFIX}{setting_name}")
+}
+
+/// Fetch a Constance dynamic setting from `posthog_instancesetting`, returning
+/// the unwrapped raw string value.
+///
+/// - `Ok(None)` — row missing; callers should keep their env-var default.
+/// - `Ok(Some(""))` — row exists with `null` or empty raw value; callers
+/// typically treat this as "explicitly empty".
+/// - `Ok(Some(s))` — unwrapped value, ready for caller-specific parsing.
+pub async fn fetch_instance_setting_raw_value(
+ pool: &PgPool,
+ full_key: &str,
+) -> Result<Option<String>, String> {
+ let row: Option<(String,)> =
+ sqlx::query_as("SELECT raw_value FROM posthog_instancesetting WHERE key = $1")
+ .bind(full_key)
+ .fetch_optional(pool)
+ .await
+ .map_err(|e| format!("DB query failed: {e}"))?;
+
+ let raw_value = match row {
+ Some((val,)) => val,
+ None => return Ok(None),
+ };
+
+ let unwrapped = match serde_json::from_str::<serde_json::Value>(&raw_value) {
+ Ok(serde_json::Value::String(s)) => s,
+ Ok(serde_json::Value::Null) => String::new(),
+ // For other JSON shapes (numbers, bools, arrays, objects) return the
+ // raw bytes from the DB rather than re-serialising via serde, so
+ // whitespace and formatting survive a round-trip.
+ Ok(_) => raw_value,
+ Err(_) => raw_value,
+ };
+
+ Ok(Some(unwrapped))
+}
diff --git a/rust/feature-flags/src/api/mod.rs b/rust/feature-flags/src/api/mod.rs
index 7cbc839cef9a..45ca92609fb7 100644
--- a/rust/feature-flags/src/api/mod.rs
+++ b/rust/feature-flags/src/api/mod.rs
@@ -6,6 +6,7 @@ pub mod errors;
pub mod flag_definitions;
pub mod flag_definitions_rate_limiter;
pub mod flags_rate_limiter;
+pub mod instance_setting;
pub mod pak_usage;
pub mod rate_parser;
pub mod types;
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index 85d1abf4dc65..8a8f8bd0379a 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -277,6 +277,83 @@ impl FromStr for RateLimitingAllowList {
}
}
+/// Per-team /flags request/response body logging config.
+/// Parses JSON from FLAGS_LOG_BODIES_TEAMS environment variable, also refreshed
+/// at runtime from posthog_instancesetting (key:
+/// `constance:posthog:FLAGS_LOG_BODIES_TEAMS`).
+///
+/// Format: {"team_id": ["pattern", ...], ...}
+/// Each team must specify at least one pattern; the response's `flags` map is
+/// filtered to keys matching any pattern. To capture every flag (rare and
+/// noisy), use `["*"]` explicitly.
+/// Patterns support `*` wildcards (e.g., "my-feature", "checkout-*", "*-targeting-*").
+#[derive(Debug, Clone, PartialEq, Eq, Default)]
+pub struct BodyLogTeams(pub HashMap<TeamId, Vec<String>>);
+
+// Caps on the parsed `FLAGS_LOG_BODIES_TEAMS` shape. Mirrors the pattern in
+// `MAX_FLAGS_RATE_LIMIT_OVERRIDES`: the setting is admin-gated, but a typo
+// or paste of a large blob would otherwise fan out across every pod and
+// flood Loki silently.
+
+/// Matches `MAX_FLAGS_RATE_LIMIT_OVERRIDES`; well above any realistic
+/// per-cluster opt-in count.
+pub const MAX_BODY_LOG_TEAMS: usize = 100;
+/// Realistic teams configure <10 patterns; 50 leaves headroom without
+/// inviting blob-pasting.
+pub const MAX_BODY_LOG_PATTERNS_PER_TEAM: usize = 50;
+/// Longest production flag-key is ~80 chars; 256 bytes leaves room for
+/// `*` prefixes and suffixes.
+pub const MAX_BODY_LOG_PATTERN_LEN: usize = 256;
+
+impl FromStr for BodyLogTeams {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ let s = s.trim();
+
+ if s.is_empty() {
+ return Ok(BodyLogTeams::default());
+ }
+
+ let parsed: HashMap<String, Vec<String>> = serde_json::from_str(s)
+ .map_err(|e| format!("Failed to parse FLAGS_LOG_BODIES_TEAMS as JSON: {e}"))?;
+
+ if parsed.len() > MAX_BODY_LOG_TEAMS {
+ return Err(format!(
+ "Too many FLAGS_LOG_BODIES_TEAMS entries: {} (max {MAX_BODY_LOG_TEAMS})",
+ parsed.len()
+ ));
+ }
+
+ let mut out = HashMap::new();
+ for (team_id_str, patterns) in parsed {
+ if patterns.is_empty() {
+ return Err(format!(
+ "Team {team_id_str} has no patterns; specify at least one (use [\"*\"] to log every flag)"
+ ));
+ }
+ if patterns.len() > MAX_BODY_LOG_PATTERNS_PER_TEAM {
+ return Err(format!(
+ "Too many patterns for team {team_id_str}: {} (max {MAX_BODY_LOG_PATTERNS_PER_TEAM})",
+ patterns.len()
+ ));
+ }
+ if let Some(p) = patterns.iter().find(|p| p.len() > MAX_BODY_LOG_PATTERN_LEN) {
+ return Err(format!(
+ "Pattern too long for team {team_id_str}: {} bytes (max {MAX_BODY_LOG_PATTERN_LEN})",
+ p.len()
+ ));
+ }
+ let team_id = team_id_str.parse::<TeamId>().map_err(|e| {
+ format!("Invalid team ID '{team_id_str}' in FLAGS_LOG_BODIES_TEAMS: {e}")
+ })?;
+ out.insert(team_id, patterns);
+ }
+
+ Ok(BodyLogTeams(out))
+ }
+}
+
/// Per-token rate limit overrides for the /flags endpoint.
/// Parses JSON from FLAGS_TOKEN_RATE_LIMIT_OVERRIDES environment variable.
/// Format: {"token_string": "rate_string", ...}
@@ -606,6 +683,19 @@ pub struct Config {
#[envconfig(from = "RATE_LIMITING_ALLOW_LIST_TEAMS", default = "")]
pub rate_limiting_allow_list_teams: RateLimitingAllowList,
+ // Per-team /flags body logging. JSON: {"team_id": ["flag-key-pattern", ...], ...}
+ // Mirrors Django's FLAGS_LOG_BODIES_TEAMS dynamic setting; refreshed every ~60s
+ // from posthog_instancesetting at runtime.
+ #[envconfig(from = "FLAGS_LOG_BODIES_TEAMS", default = "")]
+ pub flags_log_bodies_teams: BodyLogTeams,
+
+ // Maximum request body bytes to include in body-log events.
+ // Bodies larger than this are truncated; truncated/original_size_bytes fields
+ // record what happened. Response side is naturally bounded by the per-flag
+ // filter when one is set.
+ #[envconfig(from = "FLAGS_LOG_BODIES_REQUEST_MAX_BYTES", default = "65536")]
+ pub flags_log_bodies_request_max_bytes: usize,
+
// OpenTelemetry configuration
#[envconfig(from = "OTEL_EXPORTER_OTLP_ENDPOINT")]
pub otel_url: Option<String>,
@@ -985,6 +1075,8 @@ impl Config {
flag_definitions_default_rate_per_minute: 600,
flag_definitions_rate_limits: FlagDefinitionsRateLimits::default(),
rate_limiting_allow_list_teams: RateLimitingAllowList::default(),
+ flags_log_bodies_teams: BodyLogTeams::default(),
+ flags_log_bodies_request_max_bytes: 65_536,
otel_url: None,
otel_sampling_rate: 1.0,
otel_service_name: "posthog-feature-flags".to_string(),
diff --git a/rust/feature-flags/src/handler/authentication.rs b/rust/feature-flags/src/handler/authentication.rs
index 8c6529d89bec..4d68b945520a 100644
--- a/rust/feature-flags/src/handler/authentication.rs
+++ b/rust/feature-flags/src/handler/authentication.rs
@@ -12,7 +12,17 @@ pub async fn parse_and_authenticate(
context: &RequestContext,
flag_service: &FlagService,
) -> Result<(Option<String>, Team, FlagRequest), FlagError> {
- let request = decoding::decode_request(&context.headers, context.body.clone(), &context.meta)?;
+ let (request, decoded_body) =
+ decoding::decode_request(&context.headers, context.body.clone(), &context.meta)?;
+
+ // Hand the decoded body to the body-log side channel if one is installed.
+ // `set` is a no-op once filled, which can't happen here because each
+ // request has its own OnceLock — but this future-proofs against a
+ // hypothetical retry that calls `parse_and_authenticate` twice.
+ if let Some(slot) = context.decoded_body_for_logging.as_ref() {
+ slot.set(decoded_body).ok();
+ }
+
let token = request.extract_token()?;
let team = flag_service.verify_token_and_get_team(&token).await?;
diff --git a/rust/feature-flags/src/handler/body_logger.rs b/rust/feature-flags/src/handler/body_logger.rs
new file mode 100644
index 000000000000..26d0962a735b
--- /dev/null
+++ b/rust/feature-flags/src/handler/body_logger.rs
@@ -0,0 +1,783 @@
+//! Per-team request/response body logging for the `/flags` endpoint.
+//!
+//! Configured via the `FLAGS_LOG_BODIES_TEAMS` env var at startup and refreshed
+//! at runtime from `posthog_instancesetting`
+//! (key: `constance:posthog:FLAGS_LOG_BODIES_TEAMS`) every ~60s.
+//!
+//! Stored per-team config maps a team ID to a non-empty list of glob patterns;
+//! the response's `flags` map is filtered to keys matching any pattern. To
+//! capture every flag (rare and noisy), specify `["*"]` explicitly.
+//!
+//! Patterns support `*` wildcards (e.g., `my-feature`, `checkout-*`,
+//! `*-targeting-*`); exact keys (no `*`) match by string equality.
+
+use crate::api::instance_setting::{constance_key, fetch_instance_setting_raw_value};
+use crate::api::types::{FlagDetails, FlagsResponse};
+use crate::config::BodyLogTeams;
+use crate::metrics::consts::FLAG_BODY_LOG_REFRESH_TOTAL;
+use arc_swap::ArcSwap;
+use bytes::Bytes;
+use common_types::TeamId;
+use once_cell::sync::Lazy;
+use rand::Rng;
+use regex::Regex;
+use serde::Serialize;
+use sqlx::PgPool;
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use tracing::warn;
+use uuid::Uuid;
+
+/// Refresh interval for the in-memory team config; matches the Django-side
+/// `RATE_LIMITING_ALLOW_LIST_TEAMS` cadence so admins see propagation in <1m.
+const REFRESH_INTERVAL: Duration = Duration::from_secs(60);
+
+/// Tracing target for body-log events. Stable identifier independent of the
+/// module path; promoted to a Loki label for differential retention and used
+/// in `main.rs` to keep these events out of the OpenTelemetry sink.
+pub const BODY_LOG_TARGET: &str = "feature_flags::flags_body_log";
+
+static CONSTANCE_KEY: Lazy<String> = Lazy::new(|| constance_key("FLAGS_LOG_BODIES_TEAMS"));
+
+/// Compiles a glob-style pattern (`*` wildcard, no other metacharacters) into
+/// an anchored regex. Exact keys (no `*`) compile to `^literal$`.
+fn compile_pattern(raw: &str) -> Result<Regex, regex::Error> {
+ let escaped = regex::escape(raw).replace("\\*", ".*");
+ Regex::new(&format!("^{escaped}$"))
+}
+
+/// Per-team body-logging filter. Holds the joined pattern strings (for the
+/// `response_filter_patterns` log field) and their compiled regexes (for
+/// matching). The parser guarantees `compiled` is non-empty; an operator who
+/// truly wants every flag must specify `["*"]` explicitly.
+#[derive(Debug)]
+pub struct TeamPatterns {
+ /// Original patterns pre-joined with `,` for the log field; built once at
+ /// refresh time so the opt-in path doesn't allocate per request.
+ raw_joined: String,
+ compiled: Vec<Regex>,
+}
+
+impl TeamPatterns {
+ fn new(raw: Vec<String>) -> Self {
+ let raw_joined = raw.join(",");
+ let compiled = raw
+ .iter()
+ .filter_map(|p| match compile_pattern(p) {
+ Ok(re) => Some(re),
+ Err(e) => {
+ warn!(pattern = %p, error = %e, "invalid FLAGS_LOG_BODIES_TEAMS pattern, skipping");
+ None
+ }
+ })
+ .collect();
+ Self {
+ raw_joined,
+ compiled,
+ }
+ }
+
+ /// True when `key` matches one of the configured patterns.
+ pub fn matches(&self, key: &str) -> bool {
+ self.compiled.iter().any(|re| re.is_match(key))
+ }
+}
+
+/// In-memory body-logging config, refreshed periodically from Postgres by a
+/// background task spawned via [`BodyLogger::spawn_refresh_task`].
+///
+/// `config` uses [`ArcSwap`] so the request hot path is a single atomic load
+/// — no `RwLock`, so a panic in the refresh task can't poison a lock the hot
+/// path then walks into. `last_applied` is touched only by the single-threaded
+/// refresh task, so its `Mutex` is uncontended.
+///
+/// On persistent Postgres failure, the refresh task keeps ticking every
+/// `REFRESH_INTERVAL` and the cached config is held indefinitely — fail-static
+/// rather than fail-open. Operators should alert on absence of
+/// `FLAG_BODY_LOG_REFRESH_TOTAL{result="success"}` increments rather than
+/// expecting the process to surface a hard failure.
+pub struct BodyLogger {
+ config: ArcSwap<HashMap<TeamId, Arc<TeamPatterns>>>,
+ /// Last `BodyLogTeams` we successfully applied. Used to skip the
+ /// recompile when the DB row is unchanged so concurrent readers retain
+ /// `Arc<TeamPatterns>` identity across no-op refreshes.
+ last_applied: Mutex<Option<BodyLogTeams>>,
+ /// Cheap short-circuit for the common no-team-enabled path. Tracks
+ /// whether the config map is non-empty so per-request lookups can skip
+ /// the `ArcSwap` load entirely. Updated alongside `config`.
+ any_enabled: AtomicBool,
+ /// Maximum request body bytes to log; bodies above this are truncated.
+ request_max_bytes: usize,
+}
+
+impl BodyLogger {
+ pub fn new(initial: BodyLogTeams, request_max_bytes: usize) -> Self {
+ let map = compile_all(&initial);
+ let any_enabled = AtomicBool::new(!map.is_empty());
+ Self {
+ config: ArcSwap::from(Arc::new(map)),
+ last_applied: Mutex::new(Some(initial)),
+ any_enabled,
+ request_max_bytes,
+ }
+ }
+
+ /// True when at least one team is in the allow-list. Lets callers skip
+ /// per-request work (body clone, ArcSwap load) in the common case.
+ pub fn has_any_enabled(&self) -> bool {
+ self.any_enabled.load(Ordering::Relaxed)
+ }
+
+ /// Returns the per-team filter, or `None` when the team isn't enabled.
+ pub fn for_team(&self, team_id: TeamId) -> Option<Arc<TeamPatterns>> {
+ if !self.has_any_enabled() {
+ return None;
+ }
+ self.config.load().get(&team_id).cloned()
+ }
+
+ fn update(&self, raw: BodyLogTeams) {
+ let mut last_applied = self
+ .last_applied
+ .lock()
+ .expect("body logger last_applied poisoned");
+ if last_applied.as_ref() == Some(&raw) {
+ return;
+ }
+ let map = compile_all(&raw);
+ self.any_enabled.store(!map.is_empty(), Ordering::Relaxed);
+ self.config.store(Arc::new(map));
+ *last_applied = Some(raw);
+ }
+
+ /// Spawn a background task that refreshes the in-memory config from
+ /// Postgres on `REFRESH_INTERVAL`. The task sleeps a random startup
+ /// jitter in `[0, REFRESH_INTERVAL)` before the first refresh so a
+ /// coordinated deploy (N pods booting together) smears its initial DB
+ /// queries across the interval instead of all hitting Postgres in the
+ /// same scheduler hop. The task runs for the lifetime of the runtime;
+ /// on graceful shutdown the runtime cancels it.
+ ///
+ /// `MissedTickBehavior::Delay` keeps the steady-state cadence after a
+ /// runtime stall (clock jump, host suspend) instead of firing a flurry
+ /// of catch-up refreshes against a recovering DB.
+ pub fn spawn_refresh_task(self: Arc<Self>, pool: Arc<PgPool>) {
+ let jitter = Duration::from_millis(
+ rand::thread_rng().gen_range(0..REFRESH_INTERVAL.as_millis() as u64),
+ );
+ tokio::spawn(async move {
+ tokio::time::sleep(jitter).await;
+ let mut ticker = tokio::time::interval(REFRESH_INTERVAL);
+ ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ loop {
+ ticker.tick().await;
+ self.do_refresh(&pool).await;
+ }
+ });
+ }
+
+ /// Fetch the body-log config from the database and apply it.
+ /// Best-effort: on DB error, the cached config is kept and a warning is
+ /// logged. Each attempt increments `FLAG_BODY_LOG_REFRESH_TOTAL` labeled
+ /// by `result="success"|"failure"` so operators can alert on absence of
+ /// recent successes.
+ pub async fn do_refresh(&self, pool: &PgPool) {
+ let result_label = match fetch_from_db(pool).await {
+ Ok(Some(raw)) => {
+ self.update(raw);
+ "success"
+ }
+ Ok(None) => {
+ // Row absent: keep cached value (env-var default or prior refresh).
+ "success"
+ }
+ Err(e) => {
+ warn!(
+ error = %e,
+ "Failed to refresh FLAGS_LOG_BODIES_TEAMS from database, keeping cached value"
+ );
+ "failure"
+ }
+ };
+ common_metrics::inc(
+ FLAG_BODY_LOG_REFRESH_TOTAL,
+ &[("result".to_string(), result_label.to_string())],
+ 1,
+ );
+ }
+
+ /// Emit a tracing record on target `feature_flags::flags_body_log` when
+ /// `team_id` resolves to an opted-in team. No-op otherwise.
+ ///
+ /// `decoded_body` is the post-gzip, post-base64 request body captured
+ /// during normal request decoding (see [`RequestContext`] and
+ /// [`crate::handler::authentication::parse_and_authenticate`]). Reusing
+ /// those bytes means opted-in teams using gzip don't pay for a second
+ /// decompress, and base64-wrapped bodies are logged as the JSON they
+ /// actually parsed as — not as the raw base64 string.
+ pub fn log_response(
+ &self,
+ request_id: Uuid,
+ team_id: Option<TeamId>,
+ decoded_body: Option<Bytes>,
+ response: &FlagsResponse,
+ ) {
+ let (Some(team_id), Some(decoded)) = (team_id, decoded_body) else {
+ return;
+ };
+ let Some(patterns) = self.for_team(team_id) else {
+ return;
+ };
+
+ let (truncated, request_truncated, request_original_size_bytes) =
+ truncate_body(&decoded, self.request_max_bytes);
+ let request_body = String::from_utf8_lossy(truncated);
+ let (response_flags_body, total, logged) = serialize_filtered_response(response, &patterns);
+
+ // Override the default target (module path) with a stable, semantic
+ // identifier. Keeps the `feature_flags::` prefix so `RUST_LOG` filters
+ // and prefix-based tooling continue to match. This is the discriminator
+ // forwarders can promote to a Loki label for differential retention.
+ // Loki joins this record to the canonical log line on `request_id`.
+ tracing::info!(
+ target: BODY_LOG_TARGET,
+ request_id = %request_id,
+ team_id = team_id,
+ request_body = %request_body,
+ response_flags_body = %response_flags_body,
+ request_truncated = request_truncated,
+ request_original_size_bytes = request_original_size_bytes,
+ response_filter_patterns = %patterns.raw_joined,
+ response_flag_count_total = total,
+ response_flag_count_logged = logged,
+ "logged",
+ );
+ }
+}
+
+fn compile_all(raw: &BodyLogTeams) -> HashMap<TeamId, Arc<TeamPatterns>> {
+ raw.0
+ .iter()
+ .map(|(team_id, patterns)| (*team_id, Arc::new(TeamPatterns::new(patterns.clone()))))
+ .collect()
+}
+
+async fn fetch_from_db(pool: &PgPool) -> Result<Option<BodyLogTeams>, String> {
+ let raw = match fetch_instance_setting_raw_value(pool, &CONSTANCE_KEY).await? {
+ Some(v) => v,
+ None => return Ok(None),
+ };
+ raw.parse::<BodyLogTeams>().map(Some)
+}
+
+/// Truncate a body to `max_bytes`, returning the prefix slice, whether it was
+/// truncated, and the original byte length. Respects UTF-8 char boundaries
+/// (RFC 3629) so the resulting slice is safe to pass to `from_utf8_lossy`
+/// without splitting a multi-byte sequence.
+pub(crate) fn truncate_body(body: &[u8], max_bytes: usize) -> (&[u8], bool, usize) {
+ let original_len = body.len();
+ if original_len <= max_bytes {
+ return (body, false, original_len);
+ }
+
+ let mut end = max_bytes;
+ while end > 0 {
+ match std::str::from_utf8(&body[..end]) {
+ Ok(_) => break,
+ Err(e) => end = e.valid_up_to(),
+ }
+ }
+ (&body[..end], true, original_len)
+}
+
+/// Subset of `FlagsResponse` we emit on the body-log line. The flattened
+/// `ConfigResponse` (sessionRecording, surveys, siteApps, toolbarParams) is
+/// intentionally omitted: it can be tens of KB per response and is unrelated
+/// to flag debugging. The corresponding log field is named
+/// `response_flags_body` to document the omission at the use site.
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct LoggedResponse<'a> {
+ errors_while_computing_flags: bool,
+ flags: HashMap<&'a String, &'a FlagDetails>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ quota_limited: &'a Option<Vec<String>>,
+ request_id: Uuid,
+ evaluated_at: i64,
+}
+
+/// Serialize the response with `flags` filtered to keys matching `patterns`.
+/// Returns the JSON string plus `(total_flags, logged_flags)` counts.
+fn serialize_filtered_response(
+ response: &FlagsResponse,
+ patterns: &TeamPatterns,
+) -> (String, usize, usize) {
+ let total = response.flags.len();
+
+ let flags: HashMap<&String, &FlagDetails> = response
+ .flags
+ .iter()
+ .filter(|(key, _)| patterns.matches(key))
+ .collect();
+ let logged = flags.len();
+
+ let payload = LoggedResponse {
+ errors_while_computing_flags: response.errors_while_computing_flags,
+ flags,
+ quota_limited: &response.quota_limited,
+ request_id: response.request_id,
+ evaluated_at: response.evaluated_at,
+ };
+
+ let body = match serde_json::to_string(&payload) {
+ Ok(s) => s,
+ Err(e) => {
+ warn!(error = %e, "flags_body_log response serialize failed, emitting sentinel");
+ "<serialize-failed>".to_string()
+ }
+ };
+ (body, total, logged)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::api::types::{
+ FlagDetails, FlagDetailsMetadata, FlagEvaluationReason, FlagsResponse,
+ };
+ use std::collections::HashMap;
+ use uuid::Uuid;
+
+ fn make_flag(key: &str, enabled: bool) -> FlagDetails {
+ FlagDetails {
+ key: key.to_string(),
+ enabled,
+ variant: None,
+ failed: false,
+ reason: FlagEvaluationReason {
+ code: "matched".to_string(),
+ description: None,
+ condition_index: None,
+ },
+ metadata: FlagDetailsMetadata {
+ id: 1,
+ version: 1,
+ description: None,
+ payload: None,
+ },
+ conditions: None,
+ }
+ }
+
+ fn make_response(flag_keys: &[&str]) -> FlagsResponse {
+ let mut flags = HashMap::new();
+ for k in flag_keys {
+ flags.insert(k.to_string(), make_flag(k, true));
+ }
+ FlagsResponse::new(false, flags, None, Uuid::nil())
+ }
+
+ fn matches(pattern: &str, key: &str) -> bool {
+ compile_pattern(pattern).unwrap().is_match(key)
+ }
+
+ #[test]
+ fn pattern_matching() {
+ let cases: &[(&str, &str, bool)] = &[
+ // Exact match.
+ ("my-feature", "my-feature", true),
+ ("my-feature", "my-feature-2", false),
+ ("my-feature", "not-my-feature", false),
+ // Prefix wildcard.
+ ("checkout-*", "checkout-foo", true),
+ ("checkout-*", "checkout-", true),
+ ("checkout-*", "checkout-bar-baz", true),
+ ("checkout-*", "checkou", false),
+ ("checkout-*", "not-checkout-x", false),
+ // Suffix wildcard.
+ ("*-targeting", "survey-targeting", true),
+ ("*-targeting", "-targeting", true),
+ ("*-targeting", "targeting-other", false),
+ // Middle wildcard.
+ ("survey-*-targeting", "survey-abc-targeting", true),
+ ("survey-*-targeting", "survey--targeting", true),
+ ("survey-*-targeting", "survey-abc-other", false),
+ ("survey-*-targeting", "not-survey-abc-targeting", false),
+ // Match-all wildcard.
+ ("*", "", true),
+ ("*", "anything", true),
+ ("*", "with-dashes-123", true),
+ ];
+
+ for (pattern, key, expected) in cases {
+ assert_eq!(
+ matches(pattern, key),
+ *expected,
+ "pattern={pattern:?} key={key:?}"
+ );
+ }
+ }
+
+ #[test]
+ fn for_team_skip_when_unlisted() {
+ let logger = BodyLogger::new(BodyLogTeams::default(), 65_536);
+ assert!(!logger.has_any_enabled());
+ assert!(logger.for_team(42).is_none());
+ }
+
+ #[test]
+ fn for_team_log_all_when_wildcard_pattern() {
+ let mut map = HashMap::new();
+ map.insert(42, vec!["*".into()]);
+ let logger = BodyLogger::new(BodyLogTeams(map), 65_536);
+ assert!(logger.has_any_enabled());
+ let p = logger.for_team(42).expect("expected entry for team 42");
+ assert!(p.matches("anything-goes"));
+ assert!(p.matches("checkout-foo"));
+ }
+
+ #[test]
+ fn for_team_log_matching_when_patterns_set() {
+ let mut map = HashMap::new();
+ map.insert(42, vec!["my-feature".into(), "checkout-*".into()]);
+ let logger = BodyLogger::new(BodyLogTeams(map), 65_536);
+ let p = logger.for_team(42).expect("expected entry for team 42");
+ assert_eq!(p.raw_joined, "my-feature,checkout-*");
+ assert!(p.matches("my-feature"));
+ assert!(p.matches("checkout-foo"));
+ assert!(!p.matches("other-flag"));
+ }
+
+ #[test]
+ fn serialize_filtered_response_passes_all_when_wildcard() {
+ let resp = make_response(&["a", "b", "c"]);
+ let patterns = TeamPatterns::new(vec!["*".into()]);
+ let (_body, total, logged) = serialize_filtered_response(&resp, &patterns);
+ assert_eq!(total, 3);
+ assert_eq!(logged, 3);
+ }
+
+ #[test]
+ fn serialize_filtered_response_filters_to_matching() {
+ let resp = make_response(&["my-feature", "checkout-foo", "other"]);
+ let patterns = TeamPatterns::new(vec!["my-feature".into(), "checkout-*".into()]);
+ let (_body, total, logged) = serialize_filtered_response(&resp, &patterns);
+ assert_eq!(total, 3);
+ assert_eq!(logged, 2);
+ }
+
+ #[test]
+ fn serialize_filtered_response_zero_when_no_match() {
+ let resp = make_response(&["a", "b"]);
+ let patterns = TeamPatterns::new(vec!["nothing-matches-*".into()]);
+ let (_body, total, logged) = serialize_filtered_response(&resp, &patterns);
+ assert_eq!(total, 2);
+ assert_eq!(logged, 0);
+ }
+
+ #[test]
+ fn truncate_body_under_cap() {
+ let (out, truncated, original) = truncate_body(b"hello", 10);
+ assert_eq!(out, b"hello");
+ assert!(!truncated);
+ assert_eq!(original, 5);
+ }
+
+ #[test]
+ fn truncate_body_at_cap() {
+ let (out, truncated, original) = truncate_body(b"hello", 5);
+ assert_eq!(out, b"hello");
+ assert!(!truncated);
+ assert_eq!(original, 5);
+ }
+
+ #[test]
+ fn truncate_body_over_cap() {
+ let (out, truncated, original) = truncate_body(b"hello world", 5);
+ assert_eq!(out, b"hello");
+ assert!(truncated);
+ assert_eq!(original, 11);
+ }
+
+ #[test]
+ fn truncate_body_respects_utf8_boundary() {
+ // "héllo" — é is 2 bytes (0xC3 0xA9). Cap at 2 must not split it.
+ let body = "héllo".as_bytes();
+ let (out, truncated, _) = truncate_body(body, 2);
+ assert_eq!(out, b"h");
+ assert!(truncated);
+ }
+
+ #[test]
+ fn body_log_teams_parses_empty() {
+ assert!("{}".parse::<BodyLogTeams>().unwrap().0.is_empty());
+ assert!("".parse::<BodyLogTeams>().unwrap().0.is_empty());
+ }
+
+ #[test]
+ fn body_log_teams_parses_populated() {
+ let parsed: BodyLogTeams = r#"{"123": ["*"], "456": ["my-feature", "checkout-*"]}"#
+ .parse()
+ .unwrap();
+ assert_eq!(parsed.0.len(), 2);
+ assert_eq!(parsed.0[&123], vec!["*"]);
+ assert_eq!(parsed.0[&456], vec!["my-feature", "checkout-*"]);
+ }
+
+ #[test]
+ fn body_log_teams_rejects_invalid_team_id() {
+ let result: Result<BodyLogTeams, _> = r#"{"abc": ["*"]}"#.parse();
+ assert!(result.is_err());
+ }
+
+ #[test]
+ fn body_log_teams_rejects_empty_patterns_for_team() {
+ let err = r#"{"42": []}"#.parse::<BodyLogTeams>().unwrap_err();
+ assert!(err.contains("Team 42 has no patterns"));
+ assert!(err.contains(r#"["*"]"#));
+ }
+
+ #[test]
+ fn body_log_teams_rejects_too_many_teams() {
+ use crate::config::MAX_BODY_LOG_TEAMS;
+ let mut entries = String::from("{");
+ for i in 0..=MAX_BODY_LOG_TEAMS {
+ if i > 0 {
+ entries.push(',');
+ }
+ entries.push_str(&format!(r#""{i}": ["*"]"#));
+ }
+ entries.push('}');
+ let err = entries.parse::<BodyLogTeams>().unwrap_err();
+ assert!(err.contains("Too many FLAGS_LOG_BODIES_TEAMS entries"));
+ }
+
+ #[test]
+ fn body_log_teams_rejects_too_many_patterns_per_team() {
+ use crate::config::MAX_BODY_LOG_PATTERNS_PER_TEAM;
+ let patterns: Vec<String> = (0..=MAX_BODY_LOG_PATTERNS_PER_TEAM)
+ .map(|i| format!(r#""p{i}""#))
+ .collect();
+ let json = format!(r#"{{"42": [{}]}}"#, patterns.join(","));
+ let err = json.parse::<BodyLogTeams>().unwrap_err();
+ assert!(err.contains("Too many patterns for team 42"));
+ }
+
+ #[test]
+ fn body_log_teams_rejects_pattern_too_long() {
+ use crate::config::MAX_BODY_LOG_PATTERN_LEN;
+ let big = "a".repeat(MAX_BODY_LOG_PATTERN_LEN + 1);
+ let json = format!(r#"{{"42": ["{big}"]}}"#);
+ let err = json.parse::<BodyLogTeams>().unwrap_err();
+ assert!(err.contains("Pattern too long for team 42"));
+ }
+
+ #[test]
+ fn update_skips_recompile_when_unchanged() {
+ let mut map = HashMap::new();
+ map.insert(42, vec!["foo".into()]);
+ let logger = BodyLogger::new(BodyLogTeams(map.clone()), 65_536);
+ let before = Arc::as_ptr(&logger.for_team(42).unwrap());
+ logger.update(BodyLogTeams(map));
+ let after = Arc::as_ptr(&logger.for_team(42).unwrap());
+ assert_eq!(
+ before, after,
+ "Arc identity preserved when config unchanged"
+ );
+ }
+
+ /// In-memory `MakeWriter` that captures emitted log lines so tests can
+ /// assert the `flags_body_log` event shape without the JSON formatter
+ /// going to stdout.
+ #[derive(Clone, Default)]
+ struct CaptureWriter(Arc<std::sync::Mutex<Vec<u8>>>);
+
+ impl CaptureWriter {
+ fn captured(&self) -> String {
+ String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
+ }
+ }
+
+ impl std::io::Write for CaptureWriter {
+ fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(buf);
+ Ok(buf.len())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+
+ impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for CaptureWriter {
+ type Writer = Self;
+ fn make_writer(&'a self) -> Self::Writer {
+ self.clone()
+ }
+ }
+
+ fn capture_log_response<F: FnOnce(&CaptureWriter)>(f: F) -> String {
+ let writer = CaptureWriter::default();
+ let subscriber = tracing_subscriber::fmt()
+ .json()
+ .with_writer(writer.clone())
+ .with_max_level(tracing::Level::INFO)
+ .finish();
+ tracing::subscriber::with_default(subscriber, || f(&writer));
+ writer.captured()
+ }
+
+ #[test]
+ fn log_response_emits_event_for_opted_in_team() {
+ let mut map = HashMap::new();
+ map.insert(42, vec!["*".into()]);
+ let logger = BodyLogger::new(BodyLogTeams(map), 65_536);
+ let resp = make_response(&["my-feature"]);
+
+ let captured = capture_log_response(|_| {
+ logger.log_response(
+ Uuid::nil(),
+ Some(42),
+ Some(Bytes::from_static(b"{\"token\":\"phc_abc\"}")),
+ &resp,
+ );
+ });
+
+ assert!(
+ captured.contains("flags_body_log"),
+ "expected target in log line: {captured}"
+ );
+ assert!(
+ captured.contains("\"team_id\":42"),
+ "expected team_id field: {captured}"
+ );
+ assert!(
+ captured.contains("\"response_flag_count_total\":1"),
+ "expected total count: {captured}"
+ );
+ assert!(
+ captured.contains("\"response_flag_count_logged\":1"),
+ "expected logged count: {captured}"
+ );
+ assert!(
+ captured.contains("phc_abc"),
+ "expected request body to be logged: {captured}"
+ );
+ }
+
+ #[test]
+ fn log_response_skips_unopted_team() {
+ let logger = BodyLogger::new(BodyLogTeams::default(), 65_536);
+ let resp = make_response(&["a"]);
+
+ let captured = capture_log_response(|_| {
+ logger.log_response(Uuid::nil(), Some(42), Some(Bytes::from_static(b"x")), &resp);
+ });
+
+ assert!(
+ !captured.contains("flags_body_log"),
+ "unopted team should produce no event: {captured}"
+ );
+ }
+
+ #[test]
+ fn log_response_skips_when_team_id_missing() {
+ let mut map = HashMap::new();
+ map.insert(42, vec!["*".into()]);
+ let logger = BodyLogger::new(BodyLogTeams(map), 65_536);
+ let resp = make_response(&["a"]);
+
+ let captured = capture_log_response(|_| {
+ logger.log_response(Uuid::nil(), None, Some(Bytes::from_static(b"x")), &resp);
+ });
+
+ assert!(
+ !captured.contains("flags_body_log"),
+ "missing team_id should produce no event: {captured}"
+ );
+ }
+
+ #[test]
+ fn log_response_includes_filter_metadata_when_patterns_set() {
+ let mut map = HashMap::new();
+ map.insert(42, vec!["my-feature".into(), "checkout-*".into()]);
+ let logger = BodyLogger::new(BodyLogTeams(map), 65_536);
+ let resp = make_response(&["my-feature", "checkout-foo", "other"]);
+
+ let captured = capture_log_response(|_| {
+ logger.log_response(
+ Uuid::nil(),
+ Some(42),
+ Some(Bytes::from_static(b"{}")),
+ &resp,
+ );
+ });
+
+ assert!(captured.contains("\"response_filter_patterns\":\"my-feature,checkout-*\""));
+ assert!(captured.contains("\"response_flag_count_total\":3"));
+ assert!(captured.contains("\"response_flag_count_logged\":2"));
+ }
+
+ #[test]
+ fn log_response_omits_config_response_fields() {
+ // ConfigResponse (sessionRecording, surveys, siteApps, toolbarParams)
+ // is intentionally excluded from the logged response — flag debugging
+ // does not need it and including it makes the log line unbounded.
+ let mut map = HashMap::new();
+ map.insert(42, vec!["*".into()]);
+ let logger = BodyLogger::new(BodyLogTeams(map), 65_536);
+
+ let mut resp = make_response(&["my-feature"]);
+ resp.config
+ .set("sessionRecording", serde_json::json!(false));
+ resp.config
+ .set("toolbarParams", serde_json::json!({"foo": "bar"}));
+
+ let captured = capture_log_response(|_| {
+ logger.log_response(
+ Uuid::nil(),
+ Some(42),
+ Some(Bytes::from_static(b"{}")),
+ &resp,
+ );
+ });
+
+ assert!(
+ !captured.contains("sessionRecording"),
+ "config flatten leaked into log: {captured}"
+ );
+ assert!(
+ !captured.contains("toolbarParams"),
+ "config flatten leaked into log: {captured}"
+ );
+ // The flag itself should still be present.
+ assert!(
+ captured.contains("my-feature"),
+ "expected flag key in log: {captured}"
+ );
+ }
+
+ #[test]
+ fn serialize_filtered_response_filters_correct_keys() {
+ let resp = make_response(&["my-feature", "checkout-foo", "other"]);
+ let patterns = TeamPatterns::new(vec!["my-feature".into(), "checkout-*".into()]);
+ let (body, total, logged) = serialize_filtered_response(&resp, &patterns);
+ assert_eq!(total, 3);
+ assert_eq!(logged, 2);
+ assert!(body.contains("\"my-feature\""));
+ assert!(body.contains("\"checkout-foo\""));
+ assert!(!body.contains("\"other\""));
+ }
+
+ #[test]
+ fn truncate_body_caps_below_first_multibyte_char_returns_empty() {
+ // "é" is 2 bytes (0xC3 0xA9). Cap of 1 falls inside the char, so
+ // `valid_up_to()` returns 0 and we end up with an empty prefix.
+ let body = "é".as_bytes();
+ let (out, truncated, original) = truncate_body(body, 1);
+ assert_eq!(out, b"");
+ assert!(truncated);
+ assert_eq!(original, 2);
+ }
+}
diff --git a/rust/feature-flags/src/handler/decoding.rs b/rust/feature-flags/src/handler/decoding.rs
index 4dfea31adc1e..e4342aa667b4 100644
--- a/rust/feature-flags/src/handler/decoding.rs
+++ b/rust/feature-flags/src/handler/decoding.rs
@@ -37,11 +37,18 @@ pub fn extract_token(body: &Bytes) -> Option<String> {
})
}
+/// Decode and parse a /flags request body.
+///
+/// Returns the parsed [`FlagRequest`] along with the **decoded** body bytes
+/// — post gzip-decompression and post base64-decoding when those apply, or
+/// the raw body for plain JSON. Callers that want to log or otherwise reuse
+/// the parsed-form bytes (e.g. body logging) can avoid a second decompress
+/// pass by reusing the returned `Bytes`.
pub fn decode_request(
headers: &HeaderMap,
body: Bytes,
query: &FlagsQueryParams,
-) -> Result<FlagRequest, FlagError> {
+) -> Result<(FlagRequest, Bytes), FlagError> {
let content_type = headers
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
@@ -69,7 +76,13 @@ pub fn decode_request(
}
}
-fn decode_body(
+/// Decode a request body to its raw JSON bytes.
+///
+/// Handles gzip explicitly via `Compression::Gzip`, the `Content-Encoding`
+/// header, or auto-detection from magic bytes. `Compression::Base64` is left
+/// to `try_parse_with_fallbacks`; this function returns the body unchanged in
+/// that case.
+pub(crate) fn decode_body(
body: Bytes,
compression: Option<Compression>,
headers: &HeaderMap,
@@ -158,13 +171,21 @@ fn decode_base64(body: Bytes) -> Result<Bytes, FlagError> {
Ok(Bytes::from(decoded))
}
+/// Parse a request body that has already been gzip-decompressed (if it was
+/// gzipped). Falls back to base64-decoding when the body is not direct JSON
+/// — some SDKs send base64-wrapped JSON via `application/json` rather than
+/// the form-urlencoded path.
+///
+/// Returns the parsed [`FlagRequest`] along with the bytes that successfully
+/// parsed: the input bytes when direct JSON parsing wins, or the
+/// base64-decoded bytes when the fallback wins.
pub fn try_parse_with_fallbacks(
body: Bytes,
user_agent: Option<&str>,
-) -> Result<FlagRequest, FlagError> {
+) -> Result<(FlagRequest, Bytes), FlagError> {
// Strategy 1: Try parsing as JSON directly
if let Ok(request) = FlagRequest::from_bytes(body.clone()) {
- return Ok(request);
+ return Ok((request, body));
}
// Strategy 2: Try base64 decode then JSON
@@ -175,7 +196,7 @@ pub fn try_parse_with_fallbacks(
"Direct JSON parsing failed, trying base64 decode fallback"
);
match decode_base64(body.clone()) {
- Ok(decoded) => match FlagRequest::from_bytes(decoded) {
+ Ok(decoded) => match FlagRequest::from_bytes(decoded.clone()) {
Ok(request) => {
inc(
FLAG_REQUEST_KLUDGE_COUNTER,
@@ -189,7 +210,7 @@ pub fn try_parse_with_fallbacks(
client_type = client_type,
"Successfully parsed request after base64 fallback decoding"
);
- return Ok(request);
+ return Ok((request, decoded));
}
Err(e) => {
tracing::warn!("Base64 decode succeeded but JSON parsing failed: {}", e);
@@ -207,7 +228,7 @@ pub fn decode_form_data(
body: Bytes,
compression: Option<Compression>,
user_agent: Option<&str>,
-) -> Result<FlagRequest, FlagError> {
+) -> Result<(FlagRequest, Bytes), FlagError> {
// Convert bytes to string first so we can manipulate it
let form_data = String::from_utf8(body.to_vec()).map_err(|e| {
tracing::warn!("Invalid UTF-8 in form data: {}", e);
@@ -288,11 +309,15 @@ pub fn decode_form_data(
lossy_str.into_owned()
};
- // Parse JSON into FlagRequest
- serde_json::from_str(&json_str).map_err(|e| {
+ // Parse JSON into FlagRequest. Return the decoded JSON bytes alongside
+ // the parsed request so callers (e.g. body logging) don't have to redo
+ // the URL-decode + base64-decode dance to recover them.
+ let json_bytes = Bytes::from(json_str.into_bytes());
+ let request = serde_json::from_slice(&json_bytes).map_err(|e| {
tracing::warn!("failed to parse JSON: {}", e);
FlagError::RequestDecodingError("invalid JSON structure".into())
- })
+ })?;
+ Ok((request, json_bytes))
}
#[cfg(test)]
@@ -320,9 +345,12 @@ mod tests {
let result = decode_request(&headers, gzipped_body, &query);
assert!(result.is_ok());
- let request = result.unwrap();
+ let (request, decoded) = result.unwrap();
assert_eq!(request.distinct_id, Some("test".to_string()));
assert_eq!(request.token, Some("test_token".to_string()));
+ // Decoded body is the post-gzip JSON, not the gzipped bytes.
+ assert!(decoded.starts_with(b"{"));
+ assert!(decoded.windows(11).any(|w| w == b"distinct_id"));
}
#[test]
@@ -338,7 +366,7 @@ mod tests {
let result = decode_request(&headers, gzipped_body, &query);
assert!(result.is_ok());
- let request = result.unwrap();
+ let (request, _decoded) = result.unwrap();
assert_eq!(request.distinct_id, Some("test".to_string()));
assert_eq!(request.token, Some("test_token".to_string()));
}
@@ -411,7 +439,7 @@ mod tests {
let result = decode_request(&headers, gzipped_body, &query);
assert!(result.is_ok());
- let request = result.unwrap();
+ let (request, _decoded) = result.unwrap();
assert_eq!(request.distinct_id, Some("test".to_string()));
assert_eq!(request.token, Some("test_token".to_string()));
}
@@ -424,12 +452,14 @@ mod tests {
let headers = HeaderMap::new();
let query = FlagsQueryParams::default();
- let result = decode_request(&headers, body, &query);
+ let result = decode_request(&headers, body.clone(), &query);
assert!(result.is_ok());
- let request = result.unwrap();
+ let (request, decoded) = result.unwrap();
assert_eq!(request.distinct_id, Some("test".to_string()));
assert_eq!(request.token, Some("test_token".to_string()));
+ // Plain-JSON path returns the input bytes unchanged.
+ assert_eq!(decoded, body);
}
#[test]
@@ -449,9 +479,12 @@ mod tests {
let result = decode_request(&headers, body, &query);
assert!(result.is_ok());
- let request = result.unwrap();
+ let (request, decoded) = result.unwrap();
assert_eq!(request.distinct_id, Some("user".to_string()));
assert_eq!(request.token, Some("test".to_string()));
+ // Base64 fallback returns the *decoded* JSON bytes, not the base64 string.
+ assert!(decoded.starts_with(b"{"));
+ assert!(!decoded.windows(7).any(|w| w == b"eyJ0b2t"));
}
#[test]
diff --git a/rust/feature-flags/src/handler/mod.rs b/rust/feature-flags/src/handler/mod.rs
index 085a278982e3..25fcbcaaa30a 100644
--- a/rust/feature-flags/src/handler/mod.rs
+++ b/rust/feature-flags/src/handler/mod.rs
@@ -1,5 +1,6 @@
pub mod authentication;
pub mod billing;
+pub mod body_logger;
pub mod canonical_log;
pub mod config_response_builder;
pub mod cookieless;
diff --git a/rust/feature-flags/src/handler/tests.rs b/rust/feature-flags/src/handler/tests.rs
index a9d1a3b9a154..92faef106fcf 100644
--- a/rust/feature-flags/src/handler/tests.rs
+++ b/rust/feature-flags/src/handler/tests.rs
@@ -349,7 +349,7 @@ fn test_decode_request() {
let result = decoding::decode_request(&headers, body, &meta);
assert!(result.is_ok());
- let request = result.unwrap();
+ let (request, _decoded) = result.unwrap();
assert_eq!(request.token, Some("test_token".to_string()));
assert_eq!(request.distinct_id, Some("user123".to_string()));
}
@@ -451,7 +451,7 @@ fn test_decode_request_form_urlencoded() {
let result = decoding::decode_request(&headers, body, &meta);
assert!(result.is_ok());
- let request = result.unwrap();
+ let (request, _decoded) = result.unwrap();
assert_eq!(request.token, Some("test_token".to_string()));
assert_eq!(request.distinct_id, Some("user123".to_string()));
}
@@ -479,7 +479,7 @@ fn test_decode_form_data_kludges() {
if should_succeed {
assert!(result.is_ok(), "Failed to decode: {input}");
- let request = result.unwrap();
+ let (request, _decoded) = result.unwrap();
if input.contains("bio") {
// Verify we can handle newlines in the decoded JSON
let person_properties = request.person_properties.unwrap();
@@ -512,7 +512,7 @@ fn test_handle_unencoded_form_data_with_emojis() {
let result = decoding::decode_form_data(body, None, None);
assert!(result.is_ok(), "Failed to decode emoji content");
- let request = result.unwrap();
+ let (request, _decoded) = result.unwrap();
assert_eq!(request.token, Some("test_token".to_string()));
assert_eq!(request.distinct_id, Some("test_id".to_string()));
@@ -539,7 +539,7 @@ fn test_decode_base64_encoded_form_data_with_emojis() {
let result = decoding::decode_form_data(body, Some(Compression::Base64), None);
assert!(result.is_ok(), "Failed to decode emoji content");
- let request = result.unwrap();
+ let (request, _decoded) = result.unwrap();
assert_eq!(request.token, Some("test_token".to_string()));
assert_eq!(request.distinct_id, Some("test_id".to_string()));
@@ -606,7 +606,7 @@ fn test_decode_form_data_real_world_payload() {
let result = decoding::decode_form_data(body, Some(Compression::Base64), None);
assert!(result.is_ok(), "Failed to decode real world payload");
- let request = result.unwrap();
+ let (request, _decoded) = result.unwrap();
// Verify key fields from the decoded request
assert_eq!(request.token, Some("sTMFPsFhdP1Ssg".to_string()));
@@ -1089,7 +1089,7 @@ fn test_decode_request_content_types() {
headers.insert(CONTENT_TYPE, "application/json".parse().unwrap());
let result = decoding::decode_request(&headers, body.clone(), &meta);
assert!(result.is_ok());
- let request = result.unwrap();
+ let (request, _decoded) = result.unwrap();
assert_eq!(request.token, Some("test_token".to_string()));
assert_eq!(request.distinct_id, Some("user123".to_string()));
@@ -1098,7 +1098,7 @@ fn test_decode_request_content_types() {
headers.insert(CONTENT_TYPE, "text/plain".parse().unwrap());
let result = decoding::decode_request(&headers, body.clone(), &meta);
assert!(result.is_ok());
- let request = result.unwrap();
+ let (request, _decoded) = result.unwrap();
assert_eq!(request.token, Some("test_token".to_string()));
assert_eq!(request.distinct_id, Some("user123".to_string()));
@@ -1110,7 +1110,7 @@ fn test_decode_request_content_types() {
);
let result = decoding::decode_request(&headers, body.clone(), &meta);
assert!(result.is_ok());
- let request = result.unwrap();
+ let (request, _decoded) = result.unwrap();
assert_eq!(request.token, Some("test_token".to_string()));
assert_eq!(request.distinct_id, Some("user123".to_string()));
@@ -1118,7 +1118,7 @@ fn test_decode_request_content_types() {
let headers = HeaderMap::new();
let result = decoding::decode_request(&headers, body.clone(), &meta);
assert!(result.is_ok());
- let request = result.unwrap();
+ let (request, _decoded) = result.unwrap();
assert_eq!(request.token, Some("test_token".to_string()));
assert_eq!(request.distinct_id, Some("user123".to_string()));
diff --git a/rust/feature-flags/src/handler/types.rs b/rust/feature-flags/src/handler/types.rs
index efb129b9812b..9cfaf4ceaac9 100644
--- a/rust/feature-flags/src/handler/types.rs
+++ b/rust/feature-flags/src/handler/types.rs
@@ -2,7 +2,12 @@ use axum::{extract::State, http::HeaderMap};
use bytes::Bytes;
use serde::Serialize;
use serde_json::Value;
-use std::{collections::HashMap, fmt, net::IpAddr, sync::Arc};
+use std::{
+ collections::HashMap,
+ fmt,
+ net::IpAddr,
+ sync::{Arc, OnceLock},
+};
use uuid::Uuid;
use crate::{
@@ -32,6 +37,16 @@ pub struct RequestContext {
/// Request ID
pub request_id: Uuid,
+
+ /// Side channel for body logging: when at least one team is opted into
+ /// `BodyLogger`, the endpoint installs an `Arc<OnceLock<Bytes>>` here and
+ /// keeps a clone. The decode step in `parse_and_authenticate` fills it
+ /// with the decoded body (post gzip + post base64). After the handler
+ /// completes, the endpoint reads from its clone and hands the bytes to
+ /// `BodyLogger::log_response`. This avoids decoding the body twice and
+ /// also ensures base64-wrapped bodies are logged as the JSON they
+ /// actually parsed as, not as the base64 string.
+ pub decoded_body_for_logging: Option<Arc<OnceLock<Bytes>>>,
}
/// Represents the various property overrides that can be passed around
diff --git a/rust/feature-flags/src/main.rs b/rust/feature-flags/src/main.rs
index 8ac378fc0810..49c02cd623ba 100644
--- a/rust/feature-flags/src/main.rs
+++ b/rust/feature-flags/src/main.rs
@@ -14,6 +14,7 @@ use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::{EnvFilter, Layer};
use feature_flags::config::{Config, ThreadCounts};
+use feature_flags::handler::body_logger::BODY_LOG_TARGET;
use feature_flags::rayon_dispatcher::RayonDispatcher;
use feature_flags::server::{register_components, serve};
@@ -98,6 +99,22 @@ async fn async_main(mut config: Config, rayon_dispatcher: RayonDispatcher) {
};
let otel_layer = if let Some(ref otel_url) = config.otel_url {
+ // Build the OTEL filter explicitly: keep the configured level for
+ // every other target, but drop the body-log target. Body logs go to
+ // stdout (and from there to Loki on a short retention) by design;
+ // routing them through OTEL too would re-sink PII (`distinct_id`,
+ // `person_properties`, `ip_address`) into a tier the body-log
+ // retention budget was not sized for. The directive is parsed at
+ // runtime from `BODY_LOG_TARGET` so the constant stays the single
+ // source of truth.
+ let otel_filter = EnvFilter::builder()
+ .with_default_directive(LevelFilter::from_level(config.otel_log_level).into())
+ .parse_lossy("")
+ .add_directive(
+ format!("{BODY_LOG_TARGET}=off")
+ .parse()
+ .expect("BODY_LOG_TARGET must form a valid tracing directive"),
+ );
Some(
OpenTelemetryLayer::new(init_tracer(
otel_url,
@@ -105,7 +122,7 @@ async fn async_main(mut config: Config, rayon_dispatcher: RayonDispatcher) {
&config.otel_service_name,
config.otel_export_timeout_secs,
))
- .with_filter(LevelFilter::from_level(config.otel_log_level)),
+ .with_filter(otel_filter),
)
} else {
None
diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rs
index b790eb655d17..67b0629f9a16 100644
--- a/rust/feature-flags/src/metrics/consts.rs
+++ b/rust/feature-flags/src/metrics/consts.rs
@@ -70,6 +70,12 @@ pub const FLAG_RATE_LIMIT_CHECK_TIME_MS: &str = "flags_rate_limit_check_ms";
// raw body). Pathological large bodies are the suspected outlier driver.
pub const FLAG_TOKEN_EXTRACT_TIME_MS: &str = "flags_token_extract_ms";
+// Counter of FLAGS_LOG_BODIES_TEAMS refresh attempts. Labeled by
+// `result="success"|"failure"`. Emit absence-of-success alerts on this
+// (e.g., `rate(flags_body_log_refresh_total{result="success"}[10m]) == 0`)
+// to detect a stuck cache while DB or parse errors keep firing.
+pub const FLAG_BODY_LOG_REFRESH_TOTAL: &str = "flags_body_log_refresh_total";
+
// Permit-acquisition wait time on the tower `ConcurrencyLimitLayer`.
// Populated by Phase F; emitted only when populated. No `team_id` label
// because permit wait is a property of pod-level load, not of any one team.
diff --git a/rust/feature-flags/src/router.rs b/rust/feature-flags/src/router.rs
index 527716ed9648..4b35e5d2ab39 100644
--- a/rust/feature-flags/src/router.rs
+++ b/rust/feature-flags/src/router.rs
@@ -46,6 +46,7 @@ use crate::{
flag_definitions_cache::FlagDefinitionsCache,
flag_group_type_mapping::GroupTypeCacheManager,
},
+ handler::body_logger::BodyLogger,
metrics::{
buckets::bucket_overrides,
consts::{
@@ -107,6 +108,9 @@ pub struct State {
/// Shadow-keyspace billing aggregator. See `crate::billing` for the
/// dual-write contract.
pub billing_aggregator: Option<Arc<BillingAggregator>>,
+ /// Per-team request/response body logging for `/flags`. Refreshed
+ /// every ~60s from `posthog_instancesetting`.
+ pub body_logger: Arc<BodyLogger>,
}
#[allow(clippy::too_many_arguments)]
@@ -200,6 +204,16 @@ pub fn router(
// (sub-ms) build cost on its hot path.
bot_detection::warm_caches();
+ let body_logger = Arc::new(BodyLogger::new(
+ config.flags_log_bodies_teams.clone(),
+ config.flags_log_bodies_request_max_bytes,
+ ));
+
+ // 1 query per pod per interval regardless of /flags RPS.
+ body_logger
+ .clone()
+ .spawn_refresh_task(database_pools.non_persons_reader.clone());
+
let state = State {
redis_client,
dedicated_redis_client,
@@ -225,6 +239,7 @@ pub fn router(
cohort_membership_provider,
auth_token_cache,
billing_aggregator,
+ body_logger,
};
// Very permissive CORS policy, as old SDK versions
diff --git a/rust/feature-flags/tests/test_body_logger.rs b/rust/feature-flags/tests/test_body_logger.rs
new file mode 100644
index 000000000000..9618583ec367
--- /dev/null
+++ b/rust/feature-flags/tests/test_body_logger.rs
@@ -0,0 +1,113 @@
+//! End-to-end tests for the per-team /flags body-logger config refresh path.
+//!
+//! Verifies that a row written to `posthog_instancesetting` under
+//! `constance:posthog:FLAGS_LOG_BODIES_TEAMS` propagates into the Rust
+//! service's in-memory config when `BodyLogger::do_refresh` runs.
+//!
+//! All scenarios share one combined test so they don't race on the same
+//! `posthog_instancesetting` row when cargo runs integration tests in parallel.
+
+use feature_flags::config::{BodyLogTeams, Config};
+use feature_flags::handler::body_logger::BodyLogger;
+use feature_flags::utils::test_utils::TestContext;
+use sqlx::postgres::PgPoolOptions;
+
+fn pg_pool_from_config(config: &Config) -> sqlx::PgPool {
+ PgPoolOptions::new()
+ .max_connections(2)
+ .connect_lazy(&config.read_database_url)
+ .expect("failed to create test PgPool")
+}
+
+#[tokio::test]
+async fn test_db_body_logger_refresh() {
+ let context = TestContext::new(None).await;
+ context
+ .delete_instance_setting("FLAGS_LOG_BODIES_TEAMS")
+ .await
+ .unwrap();
+
+ let pool = pg_pool_from_config(&Config::default_test_config());
+
+ // --- Scenario 1: missing row preserves env-var default ---
+ {
+ let mut initial = std::collections::HashMap::new();
+ initial.insert(42, vec!["env-default".into()]);
+ let logger = BodyLogger::new(BodyLogTeams(initial), 65_536);
+
+ logger.do_refresh(&pool).await;
+
+ let patterns = logger
+ .for_team(42)
+ .expect("missing DB row should preserve env-var default");
+ assert!(patterns.matches("env-default"));
+ assert!(!patterns.matches("other-flag"));
+ }
+
+ // --- Scenario 2: wildcard pattern yields log-all ---
+ {
+ let logger = BodyLogger::new(BodyLogTeams::default(), 65_536);
+ assert!(logger.for_team(123).is_none(), "scenario 2: starts empty");
+
+ context
+ .set_instance_setting("FLAGS_LOG_BODIES_TEAMS", r#"{"123": ["*"]}"#)
+ .await
+ .unwrap();
+
+ logger.do_refresh(&pool).await;
+
+ let patterns = logger
+ .for_team(123)
+ .expect("scenario 2: team 123 should be enabled after refresh");
+ assert!(
+ patterns.matches("anything"),
+ "scenario 2: wildcard matches any flag key"
+ );
+ assert!(
+ logger.for_team(456).is_none(),
+ "scenario 2: team 456 stays unlisted"
+ );
+ }
+
+ // --- Scenario 3: non-empty patterns filter by flag key ---
+ {
+ context
+ .set_instance_setting(
+ "FLAGS_LOG_BODIES_TEAMS",
+ r#"{"789": ["my-feature", "checkout-*"]}"#,
+ )
+ .await
+ .unwrap();
+
+ let logger = BodyLogger::new(BodyLogTeams::default(), 65_536);
+ logger.do_refresh(&pool).await;
+
+ let patterns = logger
+ .for_team(789)
+ .expect("scenario 3: team 789 should be enabled after refresh");
+ assert!(patterns.matches("my-feature"));
+ assert!(patterns.matches("checkout-foo"));
+ assert!(!patterns.matches("other-flag"));
+ }
+
+ // --- Scenario 4: Django string-encoded value also parses ---
+ {
+ context
+ .set_instance_setting("FLAGS_LOG_BODIES_TEAMS", r#""{\"555\": [\"*\"]}""#)
+ .await
+ .unwrap();
+
+ let logger = BodyLogger::new(BodyLogTeams::default(), 65_536);
+ logger.do_refresh(&pool).await;
+
+ let patterns = logger
+ .for_team(555)
+ .expect("scenario 4: team 555 should be enabled after refresh");
+ assert!(patterns.matches("anything"), "scenario 4: wildcard matches");
+ }
+
+ context
+ .delete_instance_setting("FLAGS_LOG_BODIES_TEAMS")
+ .await
+ .unwrap();
+}