:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(integration-secrets): read the secret through a kubernetes watch (#116078)
Tom Owers8213ee3814c7
diff --git a/services/integration-service/README.md b/services/integration-service/README.mdindex 500c385e4a6c..40ce99b6e8ea 100644--- a/services/integration-service/README.md+++ b/services/integration-service/README.md@@ -106,15 +106,40 @@ The same value goes into that deployment's own secret as `INTEGRATION_SERVICE_JWFlat and uppercase because the `PostHog/secrets` CLI and UI only manage `[A-Z0-9_]+` keys withplain string values.-External Secrets Operator syncs that secret into a Kubernetes Secret, and kubelet mounts it as a-directory of one file per key. Kubelet rewrites the mount in place and swaps the `..data` symlink-atomically, so a rotation reaches the pod without a restart and a read never sees a half-written-set. The service re-reads on a timer (`src/mount.ts`), every-`INTEGRATION_SERVICE_RELOAD_SECONDS`, and holds the parsed set in memory.--A pod holding no credentials fails its readiness probe rather than exiting, so an empty mount-recovers on its own once ESO syncs instead of crash-looping. A mount that stops being readable-keeps what is already held, with `integration_secret_serving_stale_seconds` as the only sign.+External Secrets Operator syncs that secret into a Kubernetes Secret.+The service reads it from one of two sources, set by `INTEGRATION_SERVICE_SECRET_SOURCE` (`src/source.ts`):++- **`kubernetes`**: the service lists the Secret through the API server, then watches it (`src/kubernetes.ts`).+ Every replica gets an edit within about a second of ESO writing it.+- **`directory`** (the default): kubelet mounts the Secret as a directory of one file per key, and the service re-reads it on a timer.+ Kubelet refreshes the mount on each node on its own schedule, about 60-90s.+ So for a minute or more after an edit, different replicas can serve different versions.+ Use this source for local development and tests.++Each source yields the whole Secret at one version.+The service applies that one snapshot to the signing keys first and then to the credentials.+So a revocation and a rotation in one edit land together, and a revoked caller never reads the new values.++The kubernetes source:++- Lists with `fieldSelector=metadata.name=<name>` at boot, then watches from the listed `resourceVersion` with bookmarks.+- After a normal close, it watches again from the last `resourceVersion` it saw.+- After `410 Gone`, it lists again and watches from the new `resourceVersion`.+- After an error, it reconnects with capped exponential backoff.+- Every `INTEGRATION_SERVICE_RELOAD_SECONDS`, it lists the Secret again as a safety check.+ If the list finds a change that the watch did not deliver, the service applies it and replaces the watch.+- Reads the service account token again for each request, because the projected token rotates.+- Connects straight to `KUBERNETES_SERVICE_HOST:KUBERNETES_SERVICE_PORT`.+ It ignores `HTTP_PROXY` and `HTTPS_PROXY`, so the egress proxy never sees API server traffic.++It needs a Role with `get`, `list` and `watch` on `secrets`, restricted by `resourceNames` to this one Secret.+With `resourceNames`, RBAC allows a list or watch only when it carries the field selector above.++A pod holding no credentials fails its readiness probe rather than exiting.+So an empty mount, or an API server it cannot reach at boot, recovers on its own instead of crash-looping.+A source that stops being readable keeps what is already held, with `integration_secret_serving_stale_seconds` as the only sign.+A deleted Secret also keeps what is held: an empty set would answer every resolve all-missing, which callers treat as deleted credentials.+`integration_secret_watch_restarts_total{reason}` counts watch restarts by why the previous watch ended.```textintegration-service-secrets@@ -180,7 +205,8 @@ carry it; anything else collapses to a constant, and the `caller` claim is not a| `integration_secret_last_resolved_timestamp{key}` | which credentials nothing reads any more || `integration_secret_previous_version_served_total{key}` | how much traffic is reading a key mid-rotation || `integration_secret_serving_stale_seconds` | how long this pod has served credentials it could not refresh |-| `integration_secret_store_errors_total` | mount reads that returned nothing |+| `integration_secret_store_errors_total` | source reads that returned nothing |+| `integration_secret_watch_restarts_total{reason}` | Kubernetes watch restarts, by why the previous watch ended || `integration_service_signing_keys_last_loaded_timestamp` | staleness means a revocation has not landed on this pod || `integration_service_signing_key_reload_failures_total` | reloads that kept the previous key set || `integration_service_auth_failures_total{reason}` | rejected tokens, by why |@@ -223,17 +249,21 @@ mount.## Configuration-| Variable | Default | Notes |-| ------------------------------------ | -------------------------- | ------------------------------------------------------- |-| `INTEGRATION_SERVICE_ENV` | `dev` | Logical env, recorded on every startup log line |-| `INTEGRATION_SERVICE_SECRETS_DIR` | `/etc/integration-secrets` | Where the Kubernetes Secret is mounted |-| `INTEGRATION_SERVICE_RELOAD_SECONDS` | `30` | How often to re-read the mount |-| `INTEGRATION_SERVICE_METRICS_PORT` | `9090` | Dedicated `/metrics` listener, kept off the ingress |-| `INTEGRATION_SERVICE_LOG_LEVEL` | by `NODE_ENV` | `debug`, `info`, `warn` or `error` |-| `PORT` | `8004` | |-| `HOST` | `0.0.0.0` | |-| `SHUTDOWN_PRESTOP_DELAY_MS` | `5000` | Wait before draining, for the Kubernetes prestop window |--The service exits at boot rather than starting degraded: a missing production variable, or a-numeric variable that does not parse. An empty secret mount does not exit; the pod fails its+| Variable | Default | Notes |+| -------------------------------------- | ----------------------------- | ------------------------------------------------------- |+| `INTEGRATION_SERVICE_ENV` | `dev` | Logical env, recorded on every startup log line |+| `INTEGRATION_SERVICE_SECRET_SOURCE` | `directory` | `directory` or `kubernetes`; anything else fails boot |+| `INTEGRATION_SERVICE_SECRETS_DIR` | `/etc/integration-secrets` | Where the Kubernetes Secret is mounted (`directory`) |+| `INTEGRATION_SERVICE_SECRET_NAME` | `integration-service-secrets` | The Secret to watch (`kubernetes`) |+| `INTEGRATION_SERVICE_SECRET_NAMESPACE` | the pod's namespace | Read from the service account when unset (`kubernetes`) |+| `INTEGRATION_SERVICE_RELOAD_SECONDS` | `30` | Re-read interval; a safety re-list next to the watch |+| `INTEGRATION_SERVICE_METRICS_PORT` | `9090` | Dedicated `/metrics` listener, kept off the ingress |+| `INTEGRATION_SERVICE_LOG_LEVEL` | by `NODE_ENV` | `debug`, `info`, `warn` or `error` |+| `PORT` | `8004` | |+| `HOST` | `0.0.0.0` | |+| `SHUTDOWN_PRESTOP_DELAY_MS` | `5000` | Wait before draining, for the Kubernetes prestop window |++The service exits at boot rather than starting degraded: a missing production variable, a+numeric variable that does not parse, or a `kubernetes` source without `KUBERNETES_SERVICE_HOST`+or a namespace. An empty secret mount does not exit; the pod fails itsreadiness probe and recovers on its own once External Secrets Operator syncs.diff --git a/services/integration-service/src/auth/registry.ts b/services/integration-service/src/auth/registry.tsindex d0a53c66337d..f5493ff6845e 100644--- a/services/integration-service/src/auth/registry.ts+++ b/services/integration-service/src/auth/registry.ts@@ -34,7 +34,11 @@ export function assertNoSharedKeys(keys: SigningKeys): void {/** Every signing key on the mount, keyed by deployment. */export async function readSigningKeys(dir: string): Promise<SigningKeys> {- const values = (await readMount(dir)) ?? {}+ return parseSigningKeys((await readMount(dir)) ?? {})+}++/** Every signing key in one snapshot of the secret, keyed by deployment. */+export function parseSigningKeys(values: Record<string, string>): SigningKeys {const keys: SigningKeys = {}for (const [entry, value] of Object.entries(values)) {if (!entry.startsWith(CALLER_KEY_PREFIX)) {@@ -62,13 +66,23 @@ export class SigningKeyLoader {private keys: SigningKeys = {}private loaded = false+ /**+ * @param dir The mount directory `load()` and `reload()` read. A server fed by a secret+ * source calls `loadFrom()` and `reloadFrom()` instead and passes a description of the+ * source here, for error messages only.+ */constructor(private readonly dir: string) {}/** Replace the in-memory key set. Throws on the first load so boot fails closed. */async load(): Promise<void> {- const keys = await readSigningKeys(this.dir)+ this.loadFrom((await readMount(this.dir)) ?? {})+ }++ /** As `load()`, from one snapshot of the secret. */+ loadFrom(values: Record<string, string>): void {+ const keys = parseSigningKeys(values)if (Object.keys(keys).length === 0) {- throw new Error(`no ${CALLER_KEY_PREFIX}* entries on the secret mount at ${this.dir}`)+ throw new Error(`no ${CALLER_KEY_PREFIX}* entries in ${this.dir}`)}assertNoSharedKeys(keys)this.keys = keys@@ -83,8 +97,16 @@ export class SigningKeyLoader {* visible when a revocation does not land.*/async reload(): Promise<void> {+ this.reloadFrom(await readMount(this.dir))+ }++ /** As `reload()`, from one snapshot of the secret. Null means the source could not be read. */+ reloadFrom(values: Record<string, string> | null): void {try {- await this.load()+ if (values === null) {+ throw new Error(`could not read ${this.dir}`)+ }+ this.loadFrom(values)} catch (err) {signingKeyReloadFailuresTotal.inc()logger.error('auth:signing_keys_reload_failed', {diff --git a/services/integration-service/src/kubernetes.ts b/services/integration-service/src/kubernetes.tsnew file mode 100644index 000000000000..5e8430ad3aad--- /dev/null+++ b/services/integration-service/src/kubernetes.ts@@ -0,0 +1,423 @@+// Reads the Kubernetes Secret through the API server with a watch, instead of through a+// mounted volume. Kubelet refreshes a mounted Secret on each node on its own schedule, so+// replicas served different versions for a minute or more after an edit. A watch delivers+// the edit to every replica within about a second of External Secrets Operator writing it.+//+// A small client on node:http(s) instead of @kubernetes/client-node, to keep this service's+// dependency tree small. RBAC grants get/list/watch on this one Secret through+// `resourceNames`, which only authorizes a list or watch that carries+// `fieldSelector=metadata.name=<name>`.++import { readFile } from 'node:fs/promises'+import http, { type IncomingMessage } from 'node:http'+import https from 'node:https'++import type { KubernetesSourceConfig } from './lib/config'+import { logger } from './lib/logging'+import { secretWatchRestartsTotal } from './metrics'+import type { SecretSnapshot, SecretSource, SnapshotListener } from './source'++/** A list that sends nothing for this long has hung, and the read fails. */+const REQUEST_IDLE_TIMEOUT_MS = 10_000++// The API server sends a bookmark on an idle watch about once a minute, so a watch that sends+// nothing for much longer is a dead connection that never closed.+const WATCH_IDLE_TIMEOUT_MS = 5 * 60_000++/** Why a watch connection ended. A metric label, so keep the set small and stable. */+type WatchEnd = 'closed' | 'gone' | 'error' | 'idle' | 'stalled' | 'stopped'++interface SecretObject {+ metadata?: { name?: string; resourceVersion?: string }+ data?: Record<string, string> | null+}++interface SecretList {+ metadata?: { resourceVersion?: string }+ items?: SecretObject[]+}++interface WatchEvent {+ type?: string+ object?: SecretObject & { code?: number }+}++interface Listed {+ snapshot: SecretSnapshot | null+ resourceVersion: string+}++export interface KubernetesSecretSourceOptions extends KubernetesSourceConfig {+ backoff?: { initialMs: number; maxMs: number }+}++function errorMessage(err: unknown): string {+ return err instanceof Error ? err.message : String(err)+}++export class KubernetesSecretSource implements SecretSource {+ readonly kind = 'kubernetes'+ readonly description: string++ private readonly agent: http.Agent+ private readonly backoff: { initialMs: number; maxMs: number }+ private listener: SnapshotListener | null = null+ private stopped = false+ /** Where the next watch starts. Null means list first. */+ private resourceVersion: string | null = null+ /** The newest snapshot this source has produced. */+ private latest: SecretSnapshot | null = null+ /** Counts snapshots applied by the watch or a safety read, so a list can tell that one landed while it ran. */+ private changes = 0+ private endActiveWatch: ((reason: WatchEnd) => void) | null = null+ private readonly inFlight = new Set<AbortController>()+ private cancelSleep: (() => void) | null = null++ constructor(private readonly opts: KubernetesSecretSourceOptions) {+ this.description = `kubernetes secret ${opts.namespace}/${opts.secretName}`+ this.backoff = opts.backoff ?? { initialMs: 500, maxMs: 30_000 }+ // The pods carry HTTP_PROXY/HTTPS_PROXY for the egress proxy, and NO_PROXY may not be+ // widened. An agent built without `proxyEnv` never reads those variables, even under+ // NODE_USE_ENV_PROXY, so the API server is always reached directly.+ this.agent = new URL(opts.apiUrl).protocol === 'https:' ? new https.Agent() : new http.Agent()+ }++ async read(): Promise<SecretSnapshot | null> {+ const changesBefore = this.changes+ let listed: Listed+ try {+ listed = await this.list()+ } catch (err) {+ logger.warn('source:read_failed', { source: this.description, error: errorMessage(err) })+ return null+ }++ if (this.changes !== changesBefore) {+ // The watch delivered a change while this list was in flight, so the list result+ // can be older than what the watch delivered. Returning it would briefly undo that+ // change, for example bring back a revoked signing key.+ return this.latest+ }++ if (this.endActiveWatch && listed.snapshot?.revision !== this.latest?.revision) {+ // A live watch should have delivered this change already. It has stalled without an+ // error, so replace it with a watch that starts from this list.+ this.resourceVersion = listed.resourceVersion+ this.endActiveWatch('stalled')+ } else if (!this.endActiveWatch) {+ this.resourceVersion = listed.resourceVersion+ }+ this.changes+++ this.latest = listed.snapshot+ return listed.snapshot+ }++ watch(listener: SnapshotListener): void {+ if (this.listener || this.stopped) {+ return+ }+ this.listener = listener+ this.run().catch((err: unknown) => {+ logger.error('source:watch_crashed', { source: this.description, error: errorMessage(err) })+ })+ }++ stop(): void {+ this.stopped = true+ this.endActiveWatch?.('stopped')+ for (const controller of this.inFlight) {+ controller.abort()+ }+ this.cancelSleep?.()+ }++ private async run(): Promise<void> {+ // Restarts in a row whose watch delivered nothing. The first restart after a working+ // watch is immediate. A run of watches that end without events backs off, so a broken+ // API server does not get a tight reconnect loop.+ let quietRestarts = 0++ while (!this.stopped) {+ if (this.resourceVersion === null) {+ const changesBefore = this.changes+ let listed: Listed+ try {+ listed = await this.list()+ } catch (err) {+ if (this.stopped) {+ return+ }+ const delayMs = this.backoffMs(quietRestarts++)+ logger.warn('source:list_failed', { source: this.description, error: errorMessage(err), delayMs })+ await this.sleep(delayMs)+ continue+ }+ if (this.changes !== changesBefore) {+ // A safety read or a watch event applied a snapshot while this list was in+ // flight, so this list can be older. Publishing it could bring back a+ // revoked key. Start over from whatever that snapshot left behind.+ continue+ }+ this.resourceVersion = listed.resourceVersion+ this.publish(listed.snapshot)+ }++ const { reason, sawEvents } = await this.watchOnce(this.resourceVersion)+ if (reason === 'stopped' || this.stopped) {+ return+ }+ if (reason === 'gone') {+ this.resourceVersion = null+ }++ quietRestarts = sawEvents ? 0 : quietRestarts + 1+ const delayMs =+ reason !== 'error' && quietRestarts <= 1 ? 0 : this.backoffMs(Math.max(quietRestarts - 1, 0))+ secretWatchRestartsTotal.labels({ reason }).inc()+ logger.info('source:watch_restart', {+ source: this.description,+ reason,+ resourceVersion: this.resourceVersion,+ delayMs,+ })+ if (delayMs > 0) {+ await this.sleep(delayMs)+ }+ }+ }++ private backoffMs(attempt: number): number {+ return Math.min(this.backoff.initialMs * 2 ** attempt, this.backoff.maxMs)+ }++ private sleep(ms: number): Promise<void> {+ return new Promise((resolve) => {+ const timer = setTimeout(() => {+ this.cancelSleep = null+ resolve()+ }, ms)+ this.cancelSleep = () => {+ clearTimeout(timer)+ this.cancelSleep = null+ resolve()+ }+ })+ }++ private publish(snapshot: SecretSnapshot | null): void {+ this.changes+++ this.latest = snapshot+ this.listener?.(snapshot)+ }++ private snapshotOf(object: SecretObject | undefined): SecretSnapshot {+ const values: Record<string, string> = {}+ for (const [key, encoded] of Object.entries(object?.data ?? {})) {+ // Same rules as the mount reader, so both sources hash the same content to the+ // same version id: skip dot-prefixed entries and trim what a human left behind.+ if (!key.startsWith('.')) {+ values[key] = Buffer.from(encoded, 'base64').toString('utf8').trim()+ }+ }+ return { values, revision: object?.metadata?.resourceVersion ?? null }+ }++ private async list(): Promise<Listed> {+ const controller = this.track(new AbortController())+ try {+ const res = await this.open(new URLSearchParams({ fieldSelector: this.fieldSelector() }), controller, null)+ const body = (await readJson(res)) as SecretList+ const resourceVersion = body.metadata?.resourceVersion+ if (!resourceVersion) {+ throw new Error('list response has no resourceVersion')+ }+ const item = body.items?.find((candidate) => candidate.metadata?.name === this.opts.secretName)+ if (!item) {+ logger.error('source:secret_missing', { source: this.description })+ }+ return { snapshot: item ? this.snapshotOf(item) : null, resourceVersion }+ } finally {+ this.inFlight.delete(controller)+ }+ }++ private async watchOnce(resourceVersion: string): Promise<{ reason: WatchEnd; sawEvents: boolean }> {+ const controller = this.track(new AbortController())+ let ended: WatchEnd | null = null+ const end = (reason: WatchEnd): void => {+ if (ended === null) {+ ended = reason+ controller.abort()+ }+ }+ this.endActiveWatch = end++ try {+ let res: IncomingMessage+ try {+ res = await this.open(+ new URLSearchParams({+ watch: '1',+ fieldSelector: this.fieldSelector(),+ resourceVersion,+ allowWatchBookmarks: 'true',+ }),+ controller,+ () => end('idle')+ )+ } catch (err) {+ if (ended === null) {+ logger.warn('source:watch_failed', { source: this.description, error: errorMessage(err) })+ }+ return { reason: ended ?? 'error', sawEvents: false }+ }++ if (res.statusCode !== 200) {+ res.resume()+ logger.warn('source:watch_rejected', { source: this.description, status: res.statusCode })+ return { reason: res.statusCode === 410 ? 'gone' : 'error', sawEvents: false }+ }++ return await new Promise((resolve) => {+ let buffer = ''+ let sawEvents = false+ let settled = false+ const finish = (reason: WatchEnd): void => {+ if (!settled) {+ settled = true+ end(reason)+ resolve({ reason: ended ?? reason, sawEvents })+ }+ }++ res.setEncoding('utf8')+ res.on('data', (chunk: string) => {+ buffer += chunk+ let newline = buffer.indexOf('\n')+ while (newline >= 0 && ended === null) {+ const line = buffer.slice(0, newline).trim()+ buffer = buffer.slice(newline + 1)+ newline = buffer.indexOf('\n')+ if (!line) {+ continue+ }+ sawEvents = true+ const outcome = this.handleEvent(line)+ if (outcome) {+ finish(outcome)+ }+ }+ })+ res.on('end', () => finish('closed'))+ res.on('error', (err) => {+ logger.warn('source:watch_stream_failed', { source: this.description, error: errorMessage(err) })+ finish('error')+ })+ res.on('close', () => finish('closed'))+ })+ } finally {+ this.inFlight.delete(controller)+ if (this.endActiveWatch === end) {+ this.endActiveWatch = null+ }+ }+ }++ /** Apply one watch event. Returns why the watch must end, or null to keep reading. */+ private handleEvent(line: string): WatchEnd | null {+ let event: WatchEvent+ try {+ event = JSON.parse(line) as WatchEvent+ } catch {+ logger.warn('source:watch_bad_event', { source: this.description })+ return 'error'+ }++ const resourceVersion = event.object?.metadata?.resourceVersion+ switch (event.type) {+ case 'ADDED':+ case 'MODIFIED':+ if (resourceVersion) {+ this.resourceVersion = resourceVersion+ }+ this.publish(this.snapshotOf(event.object))+ return null+ case 'BOOKMARK':+ if (resourceVersion) {+ this.resourceVersion = resourceVersion+ }+ return null+ case 'DELETED':+ if (resourceVersion) {+ this.resourceVersion = resourceVersion+ }+ // Going empty would fail every resolve, which callers treat as a deleted+ // credential. Keep serving what is held; the staleness gauge and the error+ // counter make the deletion visible.+ logger.error('source:secret_deleted', { source: this.description })+ this.publish(null)+ return null+ case 'ERROR':+ logger.warn('source:watch_error_event', { source: this.description, code: event.object?.code })+ return event.object?.code === 410 ? 'gone' : 'error'+ default:+ return null+ }+ }++ private fieldSelector(): string {+ return `metadata.name=${this.opts.secretName}`+ }++ private track(controller: AbortController): AbortController {+ this.inFlight.add(controller)+ return controller+ }++ /**+ * Open a GET on the namespace's secrets collection. `onIdle` runs when the socket sends+ * nothing for the idle limit. Without it the request fails at the shorter request limit.+ */+ private async open(+ query: URLSearchParams,+ controller: AbortController,+ onIdle: (() => void) | null+ ): Promise<IncomingMessage> {+ const url = new URL(`/api/v1/namespaces/${this.opts.namespace}/secrets?${query.toString()}`, this.opts.apiUrl)+ // The projected token rotates, so a token read at boot expires in a long-lived pod.+ const token = (await readFile(this.opts.tokenFile, 'utf8')).trim()+ const options: https.RequestOptions = {+ method: 'GET',+ agent: this.agent,+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },+ signal: controller.signal,+ }++ const ca = url.protocol === 'https:' ? await readFile(this.opts.caFile) : null++ return await new Promise<IncomingMessage>((resolve, reject) => {+ const req = ca ? https.request(url, { ...options, ca }, resolve) : http.request(url, options, resolve)+ req.setTimeout(onIdle ? WATCH_IDLE_TIMEOUT_MS : REQUEST_IDLE_TIMEOUT_MS, () => {+ if (onIdle) {+ onIdle()+ } else {+ req.destroy(new Error('request timed out'))+ }+ })+ req.on('error', reject)+ req.end()+ })+ }+}++async function readJson(res: IncomingMessage): Promise<unknown> {+ if (res.statusCode !== 200) {+ res.resume()+ throw new Error(`API server answered HTTP ${res.statusCode}`)+ }+ const chunks: Buffer[] = []+ for await (const chunk of res) {+ chunks.push(chunk as Buffer)+ }+ return JSON.parse(Buffer.concat(chunks).toString('utf8'))+}diff --git a/services/integration-service/src/lib/config.ts b/services/integration-service/src/lib/config.tsindex 1787ec308d92..88b13dc5eefe 100644--- a/services/integration-service/src/lib/config.ts+++ b/services/integration-service/src/lib/config.ts@@ -1,6 +1,27 @@// Configuration, read from the environment once at boot. Anything missing or malformed// that the service cannot safely run without fails the boot rather than a request later.+import { readFileSync } from 'node:fs'+import { join } from 'node:path'++/** Where the pod's service account credentials are projected. */+export const SERVICE_ACCOUNT_DIR = '/var/run/secrets/kubernetes.io/serviceaccount'++export type SecretSourceKind = 'directory' | 'kubernetes'++const SECRET_SOURCES: readonly SecretSourceKind[] = ['directory', 'kubernetes']++/** How to reach the Kubernetes Secret through the API server. */+export interface KubernetesSourceConfig {+ /** Base URL of the API server, e.g. `https://10.0.0.1:443`. */+ apiUrl: string+ namespace: string+ secretName: string+ /** Re-read on every request: the projected token rotates. */+ tokenFile: string+ caFile: string+}+export interface Config {port: numberhost: string@@ -10,10 +31,20 @@ export interface Config {/** Logical environment (dev | prod-us | prod-eu). */env: string- /** Directory the Kubernetes Secret is mounted at. */+ /** Directory the Kubernetes Secret is mounted at. Read when no `kubernetes` source is set. */mountDir: string- /** How often to re-read the mount. Kubelet updates it in roughly 60-90s. */+ /**+ * Set when INTEGRATION_SERVICE_SECRET_SOURCE is `kubernetes`: the service then reads the+ * Secret through the API server instead of from `mountDir`.+ */+ kubernetes?: KubernetesSourceConfig++ /**+ * How often to re-read the secret. For the directory source this is the only refresh. For+ * the kubernetes source it is a safety re-fetch next to the watch, so a watch that stalls+ * without an error cannot leave the pod stale for longer than this.+ */reloadSeconds: number/** Serves /metrics on its own listener, kept off the ingress like every other service. */@@ -33,7 +64,66 @@ function intFromEnv(key: string, fallback: number, min = 0): number {return Number.parseInt(raw, 10)}-export function loadConfig(): Config {+function secretSourceFromEnv(): SecretSourceKind {+ const raw = process.env.INTEGRATION_SERVICE_SECRET_SOURCE+ if (!raw) {+ return 'directory'+ }+ const kind = SECRET_SOURCES.find((source) => source === raw)+ if (!kind) {+ throw new Error(+ `INTEGRATION_SERVICE_SECRET_SOURCE must be one of ${SECRET_SOURCES.join(', ')}, got ${JSON.stringify(raw)}`+ )+ }+ return kind+}++// Both names go into an API path, so a value outside the Kubernetes naming rules must fail+// the boot instead of building a different request.+const DNS_SUBDOMAIN = /^[a-z0-9]([-a-z0-9.]{0,251}[a-z0-9])?$/+const DNS_LABEL = /^[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?$/++function kubernetesFromEnv(serviceAccountDir: string): KubernetesSourceConfig {+ const host = process.env.KUBERNETES_SERVICE_HOST+ const port = process.env.KUBERNETES_SERVICE_PORT+ if (!host || !port) {+ throw new Error(+ 'INTEGRATION_SERVICE_SECRET_SOURCE=kubernetes needs KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT'+ )+ }+ if (!/^\d+$/.test(port)) {+ throw new Error(`KUBERNETES_SERVICE_PORT must be an integer, got ${JSON.stringify(port)}`)+ }++ const secretName = process.env.INTEGRATION_SERVICE_SECRET_NAME || 'integration-service-secrets'+ if (!DNS_SUBDOMAIN.test(secretName)) {+ throw new Error(`INTEGRATION_SERVICE_SECRET_NAME is not a valid Secret name: ${JSON.stringify(secretName)}`)+ }++ let namespace = process.env.INTEGRATION_SERVICE_SECRET_NAMESPACE+ if (!namespace) {+ const namespaceFile = join(serviceAccountDir, 'namespace')+ try {+ namespace = readFileSync(namespaceFile, 'utf8').trim()+ } catch {+ throw new Error(`INTEGRATION_SERVICE_SECRET_NAMESPACE is unset and ${namespaceFile} is unreadable`)+ }+ }+ if (!DNS_LABEL.test(namespace)) {+ throw new Error(`the Secret namespace is not a valid namespace name: ${JSON.stringify(namespace)}`)+ }++ return {+ // An IPv6 service host needs brackets to form a URL.+ apiUrl: `https://${host.includes(':') ? `[${host}]` : host}:${port}`,+ namespace,+ secretName,+ tokenFile: join(serviceAccountDir, 'token'),+ caFile: join(serviceAccountDir, 'ca.crt'),+ }+}++export function loadConfig(serviceAccountDir = SERVICE_ACCOUNT_DIR): Config {const config: Config = {port: intFromEnv('PORT', 8004),host: process.env.HOST ?? '0.0.0.0',@@ -43,13 +133,18 @@ export function loadConfig(): Config {mountDir: process.env.INTEGRATION_SERVICE_SECRETS_DIR ?? '/etc/integration-secrets',- // Shorter than kubelet's own sync so a rotation is visible within about a minute- // of the mount changing.+ // Kubelet syncs a mounted Secret on each node on its own schedule, so for the directory+ // source a change lands on different pods up to a minute or more apart whatever this+ // is. The kubernetes source gets changes from its watch within about a second.reloadSeconds: intFromEnv('INTEGRATION_SERVICE_RELOAD_SECONDS', 30, 1),metricsPort: intFromEnv('INTEGRATION_SERVICE_METRICS_PORT', 9090),}+ if (secretSourceFromEnv() === 'kubernetes') {+ config.kubernetes = kubernetesFromEnv(serviceAccountDir)+ }+if (process.env.NODE_ENV === 'production' && !process.env.INTEGRATION_SERVICE_ENV) {throw new Error('missing required configuration: INTEGRATION_SERVICE_ENV')}diff --git a/services/integration-service/src/metrics.ts b/services/integration-service/src/metrics.tsindex 88a60fc8e710..9b0ee397e3ae 100644--- a/services/integration-service/src/metrics.ts+++ b/services/integration-service/src/metrics.ts@@ -36,17 +36,26 @@ export const previousVersionServedTotal = new Counter({registers: [register],})-// An unreadable mount keeps the secrets already held rather than failing every read, so-// this gauge is the only sign of that degradation. Alert on it.+// An unreadable secret source keeps the secrets already held rather than failing every read,+// so this gauge is the only sign of that degradation. Alert on it.export const servingStaleSeconds = new Gauge({name: 'integration_secret_serving_stale_seconds',- help: 'Age of the secrets still being served because the mount could not be re-read (0 when healthy)',+ help: 'Age of the secrets still being served because the secret source could not be re-read (0 when healthy)',registers: [register],})export const mountErrorsTotal = new Counter({name: 'integration_secret_store_errors_total',- help: 'Reads of the secret mount that returned nothing',+ help: 'Reads of the secret source (mount or Kubernetes API) that returned nothing',+ registers: [register],+})++// A watch that restarts often is a source of lag between pods. `stalled` means the safety+// re-fetch found a change the watch never delivered.+export const secretWatchRestartsTotal = new Counter({+ name: 'integration_secret_watch_restarts_total',+ help: 'Restarts of the Kubernetes Secret watch, by why the previous watch ended',+ labelNames: ['reason'],registers: [register],})diff --git a/services/integration-service/src/mount.ts b/services/integration-service/src/mount.tsindex 9f018a901ea2..b1baedfed67b 100644--- a/services/integration-service/src/mount.ts+++ b/services/integration-service/src/mount.ts@@ -1,8 +1,9 @@-// The mounted Kubernetes Secret: reads it and holds the secrets it carries.+// The Kubernetes Secret's contents: parses them and holds the secrets they carry.//-// Kubelet projects the secret as a directory, one file per key, and rewrites it in place-// when the content changes, swapping the `..data` symlink atomically. So a rotation reaches-// the pod without a restart and a read never sees a half-written set.+// The values come from a secret source (see source.ts). For the directory source, kubelet+// projects the secret as a directory, one file per key, and rewrites it in place when the+// content changes, swapping the `..data` symlink atomically. So a rotation reaches the pod+// without a restart and a read never sees a half-written set.import { createHash } from 'node:crypto'import { readFile, readdir, readlink } from 'node:fs/promises'@@ -73,8 +74,8 @@ export async function readMount(dir: string): Promise<Record<string, string> | n}export interface SecretMountOptions {- /** Directory the Kubernetes Secret is mounted at. */- dir: string+ /** Directory `reload()` reads. Absent when a secret source calls `apply()` instead. */+ dir?: stringnow?: () => number}@@ -98,8 +99,18 @@ export class SecretMount {}async reload(): Promise<void> {+ if (this.opts.dir === undefined) {+ throw new Error('SecretMount.reload() needs a directory')+ }+ this.apply(await readMount(this.opts.dir))+ }++ /**+ * Replace the held set with one parsed from `values`, the whole secret at one version.+ * Null means the source could not be read, which keeps what is held.+ */+ apply(values: Record<string, string> | null): void {const now = this.opts.now ?? Date.now- const values = await readMount(this.opts.dir)const next = values ? this.build(values) : nullif (next) {this.held = next@@ -152,7 +163,7 @@ export class SecretMount {// Counting files rather than secrets would call a mount holding nothing but// signing keys healthy, and every resolve would answer all-missing, which a// caller treats as a deleted secret.- logger.warn('mount:no_secrets', { dir: this.opts.dir })+ logger.warn('mount:no_secrets', { dir: this.opts.dir ?? null })return null}diff --git a/services/integration-service/src/server.ts b/services/integration-service/src/server.tsindex 0bfd80e72165..40ca95aad318 100644--- a/services/integration-service/src/server.ts+++ b/services/integration-service/src/server.ts@@ -16,6 +16,7 @@ import type { Config } from './lib/config'import { logger } from './lib/logging'import { register, shuttingDown } from './metrics'import { SecretMount } from './mount'+import { createSecretSource, type SecretSnapshot, type SecretSource } from './source'import type { Lifecycle } from './types'/** How long a drain may take once the prestop window has passed. */@@ -34,6 +35,7 @@ type ServeFn = (export interface IntegrationServerOverrides {serve?: ServeFnexit?: (code: number) => void+ source?: SecretSource}const sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))@@ -55,6 +57,7 @@ export class IntegrationServer {private readonly lifecycle: Lifecycle = { shuttingDown: false, ready: false }private server: DrainableServer | undefinedprivate metricsServer: Server | undefined+ private source: SecretSource | undefinedprivate mount: SecretMount | undefinedprivate signingKeys: SigningKeyLoader | undefinedprivate cancelTimers: (() => void)[] = []@@ -77,37 +80,72 @@ export class IntegrationServer {return address && typeof address === 'object' ? (address as AddressInfo).port : undefined}- /** Re-read the signing keys and the mount now, without waiting for the timer. */+ /** Re-read the secret now, without waiting for the timer. */async reload(): Promise<void> {+ const source = this.source+ if (source) {+ this.apply(source, await source.read())+ }+ }++ /** Apply one snapshot of the secret to the signing keys and the secrets together. */+ private apply(source: SecretSource, snapshot: SecretSnapshot | null): void {// Keys before secrets: a revocation and a rotation can land in one secret// edit, and the revoked caller must not see the new values in the gap between.- await this.signingKeys?.reload()- await this.mount?.reload()- this.lifecycle.ready = this.mount?.current() != null+ this.signingKeys?.reloadFrom(snapshot?.values ?? null)+ this.applySecrets(source, snapshot)+ }++ private applySecrets(source: SecretSource, snapshot: SecretSnapshot | null): void {+ const mount = this.mount+ if (!mount) {+ return+ }+ const before = mount.current()?.versionId+ mount.apply(snapshot?.values ?? null)+ const after = mount.current()+ if (after && after.versionId !== before) {+ logger.info('secrets:applied', {+ source: source.kind,+ versionId: after.versionId,+ revision: snapshot?.revision ?? null,+ })+ }+ this.lifecycle.ready = after != null && this.signingKeys?.isLoaded === true}async start(): Promise<void> {const config = this.config- const signingKeys = new SigningKeyLoader(config.mountDir)+ const source = this.overrides.source ?? createSecretSource(config)+ this.source = source+ const signingKeys = new SigningKeyLoader(source.description)this.signingKeys = signingKeys- await signingKeys.load()-- const mount = new SecretMount({ dir: config.mountDir })+ const mount = new SecretMount({})this.mount = mount+ const first = await source.read()+ // Boot fails closed when the secret carries no usable signing keys. A Kubernetes API+ // that cannot be read at boot is different: the pod stays not-ready, and the watch+ // retries until the first read succeeds, the same as an empty mount.+ if (first || source.kind === 'directory') {+ signingKeys.loadFrom(first?.values ?? {})+ }+ this.applySecrets(source, first)+const app = createApp({verifier: new JwtVerifier(signingKeys),lifecycle: this.lifecycle,secrets: () => mount.current(),})- await mount.reload()- this.lifecycle.ready = mount.current() != nullif (!this.lifecycle.ready) {- logger.error('startup:no_secrets_on_mount', { dir: config.mountDir })+ logger.error('startup:no_secrets_on_mount', { source: source.description })}+ source.watch((snapshot) => this.apply(source, snapshot))+ this.cancelTimers.push(() => source.stop())+const serveFn = this.overrides.serve ?? servethis.server = serveFn({ fetch: app.fetch, port: config.port, hostname: config.host }, (info) => {logger.info('server:started', { host: config.host, port: info.port, env: config.env })diff --git a/services/integration-service/src/source.ts b/services/integration-service/src/source.tsnew file mode 100644index 000000000000..ab1368953da7--- /dev/null+++ b/services/integration-service/src/source.ts@@ -0,0 +1,54 @@+// Where the service reads the Kubernetes Secret from. A source yields the WHOLE secret at one+// version, and the server applies that one snapshot to both the signing keys and the secrets.+// So a revocation and a rotation made in one edit of the secret land together.++import { KubernetesSecretSource } from './kubernetes'+import type { Config, SecretSourceKind } from './lib/config'+import { readMount } from './mount'++/** Every entry in the secret, as one version of it held them. */+export interface SecretSnapshot {+ values: Record<string, string>+ /** The source's own version label, e.g. a resourceVersion. For logs only. */+ revision: string | null+}++/** Receives a snapshot, or null when the source has nothing it can serve. */+export type SnapshotListener = (snapshot: SecretSnapshot | null) => void++export interface SecretSource {+ readonly kind: SecretSourceKind+ /** Names the secret in logs and error messages. Never a value. */+ readonly description: string+ /** Read the whole secret once. Null when it cannot be read. */+ read(): Promise<SecretSnapshot | null>+ /** Push later changes to `listener` until `stop()`. A source without a watch pushes nothing. */+ watch(listener: SnapshotListener): void+ stop(): void+}++/** The mounted Secret volume. Kubelet refreshes it, so there is nothing to watch. */+export class DirectorySecretSource implements SecretSource {+ readonly kind = 'directory'++ constructor(private readonly dir: string) {}++ get description(): string {+ return this.dir+ }++ async read(): Promise<SecretSnapshot | null> {+ const values = await readMount(this.dir)+ return values ? { values, revision: null } : null+ }++ watch(): void {}++ stop(): void {}+}++export function createSecretSource(config: Config): SecretSource {+ return config.kubernetes+ ? new KubernetesSecretSource(config.kubernetes)+ : new DirectorySecretSource(config.mountDir)+}diff --git a/services/integration-service/tests/unit/config.test.ts b/services/integration-service/tests/unit/config.test.tsindex 4b9b371f546b..01c5a0ec4fb0 100644--- a/services/integration-service/tests/unit/config.test.ts+++ b/services/integration-service/tests/unit/config.test.ts@@ -1,3 +1,6 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'import { afterEach, describe, expect, it } from 'vitest'import { loadConfig } from '@/lib/config'@@ -47,3 +50,98 @@ describe('loadConfig production guards', () => {expect(loadConfig().env).toBe('prod-us')})})++describe('loadConfig secret source', () => {+ const SOURCE_VARS = [+ 'INTEGRATION_SERVICE_SECRET_SOURCE',+ 'INTEGRATION_SERVICE_SECRET_NAME',+ 'INTEGRATION_SERVICE_SECRET_NAMESPACE',+ 'KUBERNETES_SERVICE_HOST',+ 'KUBERNETES_SERVICE_PORT',+ ]+ const dirs: string[] = []++ afterEach(async () => {+ for (const key of SOURCE_VARS) {+ delete process.env[key]+ }+ await Promise.all(dirs.splice(0).map((d) => rm(d, { recursive: true, force: true })))+ })++ async function serviceAccountDir(namespace: string | null): Promise<string> {+ const dir = await mkdtemp(join(tmpdir(), 'integration-sa-'))+ dirs.push(dir)+ if (namespace !== null) {+ await writeFile(join(dir, 'namespace'), `${namespace}\n`)+ }+ return dir+ }++ it.each([+ ['unset reads the mount directory', {}, undefined],+ ['directory reads the mount directory', { INTEGRATION_SERVICE_SECRET_SOURCE: 'directory' }, undefined],+ [+ 'kubernetes reads the service account namespace and the default secret name',+ { INTEGRATION_SERVICE_SECRET_SOURCE: 'kubernetes' },+ { apiUrl: 'https://10.0.0.1:443', namespace: 'from-file', secretName: 'integration-service-secrets' },+ ],+ [+ 'kubernetes prefers an explicit namespace and secret name',+ {+ INTEGRATION_SERVICE_SECRET_SOURCE: 'kubernetes',+ INTEGRATION_SERVICE_SECRET_NAMESPACE: 'explicit',+ INTEGRATION_SERVICE_SECRET_NAME: 'other-secret',+ },+ { namespace: 'explicit', secretName: 'other-secret' },+ ],+ [+ 'kubernetes brackets an IPv6 service host',+ { INTEGRATION_SERVICE_SECRET_SOURCE: 'kubernetes', KUBERNETES_SERVICE_HOST: 'fd00::1' },+ { apiUrl: 'https://[fd00::1]:443' },+ ],+ ])('%s', async (_label, env: Record<string, string>, expected) => {+ process.env.KUBERNETES_SERVICE_HOST = '10.0.0.1'+ process.env.KUBERNETES_SERVICE_PORT = '443'+ Object.assign(process.env, env)+ const dir = await serviceAccountDir('from-file')++ const config = loadConfig(dir)++ if (expected === undefined) {+ expect(config.kubernetes).toBeUndefined()+ } else {+ expect(config.kubernetes).toMatchObject(expected)+ // The token rotates, so the source must know the file, not a value read at boot.+ expect(config.kubernetes).toMatchObject({ tokenFile: join(dir, 'token'), caFile: join(dir, 'ca.crt') })+ }+ })++ it.each([+ ['an unknown source', { INTEGRATION_SERVICE_SECRET_SOURCE: 'kube' }, 'INTEGRATION_SERVICE_SECRET_SOURCE', true],+ [+ 'kubernetes outside a cluster',+ { INTEGRATION_SERVICE_SECRET_SOURCE: 'kubernetes', KUBERNETES_SERVICE_HOST: '' },+ 'KUBERNETES_SERVICE_HOST',+ true,+ ],+ [+ 'kubernetes with no namespace anywhere',+ { INTEGRATION_SERVICE_SECRET_SOURCE: 'kubernetes' },+ 'INTEGRATION_SERVICE_SECRET_NAMESPACE',+ false,+ ],+ [+ 'a secret name the API path cannot carry',+ { INTEGRATION_SERVICE_SECRET_SOURCE: 'kubernetes', INTEGRATION_SERVICE_SECRET_NAME: '../configmaps/x' },+ 'INTEGRATION_SERVICE_SECRET_NAME',+ true,+ ],+ ])('refuses to boot with %s', async (_label, env: Record<string, string>, message, namespaceFile) => {+ process.env.KUBERNETES_SERVICE_HOST = '10.0.0.1'+ process.env.KUBERNETES_SERVICE_PORT = '443'+ Object.assign(process.env, env)+ const dir = await serviceAccountDir(namespaceFile ? 'posthog' : null)++ expect(() => loadConfig(dir)).toThrow(message)+ })+})diff --git a/services/integration-service/tests/unit/kubernetes.test.ts b/services/integration-service/tests/unit/kubernetes.test.tsnew file mode 100644index 000000000000..85f147b66c3e--- /dev/null+++ b/services/integration-service/tests/unit/kubernetes.test.ts@@ -0,0 +1,472 @@+import { SignJWT } from 'jose'+import { mkdtemp, rm, writeFile } from 'node:fs/promises'+import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'+import type { AddressInfo } from 'node:net'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { AUDIENCE } from '@/auth/types'+import { KubernetesSecretSource } from '@/kubernetes'+import type { Config } from '@/lib/config'+import { mountErrorsTotal, register, secretWatchRestartsTotal, servingStaleSeconds } from '@/metrics'+import { IntegrationServer } from '@/server'+import type { SecretSnapshot } from '@/source'++const NAMESPACE = 'posthog'+const SECRET_NAME = 'integration-service-secrets'+const KEY = 'HUBSPOT_APP_CLIENT_SECRET'+const SIGNING_KEY = 'k8s-test-signing-key'+const NEW_SIGNING_KEY = 'k8s-test-signing-key-new'++const WAIT = { timeout: 2000, interval: 5 }++interface Recorded {+ query: URLSearchParams+ auth: string | undefined+}++interface Watch extends Recorded {+ res: ServerResponse+ closed: boolean+}++/** Answers the list and watch calls the source makes, the way the API server does. */+class FakeApiServer {+ secret: { resourceVersion: string; data: Record<string, string> } | null = null+ listResourceVersion = '100'+ listStatus = 200+ /** Statuses to answer the next watch connections with, instead of opening a stream. */+ watchStatuses: number[] = []+ /** While set, list responses wait for it, so a test can deliver a watch event first. */+ holdLists: Promise<void> | null = null+ /** Like `holdLists`, but only for the next list, which is answered with the secret as it is now. */+ holdNextList: Promise<void> | null = null+ readonly lists: Recorded[] = []+ readonly watches: Watch[] = []++ private readonly server: Server = createServer((req, res) => void this.handle(req, res))++ async start(): Promise<string> {+ await new Promise<void>((resolve) => this.server.listen(0, '127.0.0.1', resolve))+ return `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`+ }++ async close(): Promise<void> {+ this.server.closeAllConnections()+ await new Promise<void>((resolve) => this.server.close(() => resolve()))+ }++ get openWatch(): Watch | undefined {+ return this.watches.filter((watch) => !watch.closed).at(-1)+ }++ /** Write one event to the open watch. */+ send(type: string, object: object): void {+ const watch = this.openWatch+ if (!watch) {+ throw new Error('no open watch')+ }+ watch.res.write(`${JSON.stringify({ type, object })}\n`)+ }++ private async handle(req: IncomingMessage, res: ServerResponse): Promise<void> {+ const url = new URL(req.url ?? '/', 'http://fake')+ expect(url.pathname).toBe(`/api/v1/namespaces/${NAMESPACE}/secrets`)+ const recorded = { query: url.searchParams, auth: req.headers.authorization }++ if (url.searchParams.get('watch') === '1') {+ const status = this.watchStatuses.shift()+ const watch: Watch = { ...recorded, res, closed: status !== undefined }+ this.watches.push(watch)+ if (status !== undefined) {+ res.statusCode = status+ res.end()+ return+ }+ res.on('close', () => {+ watch.closed = true+ })+ res.writeHead(200, { 'Content-Type': 'application/json' })+ res.flushHeaders()+ return+ }++ this.lists.push(recorded)+ const held = this.holdNextList+ this.holdNextList = null+ const body = JSON.stringify({+ kind: 'SecretList',+ metadata: { resourceVersion: this.listResourceVersion },+ items: this.secret ? [secretObject(this.secret.resourceVersion, this.secret.data)] : [],+ })+ await held+ await this.holdLists+ if (this.listStatus !== 200) {+ res.statusCode = this.listStatus+ res.end()+ return+ }+ res.end(body)+ }+}++function secretObject(resourceVersion: string, values: Record<string, string>): object {+ return {+ metadata: { name: SECRET_NAME, namespace: NAMESPACE, resourceVersion },+ data: Object.fromEntries(Object.entries(values).map(([k, v]) => [k, Buffer.from(v).toString('base64')])),+ }+}++const cleanups: (() => Promise<void> | void)[] = []++afterEach(async () => {+ for (const cleanup of cleanups.splice(0).reverse()) {+ await cleanup()+ }+ vi.useRealTimers()+})++async function fakeApi(values: Record<string, string> | null): Promise<{ api: FakeApiServer; url: string }> {+ const api = new FakeApiServer()+ if (values) {+ api.secret = { resourceVersion: '90', data: values }+ }+ const url = await api.start()+ cleanups.push(() => api.close())+ return { api, url }+}++async function tokenFile(token: string): Promise<string> {+ const dir = await mkdtemp(join(tmpdir(), 'integration-k8s-'))+ cleanups.push(() => rm(dir, { recursive: true, force: true }))+ const file = join(dir, 'token')+ await writeFile(file, token)+ return file+}++async function kubernetesSource(apiUrl: string, tokenPath?: string): Promise<KubernetesSecretSource> {+ const source = new KubernetesSecretSource({+ apiUrl,+ namespace: NAMESPACE,+ secretName: SECRET_NAME,+ tokenFile: tokenPath ?? (await tokenFile('token-1')),+ caFile: '/nonexistent/ca.crt',+ backoff: { initialMs: 1, maxMs: 5 },+ })+ cleanups.push(() => source.stop())+ return source+}++async function restarts(reason: string): Promise<number> {+ const values = (await secretWatchRestartsTotal.get()).values+ return values.find((v) => v.labels.reason === reason)?.value ?? 0+}++describe('kubernetes secret source', () => {+ beforeEach(() => {+ register.resetMetrics()+ })++ it('lists the secret by field selector and decodes it into one snapshot', async () => {+ const { api, url } = await fakeApi({ [KEY]: 'sec\n', __CALLER_KEY_POSTHOG_DJANGO: SIGNING_KEY })+ const source = await kubernetesSource(url)++ expect(await source.read()).toEqual({+ values: { [KEY]: 'sec', __CALLER_KEY_POSTHOG_DJANGO: SIGNING_KEY },+ revision: '90',+ })+ // RBAC restricted by resourceNames denies a list without this selector.+ expect(api.lists[0]?.query.get('fieldSelector')).toBe(`metadata.name=${SECRET_NAME}`)+ })++ it.each([+ ['the API server fails', 500],+ ['RBAC denies the read', 403],+ ])('reads nothing when %s', async (_label, status) => {+ const { api, url } = await fakeApi({ [KEY]: 'sec' })+ api.listStatus = status+ const source = await kubernetesSource(url)++ expect(await source.read()).toBeNull()+ })++ it('watches from the listed resourceVersion and pushes each change', async () => {+ const { api, url } = await fakeApi({ [KEY]: 'one' })+ const source = await kubernetesSource(url)+ await source.read()++ const pushed: (SecretSnapshot | null)[] = []+ source.watch((snapshot) => pushed.push(snapshot))+ await vi.waitFor(() => expect(api.openWatch).toBeDefined(), WAIT)++ const query = api.openWatch?.query+ expect(query?.get('resourceVersion')).toBe('100')+ expect(query?.get('fieldSelector')).toBe(`metadata.name=${SECRET_NAME}`)+ expect(query?.get('allowWatchBookmarks')).toBe('true')++ api.send('MODIFIED', secretObject('101', { [KEY]: 'two' }))+ await vi.waitFor(() => expect(pushed).toEqual([{ values: { [KEY]: 'two' }, revision: '101' }]), WAIT)+ })++ it('reconnects from the last resourceVersion when the watch closes, without listing again', async () => {+ const { api, url } = await fakeApi({ [KEY]: 'one' })+ const source = await kubernetesSource(url)+ await source.read()+ source.watch(() => {})+ await vi.waitFor(() => expect(api.openWatch).toBeDefined(), WAIT)++ // A bookmark moves the resourceVersion forward without a change to the secret.+ api.send('BOOKMARK', { metadata: { resourceVersion: '150' } })+ await new Promise((resolve) => setImmediate(resolve))+ api.openWatch?.res.end()++ await vi.waitFor(() => expect(api.watches).toHaveLength(2), WAIT)+ expect(api.watches[1]?.query.get('resourceVersion')).toBe('150')+ expect(api.lists).toHaveLength(1)+ expect(await restarts('closed')).toBe(1)+ })++ it.each([+ ['an ERROR event with code 410', 'event'],+ ['an HTTP 410 on connect', 'status'],+ ])('lists again and watches from the new resourceVersion after %s', async (_label, how) => {+ const { api, url } = await fakeApi({ [KEY]: 'one' })+ const source = await kubernetesSource(url)+ await source.read()+ if (how === 'status') {+ api.watchStatuses.push(410)+ }+ const pushed: (SecretSnapshot | null)[] = []+ source.watch((snapshot) => pushed.push(snapshot))++ if (how === 'event') {+ await vi.waitFor(() => expect(api.openWatch).toBeDefined(), WAIT)+ api.send('ERROR', { kind: 'Status', code: 410, reason: 'Expired' })+ }+ api.secret = { resourceVersion: '205', data: { [KEY]: 'two' } }+ api.listResourceVersion = '210'++ await vi.waitFor(() => expect(api.openWatch?.query.get('resourceVersion')).toBe('210'), WAIT)+ expect(api.lists).toHaveLength(2)+ expect(pushed).toEqual([{ values: { [KEY]: 'two' }, revision: '205' }])+ expect(await restarts('gone')).toBe(1)+ })++ it('backs off and retries when the watch cannot connect', async () => {+ const { api, url } = await fakeApi({ [KEY]: 'one' })+ api.watchStatuses.push(500, 500)+ const source = await kubernetesSource(url)+ await source.read()+ source.watch(() => {})++ await vi.waitFor(() => expect(api.openWatch).toBeDefined(), WAIT)+ expect(api.watches).toHaveLength(3)+ expect(api.openWatch?.query.get('resourceVersion')).toBe('100')+ expect(await restarts('error')).toBe(2)+ })++ it('reads the token file again for every request and watch connection', async () => {+ const { api, url } = await fakeApi({ [KEY]: 'one' })+ const file = await tokenFile('token-1')+ const source = await kubernetesSource(url, file)++ await source.read()+ source.watch(() => {})+ await vi.waitFor(() => expect(api.openWatch).toBeDefined(), WAIT)++ // Kubelet rotates the projected token in place.+ await writeFile(file, 'token-2\n')+ await source.read()+ api.openWatch?.res.end()+ await vi.waitFor(() => expect(api.watches).toHaveLength(2), WAIT)++ expect(api.lists.map((r) => r.auth)).toEqual(['Bearer token-1', 'Bearer token-2'])+ expect(api.watches.map((r) => r.auth)).toEqual(['Bearer token-1', 'Bearer token-2'])+ })++ // A watch can hang without an error. The safety read is what notices, and it must+ // replace the watch instead of leaving it stalled until the next change.+ it('replaces a watch that missed a change the safety read found', async () => {+ const { api, url } = await fakeApi({ [KEY]: 'one' })+ const source = await kubernetesSource(url)+ await source.read()+ source.watch(() => {})+ await vi.waitFor(() => expect(api.openWatch).toBeDefined(), WAIT)++ api.secret = { resourceVersion: '300', data: { [KEY]: 'two' } }+ api.listResourceVersion = '301'+ expect(await source.read()).toEqual({ values: { [KEY]: 'two' }, revision: '300' })++ await vi.waitFor(() => expect(api.openWatch?.query.get('resourceVersion')).toBe('301'), WAIT)+ expect(api.watches[0]?.closed).toBe(true)+ expect(await restarts('stalled')).toBe(1)+ })++ // The list started before the watch delivered a change, so its body is older. Returning+ // it would briefly undo the change, e.g. bring back a signing key a revocation removed.+ it('does not let a slower safety read undo a change the watch delivered', async () => {+ const { api, url } = await fakeApi({ [KEY]: 'old' })+ const source = await kubernetesSource(url)+ await source.read()+ source.watch(() => {})+ await vi.waitFor(() => expect(api.openWatch).toBeDefined(), WAIT)++ let release!: () => void+ api.holdLists = new Promise((resolve) => {+ release = resolve+ })+ const reading = source.read()+ await vi.waitFor(() => expect(api.lists).toHaveLength(2), WAIT)+ api.send('MODIFIED', secretObject('400', { [KEY]: 'new' }))+ await new Promise((resolve) => setTimeout(resolve, 10))+ release()++ expect(await reading).toEqual({ values: { [KEY]: 'new' }, revision: '400' })+ })++ it('discards a re-list after a 410 that a safety read overtook', async () => {+ const { api, url } = await fakeApi({ [KEY]: 'one' })+ const source = await kubernetesSource(url)+ await source.read()+ api.watchStatuses.push(410)+ let release!: () => void+ api.holdNextList = new Promise((resolve) => {+ release = resolve+ })+ const pushed: (SecretSnapshot | null)[] = []+ source.watch((snapshot) => pushed.push(snapshot))+ await vi.waitFor(() => expect(api.lists).toHaveLength(2), WAIT)++ api.secret = { resourceVersion: '500', data: { [KEY]: 'two' } }+ api.listResourceVersion = '501'+ expect(await source.read()).toEqual({ values: { [KEY]: 'two' }, revision: '500' })+ release()++ await vi.waitFor(() => expect(api.openWatch?.query.get('resourceVersion')).toBe('501'), WAIT)+ expect(pushed).toEqual([])+ })++ it('closes the watch and stops reconnecting once stopped', async () => {+ const { api, url } = await fakeApi({ [KEY]: 'one' })+ const source = await kubernetesSource(url)+ await source.read()+ source.watch(() => {})+ await vi.waitFor(() => expect(api.openWatch).toBeDefined(), WAIT)++ source.stop()++ await vi.waitFor(() => expect(api.watches[0]?.closed).toBe(true), WAIT)+ await new Promise((resolve) => setTimeout(resolve, 20))+ expect(api.watches).toHaveLength(1)+ expect(api.lists).toHaveLength(1)+ })+})++describe('integration server on the kubernetes source', () => {+ beforeEach(() => {+ register.resetMetrics()+ })++ function config(): Config {+ return {+ port: 0,+ host: '127.0.0.1',+ shutdownPrestopDelayMs: 0,+ env: 'test',+ mountDir: '/nonexistent/mount',+ reloadSeconds: 3600,+ metricsPort: 0,+ }+ }++ async function mint(signingKey: string): Promise<string> {+ return new SignJWT({ caller: 'warehouse-sources', keys: [KEY] })+ .setProtectedHeader({ alg: 'HS256' })+ .setAudience(AUDIENCE)+ .setIssuedAt()+ .setExpirationTime('5m')+ .sign(new TextEncoder().encode(signingKey))+ }++ async function boot(apiUrl: string): Promise<{+ server: IntegrationServer+ resolve: (signingKey: string) => Promise<Response>+ }> {+ let fetch!: (req: Request) => Response | Promise<Response>+ const server = new IntegrationServer(config(), {+ source: await kubernetesSource(apiUrl),+ serve: (options) => {+ fetch = options.fetch as typeof fetch+ return { close: (cb) => cb() }+ },+ exit: () => {},+ })+ await server.start()+ cleanups.push(() => server.stop('SIGTERM'))+ const resolve = async (signingKey: string): Promise<Response> =>+ await fetch(+ new Request('http://svc/v1/secrets/resolve', {+ method: 'POST',+ headers: { Authorization: `Bearer ${await mint(signingKey)}` },+ })+ )+ return { server, resolve }+ }++ // One edit of the secret can revoke a caller and rotate a credential. Both must come+ // from the same snapshot, so the revoked caller never reads the new value.+ it('applies a signing-key revocation and a credential change from one watch event', async () => {+ const { api, url } = await fakeApi({ [KEY]: 'value-1', __CALLER_KEY_TEST_DEPLOYMENT: SIGNING_KEY })+ const { server, resolve } = await boot(url)++ expect(server.lifecycleState().ready).toBe(true)+ expect(await (await resolve(SIGNING_KEY)).json()).toMatchObject({ secrets: { [KEY]: { value: 'value-1' } } })++ await vi.waitFor(() => expect(api.openWatch).toBeDefined(), WAIT)+ api.send('MODIFIED', secretObject('101', { [KEY]: 'value-2', __CALLER_KEY_TEST_DEPLOYMENT: NEW_SIGNING_KEY }))++ await vi.waitFor(async () => expect((await resolve(SIGNING_KEY)).status).toBe(401), WAIT)+ expect(await (await resolve(NEW_SIGNING_KEY)).json()).toMatchObject({+ secrets: { [KEY]: { value: 'value-2' } },+ })+ })++ it('stays not-ready while the API server is down at boot, then becomes ready', async () => {+ const { api, url } = await fakeApi({ [KEY]: 'value-1', __CALLER_KEY_TEST_DEPLOYMENT: SIGNING_KEY })+ api.listStatus = 503+ const { server, resolve } = await boot(url)++ expect(server.lifecycleState().ready).toBe(false)+ expect((await resolve(SIGNING_KEY)).status).toBe(401)++ api.listStatus = 200+ await vi.waitFor(() => expect(server.lifecycleState().ready).toBe(true), WAIT)+ expect((await resolve(SIGNING_KEY)).status).toBe(200)+ })++ it.each([+ ['the secret is deleted', 'deleted'],+ ['the API server is down at the safety read', 'down'],+ ])('keeps serving what it holds when %s, and says so on the metrics', async (_label, how) => {+ const { api, url } = await fakeApi({ [KEY]: 'value-1', __CALLER_KEY_TEST_DEPLOYMENT: SIGNING_KEY })+ const { server, resolve } = await boot(url)+ await vi.waitFor(() => expect(api.openWatch).toBeDefined(), WAIT)+ // Only Date is faked, so the sockets and the watch keep real timers.+ vi.useFakeTimers({ toFake: ['Date'] })+ vi.setSystemTime(Date.now() + 60 * 60 * 1000)++ if (how === 'deleted') {+ api.send('DELETED', secretObject('500', { [KEY]: 'value-1' }))+ await vi.waitFor(async () => expect((await mountErrorsTotal.get()).values[0]?.value).toBe(1), WAIT)+ } else {+ api.listStatus = 500+ await server.reload()+ expect((await mountErrorsTotal.get()).values[0]?.value).toBe(1)+ }++ expect(server.lifecycleState().ready).toBe(true)+ expect(await (await resolve(SIGNING_KEY)).json()).toMatchObject({ secrets: { [KEY]: { value: 'value-1' } } })+ expect(Math.round((await servingStaleSeconds.get()).values[0]?.value ?? 0)).toBe(3600)+ })+})