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 remote config endpoint to the rust service (#62561)

Patricioe3b0ff72cdc4
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 84315d30d6c3..ecf3b49fde69 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag.py
@@ -47,7 +47,11 @@ from products.dashboards.backend.models.dashboard import Dashboard
from products.early_access_features.backend.models import EarlyAccessFeature
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer, parse_created_by_ids
-from products.feature_flags.backend.encrypted_flag_payloads import REDACTED_PAYLOAD_VALUE, get_decrypted_flag_payload
+from products.feature_flags.backend.encrypted_flag_payloads import (
+ REDACTED_PAYLOAD_VALUE,
+ flag_payload_codec,
+ get_decrypted_flag_payload,
+)
from products.feature_flags.backend.flag_status import FeatureFlagStatus
from products.feature_flags.backend.models.feature_flag import (
FeatureFlag,
@@ -2097,6 +2101,39 @@ class TestFeatureFlag(APIBaseTest, ClickhouseTestMixin):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json(), '{"test": true}')
+ # 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.
+ @parameterized.expand(
+ [
+ ("project_secret_key", False),
+ ("personal_api_key", True),
+ ]
+ )
+ def test_remote_config_encrypted_payload_auth_dependent(self, _name: str, should_decrypt: bool):
+ plaintext = '{"secret": "value"}'
+ token = flag_payload_codec().encrypt(plaintext.encode("utf-8")).decode("utf-8")
+ self._create_encrypted_flag(stored_payload=token)
+
+ if should_decrypt:
+ auth_token = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="X", user=self.user, scopes=["*"], secure_value=hash_key_value(auth_token)
+ )
+ else:
+ self.team.rotate_secret_token_and_save(user=self.user, is_impersonated_session=False)
+ secret_token = self.team.secret_api_token
+ assert secret_token is not None
+ auth_token = secret_token
+
+ self.client.logout()
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/feature_flags/my-encrypted-flag/remote_config",
+ headers={"authorization": f"Bearer {auth_token}"},
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), plaintext if should_decrypt else REDACTED_PAYLOAD_VALUE)
+
@parameterized.expand([("plaintext_payloads", False), ("encrypted_payloads", True)])
def test_remote_config_increments_remote_config_bucket_by_one_per_request(
self, _name: str, has_encrypted_payloads: bool
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 1b448aa31890..36ed801bc97e 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -3505,6 +3505,7 @@ dependencies = [
"dateparser",
"envconfig",
"fancy-regex 0.17.0",
+ "fernet",
"futures",
"governor",
"hex",
diff --git a/rust/feature-flags/Cargo.toml b/rust/feature-flags/Cargo.toml
index 030a115f5722..93ea404c6a19 100644
--- a/rust/feature-flags/Cargo.toml
+++ b/rust/feature-flags/Cargo.toml
@@ -44,6 +44,7 @@ hex = "0.4.3"
regex.workspace = true
fancy-regex.workspace = true
base64.workspace = true
+fernet = { workspace = true }
sqlx = { workspace = true, features = ["rust_decimal"] }
uuid = { workspace = true }
common-cache = { path = "../common/cache" }
diff --git a/rust/feature-flags/src/api/flag_definitions.rs b/rust/feature-flags/src/api/flag_definitions.rs
index 9dacfa479498..d92d0f5d8acd 100644
--- a/rust/feature-flags/src/api/flag_definitions.rs
+++ b/rust/feature-flags/src/api/flag_definitions.rs
@@ -4,10 +4,7 @@ use crate::{
errors::{ClientFacingError, FlagError},
instance_setting::{constance_key, fetch_instance_setting_raw_value},
},
- flags::{
- flag_analytics::is_billable_flag_key, flag_request::FlagRequestType,
- flag_service::FlagService,
- },
+ flags::{flag_analytics::is_billable_flag_key, flag_request::FlagRequestType},
handler::types::Library,
metrics::consts::{
FLAG_DEFINITIONS_AUTH_COUNTER, FLAG_DEFINITIONS_CACHE_HIT_COUNTER,
@@ -30,7 +27,6 @@ use serde::{Deserialize, Serialize};
use serde_json::Value;
use sqlx::PgPool;
use std::collections::HashSet;
-use std::sync::Arc;
use tracing::{info, warn};
const ALLOWLIST_TTL_SECS: u64 = 60;
@@ -333,7 +329,7 @@ async fn get_etag_from_redis(state: &AppState, team_key: &KeyType) -> Option<Str
}
/// Handles non-GET HTTP methods (HEAD, OPTIONS, and unsupported methods)
-fn handle_non_get_method(method: &Method) -> Response {
+pub(crate) fn handle_non_get_method(method: &Method) -> Response {
match *method {
Method::HEAD => (
StatusCode::OK,
@@ -352,22 +348,10 @@ fn handle_non_get_method(method: &Method) -> Response {
}
}
-fn flag_service(state: &AppState) -> FlagService {
- FlagService::new(
- state.redis_client.clone(),
- state.database_pools.non_persons_reader.clone(),
- state.team_hypercache_reader.clone(),
- state.flags_hypercache_reader.clone(),
- state.flag_definitions_cache.clone(),
- state.team_negative_cache.clone(),
- *state.config.skip_pg_team_fallback,
- )
-}
-
/// Fetches a team by its API token, delegating to FlagService for consistent
/// negative caching, metrics, and error handling across all endpoints.
async fn fetch_team_by_token(state: &AppState, token: &str) -> Result<Team, FlagError> {
- flag_service(state).verify_token_and_get_team(token).await
+ state.flag_service().verify_token_and_get_team(token).await
}
/// Resolves a team from the Authorization header when no `?token=` param is provided.
@@ -393,7 +377,7 @@ async fn resolve_team_from_auth(state: &AppState, headers: &HeaderMap) -> Result
// Prefer HyperCache via api_token (new cache entries include it).
// Fall back to PG for old cache entries that predate the field.
- let svc = flag_service(state);
+ let svc = state.flag_service();
return match api_token {
Some(t) => svc.verify_token_and_get_team(&t).await,
None => svc.get_team_by_id(team_id).await,
@@ -514,18 +498,8 @@ async fn authenticate_flag_definitions(
1,
);
- if !*state.config.skip_writes {
- // Use shared Redis, not the dedicated flags cache client —
- // PAK last_used_at tracking is advisory and shouldn't steal
- // capacity from the critical path.
- let redis = state.redis_client.clone();
- let pg_writer: Arc<dyn common_database::Client + Send + Sync> =
- state.database_pools.non_persons_writer.clone();
- // Redis SET NX EX is sub-millisecond, so we check inline to avoid
- // spawning a background task on every request. Only the DB write
- // (triggered when the key is newly set) runs in a spawned task.
- drop(super::pak_usage::record_pak_last_used(redis, pg_writer, pak_id).await);
- }
+ // PAK last_used_at tracking is advisory; shared with remote_config via the State helper.
+ state.record_pak_last_used(pak_id).await;
return Ok(());
}
diff --git a/rust/feature-flags/src/api/flag_definitions_rate_limiter.rs b/rust/feature-flags/src/api/flag_definitions_rate_limiter.rs
index 224eb36e8c50..2ade7c73baff 100644
--- a/rust/feature-flags/src/api/flag_definitions_rate_limiter.rs
+++ b/rust/feature-flags/src/api/flag_definitions_rate_limiter.rs
@@ -73,6 +73,10 @@ where
/// Type alias for flag definitions rate limiting (per-team)
pub(crate) type FlagDefinitionsRateLimiter = KeyedRateLimiter<TeamId>;
+/// Remote config rate limiting is keyed per credential (the personal API key id), mirroring
+/// Django's `RemoteConfigThrottle`, which buckets by hashed bearer token.
+pub(crate) type RemoteConfigRateLimiter = KeyedRateLimiter<String>;
+
impl<K> KeyedRateLimiter<K>
where
K: Hash + Eq + Clone + Display + Send + Sync + 'static,
diff --git a/rust/feature-flags/src/api/mod.rs b/rust/feature-flags/src/api/mod.rs
index 382c79d22fbe..2a6d9ba9a741 100644
--- a/rust/feature-flags/src/api/mod.rs
+++ b/rust/feature-flags/src/api/mod.rs
@@ -10,4 +10,5 @@ pub mod flags_rate_limiter;
pub mod instance_setting;
pub mod pak_usage;
pub mod rate_parser;
+pub mod remote_config;
pub mod types;
diff --git a/rust/feature-flags/src/api/remote_config.rs b/rust/feature-flags/src/api/remote_config.rs
new file mode 100644
index 000000000000..9a0c01e0a14d
--- /dev/null
+++ b/rust/feature-flags/src/api/remote_config.rs
@@ -0,0 +1,433 @@
+//! `GET /api/projects/{project_id}/feature_flags/{key}/remote_config`
+//!
+//! Port of Django's `FeatureFlagViewSet.remote_config`. Returns a remote-config flag's
+//! payload, decrypting encrypted payloads **only** for personal-API-key callers
+//! (project-secret callers get the redacted marker), matching Django exactly.
+//!
+//! Auth/scoping mirrors Django's KLUDGE: `project_id` from the URL is used as a team id
+//! for the credential check, and the flag is looked up by `team.project_id == project_id`.
+//! Session-cookie auth is intentionally not ported (not an SDK path), same as
+//! `flag_definitions`.
+//!
+//! Not ported, consistent with `flag_definitions`/`local_evaluation` (so "matches Django"
+//! does not extend to these): per-flag access control (advanced RBAC) is not enforced.
+//! Personal-key callers are checked for scope and team/org membership only, not role-based
+//! 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.
+
+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,
+ router::State as AppState,
+ team::team_models::Team,
+};
+use axum::{
+ debug_handler,
+ extract::{Path, Query, State},
+ http::{HeaderMap, Method, StatusCode},
+ response::{IntoResponse, Json, Response},
+};
+use common_metrics::inc;
+use serde::Deserialize;
+use serde_json::Value;
+use tracing::warn;
+
+/// 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`).
+#[derive(Deserialize)]
+pub struct RemoteConfigQuery {
+ token: Option<String>,
+ api_key: Option<String>,
+}
+
+enum AuthOutcome {
+ Authorized {
+ should_decrypt: bool,
+ /// The team the request is scoped to, used for the throttle allowlist bypass.
+ team_id: i32,
+ /// Per-credential throttle key. `Some(pak_id)` for personal API keys (which Django
+ /// throttles), `None` for secret keys (which Django does not throttle).
+ rate_limit_key: Option<String>,
+ },
+ /// Credential is valid but not for this project (Django: 403 team mismatch).
+ Forbidden,
+ /// No team with the scoped id (Django: `view.team` raises -> 404 "Project not found").
+ ProjectNotFound,
+}
+
+#[debug_handler]
+pub async fn remote_config(
+ State(state): State<AppState>,
+ Path((project_segment, key)): Path<(String, String)>,
+ Query(params): Query<RemoteConfigQuery>,
+ method: Method,
+ headers: HeaderMap,
+) -> Result<Response, FlagError> {
+ // Non-GET methods are handled before auth, matching the sibling endpoint: HEAD -> 200 and
+ // unsupported methods -> 405 with an Allow header. A CORS *preflight* OPTIONS (one carrying
+ // Access-Control-Request-Method) is answered upstream by the permissive CORS layer with 200; a
+ // bare OPTIONS falls through to here and `handle_non_get_method` returns 204. HEAD diverges from
+ // Django, which maps HEAD to the GET action and runs the full pipeline -- an unauthenticated
+ // HEAD is 401 there, 200 here -- but no SDK sends either method.
+ if method != Method::GET {
+ return Ok(flag_definitions::handle_non_get_method(&method));
+ }
+
+ // Resolve the effective `?token=` (Django's `get_token`: an empty value is absent, and
+ // `?api_key=` is an alias). SDKs call this with `@current` as the URL segment plus a
+ // `?token=phc_...` project key; Django resolves the project from the token first, so the token
+ // wins when present (and `@current` never needs interpreting). Without a token, a numeric
+ // segment is the project id; `@current` and other non-numeric values 404 (Django's `int()`
+ // ValueError), and the `@current`-without-token path that resolves the caller's current team
+ // is not an SDK call and is not ported.
+ let token_param = params
+ .token
+ .as_deref()
+ .filter(|t| !t.is_empty())
+ .or_else(|| params.api_key.as_deref().filter(|t| !t.is_empty()));
+
+ // Resolve only what auth needs here: the team id, and (on the `?token=` path) the resolved
+ // team. The project id is needed solely for the flag lookup, so it is computed after auth and
+ // the throttle — no DB read happens before an unauthenticated caller is rejected.
+ // `verify_token_and_get_team` is cache-backed, so the `?token=` path does no uncached DB work
+ // at this point either.
+ let (scope_team_id, resolved_team): (i32, Option<Team>) = if let Some(token) = token_param {
+ match state.flag_service().verify_token_and_get_team(token).await {
+ // Keep the team so the personal-key auth path and the project lookup below don't
+ // re-query it. Django raises AuthenticationFailed for an invalid `?token=`.
+ Ok(team) => (team.id, Some(team)),
+ Err(_) => return Ok(StatusCode::UNAUTHORIZED.into_response()),
+ }
+ } else {
+ match project_segment.parse::<i32>() {
+ Ok(id) => (id, None),
+ Err(_) => return Ok(StatusCode::NOT_FOUND.into_response()),
+ }
+ };
+
+ let (should_decrypt, team_id, rate_limit_key) =
+ match authenticate(&state, scope_team_id, resolved_team.as_ref(), &headers).await? {
+ AuthOutcome::Authorized {
+ should_decrypt,
+ team_id,
+ rate_limit_key,
+ } => (should_decrypt, team_id, rate_limit_key),
+ AuthOutcome::Forbidden => return Ok(StatusCode::FORBIDDEN.into_response()),
+ AuthOutcome::ProjectNotFound => return Ok(StatusCode::NOT_FOUND.into_response()),
+ };
+
+ // Throttle mirroring Django's RemoteConfigThrottle: only personal-API-key requests are
+ // throttled, bucketed per credential, and allowlisted teams bypass. Secret-key requests
+ // carry no `rate_limit_key` and are not throttled. Runs before the DB lookup to shield PG.
+ if let Some(cred_key) = rate_limit_key {
+ if !state
+ .config
+ .rate_limiting_allow_list_teams
+ .0
+ .contains(&team_id)
+ {
+ state.remote_config_limiter.check_rate_limit(cred_key)?;
+ }
+ }
+
+ // Resolve the project to scope the flag lookup, now that the caller is authenticated and past
+ // the throttle (deferred so no DB read precedes an unauthenticated rejection). On the
+ // `?token=` path the cached team usually carries project_id; only entries predating that field
+ // hit the DB, and a missing row means the team was deleted from Postgres but is still cached
+ // -> 401 (as Django resolves the token against PG), not a 5xx. On the numeric path the segment
+ // is itself the project id.
+ let scope_project_id: i64 = match &resolved_team {
+ Some(team) => match team.project_id {
+ Some(pid) => pid,
+ None => match project_id_for_team(&state, team.id).await? {
+ Some(pid) => pid,
+ None => return Ok(StatusCode::UNAUTHORIZED.into_response()),
+ },
+ },
+ None => i64::from(scope_team_id),
+ };
+
+ // 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)) =
+ load_remote_config_flag(&state, scope_project_id, &key).await?
+ else {
+ return Ok(StatusCode::NOT_FOUND.into_response());
+ };
+
+ let stored = filters.get("payloads").and_then(|p| p.get("true"));
+
+ // Resolve the payload, mirroring Django's `Response(payloads["true"] or None)`: the stored
+ // value (unencrypted), the decrypted plaintext (personal key), or the redacted marker (secret
+ // key on an encrypted flag).
+ //
+ // Deliberate divergence on malformed rows: an encrypted flag missing the "true" entry makes
+ // Django 500 (both credential paths index `decrypted_payloads["true"]` -> KeyError); a
+ // non-string stored value makes the decrypt path feed `str(value)` to Fernet and 500 on
+ // InvalidToken. Both are shapes the serializer shouldn't allow. We return gracefully instead
+ // -- a missing payload is an empty body on either credential, and the redact path only marks a
+ // payload that actually exists -- so phase 2 reads these rare rows as a known diff, not a bug.
+ let payload: Option<Value> = if has_encrypted_payloads != Some(true) {
+ stored.cloned()
+ } else if should_decrypt {
+ resolve_decrypted_payload(&state, stored)?
+ } else {
+ stored.map(|_| Value::String(REDACTED_PAYLOAD_VALUE.to_string()))
+ };
+
+ // 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()),
+ }
+}
+
+/// 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.
+fn resolve_decrypted_payload(
+ state: &AppState,
+ stored: Option<&Value>,
+) -> 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(),
+ ));
+ };
+ 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())
+ })
+}
+
+/// 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()
+}
+
+/// Mirrors Python truthiness for `payloads.get("true") or None`. In practice the payload
+/// is always a JSON-encoded string, but cover every falsy JSON value so the behaviour
+/// matches Python exactly: null, false, zero, and empty string/array/object.
+fn is_falsy(v: &Value) -> bool {
+ match v {
+ Value::Null => true,
+ Value::Bool(b) => !b,
+ Value::Number(n) => n.as_f64() == Some(0.0),
+ Value::String(s) => s.is_empty(),
+ Value::Array(a) => a.is_empty(),
+ Value::Object(o) => o.is_empty(),
+ }
+}
+
+/// Authenticates and resolves the decrypt gate against the already-resolved scope team,
+/// mirroring Django.
+///
+/// - `phs_` (team/project secret): the token's team must be `scope_team_id`. On mismatch,
+/// 403 if that team exists, 404 if it does not (Django's `view.team` raises). Never decrypts.
+/// - `phx_` (personal API key): validated (scopes + access) against `Team(scope_team_id)`.
+/// Decrypts.
+async fn authenticate(
+ state: &AppState,
+ scope_team_id: i32,
+ resolved_team: Option<&Team>,
+ headers: &HeaderMap,
+) -> Result<AuthOutcome, FlagError> {
+ if let Some(token) = auth::extract_team_secret_token(headers) {
+ let (team_id, _api_token, is_project_secret) =
+ auth::validate_secret_api_token(state, &token).await?;
+ // Django: authenticated_team.id == view.team.id.
+ if team_id != scope_team_id {
+ // Mismatch resolves like Django: 403 when a real (different) team owns the
+ // project, 404 when no such team exists (Django's `view.team` raises). The
+ // lookup only runs on this error path, never on the matching hot path.
+ return match state.flag_service().get_team_by_id(scope_team_id).await {
+ Ok(_) => Ok(AuthOutcome::Forbidden),
+ Err(FlagError::SecretApiTokenInvalid) | Err(FlagError::RowNotFound) => {
+ Ok(AuthOutcome::ProjectNotFound)
+ }
+ Err(e) => Err(e),
+ };
+ }
+ // Mirror the sibling's per-method auth counter; the secret-vs-personal split matters here
+ // because it decides redact-vs-decrypt, so the mix is worth watching during phase 2/3.
+ inc(
+ REMOTE_CONFIG_AUTH_COUNTER,
+ &[(
+ "method".to_string(),
+ if is_project_secret {
+ "project_secret_api_key".to_string()
+ } else {
+ "secret_api_key".to_string()
+ },
+ )],
+ 1,
+ );
+ // Secret-key requests are not throttled by Django's RemoteConfigThrottle.
+ return Ok(AuthOutcome::Authorized {
+ should_decrypt: false,
+ team_id,
+ rate_limit_key: None,
+ });
+ }
+
+ if let Some(key) = auth::extract_personal_api_key(headers)? {
+ // view.team = Team(scope_team_id); missing -> 404. Reuse the team the handler already
+ // fetched on the `?token=` path; only query on the numeric-segment path where none was.
+ let fetched;
+ let team: &Team = match resolved_team {
+ Some(t) => t,
+ None => {
+ fetched = match state.flag_service().get_team_by_id(scope_team_id).await {
+ Ok(team) => team,
+ Err(FlagError::SecretApiTokenInvalid) | Err(FlagError::RowNotFound) => {
+ return Ok(AuthOutcome::ProjectNotFound)
+ }
+ Err(e) => return Err(e),
+ };
+ &fetched
+ }
+ };
+ let pak_id =
+ auth::validate_personal_api_key_with_scopes_for_team(state, &key, team).await?;
+ inc(
+ REMOTE_CONFIG_AUTH_COUNTER,
+ &[("method".to_string(), "personal_api_key".to_string())],
+ 1,
+ );
+ // Per-credential throttle bucket (Django keys on the hashed bearer token; the stable
+ // pak id is an equivalent per-credential identifier for our in-memory limiter).
+ let rate_limit_key = Some(pak_id.clone());
+
+ // Track PAK usage so a key used only for remote config doesn't look dormant and get
+ // rotated as unused. Shared with flag_definitions via the State helper.
+ state.record_pak_last_used(pak_id).await;
+
+ return Ok(AuthOutcome::Authorized {
+ should_decrypt: true,
+ team_id: scope_team_id,
+ rate_limit_key,
+ });
+ }
+
+ Err(FlagError::NoAuthenticationProvided)
+}
+
+/// Resolves a team's `project_id`. Used on the `?token=` path only for cache entries that predate
+/// the cached `project_id`, where the flag is scoped to the token team's project, not its team id.
+/// Returns `None` when no such team exists (stale cache: team deleted from Postgres). `project_id`
+/// is non-null (validated constraint), matching the flag-lookup JOINs that compare it directly.
+async fn project_id_for_team(state: &AppState, team_id: i32) -> Result<Option<i64>, 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
+ .map_err(|e| {
+ warn!("remote_config: failed to get db connection: {e}");
+ FlagError::DatabaseUnavailable
+ })?;
+ let row: Option<(i64,)> =
+ sqlx::query_as("SELECT project_id::bigint FROM posthog_team WHERE id = $1")
+ .bind(team_id)
+ .fetch_optional(&mut *conn)
+ .await
+ .map_err(|e| {
+ warn!("remote_config project lookup failed: {e}");
+ FlagError::DatabaseUnavailable
+ })?;
+ 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.
+async fn load_remote_config_flag(
+ state: &AppState,
+ project_id: i64,
+ key: &str,
+) -> Result<Option<(Value, Option<bool>)>, 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
+ .map_err(|e| {
+ warn!("remote_config: failed to get db connection: {e}");
+ FlagError::DatabaseUnavailable
+ })?;
+
+ // Treat the segment as a flag id only if it is all digits AND fits in i64. An
+ // oversized all-digits segment can't match any real flag id, so it's a 404 — and
+ // parsing it must not panic on user-controlled input.
+ let parsed_id: Option<i64> = if !key.is_empty() && key.bytes().all(|b| b.is_ascii_digit()) {
+ match key.parse::<i64>() {
+ Ok(id) => Some(id),
+ Err(_) => return Ok(None),
+ }
+ } else {
+ None
+ };
+
+ let result = if let Some(id) = parsed_id {
+ sqlx::query_as::<_, (Value, Option<bool>)>(
+ "SELECT f.filters, f.has_encrypted_payloads \
+ 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",
+ )
+ .bind(project_id)
+ .bind(id)
+ .fetch_optional(&mut *conn)
+ .await
+ } else {
+ sqlx::query_as::<_, (Value, Option<bool>)>(
+ "SELECT f.filters, f.has_encrypted_payloads \
+ 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",
+ )
+ .bind(project_id)
+ .bind(key)
+ .fetch_optional(&mut *conn)
+ .await
+ };
+
+ result.map_err(|e| {
+ warn!("remote_config flag query failed: {e}");
+ FlagError::DatabaseUnavailable
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::is_falsy;
+ use serde_json::json;
+
+ #[test]
+ fn is_falsy_matches_python_truthiness() {
+ // Django's `payloads["true"] or None` nulls out every falsy JSON value.
+ assert!(is_falsy(&json!(null)));
+ assert!(is_falsy(&json!(false)));
+ assert!(is_falsy(&json!(0)));
+ assert!(is_falsy(&json!(0.0)));
+ assert!(is_falsy(&json!("")));
+ assert!(is_falsy(&json!([])));
+ assert!(is_falsy(&json!({})));
+ // Truthy values pass through.
+ assert!(!is_falsy(&json!(true)));
+ assert!(!is_falsy(&json!(1)));
+ assert!(!is_falsy(&json!("x")));
+ assert!(!is_falsy(&json!([1])));
+ assert!(!is_falsy(&json!({"k": "v"})));
+ }
+}
diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rs
index 05f47c9926dc..c999c09925ac 100644
--- a/rust/feature-flags/src/config.rs
+++ b/rust/feature-flags/src/config.rs
@@ -376,6 +376,17 @@ pub struct Config {
#[envconfig(default = "")]
pub behavioral_cohorts_read_database_url: String,
+ // Decryption keys for encrypted remote-config flag payloads (comma-separated, ordered:
+ // Django encrypts with the first key, this service only decrypts and tries all of them).
+ // Empty falls back to SECRET_KEY, matching Django's FLAGS_SECRET_KEYS default for
+ // self-hosted. See flags::flag_payload_decryptor.
+ #[envconfig(from = "FLAGS_SECRET_KEYS", default = "")]
+ pub flags_secret_keys: String,
+
+ // Django SECRET_KEY, used only as the FLAGS_SECRET_KEYS fallback (self-hosted).
+ #[envconfig(from = "SECRET_KEY", default = "")]
+ pub secret_key: String,
+
// Team-scoped gate for realtime cohort evaluation. When "none" (default), the
// realtime cohort block in prepare_flag_evaluation_state is skipped entirely, even
// if the behavioral cohorts DB is configured and cohorts with CohortType::Realtime
@@ -640,6 +651,13 @@ pub struct Config {
#[envconfig(from = "LOCAL_EVAL_RATE_LIMITS", default = "")]
pub flag_definitions_rate_limits: FlagDefinitionsRateLimits,
+ // Per-credential rate limit for the remote_config endpoint (requests per minute).
+ // Matches Django's RemoteConfigThrottle default of 600/minute. Django's per-project
+ // REMOTE_CONFIG_RATE_LIMITS override is not ported: it can't apply to a per-credential
+ // bucket, is rarely set, and was already mis-keyed (team id vs project id) in Django.
+ #[envconfig(from = "REMOTE_CONFIG_DEFAULT_RATE_PER_MINUTE", default = "600")]
+ pub remote_config_default_rate_per_minute: u32,
+
// Teams that bypass rate limiting entirely (comma-separated team IDs)
// Matches Django's RATE_LIMITING_ALLOW_LIST_TEAMS behavior
#[envconfig(from = "RATE_LIMITING_ALLOW_LIST_TEAMS", default = "")]
@@ -1007,6 +1025,8 @@ impl Config {
.to_string(),
behavioral_cohorts_read_database_url:
"postgres://posthog:posthog@localhost:5432/test_posthog".to_string(),
+ flags_secret_keys: String::new(),
+ secret_key: "test-secret-key-at-least-32-bytes-long".to_string(),
realtime_cohort_evaluation_team_ids: TeamIdCollection::None,
cohort_membership_cache_ttl_seconds: 60,
cohort_membership_cache_max_entries: 50_000,
@@ -1051,6 +1071,7 @@ impl Config {
flags_session_replay_quota_check: false,
flag_definitions_default_rate_per_minute: 600,
flag_definitions_rate_limits: FlagDefinitionsRateLimits::default(),
+ remote_config_default_rate_per_minute: 600,
rate_limiting_allow_list_teams: RateLimitingAllowList::default(),
flags_log_bodies_teams: BodyLogTeams::default(),
flags_log_bodies_request_max_bytes: 65_536,
diff --git a/rust/feature-flags/src/flags/flag_payload_decryptor.rs b/rust/feature-flags/src/flags/flag_payload_decryptor.rs
new file mode 100644
index 000000000000..21daea6ece9e
--- /dev/null
+++ b/rust/feature-flags/src/flags/flag_payload_decryptor.rs
@@ -0,0 +1,181 @@
+//! Decrypts encrypted remote-config flag payloads.
+//!
+//! Wire-compatible with Django's `FlagPayloadCodec`
+//! (`products/feature_flags/backend/encrypted_flag_payloads.py`): Fernet over a key
+//! derived by `_prepare_key` (pad/truncate raw key material to 32 bytes, then url-safe
+//! base64), wrapped in a `MultiFernet` so older keys still decrypt during rotation.
+//!
+//! Keys come from `FLAGS_SECRET_KEYS` (comma-separated, ordered: Django encrypts with the
+//! first key; this service only decrypts and tries all of them). Matching Django, an empty
+//! list falls back to `[SECRET_KEY]` for self-hosted.
+
+use base64::{prelude::BASE64_URL_SAFE, Engine};
+use fernet::{Fernet, MultiFernet};
+
+/// 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
+/// `REDACTED_PAYLOAD_VALUE` so responses match.
+pub const REDACTED_PAYLOAD_VALUE: &str = "\"********* (encrypted)\"";
+
+#[derive(Debug, thiserror::Error)]
+pub enum FlagPayloadDecryptorError {
+ #[error("no decryption keys configured (FLAGS_SECRET_KEYS and SECRET_KEY are both empty)")]
+ NoKeys,
+ #[error("{built} of {configured} configured keys are valid Fernet keys")]
+ InvalidKeys { built: usize, configured: usize },
+ #[error("failed to decrypt payload")]
+ Decrypt,
+ #[error("decrypted payload is not valid UTF-8")]
+ Utf8,
+}
+
+/// 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
+/// base64-encodes. NOTE: this differs from `batch-import-worker`, which assumes keys
+/// are already 32 bytes. Flag keys are 43 chars (`secrets.token_urlsafe(32)`); skipping
+/// the resize would make `Fernet::new` reject them and startup fail with `InvalidKeys`
+/// (`from_keys` requires every key to build). With the resize, any input becomes a valid
+/// 32-byte base64 key, so this returns `None` only defensively and never in practice.
+fn flag_fernet(raw: &str) -> Option<Fernet> {
+ let kb = raw.as_bytes();
+ let prepared: Vec<u8> = if kb.len() >= 32 {
+ kb[..32].to_vec()
+ } else {
+ let mut v = vec![0u8; 32 - kb.len()];
+ v.extend_from_slice(kb);
+ v
+ };
+ Fernet::new(&BASE64_URL_SAFE.encode(prepared))
+}
+
+#[derive(Clone)]
+pub struct FlagPayloadDecryptor {
+ multi: MultiFernet,
+}
+
+impl FlagPayloadDecryptor {
+ /// Resolve keys Django-style (`FLAGS_SECRET_KEYS = get_list(...) or [SECRET_KEY]`)
+ /// and build the decryptor. Fails loudly at startup if no keys resolve or any key
+ /// fails to build, rather than silently dropping keys and failing every decrypt.
+ ///
+ /// Note: empty comma-entries are dropped (`"k1,,k2"` -> `["k1", "k2"]`), unlike Django's
+ /// `get_list`, which keeps them. This is safe because Django encrypts only with the first key
+ /// (the first non-empty entry in both); an empty entry would only ever be an unused decrypt
+ /// fallback.
+ pub fn from_config(
+ flags_secret_keys: &str,
+ secret_key: &str,
+ ) -> Result<Self, FlagPayloadDecryptorError> {
+ let mut keys: Vec<String> = flags_secret_keys
+ .split(',')
+ .map(|k| k.trim().to_string())
+ .filter(|k| !k.is_empty())
+ .collect();
+
+ if keys.is_empty() {
+ let sk = secret_key.trim();
+ if !sk.is_empty() {
+ keys.push(sk.to_string());
+ }
+ }
+
+ Self::from_keys(&keys)
+ }
+
+ /// Build from an already-resolved, ordered key list (Django encrypts with the first key;
+ /// this service only decrypts and tries all of them).
+ pub fn from_keys(keys: &[String]) -> Result<Self, FlagPayloadDecryptorError> {
+ if keys.is_empty() {
+ return Err(FlagPayloadDecryptorError::NoKeys);
+ }
+ let fernets: Vec<Fernet> = keys.iter().filter_map(|k| flag_fernet(k)).collect();
+ // Defensive: `flag_fernet` resizes any input to a valid 32-byte key, so this never
+ // trips in practice. It exists so that if the resize were ever removed or broken,
+ // startup fails loudly here instead of silently dropping keys (which would surface
+ // later as unexplained decrypt failures).
+ if fernets.len() != keys.len() {
+ return Err(FlagPayloadDecryptorError::InvalidKeys {
+ built: fernets.len(),
+ configured: keys.len(),
+ });
+ }
+ Ok(Self {
+ multi: MultiFernet::new(fernets),
+ })
+ }
+
+ /// Decrypt a Fernet token, trying every key (primary then fallbacks).
+ pub fn decrypt(&self, token: &str) -> Result<String, FlagPayloadDecryptorError> {
+ let bytes = self
+ .multi
+ .decrypt(token)
+ .map_err(|_| FlagPayloadDecryptorError::Decrypt)?;
+ String::from_utf8(bytes).map_err(|_| FlagPayloadDecryptorError::Utf8)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ // Ciphertext produced by Django's FlagPayloadCodec
+ // (products/feature_flags/backend/encrypted_flag_payloads.py).
+ const PLAINTEXT: &str = r#"{"hello":"world","n":42}"#;
+ const K1: &str = "ZtTE8u7zKlorOQYJGS8EM2lFggYttXVaqnxWQP-dXEc"; // 43 chars, token_urlsafe(32)
+ const K2: &str = "DhdZV2HWVtwu8T7yPr5D7Pmg8WjYlD1B8ngynT0GAOc";
+ const TOK_PRIMARY: &str = "gAAAAABqKCSqLF1UmKt8anAe6Um8knblGLl8nLyg6qoynbsE398Yl28Nh1xZZmYB8_WKXkO7v3LjHmNOxkYWjLCbLF0gTWR0V7UO4ziqvY43WlYiG1d3ZjQ=";
+ const TOK_FALLBACK: &str = "gAAAAABqKCSqmH-bdY2DBxrvA6U9Rk2VG0rg2lgAHUVTKdkIyOFa-2Th2sbMNb_8UwkX_o1WI6r8rSC_-kfiZ7ZtMuDynAkiyXuuKeExHtQKy3SGnVI6-M8=";
+ // Encrypted under a key shorter than 32 bytes, so decrypting exercises the
+ // left-pad-with-NULs branch of `flag_fernet` (a self-hosted SECRET_KEY shorter than 32
+ // bytes). K1/K2 above are 43 chars and only ever hit the truncate branch.
+ const SHORT_KEY: &str = "short-secret"; // 12 bytes
+ const TOK_SHORT: &str = "gAAAAABqKxx2qb8lEOK_V04oEJ21oc8InnsjZHp54jnnbnomqFvG8HSSWQn6FXDV6tBhoaQQ1c_cuyUZYg5lQqT9WThNKt9ywJFPZr7C2eNfBFFAhgjv_M4=";
+
+ #[test]
+ fn decrypts_python_ciphertext_via_primary_and_fallback() {
+ let d = FlagPayloadDecryptor::from_keys(&[K1.to_string(), K2.to_string()]).unwrap();
+ assert_eq!(d.decrypt(TOK_PRIMARY).unwrap(), PLAINTEXT);
+ // Encrypted under K2 only; decrypts through the fallback slot.
+ assert_eq!(d.decrypt(TOK_FALLBACK).unwrap(), PLAINTEXT);
+ }
+
+ #[test]
+ fn decrypts_python_ciphertext_under_short_key() {
+ // Pins the pad direction: if the NUL padding were on the wrong side, this fails
+ // while the 43-char fixtures above still pass.
+ let d = FlagPayloadDecryptor::from_keys(&[SHORT_KEY.to_string()]).unwrap();
+ assert_eq!(d.decrypt(TOK_SHORT).unwrap(), PLAINTEXT);
+ }
+
+ #[test]
+ fn from_config_splits_and_trims_flags_secret_keys() {
+ let d = FlagPayloadDecryptor::from_config(&format!(" {K1} , {K2} "), "").unwrap();
+ assert_eq!(d.decrypt(TOK_PRIMARY).unwrap(), PLAINTEXT);
+ assert_eq!(d.decrypt(TOK_FALLBACK).unwrap(), PLAINTEXT);
+ }
+
+ #[test]
+ fn from_config_falls_back_to_secret_key_when_flags_empty() {
+ // Self-hosted: FLAGS_SECRET_KEYS unset -> use [SECRET_KEY]. K1 acts as SECRET_KEY here.
+ let d = FlagPayloadDecryptor::from_config("", K1).unwrap();
+ assert_eq!(d.decrypt(TOK_PRIMARY).unwrap(), PLAINTEXT);
+ }
+
+ #[test]
+ fn from_config_errors_when_no_keys() {
+ assert!(matches!(
+ FlagPayloadDecryptor::from_config("", ""),
+ Err(FlagPayloadDecryptorError::NoKeys)
+ ));
+ }
+
+ #[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)
+ ));
+ }
+}
diff --git a/rust/feature-flags/src/flags/mod.rs b/rust/feature-flags/src/flags/mod.rs
index 17e5786d20b6..a3a8631d4160 100644
--- a/rust/feature-flags/src/flags/mod.rs
+++ b/rust/feature-flags/src/flags/mod.rs
@@ -11,6 +11,7 @@ pub mod flag_matching;
pub mod flag_matching_utils;
pub mod flag_models;
pub mod flag_operations;
+pub mod flag_payload_decryptor;
pub mod flag_property_group;
pub mod flag_request;
pub mod flag_service;
diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rs
index 048a42881ceb..89e528c057f1 100644
--- a/rust/feature-flags/src/metrics/consts.rs
+++ b/rust/feature-flags/src/metrics/consts.rs
@@ -303,6 +303,17 @@ pub const FLAG_DEFINITIONS_RATE_LIMIT_BYPASSED_COUNTER: &str =
"flags_flag_definitions_rate_limit_bypassed_total";
pub const FLAG_DEFINITIONS_REQUESTS_COUNTER: &str = "flags_flag_definitions_requests_total";
+// Remote config rate limiting
+pub const REMOTE_CONFIG_RATE_LIMITED_COUNTER: &str = "flags_remote_config_rate_limited_total";
+pub const REMOTE_CONFIG_RATE_LIMIT_BYPASSED_COUNTER: &str =
+ "flags_remote_config_rate_limit_bypassed_total";
+pub const REMOTE_CONFIG_REQUESTS_COUNTER: &str = "flags_remote_config_requests_total";
+
+// Remote config auth method
+// Labels: method (project_secret_api_key, secret_api_key, personal_api_key). The secret-vs-personal
+// 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";
+
// 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/src/router.rs b/rust/feature-flags/src/router.rs
index a55d011352c7..60961faef560 100644
--- a/rust/feature-flags/src/router.rs
+++ b/rust/feature-flags/src/router.rs
@@ -38,14 +38,17 @@ use crate::{
body_read_metrics::{record_body_read, MAX_FLAGS_BODY_BYTES},
concurrency_metrics::{record_concurrency_enter, record_concurrency_wait},
endpoint, flag_definitions,
- flag_definitions_rate_limiter::FlagDefinitionsRateLimiter,
+ flag_definitions_rate_limiter::{FlagDefinitionsRateLimiter, RemoteConfigRateLimiter},
flags_rate_limiter::{FlagsRateLimiter, IpRateLimiter},
+ remote_config,
},
cohorts::{cohort_cache_manager::CohortCacheManager, membership::CohortMembershipProvider},
config::{Config, ServiceMode, TeamIdCollection},
flags::{
flag_definitions_cache::FlagDefinitionsCache,
flag_group_type_mapping::GroupTypeCacheManager,
+ flag_payload_decryptor::{FlagPayloadDecryptor, FlagPayloadDecryptorError},
+ flag_service::FlagService,
},
handler::body_logger::BodyLogger,
metrics::{
@@ -53,6 +56,8 @@ use crate::{
consts::{
FLAG_DEFINITIONS_RATE_LIMITED_COUNTER, FLAG_DEFINITIONS_RATE_LIMIT_BYPASSED_COUNTER,
FLAG_DEFINITIONS_REQUESTS_COUNTER, FLAG_REQUEST_TIMEOUT_COUNTER,
+ REMOTE_CONFIG_RATE_LIMITED_COUNTER, REMOTE_CONFIG_RATE_LIMIT_BYPASSED_COUNTER,
+ REMOTE_CONFIG_REQUESTS_COUNTER,
},
utils::team_id_label_filter,
},
@@ -78,6 +83,9 @@ pub struct State {
pub session_replay_billing_limiter: SessionReplayLimiter,
pub cookieless_manager: Arc<CookielessManager>,
pub(crate) flag_definitions_limiter: FlagDefinitionsRateLimiter,
+ /// Per-credential limiter (keyed on the personal API key id) for the remote_config endpoint,
+ /// mirroring Django's RemoteConfigThrottle. Separate budget from flag definitions.
+ pub(crate) remote_config_limiter: RemoteConfigRateLimiter,
pub config: Config,
pub(crate) flags_rate_limiter: FlagsRateLimiter,
pub(crate) ip_rate_limiter: IpRateLimiter,
@@ -112,6 +120,41 @@ pub struct State {
/// Per-team request/response body logging for `/flags`. Refreshed
/// every ~60s from `posthog_instancesetting`.
pub body_logger: Arc<BodyLogger>,
+ /// Decrypts encrypted remote-config flag payloads. `None` when no keys are
+ /// configured (e.g. local dev without FLAGS_SECRET_KEYS/SECRET_KEY); in that
+ /// case encrypted payloads cannot be served and the handler errors.
+ pub flag_payload_decryptor: Option<FlagPayloadDecryptor>,
+}
+
+impl State {
+ /// Builds a `FlagService` from shared state. Centralized so every endpoint gets the
+ /// same caching/fallback config instead of copying the constructor per handler.
+ pub(crate) fn flag_service(&self) -> FlagService {
+ FlagService::new(
+ self.redis_client.clone(),
+ self.database_pools.non_persons_reader.clone(),
+ self.team_hypercache_reader.clone(),
+ self.flags_hypercache_reader.clone(),
+ self.flag_definitions_cache.clone(),
+ self.team_negative_cache.clone(),
+ *self.config.skip_pg_team_fallback,
+ )
+ }
+
+ /// Records personal-API-key usage (`last_used_at`), gated on `skip_writes`. Centralized so the
+ /// personal-key auth paths (`flag_definitions`, `remote_config`) share one set of gating and
+ /// client choices instead of copying them per handler. Advisory: uses the shared Redis client
+ /// (not the flags cache) and the non-persons writer, and the DB write only fires when the
+ /// Redis debounce key is newly set.
+ pub(crate) async fn record_pak_last_used(&self, pak_id: String) {
+ if *self.config.skip_writes {
+ return;
+ }
+ let redis = self.redis_client.clone();
+ let pg_writer: Arc<dyn common_database::Client + Send + Sync> =
+ self.database_pools.non_persons_writer.clone();
+ drop(crate::api::pak_usage::record_pak_last_used(redis, pg_writer, pak_id).await);
+ }
}
#[allow(clippy::too_many_arguments)]
@@ -150,6 +193,20 @@ pub fn router(
)
.expect("Failed to initialize flag definitions rate limiter");
+ // Per-credential limiter for the remote_config endpoint (mirrors Django's
+ // RemoteConfigThrottle, which buckets per hashed bearer token). The team allowlist is
+ // applied by the handler, not the limiter, so this is constructed with an empty allowlist
+ // and no per-key overrides.
+ let remote_config_limiter = RemoteConfigRateLimiter::new(
+ config.remote_config_default_rate_per_minute,
+ std::collections::HashMap::new(),
+ std::collections::HashSet::new(),
+ REMOTE_CONFIG_REQUESTS_COUNTER,
+ REMOTE_CONFIG_RATE_LIMITED_COUNTER,
+ REMOTE_CONFIG_RATE_LIMIT_BYPASSED_COUNTER,
+ )
+ .expect("Failed to initialize remote config rate limiter");
+
// Initialize token-based rate limiter.
// Both modes use the same thresholds (warn at ratio of enforce capacity).
// log_only=true sets warn_only, so requests are never blocked.
@@ -197,6 +254,7 @@ pub fn router(
flags_rate_limiter.clone(),
ip_rate_limiter.clone(),
flag_definitions_limiter.clone(),
+ remote_config_limiter.clone(),
config.rate_limiter_cleanup_interval_secs,
);
@@ -215,6 +273,23 @@ pub fn router(
.clone()
.spawn_refresh_task(database_pools.non_persons_reader.clone());
+ // Build the remote-config payload decryptor from FLAGS_SECRET_KEYS (or SECRET_KEY
+ // fallback). Malformed keys fail boot loudly (the documented prep trap); a fully
+ // empty config is tolerated (local dev) — encrypted payloads just can't be served.
+ let flag_payload_decryptor = match FlagPayloadDecryptor::from_config(
+ &config.flags_secret_keys,
+ &config.secret_key,
+ ) {
+ Ok(d) => Some(d),
+ Err(FlagPayloadDecryptorError::NoKeys) => {
+ tracing::warn!(
+ "No FLAGS_SECRET_KEYS or SECRET_KEY configured; encrypted remote config payloads cannot be decrypted"
+ );
+ None
+ }
+ Err(e) => panic!("Invalid FLAGS_SECRET_KEYS configuration: {e}"),
+ };
+
let state = State {
redis_client,
dedicated_redis_client,
@@ -227,6 +302,7 @@ pub fn router(
session_replay_billing_limiter,
cookieless_manager,
flag_definitions_limiter,
+ remote_config_limiter,
config: config.clone(),
flags_rate_limiter,
ip_rate_limiter,
@@ -241,6 +317,7 @@ pub fn router(
auth_token_cache,
billing_aggregator,
body_logger,
+ flag_payload_decryptor,
};
// Very permissive CORS policy, as old SDK versions
@@ -357,6 +434,16 @@ pub fn router(
.route(
"/api/feature_flag/local_evaluation/",
any(flag_definitions::flags_definitions),
+ )
+ // Alias for Django's remote_config endpoint — Contour routes to Rust
+ // without path rewriting (same pattern as local_evaluation).
+ .route(
+ "/api/projects/:project_id/feature_flags/:key/remote_config",
+ any(remote_config::remote_config),
+ )
+ .route(
+ "/api/projects/:project_id/feature_flags/:key/remote_config/",
+ any(remote_config::remote_config),
);
}
@@ -443,6 +530,7 @@ fn spawn_rate_limiter_cleanup_task(
flags_rate_limiter: FlagsRateLimiter,
ip_rate_limiter: IpRateLimiter,
flag_definitions_limiter: FlagDefinitionsRateLimiter,
+ remote_config_limiter: RemoteConfigRateLimiter,
cleanup_interval_secs: u64,
) {
tokio::spawn(async move {
@@ -455,17 +543,21 @@ fn spawn_rate_limiter_cleanup_task(
flags_rate_limiter.cleanup();
ip_rate_limiter.cleanup();
flag_definitions_limiter.cleanup();
+ remote_config_limiter.cleanup();
// Report metrics for monitoring
gauge!("flags_rate_limiter_token_entries").set(flags_rate_limiter.len() as f64);
gauge!("flags_rate_limiter_ip_entries").set(ip_rate_limiter.len() as f64);
gauge!("flags_rate_limiter_definitions_entries")
.set(flag_definitions_limiter.len() as f64);
+ gauge!("flags_rate_limiter_remote_config_entries")
+ .set(remote_config_limiter.len() as f64);
tracing::debug!(
token_entries = flags_rate_limiter.len(),
ip_entries = ip_rate_limiter.len(),
definitions_entries = flag_definitions_limiter.len(),
+ remote_config_entries = remote_config_limiter.len(),
"Rate limiter cleanup completed"
);
}));
diff --git a/rust/feature-flags/src/team/team_models.rs b/rust/feature-flags/src/team/team_models.rs
index 2f4f8f863481..ad14b783d848 100644
--- a/rust/feature-flags/src/team/team_models.rs
+++ b/rust/feature-flags/src/team/team_models.rs
@@ -10,6 +10,11 @@ pub struct Team {
pub api_token: String,
pub uuid: Uuid,
pub organization_id: Option<Uuid>,
+ // The project (environment parent) this team belongs to. Django writes it into the team
+ // metadata cache payload; `#[serde(default)]` keeps cache entries written before the
+ // field existed deserializing (they get `None`, and the handler falls back to a query).
+ #[serde(default)]
+ pub project_id: Option<i64>,
pub autocapture_opt_out: Option<bool>,
pub autocapture_exceptions_opt_in: Option<bool>,
pub autocapture_web_vitals_opt_in: Option<bool>,
diff --git a/rust/feature-flags/src/team/team_operations.rs b/rust/feature-flags/src/team/team_operations.rs
index 0531b06145e9..4b44e6a763de 100644
--- a/rust/feature-flags/src/team/team_operations.rs
+++ b/rust/feature-flags/src/team/team_operations.rs
@@ -10,6 +10,7 @@ const TEAM_COLUMNS: &str = "
name,
api_token,
organization_id,
+ project_id,
cookieless_server_hash_mode,
timezone,
autocapture_opt_out,
diff --git a/rust/feature-flags/src/utils/test_utils.rs b/rust/feature-flags/src/utils/test_utils.rs
index df25dea4fb6e..dab4cf050432 100644
--- a/rust/feature-flags/src/utils/test_utils.rs
+++ b/rust/feature-flags/src/utils/test_utils.rs
@@ -55,6 +55,26 @@ pub async fn update_team_in_hypercache(
Ok(())
}
+/// Write a raw team-token hypercache entry that omits `project_id`, simulating a cache entry
+/// written before that field existed. `verify_token_and_get_team` then deserializes it with
+/// `project_id == None` (via `#[serde(default)]`), which is the only way to exercise the
+/// `project_id_for_team` fallback — the typed `update_team_in_hypercache` always carries the field.
+pub async fn update_team_in_hypercache_without_project_id(
+ client: Arc<dyn RedisClientTrait + Send + Sync>,
+ team: &Team,
+) -> Result<(), Error> {
+ let mut value = serde_json::to_value(team)?;
+ if let Some(obj) = value.as_object_mut() {
+ obj.remove("project_id");
+ }
+ let json_string = serde_json::to_string(&value)?;
+ let pickled_bytes =
+ serde_pickle::to_vec(&json_string, Default::default()).expect("Failed to pickle team");
+ let cache_key = team_token_hypercache_key(&team.api_token);
+ client.set_bytes(cache_key, pickled_bytes, None).await?;
+ Ok(())
+}
+
pub async fn insert_new_team_in_redis(
client: Arc<dyn RedisClientTrait + Send + Sync>,
) -> Result<Team, Error> {
diff --git a/rust/feature-flags/tests/test_remote_config.rs b/rust/feature-flags/tests/test_remote_config.rs
new file mode 100644
index 000000000000..ee7f400766dd
--- /dev/null
+++ b/rust/feature-flags/tests/test_remote_config.rs
@@ -0,0 +1,1321 @@
+//! Integration tests for the remote_config endpoint
+//! (`GET /api/projects/:project_id/feature_flags/:key/remote_config`).
+//!
+//! Mirrors the Django contract in
+//! `products/feature_flags/backend/api/test/test_feature_flag.py`: project-secret keys
+//! get the redacted marker for encrypted payloads, personal keys get plaintext, and
+//! lookups are scoped to the project (cross-team -> 403, cross-project -> 404).
+
+mod common;
+
+use feature_flags::{
+ config::Config,
+ utils::test_utils::{
+ setup_redis_client, update_team_in_hypercache_without_project_id, TestContext,
+ },
+};
+use serde_json::Value;
+
+// Ciphertext produced by Django's FlagPayloadCodec (see flag_payload_decryptor.rs).
+const K1: &str = "ZtTE8u7zKlorOQYJGS8EM2lFggYttXVaqnxWQP-dXEc";
+const TOK_PRIMARY: &str = "gAAAAABqKCSqLF1UmKt8anAe6Um8knblGLl8nLyg6qoynbsE398Yl28Nh1xZZmYB8_WKXkO7v3LjHmNOxkYWjLCbLF0gTWR0V7UO4ziqvY43WlYiG1d3ZjQ=";
+const PLAINTEXT: &str = r#"{"hello":"world","n":42}"#;
+const REDACTED: &str = "\"********* (encrypted)\"";
+
+/// Insert a flag straight into Postgres with full control over the remote-config
+/// columns, returning its id. The flag helpers don't expose these columns.
+async fn insert_rc_flag(
+ context: &TestContext,
+ team_id: i32,
+ key: &str,
+ payload_true: &str,
+ is_remote_configuration: bool,
+ has_encrypted_payloads: bool,
+) -> i32 {
+ let filters = serde_json::json!({
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {"true": payload_true},
+ });
+ insert_flag_with_filters(
+ context,
+ team_id,
+ key,
+ filters,
+ is_remote_configuration,
+ has_encrypted_payloads,
+ )
+ .await
+}
+
+/// Like `insert_rc_flag` but with full control over the `filters` JSON — used for the rare
+/// shape of an encrypted flag whose `payloads` map has no `"true"` entry.
+async fn insert_flag_with_filters(
+ context: &TestContext,
+ team_id: i32,
+ key: &str,
+ filters: Value,
+ is_remote_configuration: bool,
+ has_encrypted_payloads: bool,
+) -> i32 {
+ let mut conn = context.get_non_persons_connection().await.unwrap();
+ let row: (i32,) = sqlx::query_as(
+ r#"INSERT INTO posthog_featureflag
+ (team_id, name, key, filters, deleted, active, ensure_experience_continuity,
+ is_remote_configuration, has_encrypted_payloads, created_at)
+ VALUES ($1, $2, $3, $4, false, true, false, $5, $6, '2024-06-17')
+ RETURNING id"#,
+ )
+ .bind(team_id)
+ .bind(key)
+ .bind(key)
+ .bind(filters)
+ .bind(is_remote_configuration)
+ .bind(has_encrypted_payloads)
+ .fetch_one(&mut *conn)
+ .await
+ .unwrap();
+ row.0
+}
+
+/// Poll until `last_used_at` is set for the given PAK, or panic after ~4s. (Replicated from
+/// test_flag_definitions.rs — integration test binaries can't share helpers.)
+async fn poll_for_pak_last_used_at(context: &TestContext, pak_id: &str, message: &str) {
+ use tokio::time::{sleep, Duration};
+ let mut conn = context.get_non_persons_connection().await.unwrap();
+ for _ in 0..80 {
+ let count: (i64,) = sqlx::query_as(
+ "SELECT COUNT(*) FROM posthog_personalapikey WHERE id = $1 AND last_used_at IS NOT NULL",
+ )
+ .bind(pak_id)
+ .fetch_one(&mut *conn)
+ .await
+ .unwrap();
+ if count.0 > 0 {
+ return;
+ }
+ sleep(Duration::from_millis(50)).await;
+ }
+ panic!("{message}");
+}
+
+fn url(addr: &std::net::SocketAddr, project_id: i32, key: &str) -> String {
+ format!("http://{addr}/api/projects/{project_id}/feature_flags/{key}/remote_config")
+}
+
+#[tokio::test]
+async fn test_remote_config_project_secret_plaintext_returns_payload() {
+ 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-plain", "plain-payload", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-plain"))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+ assert_eq!(
+ response.json::<Value>().await.unwrap(),
+ Value::String("plain-payload".to_string())
+ );
+}
+
+#[tokio::test]
+async fn test_remote_config_api_key_alias_resolves_project() {
+ 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();
+ context.populate_cache_for_team(team.id).await.unwrap();
+ insert_rc_flag(&context, team.id, "rc-apikey", "plain-payload", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ // Django accepts ?api_key= as an alias for ?token=.
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/api/projects/@current/feature_flags/rc-apikey/remote_config?api_key={}",
+ server.addr, team.api_token
+ ))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+ assert_eq!(
+ response.json::<Value>().await.unwrap(),
+ Value::String("plain-payload".to_string())
+ );
+}
+
+#[tokio::test]
+async fn test_remote_config_empty_token_falls_through_to_numeric_segment() {
+ 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-emptytok",
+ "plain-payload",
+ true,
+ false,
+ )
+ .await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ // Empty ?token= is treated as absent (Django's get_token), so the numeric segment wins.
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/api/projects/{}/feature_flags/rc-emptytok/remote_config?token=",
+ server.addr, team.id
+ ))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+ assert_eq!(
+ response.json::<Value>().await.unwrap(),
+ Value::String("plain-payload".to_string())
+ );
+}
+
+#[tokio::test]
+async fn test_remote_config_by_numeric_id_returns_payload() {
+ 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();
+ let flag_id = insert_rc_flag(&context, team.id, "rc-by-id", "plain-payload", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, &flag_id.to_string()))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+ assert_eq!(
+ response.json::<Value>().await.unwrap(),
+ Value::String("plain-payload".to_string())
+ );
+}
+
+#[tokio::test]
+async fn test_remote_config_project_secret_encrypted_returns_redacted() {
+ 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();
+ insert_rc_flag(&context, team.id, "rc-enc", TOK_PRIMARY, true, true).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-enc"))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+ // Project-secret callers never get plaintext for encrypted payloads.
+ assert_eq!(
+ response.json::<Value>().await.unwrap(),
+ Value::String(REDACTED.to_string())
+ );
+}
+
+#[tokio::test]
+async fn test_remote_config_personal_key_encrypted_returns_plaintext() {
+ let mut config = Config::default_test_config();
+ config.flags_secret_keys = K1.to_string();
+ let context = TestContext::new(Some(&config)).await;
+
+ let team = context.insert_new_team(None).await.unwrap();
+ let org_id = context.get_organization_id_for_team(&team).await.unwrap();
+ let user_email = TestContext::generate_test_email("rc_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 PAK", vec!["feature_flag:read"], None, None)
+ .await
+ .unwrap();
+
+ insert_rc_flag(&context, team.id, "rc-enc-pak", TOK_PRIMARY, true, true).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-enc-pak"))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ .await
+ .unwrap();
+
+ let status = response.status();
+ let body = response.json::<Value>().await.unwrap();
+ assert_eq!(status, 200, "body: {body}");
+ assert_eq!(body, Value::String(PLAINTEXT.to_string()));
+}
+
+#[tokio::test]
+async fn test_remote_config_cross_team_secret_returns_403() {
+ let config = Config::default_test_config();
+ let context = TestContext::new(Some(&config)).await;
+ let (_team_a, secret_a, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+ let (team_b, _secret_b, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team_b.id, "b-flag", "plain", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ // team_a's secret key against team_b's project -> team mismatch.
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team_b.id, "b-flag"))
+ .header("Authorization", format!("Bearer {secret_a}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 403);
+}
+
+#[tokio::test]
+async fn test_remote_config_cross_project_key_returns_404() {
+ let config = Config::default_test_config();
+ let context = TestContext::new(Some(&config)).await;
+ let (team_a, secret_a, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+ let (team_b, _secret_b, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+ // Flag lives in team_b's project; request it from team_a's project.
+ insert_rc_flag(&context, team_b.id, "only-in-b", "plain", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team_a.id, "only-in-b"))
+ .header("Authorization", format!("Bearer {secret_a}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 404);
+}
+
+#[tokio::test]
+async fn test_remote_config_unknown_flag_returns_404() {
+ 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();
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "does-not-exist"))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 404);
+}
+
+#[tokio::test]
+async fn test_remote_config_non_remote_config_flag_returns_404() {
+ 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();
+ // A normal (non-remote-config) flag must be invisible here.
+ insert_rc_flag(&context, team.id, "normal-flag", "plain", false, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "normal-flag"))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 404);
+}
+
+#[tokio::test]
+async fn test_remote_config_personal_key_rate_limited_returns_429() {
+ let mut config = Config::default_test_config();
+ config.remote_config_default_rate_per_minute = 1; // burst of 1, so the 2nd call is limited
+ let context = TestContext::new(Some(&config)).await;
+ let team = context.insert_new_team(None).await.unwrap();
+ let org_id = context.get_organization_id_for_team(&team).await.unwrap();
+ let user_email = TestContext::generate_test_email("rc_rl");
+ 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 RL", vec!["feature_flag:read"], None, None)
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team.id, "rc-rl", "plain", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let client = reqwest::Client::new();
+ let get = || {
+ client
+ .get(url(&server.addr, team.id, "rc-rl"))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ };
+
+ // Django throttles personal-API-key requests, bucketed per credential.
+ assert_eq!(get().await.unwrap().status(), 200);
+ assert_eq!(get().await.unwrap().status(), 429);
+}
+
+#[tokio::test]
+async fn test_remote_config_secret_key_not_throttled() {
+ let mut config = Config::default_test_config();
+ config.remote_config_default_rate_per_minute = 1; // would 429 a throttled credential
+ 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-sk", "plain", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let client = reqwest::Client::new();
+ let get = || {
+ client
+ .get(url(&server.addr, team.id, "rc-sk"))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ };
+
+ // Django's RemoteConfigThrottle only throttles personal keys, so secret-key requests are
+ // never limited even past the per-minute rate.
+ assert_eq!(get().await.unwrap().status(), 200);
+ assert_eq!(get().await.unwrap().status(), 200);
+ assert_eq!(get().await.unwrap().status(), 200);
+}
+
+#[tokio::test]
+async fn test_remote_config_oversized_project_id_returns_404() {
+ 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();
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ // project_id > i32::MAX can't name a team: 404 on the secret path too, not 403,
+ // matching the personal-key path.
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/api/projects/99999999999/feature_flags/x/remote_config",
+ server.addr
+ ))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 404);
+}
+
+#[tokio::test]
+async fn test_remote_config_nonexistent_project_secret_returns_404() {
+ 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();
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ // In-range project_id that names no team: 404 (not 403) on the secret path, matching
+ // Django and the personal-key path. 2000000000 < i32::MAX and won't collide with a
+ // sequence-assigned test team id.
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/api/projects/2000000000/feature_flags/x/remote_config",
+ server.addr
+ ))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 404);
+}
+
+#[tokio::test]
+async fn test_remote_config_oversized_numeric_id_returns_404() {
+ 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();
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ // 20 digits: passes the all-digits check but overflows i64. Must 404, not panic.
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "99999999999999999999"))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 404);
+}
+
+#[tokio::test]
+async fn test_remote_config_at_current_with_token_resolves_project() {
+ 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();
+ context.populate_cache_for_team(team.id).await.unwrap();
+ insert_rc_flag(
+ &context,
+ team.id,
+ "rc-current",
+ "plain-payload",
+ true,
+ false,
+ )
+ .await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ // How every server SDK calls this: `@current` segment + a `?token=` project key.
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/api/projects/@current/feature_flags/rc-current/remote_config?token={}",
+ server.addr, team.api_token
+ ))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+ assert_eq!(
+ response.json::<Value>().await.unwrap(),
+ Value::String("plain-payload".to_string())
+ );
+}
+
+#[tokio::test]
+async fn test_remote_config_at_current_without_token_returns_404() {
+ 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();
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ // `@current` without a `?token=` needs the caller's current team (not an SDK path, not
+ // ported), and any other non-numeric segment is Django's int() ValueError -> 404.
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/api/projects/@current/feature_flags/x/remote_config",
+ server.addr
+ ))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 404);
+}
+
+#[tokio::test]
+async fn test_remote_config_token_override_cross_team_returns_403() {
+ let config = Config::default_test_config();
+ let context = TestContext::new(Some(&config)).await;
+ let (_team_a, secret_a, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+ let (team_b, _secret_b, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+ context.populate_cache_for_team(team_b.id).await.unwrap();
+ insert_rc_flag(&context, team_b.id, "b-flag", "plain", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ // ?token resolves the project to team_b, but the secret key is team_a's -> 403.
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/api/projects/@current/feature_flags/b-flag/remote_config?token={}",
+ server.addr, team_b.api_token
+ ))
+ .header("Authorization", format!("Bearer {secret_a}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 403);
+}
+
+#[tokio::test]
+async fn test_remote_config_invalid_token_returns_401() {
+ 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();
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/api/projects/@current/feature_flags/x/remote_config?token=phc_does_not_exist",
+ server.addr
+ ))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 401);
+}
+
+#[tokio::test]
+async fn test_remote_config_no_auth_returns_401() {
+ let config = Config::default_test_config();
+ let context = TestContext::new(Some(&config)).await;
+ let (team, _secret, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team.id, "rc-noauth", "plain", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-noauth"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 401);
+}
+
+#[tokio::test]
+async fn test_remote_config_personal_key_without_flag_scopes_denied() {
+ let mut config = Config::default_test_config();
+ config.flags_secret_keys = K1.to_string();
+ let context = TestContext::new(Some(&config)).await;
+
+ let team = context.insert_new_team(None).await.unwrap();
+ let org_id = context.get_organization_id_for_team(&team).await.unwrap();
+ let user_email = TestContext::generate_test_email("rc_noscope");
+ 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();
+ // Key with a non-flag scope: must be denied and never see the decrypted payload.
+ let (_pak_id, api_key) = context
+ .create_personal_api_key(user_id, "RC NoScope", vec!["dashboard:read"], None, None)
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team.id, "rc-enc-noscope", TOK_PRIMARY, true, true).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-enc-noscope"))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ .await
+ .unwrap();
+
+ let status = response.status();
+ let body = response.text().await.unwrap();
+ assert_eq!(status, 403, "body: {body}");
+ // The deny path must never leak plaintext (PLAINTEXT is `{"hello":"world",...}`).
+ assert!(!body.contains("world"), "leaked plaintext: {body}");
+}
+
+#[tokio::test]
+async fn test_remote_config_empty_payload_returns_empty_body() {
+ 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();
+ // Empty stored payload is falsy: Django renders `Response(None)` as an empty body.
+ insert_rc_flag(&context, team.id, "rc-empty", "", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-empty"))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+ // Empty body, not the JSON literal "null".
+ assert_eq!(response.text().await.unwrap(), "");
+}
+
+#[tokio::test]
+async fn test_remote_config_head_returns_200() {
+ let config = Config::default_test_config();
+ let _context = TestContext::new(Some(&config)).await;
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ // HEAD is handled before auth here (no credential needed). This diverges from Django, which
+ // maps HEAD to the GET action and would 401 an unauthenticated HEAD -- but no SDK sends HEAD.
+ let response = reqwest::Client::new()
+ .head(format!(
+ "http://{}/api/projects/1/feature_flags/x/remote_config",
+ server.addr
+ ))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+}
+
+#[tokio::test]
+async fn test_remote_config_options_preflight_returns_200() {
+ let config = Config::default_test_config();
+ let _context = TestContext::new(Some(&config)).await;
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ // The service's permissive CORS layer answers an OPTIONS preflight with 200 before the
+ // handler runs (so this never reaches `handle_non_get_method`). 200 also matches Django's
+ // OPTIONS, so phase 2 won't flag it.
+ let response = reqwest::Client::new()
+ .request(
+ reqwest::Method::OPTIONS,
+ format!(
+ "http://{}/api/projects/1/feature_flags/x/remote_config",
+ server.addr
+ ),
+ )
+ .header("Origin", "https://example.com")
+ .header("Access-Control-Request-Method", "GET")
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+ let allow_methods = response
+ .headers()
+ .get("access-control-allow-methods")
+ .and_then(|v| v.to_str().ok())
+ .unwrap_or_default();
+ assert!(
+ allow_methods.contains("GET"),
+ "access-control-allow-methods was: {allow_methods:?}"
+ );
+}
+
+#[tokio::test]
+async fn test_remote_config_encrypted_missing_true_returns_empty_body() {
+ // An encrypted flag whose payloads map has no "true" entry: Django 500s (KeyError) but we
+ // return an empty body. The secret-key path must NOT emit the redacted marker when there is
+ // nothing to redact.
+ 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();
+ let filters = serde_json::json!({
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {},
+ });
+ insert_flag_with_filters(&context, team.id, "rc-no-true", filters, true, true).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-no-true"))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+ assert_eq!(response.text().await.unwrap(), "");
+}
+
+#[tokio::test]
+async fn test_remote_config_at_current_token_personal_key_returns_plaintext() {
+ // The SDK hot path for encrypted flags: `@current` + a `?token=` project key + a personal
+ // API key. The token resolves the project and the resolved team is threaded into auth, so
+ // this exercises the personal-key branch of the `?token=` path (untested by the others).
+ let mut config = Config::default_test_config();
+ config.flags_secret_keys = K1.to_string();
+ let context = TestContext::new(Some(&config)).await;
+
+ let team = context.insert_new_team(None).await.unwrap();
+ let org_id = context.get_organization_id_for_team(&team).await.unwrap();
+ let user_email = TestContext::generate_test_email("rc_current_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 Current PAK",
+ vec!["feature_flag:read"],
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team.id, "rc-current-pak", TOK_PRIMARY, true, true).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/api/projects/@current/feature_flags/rc-current-pak/remote_config?token={}",
+ server.addr, team.api_token
+ ))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ .await
+ .unwrap();
+
+ let status = response.status();
+ let body = response.json::<Value>().await.unwrap();
+ assert_eq!(status, 200, "body: {body}");
+ assert_eq!(body, Value::String(PLAINTEXT.to_string()));
+}
+
+#[tokio::test]
+async fn test_remote_config_cross_org_personal_key_denied() {
+ // A personal key from another org must not read (or decrypt) a flag in a project it can't
+ // access, even via `?token=`. The org-membership check rejects it before any payload is
+ // returned, pinning that auth validates against the token-resolved team, not the key's own.
+ let mut config = Config::default_test_config();
+ config.flags_secret_keys = K1.to_string();
+ let context = TestContext::new(Some(&config)).await;
+
+ // Team A holds the encrypted flag; the caller's key belongs to org B.
+ let team_a = context.insert_new_team(None).await.unwrap();
+ let team_b = context
+ .insert_new_team_with_org(None, "0b0b0b0b-0000-0000-0000-0000000b0002")
+ .await
+ .unwrap();
+ let org_b = context.get_organization_id_for_team(&team_b).await.unwrap();
+ let user_email = TestContext::generate_test_email("rc_xorg");
+ let user_id = context
+ .create_user(&user_email, &org_b, team_b.id)
+ .await
+ .unwrap();
+ context
+ .add_user_to_organization(user_id, &org_b, 15)
+ .await
+ .unwrap();
+ let (_pak_id, api_key) = context
+ .create_personal_api_key(user_id, "RC XOrg", vec!["feature_flag:read"], None, None)
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team_a.id, "rc-xorg", TOK_PRIMARY, true, true).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/api/projects/@current/feature_flags/rc-xorg/remote_config?token={}",
+ server.addr, team_a.api_token
+ ))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ .await
+ .unwrap();
+
+ let status = response.status();
+ let body = response.text().await.unwrap();
+ // Not a member of team A's org -> PersonalApiKeyInvalid -> 401, and the body must never leak
+ // the decrypted plaintext (`{"hello":"world",...}`).
+ assert_eq!(status, 401, "body: {body}");
+ assert!(!body.contains("world"), "leaked plaintext: {body}");
+}
+
+#[tokio::test]
+async fn test_remote_config_personal_key_updates_last_used_at() {
+ // A key used only for remote config must still get last_used_at set, or it looks dormant and
+ // could be rotated as unused (Django tracks this; flag_definitions ports it too).
+ let config = Config::default_test_config();
+ let context = TestContext::new(Some(&config)).await;
+
+ let team = context.insert_new_team(None).await.unwrap();
+ let org_id = context.get_organization_id_for_team(&team).await.unwrap();
+ let user_email = TestContext::generate_test_email("rc_lastused");
+ 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 LastUsed",
+ vec!["feature_flag:read"],
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team.id, "rc-lastused", "plain", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-lastused"))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status(), 200);
+
+ poll_for_pak_last_used_at(
+ &context,
+ &pak_id,
+ "Timed out waiting for last_used_at to be set for the remote_config PAK",
+ )
+ .await;
+}
+
+#[tokio::test]
+async fn test_remote_config_skip_writes_does_not_update_last_used_at() {
+ // The shared State::record_pak_last_used helper must honor skip_writes: with it on, a
+ // personal-key request still authenticates (200) but records no last_used_at. Complements
+ // test_remote_config_personal_key_updates_last_used_at, which covers the write path.
+ let mut config = Config::default_test_config();
+ config.skip_writes = feature_flags::config::FlexBool(true);
+ let context = TestContext::new(Some(&config)).await;
+
+ let team = context.insert_new_team(None).await.unwrap();
+ let org_id = context.get_organization_id_for_team(&team).await.unwrap();
+ let user_email = TestContext::generate_test_email("rc_skipwrites");
+ 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 SkipWrites",
+ vec!["feature_flag:read"],
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team.id, "rc-skipwrites", "plain", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-skipwrites"))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status(), 200);
+
+ // skip_writes returns before any write is scheduled, so last_used_at stays NULL. A brief
+ // settle window guards against a stray async write sneaking in.
+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;
+ let mut conn = context.get_non_persons_connection().await.unwrap();
+ let count: (i64,) = sqlx::query_as(
+ "SELECT COUNT(*) FROM posthog_personalapikey WHERE id = $1 AND last_used_at IS NOT NULL",
+ )
+ .bind(&pak_id)
+ .fetch_one(&mut *conn)
+ .await
+ .unwrap();
+ assert_eq!(
+ count.0, 0,
+ "last_used_at must stay NULL when skip_writes is on"
+ );
+}
+
+#[tokio::test]
+async fn test_remote_config_token_without_auth_returns_401() {
+ // A public ?token= with no bearer is rejected at auth (401). The project/flag DB lookups are
+ // deferred until after auth, so an unauthenticated caller can't drive reads off a public token.
+ let config = Config::default_test_config();
+ let context = TestContext::new(Some(&config)).await;
+ let (team, _secret, _) = context
+ .create_team_with_secret_token(None, None, None)
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team.id, "rc-tok-noauth", "plain", true, false).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/api/projects/@current/feature_flags/rc-tok-noauth/remote_config?token={}",
+ server.addr, team.api_token
+ ))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 401);
+}
+
+#[tokio::test]
+async fn test_remote_config_personal_key_no_decryptor_returns_500() {
+ // With no FLAGS_SECRET_KEYS/SECRET_KEY the decryptor is None; an encrypted-flag decrypt
+ // request must 500 (FlagError::Internal), never leak ciphertext.
+ let mut config = Config::default_test_config();
+ config.flags_secret_keys = String::new();
+ config.secret_key = String::new();
+ let context = TestContext::new(Some(&config)).await;
+
+ let team = context.insert_new_team(None).await.unwrap();
+ let org_id = context.get_organization_id_for_team(&team).await.unwrap();
+ let user_email = TestContext::generate_test_email("rc_nodecryptor");
+ 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 NoDecryptor",
+ vec!["feature_flag:read"],
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team.id, "rc-nodecryptor", TOK_PRIMARY, true, true).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-nodecryptor"))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ .await
+ .unwrap();
+
+ let status = response.status();
+ let body = response.text().await.unwrap();
+ assert_eq!(status, 500, "body: {body}");
+ assert!(!body.contains("world"), "leaked plaintext: {body}");
+}
+
+#[tokio::test]
+async fn test_remote_config_personal_key_decrypt_failure_returns_500() {
+ // A stored value that is not valid ciphertext under the configured keys must 500, not leak.
+ let mut config = Config::default_test_config();
+ config.flags_secret_keys = K1.to_string();
+ let context = TestContext::new(Some(&config)).await;
+
+ let team = context.insert_new_team(None).await.unwrap();
+ let org_id = context.get_organization_id_for_team(&team).await.unwrap();
+ let user_email = TestContext::generate_test_email("rc_decryptfail");
+ 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 DecryptFail",
+ vec!["feature_flag:read"],
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ insert_rc_flag(
+ &context,
+ team.id,
+ "rc-decryptfail",
+ "not-a-fernet-token",
+ true,
+ true,
+ )
+ .await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-decryptfail"))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 500);
+}
+
+#[tokio::test]
+async fn test_remote_config_project_secret_api_key_encrypted_returns_redacted() {
+ // A `phs_` project-secret API key (distinct from the team secret token) takes the redact path
+ // and the project_secret_api_key auth-counter branch — never decrypts.
+ let mut config = Config::default_test_config();
+ config.flags_secret_keys = K1.to_string();
+ let context = TestContext::new(Some(&config)).await;
+ let team = context.insert_new_team(None).await.unwrap();
+ let psak = context
+ .create_project_secret_api_key(team.id, "RC PSAK", Some(vec!["feature_flag:read"]))
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team.id, "rc-psak-enc", TOK_PRIMARY, true, true).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-psak-enc"))
+ .header("Authorization", format!("Bearer {psak}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+ assert_eq!(
+ response.json::<Value>().await.unwrap(),
+ Value::String(REDACTED.to_string())
+ );
+}
+
+#[tokio::test]
+async fn test_remote_config_falsy_payloads_return_empty_body() {
+ // Django's `payloads["true"] or None` nulls out falsy values; each must render as an empty
+ // body (not the JSON literal) through the handler, mirroring is_falsy.
+ 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();
+
+ let cases = [
+ ("rc-falsy-false", serde_json::json!(false)),
+ ("rc-falsy-zero", serde_json::json!(0)),
+ ("rc-falsy-arr", serde_json::json!([])),
+ ("rc-falsy-obj", serde_json::json!({})),
+ ];
+ for (key, value) in &cases {
+ let filters = serde_json::json!({
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {"true": value},
+ });
+ insert_flag_with_filters(&context, team.id, key, filters, true, false).await;
+ }
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let client = reqwest::Client::new();
+ for (key, _) in &cases {
+ let response = client
+ .get(url(&server.addr, team.id, key))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(response.status(), 200, "key {key}");
+ assert_eq!(
+ response.text().await.unwrap(),
+ "",
+ "key {key} should return an empty body"
+ );
+ }
+}
+
+#[tokio::test]
+async fn test_remote_config_allowlisted_team_not_throttled() {
+ // An allowlisted team bypasses the per-credential throttle even past the per-minute rate.
+ let mut config = Config::default_test_config();
+ config.remote_config_default_rate_per_minute = 1; // would 429 the 2nd call otherwise
+ let context = TestContext::new(Some(&config)).await;
+ let team = context.insert_new_team(None).await.unwrap();
+ let org_id = context.get_organization_id_for_team(&team).await.unwrap();
+ let user_email = TestContext::generate_test_email("rc_allow");
+ 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 Allow", vec!["feature_flag:read"], None, None)
+ .await
+ .unwrap();
+ insert_rc_flag(&context, team.id, "rc-allow", "plain", true, false).await;
+ // Allowlist this team so the limiter is skipped (parsed via RateLimitingAllowList::from_str).
+ config.rate_limiting_allow_list_teams = format!("{}", team.id).parse().unwrap();
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let client = reqwest::Client::new();
+ let get = || {
+ client
+ .get(url(&server.addr, team.id, "rc-allow"))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ };
+ assert_eq!(get().await.unwrap().status(), 200);
+ assert_eq!(get().await.unwrap().status(), 200);
+}
+
+#[tokio::test]
+async fn test_remote_config_personal_key_encrypted_missing_true_returns_empty_body() {
+ // Personal-key decrypt path with an encrypted flag that has no "true" entry: empty body
+ // (resolve_decrypted_payload returns None), not 500 and not the marker. Django 500s here.
+ let mut config = Config::default_test_config();
+ config.flags_secret_keys = K1.to_string();
+ let context = TestContext::new(Some(&config)).await;
+ let team = context.insert_new_team(None).await.unwrap();
+ let org_id = context.get_organization_id_for_team(&team).await.unwrap();
+ let user_email = TestContext::generate_test_email("rc_pak_notrue");
+ 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 PAK NoTrue",
+ vec!["feature_flag:read"],
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ let filters = serde_json::json!({
+ "groups": [{"properties": [], "rollout_percentage": 100}],
+ "payloads": {},
+ });
+ insert_flag_with_filters(&context, team.id, "rc-pak-notrue", filters, true, true).await;
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(url(&server.addr, team.id, "rc-pak-notrue"))
+ .header("Authorization", format!("Bearer {api_key}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+ assert_eq!(response.text().await.unwrap(), "");
+}
+
+#[tokio::test]
+async fn test_remote_config_token_path_resolves_project_id_from_db_when_cache_lacks_it() {
+ // The project_id fallback (cached team has no project_id -> project_id_for_team's
+ // `SELECT project_id::bigint`) is otherwise never hit: every `?token=` test resolves the team
+ // via Team::from_pg, which always populates project_id. Seed a raw team-cache entry that omits
+ // project_id (a pre-field entry) so verify_token_and_get_team returns project_id=None, forcing
+ // the fallback query. A wrong column or cast there would 404 the flag.
+ 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-stale-cache",
+ "plain-payload",
+ true,
+ false,
+ )
+ .await;
+
+ // Cache the team WITHOUT project_id so the handler must fall back to the DB query.
+ let redis = setup_redis_client(Some(config.redis_url.clone())).await;
+ update_team_in_hypercache_without_project_id(redis, &team)
+ .await
+ .unwrap();
+
+ let server = common::ServerHandle::for_config(config.clone()).await;
+ let response = reqwest::Client::new()
+ .get(format!(
+ "http://{}/api/projects/@current/feature_flags/rc-stale-cache/remote_config?token={}",
+ server.addr, team.api_token
+ ))
+ .header("Authorization", format!("Bearer {secret_token}"))
+ .send()
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), 200);
+ assert_eq!(
+ response.json::<Value>().await.unwrap(),
+ Value::String("plain-payload".to_string())
+ );
+}