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(auth): accept fallback secrets for internal API authentication (#65346)

Tom Piccirellobf75d1df7469
diff --git a/.github/workflows/ci-e2e-playwright.yml b/.github/workflows/ci-e2e-playwright.yml
index c9c0127cd078..9778d76c3790 100644
--- a/.github/workflows/ci-e2e-playwright.yml
+++ b/.github/workflows/ci-e2e-playwright.yml
@@ -73,6 +73,9 @@ env:
AZURE_INFERENCE_CREDENTIAL: ${{ secrets.AZURE_INFERENCE_CREDENTIAL }}
AZURE_INFERENCE_ENDPOINT: ${{ secrets.AZURE_INFERENCE_ENDPOINT }}
PERSONHOG_ADDR: 'localhost:50052'
+ # check_internal_api_secret requires a non-empty INTERNAL_API_SECRET outside DEBUG/TEST. The dev
+ # value matches the Node plugins container's non-prod default, so Django<->Node internal calls authenticate.
+ INTERNAL_API_SECRET: posthog123
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
diff --git a/.github/workflows/ci-mcp.yml b/.github/workflows/ci-mcp.yml
index 78325929420d..e6688770ece8 100644
--- a/.github/workflows/ci-mcp.yml
+++ b/.github/workflows/ci-mcp.yml
@@ -268,6 +268,9 @@ jobs:
# historical-flag override requests to the Rust flags service. Any non-empty
# value is fine for CI — the Rust service in the test stack accepts it.
INTERNAL_REQUEST_TOKEN: 'mcp-ci-internal-request-token'
+ # check_internal_api_secret requires a non-empty INTERNAL_API_SECRET outside DEBUG/TEST,
+ # and this job boots the app prod-like. The dev value is fine for CI.
+ INTERNAL_API_SECRET: 'posthog123'
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
diff --git a/nodejs/src/api/middleware/internal-api-auth.test.ts b/nodejs/src/api/middleware/internal-api-auth.test.ts
index 7f48b7477094..45dbb664f9c7 100644
--- a/nodejs/src/api/middleware/internal-api-auth.test.ts
+++ b/nodejs/src/api/middleware/internal-api-auth.test.ts
@@ -107,6 +107,68 @@ describe('createInternalApiAuthMiddleware', () => {
})
})
+ describe('when fallback secrets configured', () => {
+ it.each([
+ ['primary', 'new-secret'],
+ ['first fallback', 'old-secret'],
+ ['second fallback', 'older-secret'],
+ ])('should allow request when %s matches', (_, provided) => {
+ const middleware = createInternalApiAuthMiddleware({
+ secret: 'new-secret',
+ fallbacks: ['old-secret', 'older-secret'],
+ })
+ const req = mockRequest('/api/test', { 'x-internal-api-secret': provided })
+ const res = mockResponse()
+ const next = jest.fn()
+
+ middleware(req, res, next)
+
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+
+ it('should reject request when secret matches neither primary nor fallback', () => {
+ const middleware = createInternalApiAuthMiddleware({ secret: 'new-secret', fallbacks: ['old-secret'] })
+ const req = mockRequest('/api/test', { 'x-internal-api-secret': 'bogus-secret' })
+ const res = mockResponse()
+ const next = jest.fn()
+
+ middleware(req, res, next)
+
+ expect(next).not.toHaveBeenCalled()
+ expect(res.status).toHaveBeenCalledWith(401)
+ })
+
+ it('should skip auth when primary and all fallbacks are empty', () => {
+ const middleware = createInternalApiAuthMiddleware({ secret: '', fallbacks: ['', ''] })
+ const req = mockRequest('/api/test', {})
+ const res = mockResponse()
+ const next = jest.fn()
+
+ middleware(req, res, next)
+
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+ })
+
+ describe('whitespace handling', () => {
+ it.each([
+ ['configured secret has a trailing newline', 'my-secret\n', 'my-secret'],
+ ['provided secret has surrounding whitespace', 'my-secret', ' my-secret '],
+ ])('matches when %s', (_, configured, provided) => {
+ const middleware = createInternalApiAuthMiddleware({ secret: configured })
+ const req = mockRequest('/api/test', { 'x-internal-api-secret': provided })
+ const res = mockResponse()
+ const next = jest.fn()
+
+ middleware(req, res, next)
+
+ expect(next).toHaveBeenCalled()
+ expect(res.status).not.toHaveBeenCalled()
+ })
+ })
+
describe('path exclusions', () => {
it.each([
['/public/webhooks/123', 'public path'],
diff --git a/nodejs/src/api/middleware/internal-api-auth.ts b/nodejs/src/api/middleware/internal-api-auth.ts
index 6268f3ef2bd8..0ab0b32c08d0 100644
--- a/nodejs/src/api/middleware/internal-api-auth.ts
+++ b/nodejs/src/api/middleware/internal-api-auth.ts
@@ -19,21 +19,26 @@ const PUBLIC_PATH_PREFIXES = ['/public/', '/_health', '/_ready', '/_metrics', '/
export interface InternalApiAuthOptions {
secret: string
+ // Previous secrets still accepted for verification during zero-downtime rotation.
+ fallbacks?: string[]
excludedPathPrefixes?: string[]
}
export function createInternalApiAuthMiddleware(options: InternalApiAuthOptions) {
- const { secret, excludedPathPrefixes = [] } = options
+ const { secret, fallbacks = [], excludedPathPrefixes = [] } = options
const allExcludedPrefixes = [...PUBLIC_PATH_PREFIXES, ...excludedPathPrefixes]
+ // Accept the primary plus any still-trusted fallbacks (zero-downtime rotation). Trim so a
+ // mounted secret's trailing newline can't cause a spurious mismatch between sender and receiver.
+ const acceptedSecrets = [secret, ...fallbacks].map((s) => s.trim()).filter(Boolean)
return (req: Request, res: Response, next: NextFunction): void => {
- // Skip auth if no secret is configured (for backwards compatibility and local dev)
- if (!secret) {
+ // Skip auth if no secret is configured (defense-in-depth only — Contour fronts these endpoints).
+ if (acceptedSecrets.length === 0) {
next()
return
}
- // Skip auth for excluded paths
+ // Health/metrics/public endpoints never require auth.
if (allExcludedPrefixes.some((prefix) => req.path.startsWith(prefix))) {
next()
return
@@ -53,11 +58,18 @@ export function createInternalApiAuthMiddleware(options: InternalApiAuthOptions)
return
}
- // Use timing-safe comparison to prevent timing attacks
- const secretBuffer = Buffer.from(secret)
- const providedBuffer = Buffer.from(providedSecret)
+ // Use timing-safe comparison to prevent timing attacks. Compare against every accepted
+ // secret (count is fixed and non-sensitive) so a match on any current-or-fallback value passes.
+ const providedBuffer = Buffer.from(providedSecret.trim())
+ const matches = acceptedSecrets.some((candidate) => {
+ const candidateBuffer = Buffer.from(candidate)
+ return (
+ candidateBuffer.length === providedBuffer.length &&
+ crypto.timingSafeEqual(candidateBuffer, providedBuffer)
+ )
+ })
- if (secretBuffer.length !== providedBuffer.length || !crypto.timingSafeEqual(secretBuffer, providedBuffer)) {
+ if (!matches) {
logger.warn('Internal API request with invalid secret', {
path: req.path,
method: req.method,
diff --git a/nodejs/src/api/router.ts b/nodejs/src/api/router.ts
index 3f7ff30a7661..66c5baed62ae 100644
--- a/nodejs/src/api/router.ts
+++ b/nodejs/src/api/router.ts
@@ -24,6 +24,8 @@ export function initializePrometheusLabels(ingestionPipeline: string | null, ing
export interface SetupExpressAppOptions {
internalApiSecret?: string
+ // Comma-separated previous secrets still accepted for verification during rotation.
+ internalApiSecretFallbacks?: string
}
export function setupCommonRoutes(
@@ -49,7 +51,15 @@ export function setupExpressApp(options: SetupExpressAppOptions = {}): express.A
// Add internal API authentication middleware for defense-in-depth.
// Primary protection comes from Contour routing at the infra level.
- app.use(createInternalApiAuthMiddleware({ secret: options.internalApiSecret || '' }))
+ app.use(
+ createInternalApiAuthMiddleware({
+ secret: options.internalApiSecret || '',
+ fallbacks: (options.internalApiSecretFallbacks || '')
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean),
+ })
+ )
app.use(
express.json({
diff --git a/nodejs/src/common/config.ts b/nodejs/src/common/config.ts
index de571ad6c278..085a20f76384 100644
--- a/nodejs/src/common/config.ts
+++ b/nodejs/src/common/config.ts
@@ -3,6 +3,10 @@ import { isDevEnv, isProdEnv, isTestEnv } from '../utils/env-utils'
export const DEFAULT_HTTP_SERVER_PORT = 6738
+// Public dev-only default for the internal API secret. Never accepted as a valid secret in production
+// (mirrors LOCAL_DEV_INTERNAL_API_SECRET on the Django side).
+export const LOCAL_DEV_INTERNAL_API_SECRET = 'posthog123'
+
export enum KafkaSaslMechanism {
Plain = 'plain',
ScramSha256 = 'scram-sha-256',
@@ -322,7 +326,8 @@ export function getDefaultCommonConfig(): CommonConfig {
INTERNAL_API_BASE_URL: isProdEnv()
? 'http://posthog-web-django.posthog.svc.cluster.local:8000'
: 'http://localhost:8000',
- INTERNAL_API_SECRET: isProdEnv() ? '' : 'posthog123',
+ INTERNAL_API_SECRET: isProdEnv() ? '' : LOCAL_DEV_INTERNAL_API_SECRET,
+ INTERNAL_API_SECRET_FALLBACKS: '',
HOGFLOW_SCHEDULER_POLL_INTERVAL_MS: 60_000,
HOGFLOW_SCHEDULER_MAX_POLL_INTERVAL_MS: 5 * 60_000,
HOGFLOW_SCHEDULER_HEALTH_TIMEOUT_MS: 10 * 60_000,
diff --git a/nodejs/src/servers/base-server.ts b/nodejs/src/servers/base-server.ts
index 8def6da57c7d..556de0464d11 100644
--- a/nodejs/src/servers/base-server.ts
+++ b/nodejs/src/servers/base-server.ts
@@ -19,6 +19,7 @@ import { delay } from '../utils/utils'
export type BaseServerConfig = {
INTERNAL_API_SECRET: string
+ INTERNAL_API_SECRET_FALLBACKS: string
INSTRUMENT_THREAD_PERFORMANCE: boolean
HTTP_SERVER_PORT: number
POD_TERMINATION_ENABLED: boolean
@@ -68,7 +69,10 @@ export class ServerLifecycle {
private processListeners: Map<string, (...args: any[]) => void> = new Map()
constructor(private config: BaseServerConfig) {
- this.expressApp = setupExpressApp({ internalApiSecret: this.config.INTERNAL_API_SECRET })
+ this.expressApp = setupExpressApp({
+ internalApiSecret: this.config.INTERNAL_API_SECRET,
+ internalApiSecretFallbacks: this.config.INTERNAL_API_SECRET_FALLBACKS,
+ })
this.nodeInstrumentation = new NodeInstrumentation(this.config.INSTRUMENT_THREAD_PERFORMANCE)
configureEventLoopYield(this.config.EVENT_LOOP_YIELD_THRESHOLD_MS)
this.setupContinuousProfiling()
diff --git a/posthog/apps.py b/posthog/apps.py
index dc5216b79913..31c2d2138866 100644
--- a/posthog/apps.py
+++ b/posthog/apps.py
@@ -41,6 +41,7 @@ class PostHogConfig(AppConfig):
# shell) would lose them. They live in dedicated import-light modules — never wire
# ready() through an API module, even one that looks light today.
import posthog.storage.checks # noqa: F401, PLC0415
+ import posthog.internal_api_secret # noqa: F401, PLC0415
import posthog.caching.organization_serializer_cache # noqa: F401, PLC0415
import posthog.models.activity_logging.signal_handlers # noqa: F401, PLC0415
diff --git a/posthog/auth.py b/posthog/auth.py
index ff4a7095834b..6ace0446342a 100644
--- a/posthog/auth.py
+++ b/posthog/auth.py
@@ -31,6 +31,7 @@ from zxcvbn import zxcvbn
from posthog.clickhouse.query_tagging import AccessMethod, tag_authentication
from posthog.constants import AvailableFeature
from posthog.helpers.two_factor_session import enforce_two_factor
+from posthog.internal_api_secret import usable_internal_api_secrets
from posthog.jwt import PosthogJwtAudience, decode_jwt, get_oidc_verification_keys
from posthog.models.oauth import OAuthAccessToken, OAuthApplication, OAuthApplicationAuthBrand
from posthog.models.organization import OrganizationMembership
@@ -46,7 +47,6 @@ from posthog.models.user import User
from posthog.models.utils import hash_key_value
from posthog.models.webauthn_credential import WebauthnCredential
from posthog.passkey import verify_passkey_authentication_response
-from posthog.settings import LOCAL_DEV_INTERNAL_API_SECRET
from posthog.synthetic_user import SyntheticUser
@@ -1001,16 +1001,17 @@ class InternalAPIAuthentication(authentication.BaseAuthentication):
or request.headers.get(self.HEADER_NAME.lower())
or request.headers.get(self.HEADER_NAME.upper())
)
- configured_secret = settings.INTERNAL_API_SECRET
+ # Trim the inbound header (e.g. a trailing newline from a mounted secret) so it can't cause
+ # a spurious mismatch. The configured secrets are normalized at load (see data_stores.py).
+ if provided_secret:
+ provided_secret = provided_secret.strip()
- if not settings.DEBUG and not settings.TEST and configured_secret == LOCAL_DEV_INTERNAL_API_SECRET:
- logger.error(
- "Internal API authentication attempted with default development secret in production environment",
- extra={"path": request.path, "method": request.method},
- )
- raise AuthenticationFailed("Internal API authentication is not properly configured.")
+ # Primary + still-trusted fallbacks, with the dev default dropped outside dev/test. A
+ # misconfigured production deploy (no usable secret) is caught at startup by
+ # check_internal_api_secret; the empty-set guard below is a defensive backstop.
+ accepted_secrets = usable_internal_api_secrets()
- if not configured_secret:
+ if not accepted_secrets:
logger.error(
"Internal API authentication attempted without configured secret",
extra={"path": request.path, "method": request.method},
@@ -1024,7 +1025,7 @@ class InternalAPIAuthentication(authentication.BaseAuthentication):
)
raise AuthenticationFailed("Missing internal API authentication header.")
- if not hmac.compare_digest(configured_secret, provided_secret):
+ if not any(hmac.compare_digest(secret, provided_secret) for secret in accepted_secrets):
logger.warning(
"Internal API request with invalid secret",
extra={"path": request.path, "method": request.method},
diff --git a/posthog/internal_api_secret.py b/posthog/internal_api_secret.py
new file mode 100644
index 000000000000..b2e13a096f10
--- /dev/null
+++ b/posthog/internal_api_secret.py
@@ -0,0 +1,30 @@
+from django.conf import settings
+from django.core.checks import Error, register
+
+
+def usable_internal_api_secrets() -> list[str]:
+ """Internal API secrets accepted when authenticating service-to-service calls: the primary plus
+ any still-trusted fallbacks (zero-downtime rotation), dropping empties. Values are
+ whitespace-normalized at settings load (posthog/settings/data_stores.py), so this does not
+ re-normalize per call.
+ """
+ return [secret for secret in [settings.INTERNAL_API_SECRET, *settings.INTERNAL_API_SECRET_FALLBACKS] if secret]
+
+
+@register()
+def check_internal_api_secret(app_configs: object, **kwargs: object) -> list[Error]:
+ """Fail at startup if a non-dev/test deploy has no INTERNAL_API_SECRET configured, rather than
+ rejecting every internal request at runtime. The value itself is not policed — production must
+ set a real secret (the default is empty outside DEBUG/TEST), CI may set the dev value.
+ """
+ if settings.DEBUG or settings.TEST:
+ return []
+ if usable_internal_api_secrets():
+ return []
+ return [
+ Error(
+ "INTERNAL_API_SECRET is not configured.",
+ hint="Set INTERNAL_API_SECRET to a non-empty value (it is required outside DEBUG/TEST).",
+ id="posthog.E005",
+ )
+ ]
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index 96d1828077e8..84819414d374 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -558,9 +558,18 @@ if not CDP_API_URL:
"http://localhost:6738" if DEBUG else "http://ingestion-cdp-api.posthog.svc.cluster.local"
) # localhost is correct — plugin server runs on host in dev
-# Shared secret for internal API authentication between Django and Node.js services
+# Shared secret for internal API authentication between Django and Node.js services.
+# Defaults to the public dev secret only in DEBUG/TEST; elsewhere it must be set explicitly, so a
+# forgotten production config is empty and fails check_internal_api_secret at startup rather than
+# silently running on a known-public value. Normalized (stripped) at load so a trailing newline from
+# a mounted secret can't cause a spurious mismatch; get_list already strips the fallbacks.
LOCAL_DEV_INTERNAL_API_SECRET = "posthog123"
-INTERNAL_API_SECRET = get_from_env("INTERNAL_API_SECRET", LOCAL_DEV_INTERNAL_API_SECRET)
+INTERNAL_API_SECRET = get_from_env(
+ "INTERNAL_API_SECRET", LOCAL_DEV_INTERNAL_API_SECRET if DEBUG or TEST else ""
+).strip()
+# Previous secrets still accepted for verification during zero-downtime rotation, newest first.
+# Receivers accept INTERNAL_API_SECRET plus these; senders always send INTERNAL_API_SECRET.
+INTERNAL_API_SECRET_FALLBACKS = get_list(os.getenv("INTERNAL_API_SECRET_FALLBACKS", ""))
EMBEDDING_API_URL = get_from_env("EMBEDDING_API_URL", "")
diff --git a/posthog/test/test_internal_api_auth.py b/posthog/test/test_internal_api_auth.py
index bf41f1c93aea..446ab9334536 100644
--- a/posthog/test/test_internal_api_auth.py
+++ b/posthog/test/test_internal_api_auth.py
@@ -5,10 +5,12 @@ from unittest.mock import MagicMock, patch
from django.test import RequestFactory, override_settings
+from parameterized import parameterized
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.request import Request
from posthog.auth import InternalAPIAuthentication
+from posthog.internal_api_secret import check_internal_api_secret
from posthog.settings import LOCAL_DEV_INTERNAL_API_SECRET
@@ -45,13 +47,34 @@ class TestInternalAPIAuth(APIBaseTest):
self.authentication.authenticate(request)
@override_settings(INTERNAL_API_SECRET=LOCAL_DEV_INTERNAL_API_SECRET, DEBUG=False, TEST=False)
- def test_local_dev_secret_denied_outside_debug_or_test(self):
+ def test_explicitly_configured_secret_allows_access_outside_debug_or_test(self):
+ # The value is not policed — any explicitly-set secret is accepted (e.g. CI sets posthog123).
request = Request(
self.factory.get("/internal/endpoint", HTTP_X_INTERNAL_API_SECRET=LOCAL_DEV_INTERNAL_API_SECRET)
)
+ user, _ = self.authentication.authenticate(request)
+ self.assertTrue(user.is_authenticated)
+
+ @parameterized.expand([("primary", "new-secret"), ("fallback", "old-secret"), ("older_fallback", "older-secret")])
+ @override_settings(INTERNAL_API_SECRET="new-secret", INTERNAL_API_SECRET_FALLBACKS=["old-secret", "older-secret"])
+ def test_primary_and_fallback_secrets_allow_access(self, _name, provided):
+ request = Request(self.factory.get("/internal/endpoint", HTTP_X_INTERNAL_API_SECRET=provided))
+ user, auth = self.authentication.authenticate(request)
+ self.assertTrue(user.is_authenticated)
+ self.assertIsNone(auth)
+
+ @override_settings(INTERNAL_API_SECRET="new-secret", INTERNAL_API_SECRET_FALLBACKS=["old-secret"])
+ def test_unknown_secret_denied_when_fallbacks_configured(self):
+ request = Request(self.factory.get("/internal/endpoint", HTTP_X_INTERNAL_API_SECRET="bogus-secret"))
with self.assertRaises(AuthenticationFailed):
self.authentication.authenticate(request)
+ @override_settings(INTERNAL_API_SECRET="secret-value")
+ def test_surrounding_whitespace_in_header_is_ignored(self):
+ request = Request(self.factory.get("/internal/endpoint", HTTP_X_INTERNAL_API_SECRET=" secret-value "))
+ user, _ = self.authentication.authenticate(request)
+ self.assertTrue(user.is_authenticated)
+
@override_settings(INTERNAL_API_SECRET="test-secret-123")
def test_team_and_organization_inferred_from_url_params(self):
request = Request(self.factory.get("/internal/endpoint", HTTP_X_INTERNAL_API_SECRET="test-secret-123"))
@@ -112,3 +135,31 @@ class TestInternalAPIAuth(APIBaseTest):
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json(), {"error": "Missing filters for which to get blast radius"})
+
+
+class TestInternalAPISecretCheck(APIBaseTest):
+ @override_settings(
+ INTERNAL_API_SECRET="real-prod-secret", INTERNAL_API_SECRET_FALLBACKS=[], DEBUG=False, TEST=False
+ )
+ def test_check_passes_with_usable_secret_in_prod(self):
+ self.assertEqual(check_internal_api_secret(None), [])
+
+ @override_settings(
+ INTERNAL_API_SECRET="", INTERNAL_API_SECRET_FALLBACKS=["real-prod-secret"], DEBUG=False, TEST=False
+ )
+ def test_check_passes_with_usable_fallback_in_prod(self):
+ self.assertEqual(check_internal_api_secret(None), [])
+
+ @override_settings(INTERNAL_API_SECRET="", INTERNAL_API_SECRET_FALLBACKS=[], DEBUG=False, TEST=False)
+ def test_check_errors_when_unset_in_prod(self):
+ errors = check_internal_api_secret(None)
+ self.assertEqual(len(errors), 1)
+ self.assertEqual(errors[0].id, "posthog.E005")
+
+ @override_settings(INTERNAL_API_SECRET=LOCAL_DEV_INTERNAL_API_SECRET, INTERNAL_API_SECRET_FALLBACKS=[], DEBUG=True)
+ def test_check_passes_in_dev(self):
+ self.assertEqual(check_internal_api_secret(None), [])
+
+ @override_settings(INTERNAL_API_SECRET="", INTERNAL_API_SECRET_FALLBACKS=[], TEST=True)
+ def test_check_passes_in_test(self):
+ self.assertEqual(check_internal_api_secret(None), [])
diff --git a/rust/cymbal/src/core/config.rs b/rust/cymbal/src/core/config.rs
index 9f4b2f6dfc99..087f5e122373 100644
--- a/rust/cymbal/src/core/config.rs
+++ b/rust/cymbal/src/core/config.rs
@@ -74,6 +74,10 @@ pub struct ResolverConfig {
// Shared secret authenticating the cymbal <-> cymbal-resolution gRPC seam.
#[envconfig(default = "")]
pub internal_api_secret: String,
+
+ // Comma-separated previous secrets still accepted for verification during zero-downtime rotation.
+ #[envconfig(default = "")]
+ pub internal_api_secret_fallbacks: String,
}
impl ResolverConfig {
diff --git a/rust/cymbal/src/modes/resolution/auth.rs b/rust/cymbal/src/modes/resolution/auth.rs
index d542ddef7025..ca6c173b2e1e 100644
--- a/rust/cymbal/src/modes/resolution/auth.rs
+++ b/rust/cymbal/src/modes/resolution/auth.rs
@@ -5,20 +5,23 @@ pub const INTERNAL_API_SECRET_HEADER: &str = "x-internal-api-secret";
#[derive(Clone)]
pub struct InternalApiSecretInterceptor {
- expected_secret: String,
+ // Primary secret plus any still-trusted fallbacks (zero-downtime rotation), trimmed and non-empty.
+ accepted_secrets: Vec<String>,
}
impl InternalApiSecretInterceptor {
- pub fn new(expected_secret: impl Into<String>) -> Self {
- Self {
- expected_secret: expected_secret.into(),
- }
+ pub fn new(primary: impl Into<String>, fallbacks: impl IntoIterator<Item = String>) -> Self {
+ let accepted_secrets = std::iter::once(primary.into())
+ .chain(fallbacks)
+ .map(|secret| secret.trim().to_string())
+ .filter(|secret| !secret.is_empty())
+ .collect();
+ Self { accepted_secrets }
}
#[allow(clippy::result_large_err)]
pub fn authenticate(&self, request: Request<()>) -> Result<Request<()>, Status> {
- let expected_secret = self.expected_secret.trim();
- if expected_secret.is_empty() {
+ if self.accepted_secrets.is_empty() {
return Err(Status::unauthenticated(
"internal API secret is not configured",
));
@@ -37,11 +40,12 @@ impl InternalApiSecretInterceptor {
return Err(Status::unauthenticated("missing internal API secret"));
}
- if provided_secret
- .as_bytes()
- .ct_eq(expected_secret.as_bytes())
- .into()
- {
+ let matches = self
+ .accepted_secrets
+ .iter()
+ .any(|expected| provided_secret.as_bytes().ct_eq(expected.as_bytes()).into());
+
+ if matches {
Ok(request)
} else {
Err(Status::unauthenticated("invalid internal API secret"))
@@ -67,30 +71,43 @@ mod tests {
#[test]
fn allows_matching_secret() {
- let auth = InternalApiSecretInterceptor::new("test-secret");
+ let auth = InternalApiSecretInterceptor::new("test-secret", vec![]);
assert!(auth
.authenticate(request_with_secret("test-secret"))
.is_ok());
}
+ #[test]
+ fn accepts_primary_and_fallback_secrets() {
+ let auth = InternalApiSecretInterceptor::new("new-secret", vec!["old-secret".to_string()]);
+ assert!(auth.authenticate(request_with_secret("new-secret")).is_ok());
+ assert!(auth.authenticate(request_with_secret("old-secret")).is_ok());
+ let err = auth.authenticate(request_with_secret("bogus")).unwrap_err();
+ assert_eq!(err.code(), Code::Unauthenticated);
+ }
+
#[test]
fn trims_configured_and_provided_secret() {
- let auth = InternalApiSecretInterceptor::new(" test-secret\n");
+ let auth =
+ InternalApiSecretInterceptor::new(" test-secret\n", vec![" old-secret\n".to_string()]);
assert!(auth
.authenticate(request_with_secret("test-secret "))
.is_ok());
+ assert!(auth
+ .authenticate(request_with_secret(" old-secret "))
+ .is_ok());
}
#[test]
fn rejects_missing_secret() {
- let auth = InternalApiSecretInterceptor::new("test-secret");
+ let auth = InternalApiSecretInterceptor::new("test-secret", vec![]);
let err = auth.authenticate(Request::new(())).unwrap_err();
assert_eq!(err.code(), Code::Unauthenticated);
}
#[test]
fn rejects_mismatched_secret() {
- let auth = InternalApiSecretInterceptor::new("test-secret");
+ let auth = InternalApiSecretInterceptor::new("test-secret", vec![]);
let err = auth
.authenticate(request_with_secret("wrong-secret"))
.unwrap_err();
@@ -99,7 +116,7 @@ mod tests {
#[test]
fn rejects_when_not_configured() {
- let auth = InternalApiSecretInterceptor::new("");
+ let auth = InternalApiSecretInterceptor::new("", vec![]);
let err = auth
.authenticate(request_with_secret("test-secret"))
.unwrap_err();
diff --git a/rust/cymbal/src/modes/resolution/mod.rs b/rust/cymbal/src/modes/resolution/mod.rs
index 9ee6eeab9975..4be5dd1518a0 100644
--- a/rust/cymbal/src/modes/resolution/mod.rs
+++ b/rust/cymbal/src/modes/resolution/mod.rs
@@ -70,7 +70,15 @@ pub async fn serve(
service_config,
draining,
);
- let auth_interceptor = InternalApiSecretInterceptor::new(resolver.internal_api_secret.clone());
+ let internal_api_secret_fallbacks = resolver
+ .internal_api_secret_fallbacks
+ .split(',')
+ .map(str::to_string)
+ .collect::<Vec<_>>();
+ let auth_interceptor = InternalApiSecretInterceptor::new(
+ resolver.internal_api_secret.clone(),
+ internal_api_secret_fallbacks,
+ );
let listener = tokio::net::TcpListener::bind(res.grpc_address).await?;
let incoming = tracked_tcp_incoming(listener);