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.

fix(flags): return JSON on remote_config decrypt failure instead of a raw 500 (#75002)

Gustavo H. Strassburger0c4ca0a7b765
diff --git a/products/feature_flags/backend/api/feature_flag.py b/products/feature_flags/backend/api/feature_flag.py
index eb23bb2dde46..44f233d504cd 100644
--- a/products/feature_flags/backend/api/feature_flag.py
+++ b/products/feature_flags/backend/api/feature_flag.py
@@ -18,6 +18,7 @@ from django.db.models import Count, Prefetch, Q, QuerySet, deletion
import grpc
import requests
import structlog
+from cryptography.fernet import InvalidToken
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiExample, OpenApiParameter, OpenApiResponse, extend_schema_field
from rest_framework import exceptions, request, serializers, status, viewsets
@@ -4375,9 +4376,31 @@ class FeatureFlagViewSet(
# Note: This decryption step is protected by the feature_flag:read scope, so we can assume the
# user has access to the flag. However get_decrypted_flag_payloads_protected will also check the authentication
# method used to make the request as it is used in non-protected endpoints.
- decrypted_flag_payloads = get_decrypted_flag_payloads_protected(
- request, feature_flag.filters.get("payloads", {})
- )
+ try:
+ decrypted_flag_payloads = get_decrypted_flag_payloads_protected(
+ request, feature_flag.filters.get("payloads", {})
+ )
+ except InvalidToken as e:
+ # The stored ciphertext can't be decrypted by any key in FLAGS_SECRET_KEYS (e.g. it
+ # predates a key rotation and was never re-encrypted). Surface a typed JSON error
+ # instead of letting the exception become an unhandled 500 with an HTML body, which
+ # SDKs can't parse as JSON. The body mirrors the drf-exceptions-hog envelope the Rust
+ # feature-flags service returns for this same failure, so the phase-2 shadow-compare
+ # (shadow_compare_remote_config) sees identical bodies on both paths.
+ logger.exception(
+ "Failed to decrypt remote config payload",
+ extra={"team_id": self.team_id, "feature_flag_id": feature_flag.id},
+ )
+ capture_exception(e)
+ return Response(
+ {
+ "type": "server_error",
+ "code": "remote_config_decrypt_failed",
+ "detail": "Failed to decrypt the remote config payload. Please contact support if the problem persists.",
+ "attr": None,
+ },
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
# Count after a successful decryption so a decrypt failure (500) is never counted.
if should_count:
diff --git a/products/feature_flags/backend/api/test/test_feature_flag.py b/products/feature_flags/backend/api/test/test_feature_flag.py
index 9001392cba44..150eddc5345d 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -2365,6 +2365,44 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(shadow.call_args.kwargs["key"], "my-remote-config-flag")
self.assertIn("project_id", shadow.call_args.kwargs)
+ def test_remote_config_returns_typed_error_when_payload_cannot_be_decrypted(self):
+ # A payload that predates a FLAGS_SECRET_KEYS rotation (or is otherwise corrupt) fails to
+ # decrypt with any configured key. Without explicit handling this becomes an unhandled 500
+ # with an HTML body that SDKs can't parse as JSON, so assert it returns a typed JSON error.
+ # Decryption only runs on the personal-API-key path; a secret token gets the redacted
+ # marker and never reaches the decrypt call, so authenticate with a personal API key here.
+ FeatureFlag.objects.create(
+ team=self.team,
+ key="my-remote-config-flag",
+ name="Remote Config Flag",
+ active=True,
+ filters={
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {"true": "not-a-valid-fernet-token"},
+ },
+ is_remote_configuration=True,
+ has_encrypted_payloads=True,
+ )
+ auth_token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(label="X", user=self.user, scopes=["*"], secure_value=hash_key_value(auth_token))
+ self.client.logout()
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/feature_flags/my-remote-config-flag/remote_config",
+ headers={"authorization": f"Bearer {auth_token}"},
+ )
+ self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)
+ # Mirrors the envelope the Rust feature-flags service returns for this failure so the
+ # phase-2 shadow-compare treats both paths as a match.
+ self.assertEqual(
+ response.json(),
+ {
+ "type": "server_error",
+ "code": "remote_config_decrypt_failed",
+ "detail": "Failed to decrypt the remote config payload. Please contact support if the problem persists.",
+ "attr": None,
+ },
+ )
+
# Encrypted remote config payloads are decrypted only for personal API keys; project
# secret keys get the redacted marker. This is the parity oracle for the Rust port,
# which must replicate both.
diff --git a/rust/feature-flags/src/api/errors.rs b/rust/feature-flags/src/api/errors.rs
index cfc3101c0fa3..217a49b04afa 100644
--- a/rust/feature-flags/src/api/errors.rs
+++ b/rust/feature-flags/src/api/errors.rs
@@ -125,6 +125,11 @@ pub enum FlagError {
RayonSemaphoreTimeout(u64),
#[error(transparent)]
CookielessError(#[from] CookielessManagerError),
+ /// A stored remote-config payload could not be decrypted with any configured key (or no
+ /// decryptor is configured at all). Distinct from `Internal` so the response is JSON, not
+ /// plain text -- SDKs calling `remote_config` parse the body as JSON on every status code.
+ #[error("failed to decrypt remote config payload: {0}")]
+ RemoteConfigDecryptFailed(String),
}
impl FlagError {
@@ -175,6 +180,7 @@ impl FlagError {
FlagError::BatchEvaluationPanicked => ("batch_evaluation_panicked", 500),
FlagError::HashKeyOverrideError => ("hash_key_override_error", 500),
FlagError::RayonSemaphoreTimeout(_) => ("rayon_semaphore_timeout", 504),
+ FlagError::RemoteConfigDecryptFailed(_) => ("remote_config_decrypt_failed", 500),
// Data parsing errors (500) - internal errors, not service unavailability
FlagError::DataParsingErrorWithContext(_) => ("flag_data_parsing_error", 500),
@@ -496,6 +502,17 @@ impl IntoResponse for FlagError {
tracing::warn!("Rayon semaphore acquisition timed out after {}ms", ms);
(StatusCode::GATEWAY_TIMEOUT, format!("Evaluation pool busy, timed out after {ms}ms. Please retry."))
}
+ FlagError::RemoteConfigDecryptFailed(_) => {
+ // The failure is already logged with project_id/flag_key context at the source in
+ // resolve_decrypted_payload; don't log it a second time here.
+ let response = AuthenticationErrorResponse {
+ error_type: "server_error".to_string(),
+ code: "remote_config_decrypt_failed".to_string(),
+ detail: "Failed to decrypt the remote config payload. Please contact support if the problem persists.".to_string(),
+ attr: None,
+ };
+ return (StatusCode::INTERNAL_SERVER_ERROR, Json(response)).into_response();
+ }
FlagError::CookielessError(err) => {
match err {
// 400 Bad Request errors - client-side issues
@@ -691,6 +708,30 @@ mod tests {
);
}
+ #[test]
+ fn test_remote_config_decrypt_failed_response_is_json() {
+ // The remote_config response body must be JSON on every status code, because SDKs call
+ // res.json() on it unconditionally, so a plain-text 500 would crash them client-side.
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let err = FlagError::RemoteConfigDecryptFailed("failed to decrypt payload".to_string());
+
+ let response = err.into_response();
+ assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
+ assert_eq!(
+ response
+ .headers()
+ .get("content-type")
+ .and_then(|v| v.to_str().ok()),
+ Some("application/json")
+ );
+
+ let body_bytes = rt
+ .block_on(axum::body::to_bytes(response.into_body(), usize::MAX))
+ .unwrap();
+ let body: serde_json::Value = serde_json::from_slice(&body_bytes).unwrap();
+ assert_eq!(body["code"], "remote_config_decrypt_failed");
+ }
+
#[test]
fn test_custom_database_error_conversion_timeout() {
// Test that CustomDatabaseError::Timeout converts to FlagError::TimeoutError with client_timeout
diff --git a/rust/feature-flags/src/api/remote_config.rs b/rust/feature-flags/src/api/remote_config.rs
index 36c14e4a5e6b..e97042d368d8 100644
--- a/rust/feature-flags/src/api/remote_config.rs
+++ b/rust/feature-flags/src/api/remote_config.rs
@@ -183,7 +183,10 @@ pub async fn remote_config(
// Flag lookup scoped to the project. 404 if missing or not a remote config flag (the query
// filters on `is_remote_configuration`).
- let Some((filters, has_encrypted_payloads)) =
+ // `resolved_key` is the flag's actual `key` column, not the URL segment (which may be a
+ // numeric id when the caller addresses the flag by id), so decrypt-failure logs always carry
+ // the human-readable key.
+ let Some((filters, has_encrypted_payloads, resolved_key)) =
load_remote_config_flag(&state, scope_project_id, &key).await?
else {
return Ok(StatusCode::NOT_FOUND.into_response());
@@ -204,7 +207,7 @@ pub async fn remote_config(
let payload: Option<Value> = if has_encrypted_payloads != Some(true) {
stored.cloned()
} else if should_decrypt {
- resolve_decrypted_payload(&state, stored)?
+ resolve_decrypted_payload(&state, stored, scope_project_id, &resolved_key)?
} else {
stored.map(|_| Value::String(REDACTED_PAYLOAD_VALUE.to_string()))
};
@@ -287,24 +290,37 @@ fn not_modified(etag: &str) -> Response {
/// Decrypts the stored ciphertext on the personal-key path. Returns `None` when there is no
/// stored value or it is not a string (Django 500s on those malformed rows; we render an empty
/// body instead). Errors (500) on a decrypt failure or a missing decryptor.
+///
+/// `project_id`/`flag_key` are logged on failure only for correlation (which flag keeps
+/// failing) -- never the token or any key material, which `FlagPayloadDecryptorError`'s
+/// `Display` already excludes by construction (see `flag_payload_decryptor.rs`).
fn resolve_decrypted_payload(
state: &AppState,
stored: Option<&Value>,
+ project_id: i64,
+ flag_key: &str,
) -> Result<Option<Value>, FlagError> {
let Some(Value::String(token)) = stored else {
return Ok(None);
};
let Some(decryptor) = state.flag_payload_decryptor.as_ref() else {
- return Err(FlagError::Internal(
- "no FLAGS_SECRET_KEYS configured; cannot decrypt remote config payload".to_string(),
+ warn!(
+ project_id,
+ flag_key, "remote_config: no FLAGS_SECRET_KEYS configured; cannot decrypt payload"
+ );
+ return Err(FlagError::RemoteConfigDecryptFailed(
+ "no decryption keys configured".to_string(),
));
};
decryptor
.decrypt(token)
.map(|plaintext| Some(Value::String(plaintext)))
.map_err(|e| {
- warn!("remote_config payload decrypt failed: {e}");
- FlagError::Internal("failed to decrypt remote config payload".to_string())
+ warn!(
+ project_id,
+ flag_key, "remote_config payload decrypt failed: {e}"
+ );
+ FlagError::RemoteConfigDecryptFailed(e.to_string())
})
}
@@ -470,15 +486,17 @@ async fn project_id_for_team(state: &AppState, team_id: i32) -> Result<Option<i6
Ok(row.map(|r| r.0))
}
-/// Loads `(filters, has_encrypted_payloads)` for a remote-config flag matched by numeric id (if
-/// `key` is all digits) or key, scoped to `team.project_id == project_id`. The query filters on
-/// `is_remote_configuration IS TRUE`, so a non-remote-config flag returns `None` and the caller
-/// 404s. Uses its own query — not the flag-list path, which excludes encrypted RC flags.
+/// Loads `(filters, has_encrypted_payloads, key)` for a remote-config flag matched by numeric id
+/// (if `key` is all digits) or key, scoped to `team.project_id == project_id`. The returned `key`
+/// is the flag's canonical key column, which is why it is selected even though the caller may have
+/// addressed the flag by id. The query filters on `is_remote_configuration IS TRUE`, so a
+/// non-remote-config flag returns `None` and the caller 404s. Uses its own query, not the
+/// flag-list path, which excludes encrypted RC flags.
async fn load_remote_config_flag(
state: &AppState,
project_id: i64,
key: &str,
-) -> Result<Option<(Value, Option<bool>)>, FlagError> {
+) -> Result<Option<(Value, Option<bool>, String)>, FlagError> {
let client: common_database::PostgresReader = state.database_pools.non_persons_reader.clone();
let mut conn = get_connection_with_metrics(&client, "non_persons_reader", "remote_config")
.await
@@ -500,8 +518,8 @@ async fn load_remote_config_flag(
};
let result = if let Some(id) = parsed_id {
- sqlx::query_as::<_, (Value, Option<bool>)>(
- "SELECT f.filters, f.has_encrypted_payloads \
+ sqlx::query_as::<_, (Value, Option<bool>, String)>(
+ "SELECT f.filters, f.has_encrypted_payloads, f.key \
FROM posthog_featureflag f JOIN posthog_team t ON f.team_id = t.id \
WHERE t.project_id = $1 AND f.deleted = false AND f.is_remote_configuration IS TRUE \
AND f.id = $2 LIMIT 1",
@@ -511,8 +529,8 @@ async fn load_remote_config_flag(
.fetch_optional(&mut *conn)
.await
} else {
- sqlx::query_as::<_, (Value, Option<bool>)>(
- "SELECT f.filters, f.has_encrypted_payloads \
+ sqlx::query_as::<_, (Value, Option<bool>, String)>(
+ "SELECT f.filters, f.has_encrypted_payloads, f.key \
FROM posthog_featureflag f JOIN posthog_team t ON f.team_id = t.id \
WHERE t.project_id = $1 AND f.deleted = false AND f.is_remote_configuration IS TRUE \
AND f.key = $2 LIMIT 1",
diff --git a/rust/feature-flags/src/flags/flag_payload_decryptor.rs b/rust/feature-flags/src/flags/flag_payload_decryptor.rs
index 21daea6ece9e..6ef38b4ebc29 100644
--- a/rust/feature-flags/src/flags/flag_payload_decryptor.rs
+++ b/rust/feature-flags/src/flags/flag_payload_decryptor.rs
@@ -11,6 +11,7 @@
use base64::{prelude::BASE64_URL_SAFE, Engine};
use fernet::{Fernet, MultiFernet};
+use sha2::{Digest, Sha256};
/// Returned for encrypted payloads when the caller is not allowed to decrypt
/// (i.e. not authenticated with a personal API key). Byte-identical to Django's
@@ -23,12 +24,28 @@ pub enum FlagPayloadDecryptorError {
NoKeys,
#[error("{built} of {configured} configured keys are valid Fernet keys")]
InvalidKeys { built: usize, configured: usize },
- #[error("failed to decrypt payload")]
- Decrypt,
+ /// `key_count` is how many keys were tried (never which ones, or any key material).
+ /// `token_fingerprint` is a truncated hash of the ciphertext, for correlating repeat
+ /// failures on the same stored payload across log lines. It is not a security primitive.
+ #[error("failed to decrypt payload with any of {key_count} configured key(s) (token {token_fingerprint})")]
+ Decrypt {
+ key_count: usize,
+ token_fingerprint: String,
+ },
#[error("decrypted payload is not valid UTF-8")]
Utf8,
}
+/// Short, non-reversible identifier for a ciphertext, safe to log: lets an operator tell
+/// "same broken payload failing repeatedly" from "many different payloads failing" without
+/// exposing the token or any key material. Not a security primitive.
+fn token_fingerprint(token: &str) -> String {
+ let mut hasher = Sha256::new();
+ hasher.update(token.as_bytes());
+ let result = hasher.finalize();
+ hex::encode(&result[..6])
+}
+
/// Derive a Fernet from raw key material, mirroring Django's `_prepare_key`.
///
/// Pads (left, NUL) or truncates to the 32 bytes Fernet requires, then url-safe
@@ -52,6 +69,10 @@ fn flag_fernet(raw: &str) -> Option<Fernet> {
#[derive(Clone)]
pub struct FlagPayloadDecryptor {
multi: MultiFernet,
+ /// Number of keys `multi` was built with. `MultiFernet` doesn't expose this, and it's
+ /// useful on decrypt failure to distinguish "tried 1 key" (no rotation fallback
+ /// configured) from "tried N keys" (payload predates every configured key).
+ key_count: usize,
}
impl FlagPayloadDecryptor {
@@ -100,8 +121,10 @@ impl FlagPayloadDecryptor {
configured: keys.len(),
});
}
+ let key_count = fernets.len();
Ok(Self {
multi: MultiFernet::new(fernets),
+ key_count,
})
}
@@ -110,7 +133,10 @@ impl FlagPayloadDecryptor {
let bytes = self
.multi
.decrypt(token)
- .map_err(|_| FlagPayloadDecryptorError::Decrypt)?;
+ .map_err(|_| FlagPayloadDecryptorError::Decrypt {
+ key_count: self.key_count,
+ token_fingerprint: token_fingerprint(token),
+ })?;
String::from_utf8(bytes).map_err(|_| FlagPayloadDecryptorError::Utf8)
}
}
@@ -173,9 +199,26 @@ mod tests {
#[test]
fn wrong_key_fails_to_decrypt() {
let d = FlagPayloadDecryptor::from_keys(&[K2.to_string()]).unwrap();
- assert!(matches!(
- d.decrypt(TOK_PRIMARY),
- Err(FlagPayloadDecryptorError::Decrypt)
- ));
+ match d.decrypt(TOK_PRIMARY) {
+ Err(FlagPayloadDecryptorError::Decrypt {
+ key_count,
+ token_fingerprint,
+ }) => {
+ assert_eq!(key_count, 1);
+ // 12 hex chars (6 bytes), and never the token or key material itself.
+ assert_eq!(token_fingerprint.len(), 12);
+ assert!(!TOK_PRIMARY.contains(&token_fingerprint));
+ }
+ other => panic!("expected Decrypt error, got {other:?}"),
+ }
+ }
+
+ #[test]
+ fn decrypt_failure_reports_every_configured_key_was_tried() {
+ let d = FlagPayloadDecryptor::from_keys(&[K2.to_string(), SHORT_KEY.to_string()]).unwrap();
+ match d.decrypt(TOK_PRIMARY) {
+ Err(FlagPayloadDecryptorError::Decrypt { key_count, .. }) => assert_eq!(key_count, 2),
+ other => panic!("expected Decrypt error, got {other:?}"),
+ }
}
}
diff --git a/rust/feature-flags/tests/test_remote_config.rs b/rust/feature-flags/tests/test_remote_config.rs
index 80dd5f0384d5..502ae416270a 100644
--- a/rust/feature-flags/tests/test_remote_config.rs
+++ b/rust/feature-flags/tests/test_remote_config.rs
@@ -1418,9 +1418,13 @@ async fn test_remote_config_personal_key_no_decryptor_returns_500() {
.unwrap();
let status = response.status();
- let body = response.text().await.unwrap();
+ let body: Value = response.json().await.unwrap();
assert_eq!(status, 500, "body: {body}");
- assert!(!body.contains("world"), "leaked plaintext: {body}");
+ assert_eq!(body["code"], "remote_config_decrypt_failed");
+ assert!(
+ !body.to_string().contains("world"),
+ "leaked plaintext: {body}"
+ );
}
#[tokio::test]
@@ -1469,7 +1473,12 @@ async fn test_remote_config_personal_key_decrypt_failure_returns_500() {
.await
.unwrap();
- assert_eq!(response.status(), 500);
+ let status = response.status();
+ // The SDK parses every remote_config response body as JSON on any status code, so this
+ // must not regress to a plain-text 500 that fails res.json() client-side.
+ let body: Value = response.json().await.unwrap();
+ assert_eq!(status, 500, "body: {body}");
+ assert_eq!(body["code"], "remote_config_decrypt_failed");
}
#[tokio::test]