Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(control-api): validate Secret data keys at the SecretService chokepoint

Alfredo Lopezc01394e67d80
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index b3f3e6369..b131756a6 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.395",
+ "version": "0.1.396",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.395",
+ "version": "0.1.396",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-api/package.json b/control-api/package.json
index b422b1f3f..99b8d631e 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.395",
+ "version": "0.1.396",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/admin/recipes.ts b/control-api/src/routes/admin/recipes.ts
index 20659fe51..58a83f81f 100644
--- a/control-api/src/routes/admin/recipes.ts
+++ b/control-api/src/routes/admin/recipes.ts
@@ -15,6 +15,7 @@ import {
parseSecretOwnership,
} from '../../secretOwnership.js'
import { K8sNotFoundError } from '../../services/resourceService.js'
+import { invalidSecretDataKeyReason } from '../../services/secretKeys.js'
import {
validateWorkflowRecipeEgressPreflight,
validateWorkflowRecipeLimits,
@@ -91,7 +92,6 @@ const PROVIDER_OFFLINE_SCOPE: Record<string, string> = {
'microsoft-graph': 'offline_access',
}
-const SECRET_KEY_RE = /^[-._a-zA-Z0-9]+$/
const STEP_RUN_KEYS = new Set(['type', 'language', 'code', 'capabilities'])
const SENSITIVE_ENV_NAME_RE = /(PASSWORD|TOKEN|SECRET|API_KEY|CREDENTIAL|PRIVATE_KEY)/i
const TEMPLATE_INPUT_REF_RE = /\{\{\s*inputs\.([A-Za-z0-9_.-]+)\s*\}\}/g
@@ -215,13 +215,6 @@ function validateRecipeName(name: unknown): string | null {
return null
}
-function validateSecretKey(key: unknown): string | null {
- if (typeof key !== 'string' || key.length === 0 || !SECRET_KEY_RE.test(key)) {
- return 'secret key must contain only letters, digits, dot, dash, or underscore'
- }
- return null
-}
-
function sensitiveInputRefsInEnvValue(value: unknown): string[] {
if (typeof value !== 'string' || !value.includes('{{')) return []
@@ -740,7 +733,7 @@ export async function validateWorkflowRecipeSecretsAndCollectPending(
}
// imagePullSecrets carry no key — name + ownership are the only checks.
if (ref.kind !== 'imagePullSecret') {
- const keyErr = validateSecretKey(ref.key)
+ const keyErr = invalidSecretDataKeyReason(ref.key)
if (keyErr) {
errors.push({
field: secretRefKeyField(ref),
@@ -1601,7 +1594,7 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {
: {}
const stringData: Record<string, string> = {}
for (const [key, value] of Object.entries(rawData)) {
- const keyErr = validateSecretKey(key)
+ const keyErr = invalidSecretDataKeyReason(key)
if (keyErr) {
res.status(400).json({ error: keyErr, key })
return
diff --git a/control-api/src/routes/admin/secrets.ts b/control-api/src/routes/admin/secrets.ts
index 72432c6c5..82be1e0d4 100644
--- a/control-api/src/routes/admin/secrets.ts
+++ b/control-api/src/routes/admin/secrets.ts
@@ -11,6 +11,7 @@ import {
type SecretOwnership,
parseSecretOwnership,
} from '../../secretOwnership.js'
+import { invalidSecretDataKeyReason } from '../../services/secretKeys.js'
import { SecretUpsertRequest } from '../../types.js'
import { listHostSecrets } from './hostSecrets.js'
import { isLlmHostSecret } from './llmSecretIdentity.js'
@@ -324,8 +325,15 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
return
}
- // Ensure all values are strings
+ // Reject invalid Secret keys and non-string values up front so creating a
+ // Secret with a key the apiserver refuses returns a clear 400 instead of
+ // the opaque 500 (mirrors the rotation guard on the PUT route).
for (const [key, val] of Object.entries(data)) {
+ const keyError = invalidSecretDataKeyReason(key)
+ if (keyError) {
+ res.status(400).json({ error: keyError })
+ return
+ }
if (typeof val !== 'string') {
res.status(400).json({ error: `data["${key}"] must be a string` })
return
@@ -388,14 +396,9 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
return
}
for (const [key, val] of Object.entries(data)) {
- // A Kubernetes Secret data key must match [-._a-zA-Z0-9]+ AND is
- // additionally rejected by the apiserver when it is "." / ".." or longer
- // than 253 chars. Validate all three up front so an invalid key returns a
- // clear 400 instead of the opaque apiserver 500 this guard exists to avoid.
- if (!/^[A-Za-z0-9_.-]+$/.test(key) || key === '.' || key === '..' || key.length > 253) {
- res.status(400).json({
- error: `data key "${key}" is not a valid Secret key (only [-._a-zA-Z0-9], not "." or "..", max 253 chars)`,
- })
+ const keyError = invalidSecretDataKeyReason(key)
+ if (keyError) {
+ res.status(400).json({ error: keyError })
return
}
if (typeof val !== 'string') {
@@ -695,6 +698,11 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
return
}
for (const [key, val] of Object.entries(data)) {
+ const keyError = invalidSecretDataKeyReason(key)
+ if (keyError) {
+ res.status(400).json({ error: keyError })
+ return
+ }
if (typeof val !== 'string') {
res.status(400).json({ error: `data["${key}"] must be a string` })
return
@@ -764,6 +772,11 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
return
}
for (const [key, val] of dataEntries) {
+ const keyError = invalidSecretDataKeyReason(key)
+ if (keyError) {
+ res.status(400).json({ error: keyError })
+ return
+ }
if (typeof val !== 'string') {
res.status(400).json({ error: `data["${key}"] must be a string` })
return
diff --git a/control-api/src/services/secretKeys.ts b/control-api/src/services/secretKeys.ts
new file mode 100644
index 000000000..029f594ed
--- /dev/null
+++ b/control-api/src/services/secretKeys.ts
@@ -0,0 +1,70 @@
+// Kubernetes Secret data-key validation, centralized so every write path shares
+// ONE definition of "valid key". A Secret data key must satisfy the apiserver's
+// IsConfigMapKey check: it matches [-._a-zA-Z0-9]+, is neither "." nor "..", and
+// is at most 253 characters. A key that fails any of these is rejected by the
+// apiserver with an opaque 500; validating here turns that into an actionable
+// 400 at the single chokepoint (SecretService) every Secret write passes
+// through, so no route — present or future — can leak an invalid key to k8s.
+
+export const SECRET_DATA_KEY_RE = /^[-._a-zA-Z0-9]+$/
+export const SECRET_DATA_KEY_MAX_LENGTH = 253
+
+// The one message used by both the route-level reason string and the thrown
+// error, so an operator sees identical wording no matter which layer rejects.
+function secretKeyErrorMessage(key: string): string {
+ return `data key "${key}" is not a valid Secret key (only [-._a-zA-Z0-9], not "." or "..", max ${SECRET_DATA_KEY_MAX_LENGTH} chars)`
+}
+
+// Thrown when a Secret data key cannot be a valid Kubernetes key. Carries
+// `status = 400` so control-api's global error handler (app.ts) forwards it to
+// the client as a 400 instead of collapsing it into a 500 — the same mechanism
+// HostEnvServiceError relies on.
+export class InvalidSecretKeyError extends Error {
+ readonly status = 400
+ readonly key: string
+ constructor(key: string) {
+ super(secretKeyErrorMessage(key))
+ this.name = 'InvalidSecretKeyError'
+ this.key = key
+ }
+}
+
+// Returns a human-readable reason when `key` is not a valid Secret data key, or
+// null when it is valid. Route boundaries that already validate call this to
+// emit an early 400 with a plain `{ error }` body before touching the service
+// layer; the service layer enforces the same rule as a hard invariant.
+export function invalidSecretDataKeyReason(key: string): string | null {
+ if (
+ !SECRET_DATA_KEY_RE.test(key) ||
+ key === '.' ||
+ key === '..' ||
+ key.length > SECRET_DATA_KEY_MAX_LENGTH
+ ) {
+ return secretKeyErrorMessage(key)
+ }
+ return null
+}
+
+// Throws InvalidSecretKeyError on an invalid key. Called inside SecretService so
+// no single-key write (removeSecretKey) can carry a key the apiserver rejects.
+export function assertValidSecretDataKey(key: string): void {
+ if (invalidSecretDataKeyReason(key) !== null) {
+ throw new InvalidSecretKeyError(key)
+ }
+}
+
+// Validates every key in a Secret write payload (both `data` and `stringData`),
+// throwing InvalidSecretKeyError on the first invalid key. This is the invariant
+// enforced inside SecretService's create/update/merge ops: any Secret write,
+// from any route present or future, is guaranteed to carry only valid keys.
+export function assertValidSecretWriteKeys(req: {
+ data?: Record<string, unknown>
+ stringData?: Record<string, unknown>
+}): void {
+ if (req.data) {
+ for (const key of Object.keys(req.data)) assertValidSecretDataKey(key)
+ }
+ if (req.stringData) {
+ for (const key of Object.keys(req.stringData)) assertValidSecretDataKey(key)
+ }
+}
diff --git a/control-api/src/services/secretService.ts b/control-api/src/services/secretService.ts
index 0fd214a4c..41d8401b5 100644
--- a/control-api/src/services/secretService.ts
+++ b/control-api/src/services/secretService.ts
@@ -1,5 +1,6 @@
import * as k8s from '@kubernetes/client-node'
import { SecretUpsertRequest } from '../types.js'
+import { assertValidSecretDataKey, assertValidSecretWriteKeys } from './secretKeys.js'
export class SecretService {
constructor(
@@ -30,6 +31,7 @@ export class SecretService {
}
async createSecret(req: SecretUpsertRequest): Promise<unknown> {
+ assertValidSecretWriteKeys(req)
const body: k8s.V1Secret = {
apiVersion: 'v1',
kind: 'Secret',
@@ -62,6 +64,7 @@ export class SecretService {
* keys must survive a partial update, use `mergeSecret` instead.
*/
async updateSecret(req: SecretUpsertRequest): Promise<unknown> {
+ assertValidSecretWriteKeys(req)
const ns = req.namespace || this.defaultNamespace
const existing = await this.coreApi.readNamespacedSecret({ namespace: ns, name: req.name })
@@ -101,6 +104,7 @@ export class SecretService {
* routes that target other namespaces unless their Role has been updated.
*/
async mergeSecret(req: SecretUpsertRequest): Promise<unknown> {
+ assertValidSecretWriteKeys(req)
const ns = req.namespace || this.defaultNamespace
const body: Partial<k8s.V1Secret> = {}
@@ -125,6 +129,7 @@ export class SecretService {
}
async removeSecretKey(req: { name: string; namespace?: string; key: string }): Promise<unknown> {
+ assertValidSecretDataKey(req.key)
const ns = req.namespace || this.defaultNamespace
const body = { data: { [req.key]: null } } as unknown as Partial<k8s.V1Secret>
diff --git a/control-api/test/services.secretService.test.ts b/control-api/test/services.secretService.test.ts
new file mode 100644
index 000000000..df4d13726
--- /dev/null
+++ b/control-api/test/services.secretService.test.ts
@@ -0,0 +1,173 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import * as k8s from '@kubernetes/client-node'
+import {
+ InvalidSecretKeyError,
+ SECRET_DATA_KEY_MAX_LENGTH,
+ invalidSecretDataKeyReason,
+} from '../src/services/secretKeys.js'
+import { SecretService } from '../src/services/secretService.js'
+
+// A key the Kubernetes apiserver rejects (IsConfigMapKey). Feeding any of these
+// to a Secret write must fail here with a 400 BEFORE the apiserver ever sees it,
+// never as the opaque 500 the apiserver would return.
+const INVALID_KEYS: readonly string[] = [
+ '.', // reserved
+ '..', // reserved
+ 'foo/bar', // slash outside charset
+ 'has space', // space outside charset
+ 'key@host', // @ outside charset
+ 'café', // non-ASCII outside charset
+ '', // empty
+ 'x'.repeat(SECRET_DATA_KEY_MAX_LENGTH + 1), // 254 chars, over the limit
+]
+
+// Keys that are legitimate Secret data keys and MUST keep flowing through to the
+// apiserver untouched (env var names, credential slots, TLS files, dotted keys).
+const VALID_KEYS: readonly string[] = [
+ 'LINEAR_API_KEY',
+ 'openai-api-key',
+ 'tls.crt',
+ 'api-key',
+ 'foo.bar',
+ 'a'.repeat(SECRET_DATA_KEY_MAX_LENGTH), // exactly 253 chars
+]
+
+type CoreApiMock = {
+ readNamespacedSecret: ReturnType<typeof vi.fn>
+ createNamespacedSecret: ReturnType<typeof vi.fn>
+ replaceNamespacedSecret: ReturnType<typeof vi.fn>
+ patchNamespacedSecret: ReturnType<typeof vi.fn>
+ deleteNamespacedSecret: ReturnType<typeof vi.fn>
+}
+
+function createCoreApiMock(): CoreApiMock {
+ return {
+ readNamespacedSecret: vi.fn().mockResolvedValue({ metadata: {}, type: 'Opaque', data: {} }),
+ createNamespacedSecret: vi.fn().mockResolvedValue({ metadata: { name: 's' } }),
+ replaceNamespacedSecret: vi.fn().mockResolvedValue({ metadata: { name: 's' } }),
+ patchNamespacedSecret: vi.fn().mockResolvedValue({ metadata: { name: 's' } }),
+ deleteNamespacedSecret: vi.fn().mockResolvedValue({}),
+ }
+}
+
+describe('SecretService — invalid Secret keys never reach the apiserver', () => {
+ let coreApi: CoreApiMock
+ let svc: SecretService
+
+ beforeEach(() => {
+ coreApi = createCoreApiMock()
+ svc = new SecretService(coreApi as unknown as k8s.CoreV1Api, 'test-ns')
+ })
+
+ // Every write op that carries a data payload rejects an invalid key up front.
+ // The second assertion is the real invariant: the apiserver client is never
+ // touched, so no invalid key can produce the opaque apiserver 500.
+ const payloadOps: ReadonlyArray<{
+ name: string
+ call: (key: string) => Promise<unknown>
+ apiSurface: (keyof CoreApiMock)[]
+ }> = [
+ {
+ name: 'createSecret',
+ call: key =>
+ svc.createSecret({ name: 's', namespace: 'test-ns', stringData: { [key]: 'v' } }),
+ apiSurface: ['createNamespacedSecret'],
+ },
+ {
+ name: 'updateSecret',
+ call: key =>
+ svc.updateSecret({ name: 's', namespace: 'test-ns', stringData: { [key]: 'v' } }),
+ // The guard runs before the read, so neither read nor replace is reached.
+ apiSurface: ['readNamespacedSecret', 'replaceNamespacedSecret'],
+ },
+ {
+ name: 'mergeSecret',
+ call: key => svc.mergeSecret({ name: 's', namespace: 'test-ns', stringData: { [key]: 'v' } }),
+ apiSurface: ['patchNamespacedSecret'],
+ },
+ ]
+
+ for (const op of payloadOps) {
+ describe(op.name, () => {
+ for (const badKey of INVALID_KEYS) {
+ it(`rejects key ${JSON.stringify(badKey)} with a 400 and never calls the apiserver`, async () => {
+ const err = await op.call(badKey).then(
+ () => {
+ throw new Error('expected the write to reject')
+ },
+ (e: unknown) => e
+ )
+ expect(err).toBeInstanceOf(InvalidSecretKeyError)
+ expect((err as InvalidSecretKeyError).status).toBe(400)
+ for (const surface of op.apiSurface) {
+ expect(coreApi[surface]).not.toHaveBeenCalled()
+ }
+ })
+ }
+
+ for (const goodKey of VALID_KEYS) {
+ it(`lets valid key ${JSON.stringify(goodKey)} through to the apiserver`, async () => {
+ await op.call(goodKey)
+ // The op reached its apiserver call (the last surface is the write).
+ const writeSurface = op.apiSurface[op.apiSurface.length - 1]
+ expect(coreApi[writeSurface]).toHaveBeenCalledOnce()
+ })
+ }
+ })
+ }
+
+ // removeSecretKey validates the single key it is asked to drop: an invalid key
+ // can never exist on a Secret, so this is a 400, not a merge-patch attempt.
+ describe('removeSecretKey', () => {
+ for (const badKey of INVALID_KEYS) {
+ it(`rejects key ${JSON.stringify(badKey)} with a 400 and never calls the apiserver`, async () => {
+ const err = await svc
+ .removeSecretKey({ name: 's', namespace: 'test-ns', key: badKey })
+ .then(
+ () => {
+ throw new Error('expected the removal to reject')
+ },
+ (e: unknown) => e
+ )
+ expect(err).toBeInstanceOf(InvalidSecretKeyError)
+ expect((err as InvalidSecretKeyError).status).toBe(400)
+ expect(coreApi.patchNamespacedSecret).not.toHaveBeenCalled()
+ })
+ }
+
+ it('lets a valid key through to a merge-patch', async () => {
+ await svc.removeSecretKey({ name: 's', namespace: 'test-ns', key: 'LINEAR_API_KEY' })
+ expect(coreApi.patchNamespacedSecret).toHaveBeenCalledOnce()
+ })
+ })
+
+ // A payload can carry an invalid key in `data` (base64) as well as `stringData`.
+ it('validates keys in the base64 `data` map too, not only stringData', async () => {
+ const err = await svc
+ .createSecret({ name: 's', namespace: 'test-ns', data: { 'bad/key': 'dg==' } })
+ .then(
+ () => {
+ throw new Error('expected the write to reject')
+ },
+ (e: unknown) => e
+ )
+ expect(err).toBeInstanceOf(InvalidSecretKeyError)
+ expect(coreApi.createNamespacedSecret).not.toHaveBeenCalled()
+ })
+})
+
+describe('invalidSecretDataKeyReason — the shared rule', () => {
+ it('accepts every legitimate key', () => {
+ for (const key of VALID_KEYS) {
+ expect(invalidSecretDataKeyReason(key)).toBeNull()
+ }
+ })
+
+ it('rejects every apiserver-invalid key with an actionable message', () => {
+ for (const key of INVALID_KEYS) {
+ const reason = invalidSecretDataKeyReason(key)
+ expect(reason).not.toBeNull()
+ expect(reason).toContain('not a valid Secret key')
+ }
+ })
+})