: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(flags): add etag support for remote config endpoint (#71611)
Gustavo H. Strassburger5229391155ea
diff --git a/rust/feature-flags/src/api/flag_definitions.rs b/rust/feature-flags/src/api/flag_definitions.rsindex 4c7e81ba9ead..8708afd72c5a 100644--- a/rust/feature-flags/src/api/flag_definitions.rs+++ b/rust/feature-flags/src/api/flag_definitions.rs@@ -238,12 +238,12 @@ pub async fn flags_definitions())}-fn format_weak_etag(raw: &str) -> String {+pub(crate) fn format_weak_etag(raw: &str) -> String {format!("W/\"{}\"", raw)}/// Build a 304 Not Modified response with ETag and Cache-Control headers.-fn not_modified_response(etag: &str) -> Response {+pub(crate) fn not_modified_response(etag: &str) -> Response {(StatusCode::NOT_MODIFIED,[@@ -275,7 +275,7 @@ fn ok_response_with_etag(data: Value, etag: Option<&str>) -> Response {////// Handles both strong ETags (`"abc123"`) and weak ETags (`W/"abc123"`) per RFC 7232./// Returns `None` if the header is absent or empty.-fn extract_etag_from_header(header: Option<&axum::http::HeaderValue>) -> Option<String> {+pub(crate) fn extract_etag_from_header(header: Option<&axum::http::HeaderValue>) -> Option<String> {let value = header?.to_str().ok()?;let trimmed = value.trim();if trimmed.is_empty() {diff --git a/rust/feature-flags/src/api/remote_config.rs b/rust/feature-flags/src/api/remote_config.rsindex b92cd0fb278c..36c14e4a5e6b 100644--- a/rust/feature-flags/src/api/remote_config.rs+++ b/rust/feature-flags/src/api/remote_config.rs@@ -15,12 +15,26 @@//! feature flag access, even though this endpoint can return decrypted payloads. OAuth//! access tokens are also not accepted — any non-`phs_` bearer goes through personal-key//! validation and gets 401; only `phs_` and `phx_` credentials work.+//!+//! Supports `If-None-Match` conditional requests like `/flags/definitions`, but with a+//! content-derived ETag: no cache backs this endpoint (the payload is read from Postgres+//! per request), so the etag is a hash of the exact response body computed after payload+//! resolution. That makes it caller-dependent by construction — a secret-key caller's+//! redacted body and a personal-key caller's decrypted body hash to different etags, so a+//! 304 never validates one credential class's cached body against the other's. A match+//! saves the body transfer, not the DB read.+//!+//! Because the body varies by `Authorization` at the same URL, responses carry+//! `Cache-Control: private, no-cache` (revalidate on every reuse, not just when stale)+//! and `Vary: Authorization` — otherwise a private cache primed by a personal-key+//! request could replay the decrypted body to a secret-key caller without ever hitting+//! the etag check.use crate::{api::{auth, errors::FlagError, flag_definitions},database::get_connection_with_metrics,flags::flag_payload_decryptor::REDACTED_PAYLOAD_VALUE,- metrics::consts::REMOTE_CONFIG_AUTH_COUNTER,+ metrics::consts::{REMOTE_CONFIG_AUTH_COUNTER, REMOTE_CONFIG_ETAG_COUNTER},router::State as AppState,team::team_models::Team,};@@ -28,13 +42,19 @@ use axum::{debug_handler,extract::{Path, Query, State},http::{HeaderMap, Method, StatusCode},- response::{IntoResponse, Json, Response},+ response::{IntoResponse, Response},};use common_metrics::inc;use serde::Deserialize;use serde_json::Value;use tracing::warn;+/// The body varies by `Authorization` at the same URL (decrypted vs redacted), so caches+/// must revalidate on every reuse (`no-cache`, stronger than the sibling endpoint's+/// `must-revalidate`) and key entries by credential (`Vary: Authorization`).+const CACHE_CONTROL: &str = "private, no-cache";+const VARY: &str = "Authorization";+/// Query params. SDKs pass `?token=phc_...` (the project key) and call this with `@current`/// as the URL segment; the token resolves the project, matching Django. `api_key` is Django's/// accepted alias for `token` (see `get_token`).@@ -192,10 +212,76 @@ pub async fn remote_config(// Django applies `or None` to the final value and renders None as an empty body, not// the JSON literal `null`. Apply the falsy check after decryption so an empty decrypted// string nulls out too.- match payload.filter(|v| !is_falsy(v)) {- Some(v) => Ok(Json(v).into_response()),- None => Ok(empty_ok_no_content_type()),+ let payload = payload.filter(|v| !is_falsy(v));++ // `Value::to_string` produces the same compact JSON `Json(v)` would serialize, so the+ // etag hashes the exact bytes the client receives (empty payloads hash the empty body).+ let body = payload.as_ref().map(Value::to_string).unwrap_or_default();+ let current_etag = compute_etag(&body);++ let client_etag = flag_definitions::extract_etag_from_header(headers.get("if-none-match"));+ if client_etag.as_deref() == Some(current_etag.as_str()) {+ inc(+ REMOTE_CONFIG_ETAG_COUNTER,+ &[("result".to_string(), "hit".to_string())],+ 1,+ );+ return Ok(not_modified(¤t_etag));}+ inc(+ REMOTE_CONFIG_ETAG_COUNTER,+ &[(+ "result".to_string(),+ if client_etag.is_some() {+ "miss"+ } else {+ "none"+ }+ .to_string(),+ )],+ 1,+ );++ match payload {+ Some(_) => Ok(json_ok_with_etag(body, ¤t_etag)),+ None => Ok(empty_ok_no_content_type(¤t_etag)),+ }+}++/// Content-derived ETag over the exact response body, using the same HyperCache helper+/// that produces `/flags/definitions` etags, so SDKs see one etag format across both+/// endpoints.+fn compute_etag(body: &str) -> String {+ common_hypercache::writer::compute_etag(body)+}++/// The ETag/Cache-Control/Vary trio every response carries. Shared so the credential+/// isolation (`no-cache` + `Vary: Authorization`) can't silently drop off one response+/// path while surviving on the others.+fn revalidation_headers(etag: &str) -> [(&'static str, String); 3] {+ [+ ("etag", flag_definitions::format_weak_etag(etag)),+ ("cache-control", CACHE_CONTROL.to_string()),+ ("vary", VARY.to_string()),+ ]+}++/// 200 with a pre-serialized JSON body plus the revalidation headers.+fn json_ok_with_etag(body: String, etag: &str) -> Response {+ (+ StatusCode::OK,+ [("content-type", "application/json")],+ revalidation_headers(etag),+ body,+ )+ .into_response()+}++/// 304 carrying the same revalidation headers as the 200s — not the sibling endpoint's+/// `not_modified_response`, whose `must-revalidate` would weaken the stored entry's+/// policy when a cache updates its headers from the 304.+fn not_modified(etag: &str) -> Response {+ (StatusCode::NOT_MODIFIED, revalidation_headers(etag)).into_response()}/// Decrypts the stored ciphertext on the personal-key path. Returns `None` when there is no@@ -223,9 +309,10 @@ fn resolve_decrypted_payload(}/// 200 with an empty body and no Content-Type (NOT a JSON `null`), matching DRF's `Response(None)`:-/// the renderer emits no bytes and DRF then deletes the Content-Type header.-fn empty_ok_no_content_type() -> Response {- StatusCode::OK.into_response()+/// the renderer emits no bytes and DRF then deletes the Content-Type header. Still carries the+/// revalidation headers so a client polling a not-yet-set payload can 304 too.+fn empty_ok_no_content_type(etag: &str) -> Response {+ (StatusCode::OK, revalidation_headers(etag)).into_response()}/// Mirrors Python truthiness for `payloads.get("true") or None`. In practice the payloaddiff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex 7c4f58182558..70f5b50eba39 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -332,6 +332,13 @@ pub const REMOTE_CONFIG_REQUESTS_COUNTER: &str = "flags_remote_config_requests_t// split decides redact-vs-decrypt, so the mix is worth watching during the phase 2/3 cutover.pub const REMOTE_CONFIG_AUTH_COUNTER: &str = "flags_remote_config_auth_total";+// Remote config ETag metrics+// Labels: result (hit = 304, miss = 200 with stale etag, none = request sent no+// If-None-Match; the 200 still carries an etag since it is computed per request). Unlike flag+// definitions there is no redis_error case: no cache backs this endpoint, so the etag is+// content-derived per request and can always be computed.+pub const REMOTE_CONFIG_ETAG_COUNTER: &str = "flags_remote_config_etag_total";+// Flag definitions cache metrics// Labels: source (redis, s3, fallback)pub const FLAG_DEFINITIONS_CACHE_HIT_COUNTER: &str = "flags_flag_definitions_cache_hit_total";diff --git a/rust/feature-flags/tests/test_remote_config.rs b/rust/feature-flags/tests/test_remote_config.rsindex 6b8e60b2fb3c..80dd5f0384d5 100644--- a/rust/feature-flags/tests/test_remote_config.rs+++ b/rust/feature-flags/tests/test_remote_config.rs@@ -839,8 +839,231 @@ async fn test_remote_config_empty_payload_returns_empty_body() {.unwrap();assert_eq!(response.status(), 200);+ // Empty responses still carry an etag so a client polling a not-yet-set payload can 304.+ let etag = response+ .headers()+ .get("etag")+ .expect("empty response should carry an etag")+ .to_str()+ .unwrap()+ .to_string();+ // The credential-isolation headers must hold on the empty-body path too.+ assert_eq!(+ response+ .headers()+ .get("cache-control")+ .unwrap()+ .to_str()+ .unwrap(),+ "private, no-cache"+ );+ assert_eq!(+ response.headers().get("vary").unwrap().to_str().unwrap(),+ "Authorization"+ );+ // No Content-Type, matching DRF's `Response(None)`.+ assert!(response.headers().get("content-type").is_none());// Empty body, not the JSON literal "null".assert_eq!(response.text().await.unwrap(), "");++ let revalidated = reqwest::Client::new()+ .get(url(&server.addr, team.id, "rc-empty"))+ .header("Authorization", format!("Bearer {secret_token}"))+ .header("If-None-Match", &etag)+ .send()+ .await+ .unwrap();+ assert_eq!(revalidated.status(), 304);+}++#[tokio::test]+async fn test_remote_config_etag_roundtrip() {+ let config = Config::default_test_config();+ let context = TestContext::new(Some(&config)).await;+ let (team, secret_token, _) = context+ .create_team_with_secret_token(None, None, None)+ .await+ .unwrap();+ insert_rc_flag(&context, team.id, "rc-etag", "etag-payload", true, false).await;++ let server = common::ServerHandle::for_config(config.clone()).await;+ let client = reqwest::Client::new();++ // First request: 200 with a weak etag and revalidation cache headers.+ let response = client+ .get(url(&server.addr, team.id, "rc-etag"))+ .header("Authorization", format!("Bearer {secret_token}"))+ .send()+ .await+ .unwrap();+ assert_eq!(response.status(), 200);+ let etag = response+ .headers()+ .get("etag")+ .expect("200 response should carry an etag")+ .to_str()+ .unwrap()+ .to_string();+ assert!(etag.starts_with("W/\""), "expected weak etag, got {etag}");+ // The body is written as a pre-serialized String, so the JSON content type is an+ // explicit override of axum's text/plain default.+ assert_eq!(+ response+ .headers()+ .get("content-type")+ .unwrap()+ .to_str()+ .unwrap(),+ "application/json"+ );+ assert_eq!(+ response+ .headers()+ .get("cache-control")+ .unwrap()+ .to_str()+ .unwrap(),+ "private, no-cache"+ );+ assert_eq!(+ response.headers().get("vary").unwrap().to_str().unwrap(),+ "Authorization"+ );+ assert_eq!(+ response.json::<Value>().await.unwrap(),+ Value::String("etag-payload".to_string())+ );++ // Matching If-None-Match: 304 with no body, echoing the etag.+ let revalidated = client+ .get(url(&server.addr, team.id, "rc-etag"))+ .header("Authorization", format!("Bearer {secret_token}"))+ .header("If-None-Match", &etag)+ .send()+ .await+ .unwrap();+ assert_eq!(revalidated.status(), 304);+ assert_eq!(+ revalidated.headers().get("etag").unwrap().to_str().unwrap(),+ etag+ );+ assert_eq!(+ revalidated+ .headers()+ .get("cache-control")+ .unwrap()+ .to_str()+ .unwrap(),+ "private, no-cache"+ );+ assert_eq!(+ revalidated.headers().get("vary").unwrap().to_str().unwrap(),+ "Authorization"+ );+ assert_eq!(revalidated.text().await.unwrap(), "");++ // Stale If-None-Match: full 200 with the payload and the current etag.+ let stale = client+ .get(url(&server.addr, team.id, "rc-etag"))+ .header("Authorization", format!("Bearer {secret_token}"))+ .header("If-None-Match", "W/\"0000000000000000\"")+ .send()+ .await+ .unwrap();+ assert_eq!(stale.status(), 200);+ assert_eq!(stale.headers().get("etag").unwrap().to_str().unwrap(), etag);+ assert_eq!(+ stale.json::<Value>().await.unwrap(),+ Value::String("etag-payload".to_string())+ );+}++#[tokio::test]+async fn test_remote_config_encrypted_etag_differs_by_credential() {+ // The etag is derived from the resolved body, so a secret-key caller's redacted response+ // and a personal-key caller's decrypted response must carry different etags — an etag+ // computed from the stored row (or shared across credential classes) would let a client+ // that cached the redacted body 304-validate it where plaintext should be served.+ let mut config = Config::default_test_config();+ config.flags_secret_keys = K1.to_string();+ let context = TestContext::new(Some(&config)).await;+ let (team, secret_token, _) = context+ .create_team_with_secret_token(None, None, None)+ .await+ .unwrap();++ let org_id = context.get_organization_id_for_team(&team).await.unwrap();+ let user_email = TestContext::generate_test_email("rc_etag_pak");+ let user_id = context+ .create_user(&user_email, &org_id, team.id)+ .await+ .unwrap();+ context+ .add_user_to_organization(user_id, &org_id, 15)+ .await+ .unwrap();+ let (_pak_id, api_key) = context+ .create_personal_api_key(+ user_id,+ "RC ETag PAK",+ vec!["feature_flag:read"],+ None,+ None,+ )+ .await+ .unwrap();++ insert_rc_flag(&context, team.id, "rc-enc-etag", TOK_PRIMARY, true, true).await;++ let server = common::ServerHandle::for_config(config.clone()).await;+ let client = reqwest::Client::new();++ let redacted_response = client+ .get(url(&server.addr, team.id, "rc-enc-etag"))+ .header("Authorization", format!("Bearer {secret_token}"))+ .send()+ .await+ .unwrap();+ assert_eq!(redacted_response.status(), 200);+ let redacted_etag = redacted_response+ .headers()+ .get("etag")+ .unwrap()+ .to_str()+ .unwrap()+ .to_string();++ // The redacted-body etag must not 304 a decrypting caller: they get plaintext and its etag.+ let decrypted_response = client+ .get(url(&server.addr, team.id, "rc-enc-etag"))+ .header("Authorization", format!("Bearer {api_key}"))+ .header("If-None-Match", &redacted_etag)+ .send()+ .await+ .unwrap();+ assert_eq!(decrypted_response.status(), 200);+ let decrypted_etag = decrypted_response+ .headers()+ .get("etag")+ .unwrap()+ .to_str()+ .unwrap()+ .to_string();+ assert_ne!(decrypted_etag, redacted_etag);+ assert_eq!(+ decrypted_response.json::<Value>().await.unwrap(),+ Value::String(PLAINTEXT.to_string())+ );++ // A decrypting caller revalidating its own etag gets a 304 (decryption is deterministic).+ let revalidated = client+ .get(url(&server.addr, team.id, "rc-enc-etag"))+ .header("Authorization", format!("Bearer {api_key}"))+ .header("If-None-Match", &decrypted_etag)+ .send()+ .await+ .unwrap();+ assert_eq!(revalidated.status(), 304);}#[tokio::test]