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.

refactor(integration-secrets): name the staged value what it is (#88236)

Tom Owers415afa6f6843
diff --git a/posthog/integration_secrets/client.py b/posthog/integration_secrets/client.py
index da5c4469c990..9c076239c9d9 100644
--- a/posthog/integration_secrets/client.py
+++ b/posthog/integration_secrets/client.py
@@ -88,15 +88,22 @@ class SecretValue:
state: str
value: str | None = field(repr=False)
- previous: str | None = field(repr=False)
+ incoming: str | None = field(repr=False)
@frozen
class RotatingSecret:
- """Current value plus the outgoing one, so the two cannot be transposed silently."""
+ """The live value plus the staged replacement, so the two cannot be transposed silently.
+
+ `incoming` is the value a rotation has staged and the service already accepts — NOT the
+ outgoing one. A rotation stages the replacement in `<KEY>_FALLBACKS` while the live value
+ stays put, and completing it moves the staged value across and drops the sibling. So the
+ overlap is the staging window: once a rotation completes, the old value stops being served
+ and there is nothing to fall back to.
+ """
current: str = field(repr=False)
- previous: str | None = field(repr=False)
+ incoming: str | None = field(repr=False)
def integration_service_signing_keys() -> list[str]:
@@ -158,17 +165,18 @@ class IntegrationSecretsClient:
out[key] = secret.value
return out
- def get_with_previous(self, key: str, caller: IntegrationCaller) -> RotatingSecret:
- """Current value plus the outgoing one while a rotation is in flight.
+ def get_with_incoming(self, key: str, caller: IntegrationCaller) -> RotatingSecret:
+ """The live value plus the staged replacement, while a rotation is in flight.
- For callers that can retry against a third party: try current, and on an auth
- failure retry with previous. Nothing is reported back — the service works out for
- itself when the old value is safe to retire.
+ For callers that can retry against a third party: try current, and on an auth failure
+ retry with `incoming` — which is what you want when the credential has already been
+ rotated at the provider and the live value no longer works there. Nothing is reported
+ back; the service works out for itself when a staged value is safe to promote.
"""
secret = self._resolve([key], caller)[key]
if secret.state == "recovery" or secret.value is None:
raise SecretInRecoveryError(key)
- return RotatingSecret(current=secret.value, previous=secret.previous)
+ return RotatingSecret(current=secret.value, incoming=secret.incoming)
def _resolve(self, keys: list[str], caller: IntegrationCaller) -> dict[str, SecretValue]:
missing = _missing_config()
@@ -202,7 +210,10 @@ class IntegrationSecretsClient:
resolved[key] = SecretValue(
state=payload.get("state", "steady"),
value=payload.get("value"),
- previous=payload.get("previous"),
+ # `previous` is the wire name for the staged value. It is wrong, and renaming a
+ # field both sides read needs a release where each accepts either — so the
+ # correction stops at this boundary rather than propagating the wrong idea.
+ incoming=payload.get("previous"),
)
INTEGRATION_SECRET_FETCH_COUNTER.labels(outcome="ok").inc()
@@ -223,7 +234,7 @@ class IntegrationSecretsClient:
# Carry the reason: without it this reads as "the service doesn't have it", which is
# the one thing it does not mean — the service was never asked.
raise SecretMissingError(key, disabled_reason=disabled_reason)
- return SecretValue(state="steady", value=value, previous=None)
+ return SecretValue(state="steady", value=value, incoming=None)
_client = IntegrationSecretsClient()
@@ -237,5 +248,5 @@ def get_many(keys: list[str], caller: IntegrationCaller) -> dict[str, str]:
return _client.get_many(keys, caller)
-def get_with_previous(key: str, caller: IntegrationCaller) -> RotatingSecret:
- return _client.get_with_previous(key, caller)
+def get_with_incoming(key: str, caller: IntegrationCaller) -> RotatingSecret:
+ return _client.get_with_incoming(key, caller)
diff --git a/posthog/integration_secrets/test/test_client.py b/posthog/integration_secrets/test/test_client.py
index 8e81124de0ca..0d898b5b0da5 100644
--- a/posthog/integration_secrets/test/test_client.py
+++ b/posthog/integration_secrets/test/test_client.py
@@ -102,12 +102,15 @@ class TestIntegrationSecretsClient(SimpleTestCase):
with pytest.raises(SecretInRecoveryError):
self.secrets.get(KEY, CALLER)
- def test_get_with_previous_exposes_the_outgoing_value_during_a_rotation(self) -> None:
- rotating = {"state": "rotating", "value": "new", "previous": "old", "version_id": "v1", "fetched_at": "now"}
+ def test_get_with_incoming_exposes_the_staged_value_during_a_rotation(self) -> None:
+ # The wire still calls it `previous`; it carries the value a rotation has STAGED, which the
+ # service accepts but has not made live. A caller retries with it when the provider has
+ # already been rotated — not to reach an older value, which is not served at all.
+ rotating = {"state": "rotating", "value": "live", "previous": "staged", "version_id": "v1", "fetched_at": "now"}
with patch(POST, return_value=FakeResponse(body({KEY: rotating}))):
- secret = self.secrets.get_with_previous(KEY, CALLER)
- assert secret.current == "new"
- assert secret.previous == "old"
+ secret = self.secrets.get_with_incoming(KEY, CALLER)
+ assert secret.current == "live"
+ assert secret.incoming == "staged"
# The 503 contract: the service answers 503 rather than all-missing on a cold start,
# and only raise_for_status keeps that from surfacing as SecretMissingError, which
diff --git a/services/integration-service/README.md b/services/integration-service/README.md
index ed10ca737af7..500c385e4a6c 100644
--- a/services/integration-service/README.md
+++ b/services/integration-service/README.md
@@ -119,7 +119,7 @@ keeps what is already held, with `integration_secret_serving_stale_seconds` as t
```text
integration-service-secrets
STRIPE_APP_SECRET_KEY = "<credential>"
- STRIPE_APP_SECRET_KEY_FALLBACKS = "<outgoing value, only while rotating>"
+ STRIPE_APP_SECRET_KEY_FALLBACKS = "<staged replacement, only while rotating>"
INTEGRATION_RECOVERY_KEYS = "<comma-separated key names>"
__CALLER_KEY_POSTHOG_DJANGO = "<new>,<old>"
```
@@ -131,14 +131,20 @@ overlap silently. A sibling key is unaffected by edits to anything else, and it
PostHog already uses for rotatable keys (`SECRET_KEY_FALLBACKS`), so the rotation guard in
`PostHog/secrets` grades these automatically.
-Starting a rotation means writing the new value and moving the outgoing one into the sibling.
-Completing it means deleting the sibling. Two rotations can be in flight at once without
-interfering.
+Starting a rotation means writing the new value into the sibling, leaving the live one in place:
+both are then served, so a caller can use the replacement before it goes live. Completing it means
+moving the staged value into the key and dropping the sibling, in one write — so a sibling exists
+if and only if a rotation is in flight, and the live value is never briefly absent. Two rotations
+can be in flight at once without interfering.
+
+The live value stops being served the moment a rotation completes. The overlap is the staging
+window, not a grace period afterwards, so leave the new value staged long enough for callers to
+pick it up before completing.
| State | Condition | Response |
| ---------- | ------------------------------------------------ | ------------------------------------- |
| `steady` | no `_FALLBACKS` sibling, or it repeats the value | `value` only |
-| `rotating` | the sibling holds a different value | `value` + `previous` |
+| `rotating` | the sibling holds a different, staged value | `value` + `previous` (the staged one) |
| `recovery` | field named in `INTEGRATION_RECOVERY_KEYS` | no value; caller raises a typed error |
`recovery` covers a credential that is known-burned with no valid replacement yet. These
diff --git a/services/integration-service/src/metrics.ts b/services/integration-service/src/metrics.ts
index 8bdec82cd3f0..88a60fc8e710 100644
--- a/services/integration-service/src/metrics.ts
+++ b/services/integration-service/src/metrics.ts
@@ -29,7 +29,9 @@ export const lastResolvedTimestamp = new Gauge({
// anyone needed the previous value.
export const previousVersionServedTotal = new Counter({
name: 'integration_secret_previous_version_served_total',
- help: 'Responses in which a previous (<KEY>_FALLBACKS) value was included alongside the current one',
+ // Metric name kept as-is: renaming it would break every dashboard and alert already reading
+ // it. The help text carries the correction.
+ help: 'Responses in which a staged, incoming (<KEY>_FALLBACKS) value was included alongside the live one',
labelNames: ['key'],
registers: [register],
})
diff --git a/services/integration-service/src/mount.ts b/services/integration-service/src/mount.ts
index 6ab3a9babcbd..9f018a901ea2 100644
--- a/services/integration-service/src/mount.ts
+++ b/services/integration-service/src/mount.ts
@@ -22,7 +22,7 @@ export const RESERVED_PREFIX = '__'
/** Comma-separated names of the secrets that are in recovery. */
export const RECOVERY_KEYS = 'INTEGRATION_RECOVERY_KEYS'
-/** Suffix holding the outgoing value during a rotation, comma-separated, newest first. */
+/** Suffix holding the staged (incoming) value during a rotation, comma-separated, newest first. */
export const FALLBACK_SUFFIX = '_FALLBACKS'
function commaList(value: string | undefined): string[] {
@@ -130,8 +130,9 @@ export class SecretMount {
for (const [key, value] of Object.entries(values)) {
// Signing keys, the recovery list and rotation siblings are the mount's own
- // machinery; served as secrets they would leak the outgoing value of a
- // rotation and the list of burned keys.
+ // machinery. A sibling IS served, but as the `incoming` field of the key it belongs
+ // to — never as a secret in its own right, which would hand out a staged value under
+ // a name nobody asked for, alongside the list of burned keys.
if (key.startsWith(RESERVED_PREFIX) || key === RECOVERY_KEYS || key.endsWith(FALLBACK_SUFFIX)) {
continue
}
@@ -139,9 +140,9 @@ export class SecretMount {
secrets[key] = { state: 'recovery', versionId: contentHash, fetchedAt }
continue
}
- const previous = commaList(values[`${key}${FALLBACK_SUFFIX}`])[0]
- if (previous !== undefined && previous !== value) {
- secrets[key] = { state: 'rotating', value, previous, versionId: contentHash, fetchedAt }
+ const incoming = commaList(values[`${key}${FALLBACK_SUFFIX}`])[0]
+ if (incoming !== undefined && incoming !== value) {
+ secrets[key] = { state: 'rotating', value, incoming, versionId: contentHash, fetchedAt }
continue
}
secrets[key] = { state: 'steady', value, versionId: contentHash, fetchedAt }
diff --git a/services/integration-service/src/resolve.ts b/services/integration-service/src/resolve.ts
index 586bec424dd9..5040e6e95e3b 100644
--- a/services/integration-service/src/resolve.ts
+++ b/services/integration-service/src/resolve.ts
@@ -18,6 +18,12 @@ const UNKNOWN_KEY = 'unknown'
export interface WireSecret {
state: string
value?: string
+ /**
+ * The staged value, still named `previous` on the wire. The name is wrong — it is the
+ * incoming value, not the outgoing one — but renaming a field both sides read needs a
+ * release where each accepts either, so the internal model is accurate and this boundary
+ * lags deliberately.
+ */
previous?: string
version_id: string
fetched_at: string
@@ -50,8 +56,8 @@ export function resolveKeys(identity: CallerIdentity, mounted: MountedSecrets):
if (secret.value !== undefined) {
wire.value = secret.value
}
- if (secret.previous !== undefined) {
- wire.previous = secret.previous
+ if (secret.incoming !== undefined) {
+ wire.previous = secret.incoming
previousVersionServedTotal.labels({ key }).inc()
}
secrets[key] = wire
diff --git a/services/integration-service/src/types.ts b/services/integration-service/src/types.ts
index aea36af97196..b900a7eb1421 100644
--- a/services/integration-service/src/types.ts
+++ b/services/integration-service/src/types.ts
@@ -2,8 +2,9 @@
* Where a secret stands relative to a rotation.
*
* - `steady`: one live value, with no `<KEY>_FALLBACKS` sibling holding a different one.
- * - `rotating`: the sibling holds a different value, and both are served, because a third
- * party may still hand back tokens minted against the old one.
+ * - `rotating`: the sibling holds a different value, and both are served, so a caller can use
+ * the staged replacement before it goes live — useful when the third party has already been
+ * rotated and the live value no longer works there.
* - `recovery`: the value is known-burned with no replacement yet, so nothing is served and
* callers raise a typed error rather than calling out with a secret that cannot work.
*/
@@ -14,8 +15,15 @@ export interface Secret {
state: SecretState
/** Absent only in `recovery`. */
value?: string
- /** Present only in `rotating`. */
- previous?: string
+ /**
+ * The other value the mount serves for this key, present only in `rotating`.
+ *
+ * It is the INCOMING value, not the outgoing one: a rotation stages the new value in the
+ * sibling while `value` stays live, and promoting it moves the staged value into `value` and
+ * drops the sibling. So a key with a sibling is one whose replacement is staged and accepted
+ * but not yet live.
+ */
+ incoming?: string
versionId: string
/** When the mount this value came from was last read. */
fetchedAt: string
diff --git a/services/integration-service/tests/integration/server.e2e.test.ts b/services/integration-service/tests/integration/server.e2e.test.ts
index 71d31144bd63..6e8fc3f4c6e9 100644
--- a/services/integration-service/tests/integration/server.e2e.test.ts
+++ b/services/integration-service/tests/integration/server.e2e.test.ts
@@ -127,10 +127,10 @@ describe('integration server end to end', () => {
})
// Start a rotation on the mount; the running server picks it up on reload.
- await writeFile(join(dir, `${KEY}_FALLBACKS`), 'previous-value-0')
+ await writeFile(join(dir, `${KEY}_FALLBACKS`), 'staged-value-2')
await server.reload()
expect(await (await resolve(port, token)).json()).toMatchObject({
- secrets: { [KEY]: { state: 'rotating', value: 'current-value-1', previous: 'previous-value-0' } },
+ secrets: { [KEY]: { state: 'rotating', value: 'current-value-1', previous: 'staged-value-2' } },
})
// Completing a rotation is deleting the sibling, and that has to end the
diff --git a/services/integration-service/tests/unit/mount.test.ts b/services/integration-service/tests/unit/mount.test.ts
index 2cf5db1fde6e..5a7142f01d08 100644
--- a/services/integration-service/tests/unit/mount.test.ts
+++ b/services/integration-service/tests/unit/mount.test.ts
@@ -75,14 +75,14 @@ describe('reading the mount', () => {
it.each([
['steady with no fallback sibling', { HUBSPOT_APP_CLIENT_SECRET: 'sec' }, { state: 'steady', value: 'sec' }],
[
- 'rotating when the sibling holds the outgoing value',
- { HUBSPOT_APP_CLIENT_SECRET: 'new', HUBSPOT_APP_CLIENT_SECRET_FALLBACKS: 'old' },
- { state: 'rotating', value: 'new', previous: 'old' },
+ 'rotating when the sibling holds a staged replacement',
+ { HUBSPOT_APP_CLIENT_SECRET: 'live', HUBSPOT_APP_CLIENT_SECRET_FALLBACKS: 'staged' },
+ { state: 'rotating', value: 'live', incoming: 'staged' },
],
[
'the newest entry when the fallback list holds several',
- { HUBSPOT_APP_CLIENT_SECRET: 'new', HUBSPOT_APP_CLIENT_SECRET_FALLBACKS: 'old, older' },
- { state: 'rotating', previous: 'old' },
+ { HUBSPOT_APP_CLIENT_SECRET: 'live', HUBSPOT_APP_CLIENT_SECRET_FALLBACKS: 'staged, older' },
+ { state: 'rotating', incoming: 'staged' },
],
[
'steady when the fallback repeats the current value',
diff --git a/services/integration-service/tests/unit/resolve.test.ts b/services/integration-service/tests/unit/resolve.test.ts
index 40ed2e8204c0..7240cf7cb1d3 100644
--- a/services/integration-service/tests/unit/resolve.test.ts
+++ b/services/integration-service/tests/unit/resolve.test.ts
@@ -12,8 +12,8 @@ const MOUNTED = mounted({
GOOGLE_ADS_APP_CLIENT_ID: { state: 'steady', value: 'ga-id', versionId: 'v1', fetchedAt: 'now' },
GOOGLE_ADS_APP_CLIENT_SECRET: {
state: 'rotating',
- value: 'ga-new',
- previous: 'ga-old',
+ value: 'ga-live',
+ incoming: 'ga-staged',
versionId: 'v1',
fetchedAt: 'now',
},
@@ -39,10 +39,12 @@ describe('resolve', () => {
const response = resolveKeys(identity(['GOOGLE_ADS_APP_CLIENT_ID', 'GOOGLE_ADS_APP_CLIENT_SECRET']), MOUNTED)
expect(response.secrets['GOOGLE_ADS_APP_CLIENT_ID']).toMatchObject({ state: 'steady', value: 'ga-id' })
+ // `previous` is the wire name; it carries the staged (incoming) value. The mismatch is
+ // deliberate and documented on WireSecret — the boundary lags the internal rename.
expect(response.secrets['GOOGLE_ADS_APP_CLIENT_SECRET']).toMatchObject({
state: 'rotating',
- value: 'ga-new',
- previous: 'ga-old',
+ value: 'ga-live',
+ previous: 'ga-staged',
})
})