Skip to content

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

TypeScript

fix(control-api): keep secret writes names-only

Alfredo Lopez645897f3837a
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index d6782a6cb..e0697b7ef 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.488",
+ "version": "0.1.489",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.488",
+ "version": "0.1.489",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index 895f64295..ed0cabcc0 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.488",
+ "version": "0.1.489",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/k8s.ts b/control-api/src/k8s.ts
index 2c5f3ad25..d14d50977 100644
--- a/control-api/src/k8s.ts
+++ b/control-api/src/k8s.ts
@@ -1,5 +1,6 @@
import * as k8s from '@kubernetes/client-node'
import { config } from './config.js'
+import { rootLogger } from './observability/logger.js'
import { HostEnvService } from './services/hostEnvService.js'
import { HostOverviewService } from './services/hostOverviewService.js'
import {
@@ -7,7 +8,11 @@ import {
LlmAllowedModelsConfigMapWriter,
} from './services/llmAllowedModelsConfigMap.js'
import { ResourceService, mergeAnnotationsForReplace } from './services/resourceService.js'
-import { SecretService } from './services/secretService.js'
+import {
+ type DeleteSecretSummary,
+ SecretService,
+ type SecretSummary,
+} from './services/secretService.js'
import {
ClerumResourceType,
HostOverview,
@@ -15,6 +20,8 @@ import {
SecretUpsertRequest,
} from './types.js'
+const logger = rootLogger.child({ module: 'k8s-gateway' })
+
/**
* Namespaces where exec operations are permitted.
* control-api is the master control — RBAC stays cluster-wide,
@@ -401,7 +408,7 @@ export class K8sGateway {
return this.secrets.getSecret(name, namespace)
}
- async createSecret(req: SecretUpsertRequest): Promise<unknown> {
+ async createSecret(req: SecretUpsertRequest): Promise<SecretSummary> {
return this.secrets.createSecret(req)
}
@@ -409,15 +416,19 @@ export class K8sGateway {
async updateSecret(
req: SecretUpsertRequest,
precondition?: SecretPreconditions
- ): Promise<unknown> {
+ ): Promise<SecretSummary> {
return this.secrets.updateSecret(req, precondition)
}
- async mergeSecret(req: SecretUpsertRequest): Promise<unknown> {
+ async mergeSecret(req: SecretUpsertRequest): Promise<SecretSummary> {
return this.secrets.mergeSecret(req)
}
- async removeSecretKey(req: { name: string; namespace?: string; key: string }): Promise<unknown> {
+ async removeSecretKey(req: {
+ name: string
+ namespace?: string
+ key: string
+ }): Promise<SecretSummary> {
return this.secrets.removeSecretKey(req)
}
@@ -426,7 +437,7 @@ export class K8sGateway {
name: string,
namespace?: string,
precondition?: SecretPreconditions
- ): Promise<unknown> {
+ ): Promise<DeleteSecretSummary> {
return this.secrets.deleteSecret(name, namespace, precondition)
}
@@ -553,9 +564,14 @@ export class K8sGateway {
if (isExecOutputLimitError(findError)) throw findError
// BusyBox find (Alpine/node images) lacks -printf. Keep -type f in the
// fallback so directories and symlinks do not become downloadable entries.
- console.warn(
- 'find -printf failed, falling back to find -type f:',
- findError instanceof Error ? findError.message : String(findError)
+ logger.warn(
+ {
+ event: 'artifact-listing-find-printf-unsupported',
+ podName,
+ namespace,
+ containerName,
+ },
+ 'find -printf failed; falling back to find -type f'
)
return this.execRaw(
podName,
@@ -727,9 +743,9 @@ export async function listRecipePodsAcrossNamespaces(
} catch (err) {
const status = extractHttpStatus(err)
if (status === 403 || status === 404) {
- console.warn(
- `listPodsForRecipe: skipping namespace "${namespace}" (HTTP ${status}) — ` +
- 'control-api lacks pod list RBAC there or the namespace does not exist'
+ logger.warn(
+ { namespace, status, recipeName },
+ 'Skipping recipe pod namespace without list access'
)
return []
}
diff --git a/control-api/src/routes/admin/communicationChannelCredentials.ts b/control-api/src/routes/admin/communicationChannelCredentials.ts
index 306638f2d..f8bc4b4e4 100644
--- a/control-api/src/routes/admin/communicationChannelCredentials.ts
+++ b/control-api/src/routes/admin/communicationChannelCredentials.ts
@@ -4,6 +4,7 @@ import { asyncHandler } from '../../http/asyncHandler.js'
import { enforceNamespace } from '../../http/namespaceAudit.js'
import type { K8sGateway } from '../../k8s.js'
import { secretKeyNames } from '../../services/secretKeyNames.js'
+import { toPublicSecretSummary } from '../../services/secretService.js'
function ccCredentialsSecretName(ccName: string): string {
return `cc-${ccName}-credentials`
@@ -115,7 +116,7 @@ export function registerCommunicationChannelCredentialsRoutes(
secretName: existingSecretName,
namespace: ns,
rotated: true,
- result: merged,
+ result: toPublicSecretSummary(merged),
})
return
}
diff --git a/control-api/src/routes/admin/secrets.ts b/control-api/src/routes/admin/secrets.ts
index 0ec553766..8951c8e3d 100644
--- a/control-api/src/routes/admin/secrets.ts
+++ b/control-api/src/routes/admin/secrets.ts
@@ -6,6 +6,7 @@ import { asyncHandler } from '../../http/asyncHandler.js'
import { enforceNamespace } from '../../http/namespaceAudit.js'
import { isValidDNSSubdomain } from '../../http/rfc1123.js'
import { K8sGateway, extractHttpStatus } from '../../k8s.js'
+import { rootLogger } from '../../observability/logger.js'
import {
OWNER_RECIPE_LABEL_KEY,
SHARED_LABEL_KEY,
@@ -13,10 +14,13 @@ import {
parseSecretOwnership,
} from '../../secretOwnership.js'
import { invalidSecretDataKeyReason } from '../../services/secretKeys.js'
+import { toPublicDeleteSecretSummary, toPublicSecretSummary } from '../../services/secretService.js'
import { SecretUpsertRequest } from '../../types.js'
import { listHostSecrets } from './hostSecrets.js'
import { isLlmHostSecret } from './llmSecretIdentity.js'
+const logger = rootLogger
+
// The bedrock credential-slot keys and the vertex service-account key, derived
// from the shared provider package (never hardcoded here) so the write-side
// gate cannot drift from the UI's client-side gate (spec R4.5.3).
@@ -142,7 +146,7 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
namespace: config.secretsNamespace,
} as SecretUpsertRequest
const created = await gateway.createSecret(body)
- res.status(201).json(created)
+ res.status(201).json(toPublicSecretSummary(created))
})
)
@@ -242,7 +246,7 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
res.status(400).json({ error: llmSlotError })
return
}
- await gateway.updateSecret({
+ const updated = await gateway.updateSecret({
name: name.trim(),
namespace: config.secretsNamespace,
type: (req.body as { type?: string }).type,
@@ -252,11 +256,7 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
// base64 VALUES of every stored key — including keys the caller did NOT
// send (other providers' credentials). The R4 contract is names-only
// everywhere, so the response returns only the resulting key names.
- res.status(200).json({
- name: name.trim(),
- namespace: config.secretsNamespace,
- keys: Object.keys(mergedData).sort((a, b) => a.localeCompare(b)),
- })
+ res.status(200).json(toPublicSecretSummary(updated))
return
}
@@ -291,7 +291,7 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
namespace: config.secretsNamespace,
} as SecretUpsertRequest
const updated = await gateway.updateSecret(body)
- res.status(200).json(updated)
+ res.status(200).json(toPublicSecretSummary(updated))
})
)
@@ -300,7 +300,7 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
enforceNamespace(config.secretsNamespace),
asyncHandler(async (req, res) => {
const deleted = await gateway.deleteSecret(req.params.name, config.secretsNamespace)
- res.status(200).json(deleted)
+ res.status(200).json(toPublicDeleteSecretSummary(deleted))
})
)
@@ -370,8 +370,8 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
stringData: data,
}
- const created = await gateway.createSecret(secretReq)
- res.status(201).json({ name: name.trim(), namespace: targetNs, created: Boolean(created) })
+ await gateway.createSecret(secretReq)
+ res.status(201).json({ name: name.trim(), namespace: targetNs, created: true })
})
)
@@ -480,23 +480,21 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
return
}
- await gateway.mergeSecret({ name, namespace: targetNs, stringData: data })
-
- const keys = [...new Set([...Object.keys(existing.data || {}), ...Object.keys(data)])].sort(
- (a, b) => a.localeCompare(b)
- )
+ const merged = await gateway.mergeSecret({ name, namespace: targetNs, stringData: data })
// The credential IS rotated at this point. Emit the audit record NOW,
// before anything that could throw — a rotation that actually happened
// must never go unlogged just because a later, secondary step failed.
// Key NAMES are safe to log; values never are.
- console.log(
- JSON.stringify({
+ logger.info(
+ {
+ module: 'admin-secrets',
event: 'mcp-secret-rotated',
name,
namespace: targetNs,
rotatedKeys: Object.keys(data).sort((a, b) => a.localeCompare(b)),
- })
+ },
+ 'MCP Secret rotated'
)
// affectedConnectors is a best-effort convenience for the UI ("who
@@ -516,18 +514,24 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
.map(item => (item as { metadata?: { name?: string } }).metadata?.name)
.filter((connector): connector is string => typeof connector === 'string')
.sort((a, b) => a.localeCompare(b))
- } catch (err) {
- console.warn(
- JSON.stringify({
+ } catch {
+ logger.warn(
+ {
+ module: 'admin-secrets',
event: 'mcp-secret-rotated-affected-connectors-unavailable',
name,
namespace: targetNs,
- error: err instanceof Error ? err.message : String(err),
- })
+ },
+ 'Affected connectors unavailable after MCP Secret rotation'
)
}
- res.status(200).json({ name, namespace: targetNs, keys, affectedConnectors })
+ res.status(200).json({
+ name: merged.name,
+ namespace: merged.namespace,
+ keys: [...merged.keys],
+ affectedConnectors,
+ })
})
)
@@ -545,7 +549,7 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
return
}
const deleted = await gateway.deleteSecret(req.params.name, config.mcpServersNamespace)
- res.status(200).json(deleted)
+ res.status(200).json(toPublicDeleteSecretSummary(deleted))
})
)
@@ -642,12 +646,14 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
: typeof (err as { code?: unknown }).code === 'number'
? (err as { code: number }).code
: undefined
- console.warn(
- JSON.stringify({
+ logger.warn(
+ {
+ module: 'admin-secrets',
event: 'recipe-secret-namespace-list-degraded',
namespace,
statusCode,
- })
+ },
+ 'Recipe Secret namespace listing degraded'
)
return { namespace, items: [] }
}
@@ -781,12 +787,12 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
stringData: data,
}
- const created = await gateway.createSecret(secretReq)
+ await gateway.createSecret(secretReq)
res.status(201).json({
name: name.trim(),
namespace: targetNamespace,
ownership,
- created: Boolean(created),
+ created: true,
})
})
)
@@ -876,7 +882,7 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
}
const updated = await gateway.updateSecret(secretReq)
- res.status(200).json(updated)
+ res.status(200).json(toPublicSecretSummary(updated))
})
)
@@ -896,7 +902,7 @@ export function createAdminSecretsRouter(gateway: K8sGateway): Router {
return
}
const deleted = await gateway.deleteSecret(name, targetNamespace)
- res.status(200).json(deleted)
+ res.status(200).json(toPublicDeleteSecretSummary(deleted))
})
)
diff --git a/control-api/src/services/secretService.ts b/control-api/src/services/secretService.ts
index 6ff92ef00..fe7971b86 100644
--- a/control-api/src/services/secretService.ts
+++ b/control-api/src/services/secretService.ts
@@ -2,6 +2,57 @@ import * as k8s from '@kubernetes/client-node'
import { SecretPreconditions, SecretUpsertRequest } from '../types.js'
import { assertValidSecretDataKey, assertValidSecretWriteKeys } from './secretKeys.js'
+export interface SecretSummary {
+ name: string
+ namespace: string
+ keys: string[]
+}
+
+export interface DeleteSecretSummary {
+ name: string
+ namespace: string
+ deleted: true
+}
+
+export function toPublicSecretSummary(summary: SecretSummary): SecretSummary {
+ return {
+ name: summary.name,
+ namespace: summary.namespace,
+ keys: [...summary.keys],
+ }
+}
+
+export function toPublicDeleteSecretSummary(summary: DeleteSecretSummary): DeleteSecretSummary {
+ return {
+ name: summary.name,
+ namespace: summary.namespace,
+ deleted: true,
+ }
+}
+
+type Assert<T extends true> = T
+type HasExactKeys<T, Keys extends PropertyKey> =
+ Exclude<keyof T, Keys> extends never
+ ? Exclude<Keys, keyof T> extends never
+ ? true
+ : false
+ : false
+
+// Compile-time ratchet: adding `data`, `stringData`, or another field to either
+// public write DTO fails the production typecheck.
+type _SecretSummaryIsNamesOnly = Assert<HasExactKeys<SecretSummary, 'name' | 'namespace' | 'keys'>>
+type _DeleteSecretSummaryIsNamesOnly = Assert<
+ HasExactKeys<DeleteSecretSummary, 'name' | 'namespace' | 'deleted'>
+>
+
+function summarizeSecret(result: k8s.V1Secret, name: string, namespace: string): SecretSummary {
+ return toPublicSecretSummary({
+ name,
+ namespace,
+ keys: Object.keys(result.data ?? {}).sort((a, b) => a.localeCompare(b)),
+ })
+}
+
export class SecretService {
constructor(
private readonly coreApi: k8s.CoreV1Api,
@@ -15,7 +66,6 @@ export class SecretService {
name: s.metadata?.name,
namespace: s.metadata?.namespace,
labels: s.metadata?.labels || {},
- annotations: s.metadata?.annotations || {},
},
type: s.type,
keys: Object.keys(s.data || {}).sort((a, b) => a.localeCompare(b)),
@@ -30,14 +80,15 @@ export class SecretService {
return this.coreApi.readNamespacedSecret({ namespace, name })
}
- async createSecret(req: SecretUpsertRequest): Promise<unknown> {
+ async createSecret(req: SecretUpsertRequest): Promise<SecretSummary> {
assertValidSecretWriteKeys(req)
+ const ns = req.namespace || this.defaultNamespace
const body: k8s.V1Secret = {
apiVersion: 'v1',
kind: 'Secret',
metadata: {
name: req.name,
- namespace: req.namespace || this.defaultNamespace,
+ namespace: ns,
labels: req.labels,
annotations: req.annotations,
},
@@ -46,10 +97,8 @@ export class SecretService {
stringData: req.stringData,
}
- return this.coreApi.createNamespacedSecret({
- namespace: req.namespace || this.defaultNamespace,
- body,
- })
+ const created = await this.coreApi.createNamespacedSecret({ namespace: ns, body })
+ return summarizeSecret(created, req.name, ns)
}
/**
@@ -77,7 +126,7 @@ export class SecretService {
async updateSecret(
req: SecretUpsertRequest,
precondition?: SecretPreconditions
- ): Promise<unknown> {
+ ): Promise<SecretSummary> {
assertValidSecretWriteKeys(req)
const ns = req.namespace || this.defaultNamespace
const existing = precondition?.resourceVersion
@@ -102,7 +151,12 @@ export class SecretService {
stringData: req.stringData,
}
- return this.coreApi.replaceNamespacedSecret({ namespace: ns, name: req.name, body })
+ const updated = await this.coreApi.replaceNamespacedSecret({
+ namespace: ns,
+ name: req.name,
+ body,
+ })
+ return summarizeSecret(updated, req.name, ns)
}
/**
@@ -125,7 +179,7 @@ export class SecretService {
* from a route targeting any OTHER namespace unless that namespace's Role
* has been granted `patch`.
*/
- async mergeSecret(req: SecretUpsertRequest): Promise<unknown> {
+ async mergeSecret(req: SecretUpsertRequest): Promise<SecretSummary> {
assertValidSecretWriteKeys(req)
const ns = req.namespace || this.defaultNamespace
@@ -138,7 +192,7 @@ export class SecretService {
if (req.labels !== undefined) body.metadata = { labels: req.labels }
if (req.type !== undefined) body.type = req.type
- return this.coreApi.patchNamespacedSecret(
+ const merged = await this.coreApi.patchNamespacedSecret(
{
namespace: ns,
name: req.name,
@@ -148,14 +202,19 @@ export class SecretService {
middleware: [k8s.setHeaderMiddleware('Content-Type', 'application/merge-patch+json')],
}
)
+ return summarizeSecret(merged, req.name, ns)
}
- async removeSecretKey(req: { name: string; namespace?: string; key: string }): Promise<unknown> {
+ async removeSecretKey(req: {
+ name: string
+ namespace?: string
+ key: string
+ }): Promise<SecretSummary> {
assertValidSecretDataKey(req.key)
const ns = req.namespace || this.defaultNamespace
const body = { data: { [req.key]: null } } as unknown as Partial<k8s.V1Secret>
- return this.coreApi.patchNamespacedSecret(
+ const updated = await this.coreApi.patchNamespacedSecret(
{
namespace: ns,
name: req.name,
@@ -165,6 +224,7 @@ export class SecretService {
middleware: [k8s.setHeaderMiddleware('Content-Type', 'application/merge-patch+json')],
}
)
+ return summarizeSecret(updated, req.name, ns)
}
/**
@@ -182,10 +242,11 @@ export class SecretService {
name: string,
namespace?: string,
precondition?: SecretPreconditions
- ): Promise<unknown> {
+ ): Promise<DeleteSecretSummary> {
+ const ns = namespace || this.defaultNamespace
const hasPrecondition = Boolean(precondition?.uid || precondition?.resourceVersion)
- return this.coreApi.deleteNamespacedSecret({
- namespace: namespace || this.defaultNamespace,
+ await this.coreApi.deleteNamespacedSecret({
+ namespace: ns,
name,
...(hasPrecondition && {
body: {
@@ -198,5 +259,6 @@ export class SecretService {
},
}),
})
+ return { name, namespace: ns, deleted: true }
}
}
diff --git a/control-api/test/k8s.execSecurity.test.ts b/control-api/test/k8s.execSecurity.test.ts
index 271cc262a..5efa652c6 100644
--- a/control-api/test/k8s.execSecurity.test.ts
+++ b/control-api/test/k8s.execSecurity.test.ts
@@ -12,6 +12,17 @@ import {
validateExecParams,
} from '../src/k8s.js'
+const log = vi.hoisted(() => ({
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+}))
+
+vi.mock('../src/observability/logger.js', () => ({
+ rootLogger: { child: () => log },
+}))
+
// ── Module-level constants ──────────────────────────────────────────────
describe('ALLOWED_EXEC_NAMESPACES', () => {
@@ -312,20 +323,21 @@ describe('artifact listing commands', () => {
})
it('caps BusyBox fallback listing output from pod exec', async () => {
+ const sentinel = 'RP231_NESTED_ERROR_SENTINEL'
const execRaw = vi
.fn()
- .mockRejectedValueOnce(new Error('find: unrecognized: -printf'))
+ .mockRejectedValueOnce(
+ Object.assign(new Error('find: unrecognized: -printf'), {
+ response: { body: { value: sentinel } },
+ })
+ )
.mockResolvedValueOnce('report.md\n')
const gateway = makeGatewayWithExecRaw(execRaw)
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
-
- try {
- await expect(
- gateway.listFilesInDirectory('pod-1', 'mcp-host', undefined, '/tmp/clerum-output/')
- ).resolves.toContain('report.md')
- } finally {
- warnSpy.mockRestore()
- }
+ log.warn.mockClear()
+
+ await expect(
+ gateway.listFilesInDirectory('pod-1', 'mcp-host', undefined, '/tmp/clerum-output/')
+ ).resolves.toContain('report.md')
expect(execRaw).toHaveBeenNthCalledWith(
2,
@@ -336,6 +348,18 @@ describe('artifact listing commands', () => {
MAX_ARTIFACT_LISTING_BYTES,
'Artifact listing too large to return'
)
+ expect(log.warn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: 'artifact-listing-find-printf-unsupported',
+ podName: 'pod-1',
+ namespace: 'mcp-host',
+ }),
+ 'find -printf failed; falling back to find -type f'
+ )
+ const [fields] = log.warn.mock.calls[0]
+ expect(fields).not.toHaveProperty('err')
+ expect(fields).not.toHaveProperty('directory')
+ expect(JSON.stringify(log.warn.mock.calls)).not.toContain(sentinel)
})
it('does not fall back when the metadata listing exceeds the cap', async () => {
diff --git a/control-api/test/routes.adminChannelWriteResponse.test.ts b/control-api/test/routes.adminChannelWriteResponse.test.ts
new file mode 100644
index 000000000..a85dda46c
--- /dev/null
+++ b/control-api/test/routes.adminChannelWriteResponse.test.ts
@@ -0,0 +1,69 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import type { K8sGateway } from '../src/k8s.js'
+import { createAdminResourcesRouter } from '../src/routes/admin/resources.js'
+
+const gateway = {
+ createResource: vi.fn(),
+ deleteResource: vi.fn(),
+ getResource: vi.fn(),
+ updateResource: vi.fn(),
+ createSecret: vi.fn(),
+ mergeSecret: vi.fn(),
+ removeSecretKey: vi.fn(),
+ deleteSecret: vi.fn(),
+ getSecret: vi.fn(),
+}
+
+function makeApp(): express.Express {
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminResourcesRouter(gateway as unknown as K8sGateway))
+ return app
+}
+
+describe('admin channel write response', () => {
+ beforeEach(() => {
+ Object.values(gateway).forEach(fn => fn.mockReset())
+ })
+
+ it('preserves the result envelope while returning only the names-only summary', async () => {
+ const fixtureValue = 'unit-fixture-value'
+ const encodedFixtureValue = Buffer.from(fixtureValue).toString('base64')
+
+ gateway.getResource.mockResolvedValue({
+ metadata: { name: 'foo', namespace: 'channels' },
+ spec: { hostRef: 'h1', credentialsSecretRef: { name: 'cc-foo-credentials' } },
+ })
+ gateway.mergeSecret.mockResolvedValue({
+ name: 'cc-foo-credentials',
+ namespace: 'channels',
+ keys: ['telegram-bot-token'],
+ data: { 'telegram-bot-token': encodedFixtureValue },
+ stringData: { 'telegram-bot-token': fixtureValue },
+ metadata: {
+ annotations: { 'example.invalid/value': fixtureValue },
+ },
+ })
+
+ const response = await request(makeApp())
+ .put('/admin/communication-channels/foo/credentials')
+ .send({ 'telegram-bot-token': fixtureValue })
+
+ expect(response.status).toBe(200)
+ expect(response.body).toEqual({
+ name: 'foo',
+ secretName: 'cc-foo-credentials',
+ namespace: 'channels',
+ rotated: true,
+ result: {
+ name: 'cc-foo-credentials',
+ namespace: 'channels',
+ keys: ['telegram-bot-token'],
+ },
+ })
+ expect(JSON.stringify(response.body)).not.toContain(fixtureValue)
+ expect(JSON.stringify(response.body)).not.toContain(encodedFixtureValue)
+ })
+})
diff --git a/control-api/test/routes.adminCommunicationChannelCredentials.test.ts b/control-api/test/routes.adminCommunicationChannelCredentials.test.ts
index a75e3ea0d..c6fc3b4b6 100644
--- a/control-api/test/routes.adminCommunicationChannelCredentials.test.ts
+++ b/control-api/test/routes.adminCommunicationChannelCredentials.test.ts
@@ -228,13 +228,28 @@ describe('admin communicationchannels — credentials cascade', () => {
metadata: { name: 'foo', namespace: 'channels' },
spec: { hostRef: 'h1', credentialsSecretRef: { name: 'cc-foo-credentials' } },
})
- gatewayMock.mergeSecret.mockResolvedValue({})
+ gatewayMock.mergeSecret.mockResolvedValue({
+ name: 'cc-foo-credentials',
+ namespace: 'channels',
+ keys: ['telegram-bot-token'],
+ })
const res = await request(makeApp())
.put('/admin/communication-channels/foo/credentials')
.send({ 'telegram-bot-token': 'new-token' })
expect(res.status).toBe(200)
+ expect(res.body).toEqual({
+ name: 'foo',
+ secretName: 'cc-foo-credentials',
+ namespace: 'channels',
+ rotated: true,
+ result: {
+ name: 'cc-foo-credentials',
+ namespace: 'channels',
+ keys: ['telegram-bot-token'],
+ },
+ })
expect(gatewayMock.mergeSecret).toHaveBeenCalledWith(
expect.objectContaining({
name: 'cc-foo-credentials',
diff --git a/control-api/test/routes.mcpSecrets.test.ts b/control-api/test/routes.mcpSecrets.test.ts
index 243c975eb..6cbcc4e8a 100644
--- a/control-api/test/routes.mcpSecrets.test.ts
+++ b/control-api/test/routes.mcpSecrets.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
+import { rootLogger } from '../src/observability/logger.js'
import { createAdminSecretsRouter } from '../src/routes/admin/secrets.js'
/** The write shape the admin routes hand to the gateway. */
@@ -12,15 +13,29 @@ type SecretWrite = {
data?: Record<string, string>
}
+function writeSummary(body: SecretWrite) {
+ return {
+ name: body.name,
+ namespace: body.namespace || 'mcp-server',
+ keys: [
+ ...new Set([...Object.keys(body.data ?? {}), ...Object.keys(body.stringData ?? {})]),
+ ].sort((a, b) => a.localeCompare(b)),
+ }
+}
+
/**
* Minimal mock gateway with methods used by the POST /admin/mcp-secrets handler.
*/
function createGateway() {
return {
listSecrets: vi.fn(async () => []),
- createSecret: vi.fn(async (body: unknown) => body),
- updateSecret: vi.fn(async (body: unknown) => body),
- deleteSecret: vi.fn(async (_name: string, _namespace?: string) => ({ deleted: true })),
+ createSecret: vi.fn(async (body: SecretWrite) => writeSummary(body)),
+ updateSecret: vi.fn(async (body: SecretWrite) => writeSummary(body)),
+ deleteSecret: vi.fn(async (name: string, namespace?: string) => ({
+ name,
+ namespace: namespace || 'mcp-server',
+ deleted: true as const,
+ })),
getSecret: vi.fn(
async (
name: string,
@@ -38,7 +53,11 @@ function createGateway() {
// Secret, values included. A handler that echoed this back would leak
// every stored credential, so the leak assertions below are meaningful.
mergeSecret: vi.fn(async (body: SecretWrite) => ({
- metadata: { name: body.name, namespace: 'mcp-server' },
+ name: body.name,
+ namespace: body.namespace || 'mcp-server',
+ keys: ['EXISTING_KEY', ...Object.keys(body.stringData ?? {})].sort((a, b) =>
+ a.localeCompare(b)
+ ),
data: Object.fromEntries(
Object.entries(body.stringData ?? {}).map(([key, value]) => [
key,
@@ -350,7 +369,11 @@ describe('DELETE /admin/mcp-secrets/:name', () => {
const res = await request(app).delete('/admin/mcp-secrets/my-db-creds').expect(200)
- expect(res.body).toEqual({ deleted: true })
+ expect(res.body).toEqual({
+ name: 'my-db-creds',
+ namespace: 'mcp-server',
+ deleted: true,
+ })
expect(gateway.deleteSecret).toHaveBeenCalledOnce()
expect(gateway.deleteSecret).toHaveBeenCalledWith('my-db-creds', 'mcp-server')
})
@@ -640,17 +663,38 @@ describe('PUT /admin/mcp-secrets/:name (credential rotation, issue #223)', () =>
// The rotation itself succeeds; only the secondary affectedConnectors
// lookup fails. The operator must see the rotation as the success it is,
// not a 500 that suggests the credential is unchanged.
- gateway.listResource.mockRejectedValueOnce(new Error('mcpservers list forbidden'))
+ const sentinel = 'RP231_NESTED_ERROR_SENTINEL'
+ gateway.listResource.mockRejectedValueOnce(
+ Object.assign(new Error('mcpservers list forbidden'), {
+ response: { body: { value: sentinel } },
+ })
+ )
+ const warnSpy = vi.spyOn(rootLogger, 'warn').mockImplementation(() => {})
const app = makeApp(gateway)
- const res = await request(app)
- .put('/admin/mcp-secrets/linear-credentials')
- .send({ data: { LINEAR_API_KEY: 'rotated-value' } })
- .expect(200)
-
- expect(gateway.mergeSecret).toHaveBeenCalledOnce()
- expect(res.body.name).toBe('linear-credentials')
- expect(res.body.affectedConnectors).toEqual([])
+ try {
+ const res = await request(app)
+ .put('/admin/mcp-secrets/linear-credentials')
+ .send({ data: { LINEAR_API_KEY: 'rotated-value' } })
+ .expect(200)
+
+ expect(gateway.mergeSecret).toHaveBeenCalledOnce()
+ expect(res.body.name).toBe('linear-credentials')
+ expect(res.body.affectedConnectors).toEqual([])
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.objectContaining({
+ event: 'mcp-secret-rotated-affected-connectors-unavailable',
+ name: 'linear-credentials',
+ namespace: 'mcp-server',
+ }),
+ 'Affected connectors unavailable after MCP Secret rotation'
+ )
+ const [fields] = warnSpy.mock.calls[0]
+ expect(fields).not.toHaveProperty('err')
+ expect(JSON.stringify(warnSpy.mock.calls)).not.toContain(sentinel)
+ } finally {
+ warnSpy.mockRestore()
+ }
})
it('returns 500 when gateway.mergeSecret throws', async () => {
diff --git a/control-api/test/routes.recipeSecrets.ownership.test.ts b/control-api/test/routes.recipeSecrets.ownership.test.ts
index d3c5cf9a8..4c0a33012 100644
--- a/control-api/test/routes.recipeSecrets.ownership.test.ts
+++ b/control-api/test/routes.recipeSecrets.ownership.test.ts
@@ -9,6 +9,24 @@ interface MockSecret {
data?: Record<string, string>
}
+type MockWrite = {
+ name: string
+ namespace?: string
+ labels?: Record<string, string>
+ data?: Record<string, string>
+ stringData?: Record<string, string>
+}
+
+function writeSummary(body: MockWrite) {
+ return {
+ name: body.name,
+ namespace: body.namespace || 'default',
+ keys: [
+ ...new Set([...Object.keys(body.data ?? {}), ...Object.keys(body.stringData ?? {})]),
+ ].sort((a, b) => a.localeCompare(b)),
+ }
+}
+
function createGateway(opts: { recipes?: string[]; secrets?: MockSecret[] } = {}) {
const recipes = opts.recipes ?? []
const secrets = new Map<string, MockSecret>(
@@ -18,21 +36,21 @@ function createGateway(opts: { recipes?: string[]; secrets?: MockSecret[] } = {}
listResource: vi.fn(async () => recipes.map(name => ({ metadata: { name } }))),
listSecrets: vi.fn(async () => [...secrets.values()]),
getSecret: vi.fn(async (name: string) => secrets.get(name) ?? null),
- createSecret: vi.fn(async (body: { name: string; labels?: Record<string, string> }) => {
+ createSecret: vi.fn(async (body: MockWrite) => {
secrets.set(body.name, { metadata: { name: body.name, labels: body.labels ?? {} } })
- return body
+ return writeSummary(body)
}),
- updateSecret: vi.fn(async (body: { name: string; labels?: Record<string, string> }) => {
+ updateSecret: vi.fn(async (body: MockWrite) => {
const existing = secrets.get(body.name)
secrets.set(body.name, {
...(existing ?? {}),
metadata: { name: body.name, labels: body.labels ?? existing?.metadata?.labels ?? {} },
})
- return body
+ return writeSummary(body)
}),
- deleteSecret: vi.fn(async (name: string) => {
+ deleteSecret: vi.fn(async (name: string, namespace?: string) => {
secrets.delete(name)
- return { deleted: true }
+ return { name, namespace: namespace || 'default', deleted: true as const }
}),
}
}
diff --git a/control-api/test/routes.secrets.platformPullSecretName.test.ts b/control-api/test/routes.secrets.platformPullSecretName.test.ts
index f296ace9f..fc2f6536a 100644
--- a/control-api/test/routes.secrets.platformPullSecretName.test.ts
+++ b/control-api/test/routes.secrets.platformPullSecretName.test.ts
@@ -17,14 +17,32 @@ import request from 'supertest'
import { EVENFIRE_REGISTRY_PULL_SECRET_NAME } from '@clerum/workflow-runtime-core'
import { createAdminSecretsRouter } from '../src/routes/admin/secrets.js'
+function writeSummary(body: unknown) {
+ const write = body as {
+ name: string
+ namespace?: string
+ data?: Record<string, string>
+ stringData?: Record<string, string>
+ }
+ return {
+ name: write.name,
+ namespace: write.namespace || 'mcp-server',
+ keys: [...new Set([...Object.keys(write.data ?? {}), ...Object.keys(write.stringData ?? {})])],
+ }
+}
+
function createGateway() {
return {
listSecrets: vi.fn(async () => []),
listResource: vi.fn(async () => [] as unknown[]),
getSecret: vi.fn(async () => null),
- createSecret: vi.fn(async (body: unknown) => body),
- updateSecret: vi.fn(async (body: unknown) => body),
- deleteSecret: vi.fn(async (_name: string, _namespace?: string) => ({ deleted: true })),
+ createSecret: vi.fn(async (body: unknown) => writeSummary(body)),
+ updateSecret: vi.fn(async (body: unknown) => writeSummary(body)),
+ deleteSecret: vi.fn(async (name: string, namespace?: string) => ({
+ name,
+ namespace: namespace || 'mcp-server',
+ deleted: true as const,
+ })),
}
}
@@ -99,7 +117,7 @@ describe('platform-managed Secret name is reserved', () => {
type: 'kubernetes.io/dockerconfigjson',
data: { '.dockerconfigjson': 'e30=' },
})) as never
- const mergeSecret = vi.fn(async (body: unknown) => body)
+ const mergeSecret = vi.fn(async (body: unknown) => writeSummary(body))
;(gateway as unknown as { mergeSecret: unknown }).mergeSecret = mergeSecret
const res = await request(makeApp(gateway))
@@ -118,7 +136,7 @@ describe('platform-managed Secret name is reserved', () => {
type: 'Opaque',
data: {},
})) as never
- const mergeSecret = vi.fn(async (body: unknown) => body)
+ const mergeSecret = vi.fn(async (body: unknown) => writeSummary(body))
;(gateway as unknown as { mergeSecret: unknown }).mergeSecret = mergeSecret
await request(makeApp(gateway))
diff --git a/control-api/test/routes.secrets.test.ts b/control-api/test/routes.secrets.test.ts
index 7d23371fd..fcfe3f8ff 100644
--- a/control-api/test/routes.secrets.test.ts
+++ b/control-api/test/routes.secrets.test.ts
@@ -1,8 +1,25 @@
import { describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
+import { rootLogger } from '../src/observability/logger.js'
import { createAdminSecretsRouter } from '../src/routes/admin/secrets.js'
+function writeSummary(body: unknown) {
+ const write = body as {
+ name: string
+ namespace?: string
+ data?: Record<string, string>
+ stringData?: Record<string, string>
+ }
+ return {
+ name: write.name,
+ namespace: write.namespace || 'default',
+ keys: [
+ ...new Set([...Object.keys(write.data ?? {}), ...Object.keys(write.stringData ?? {})]),
+ ].sort((a, b) => a.localeCompare(b)),
+ }
+}
+
function createGateway() {
return {
listSecrets: vi.fn(async () => [
@@ -16,8 +33,8 @@ function createGateway() {
getSecret: vi.fn(async (_name: string, _namespace?: string): Promise<unknown> => {
throw new Error('not found')
}),
- createSecret: vi.fn(async (body: unknown) => body),
- updateSecret: vi.fn(async (body: unknown) => body),
+ createSecret: vi.fn(async (body: unknown) => writeSummary(body)),
+ updateSecret: vi.fn(async (body: unknown) => writeSummary(body)),
deleteSecret: vi.fn(async (name: string, namespace?: string) => ({
deleted: true,
name,
@@ -131,8 +148,8 @@ describe('routes/secrets', () => {
data: entry.data,
}
}),
- createSecret: vi.fn(async (body: unknown) => body),
- updateSecret: vi.fn(async (body: unknown) => body),
+ createSecret: vi.fn(async (body: unknown) => writeSummary(body)),
+ updateSecret: vi.fn(async (body: unknown) => writeSummary(body)),
deleteSecret: vi.fn(async (name: string, namespace?: string) => ({
deleted: true,
name,
@@ -181,7 +198,7 @@ describe('routes/secrets', () => {
]
: []
})
- const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const warnSpy = vi.spyOn(rootLogger, 'warn').mockImplementation(() => {})
const app = express()
app.use(express.json())
app.use(createAdminSecretsRouter(gateway as never))
@@ -191,9 +208,12 @@ describe('routes/secrets', () => {
expect(res.body.items).toHaveLength(1)
expect(res.body.items[0]).toMatchObject({ name: 'r1', namespace: 'sandbox-recipes' })
expect(warnSpy).toHaveBeenCalledWith(
- expect.stringContaining('"event":"recipe-secret-namespace-list-degraded"')
+ expect.objectContaining({
+ event: 'recipe-secret-namespace-list-degraded',
+ namespace: 'sandbox-ui',
+ }),
+ 'Recipe Secret namespace listing degraded'
)
- expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('"namespace":"sandbox-ui"'))
warnSpy.mockRestore()
})
diff --git a/control-api/test/services.secretService.test.ts b/control-api/test/services.secretService.test.ts
index 49f57a830..10e8c569e 100644
--- a/control-api/test/services.secretService.test.ts
+++ b/control-api/test/services.secretService.test.ts
@@ -38,6 +38,7 @@ const VALID_KEYS: readonly string[] = [
]
type CoreApiMock = {
+ listNamespacedSecret: ReturnType<typeof vi.fn>
readNamespacedSecret: ReturnType<typeof vi.fn>
createNamespacedSecret: ReturnType<typeof vi.fn>
replaceNamespacedSecret: ReturnType<typeof vi.fn>
@@ -47,6 +48,7 @@ type CoreApiMock = {
function createCoreApiMock(): CoreApiMock {
return {
+ listNamespacedSecret: vi.fn().mockResolvedValue({ items: [] }),
readNamespacedSecret: vi.fn().mockResolvedValue({ metadata: {}, type: 'Opaque', data: {} }),
createNamespacedSecret: vi.fn().mockResolvedValue({ metadata: { name: 's' } }),
replaceNamespacedSecret: vi.fn().mockResolvedValue({ metadata: { name: 's' } }),
@@ -55,6 +57,155 @@ function createCoreApiMock(): CoreApiMock {
}
}
+const SENT_SECRET_VALUE = Buffer.from('caller-sent-value', 'utf8').toString('base64')
+const ADJACENT_SECRET_VALUE = Buffer.from('adjacent-owner-value', 'utf8').toString('base64')
+const RAW_WRITE_RESULT: k8s.V1Secret = {
+ apiVersion: 'v1',
+ kind: 'Secret',
+ metadata: {
+ name: 'credentials',
+ namespace: 'channels',
+ resourceVersion: '42',
+ uid: 'uid-1',
+ },
+ type: 'Opaque',
+ data: {
+ 'caller-key': SENT_SECRET_VALUE,
+ 'adjacent-owner-key': ADJACENT_SECRET_VALUE,
+ },
+}
+
+function expectNamesOnly(
+ result: unknown,
+ expected: { name: string; namespace: string; keys: string[] }
+): void {
+ expect(result).toEqual(expected)
+ const serialized = JSON.stringify(result)
+ expect(serialized).not.toContain(SENT_SECRET_VALUE)
+ expect(serialized).not.toContain(ADJACENT_SECRET_VALUE)
+ expect(result).not.toHaveProperty('data')
+ expect(result).not.toHaveProperty('stringData')
+}
+
+describe('SecretService — write responses are names-only', () => {
+ let coreApi: CoreApiMock
+ let svc: SecretService
+
+ beforeEach(() => {
+ coreApi = createCoreApiMock()
+ coreApi.createNamespacedSecret.mockResolvedValue(RAW_WRITE_RESULT)
+ coreApi.readNamespacedSecret.mockResolvedValue(RAW_WRITE_RESULT)
+ coreApi.replaceNamespacedSecret.mockResolvedValue(RAW_WRITE_RESULT)
+ coreApi.patchNamespacedSecret.mockResolvedValue(RAW_WRITE_RESULT)
+ svc = new SecretService(coreApi as unknown as k8s.CoreV1Api, 'default-ns')
+ })
+
+ it.each([
+ [
+ 'createSecret',
+ () =>
+ svc.createSecret({
+ name: 'credentials',
+ namespace: 'channels',
+ stringData: { 'caller-key': 'caller-sent-value' },
+ }),
+ ],
+ [
+ 'updateSecret',
+ () =>
+ svc.updateSecret({
+ name: 'credentials',
+ namespace: 'channels',
+ stringData: { 'caller-key': 'caller-sent-value' },
+ }),
+ ],
+ [
+ 'mergeSecret',
+ () =>
+ svc.mergeSecret({
+ name: 'credentials',
+ namespace: 'channels',
+ stringData: { 'caller-key': 'caller-sent-value' },
+ }),
+ ],
+ [
+ 'removeSecretKey',
+ () =>
+ svc.removeSecretKey({
+ name: 'credentials',
+ namespace: 'channels',
+ key: 'caller-key',
+ }),
+ ],
+ ])('%s returns only identity and sorted key names', async (_operation, invoke) => {
+ const result = await invoke()
+ expectNamesOnly(result, {
+ name: 'credentials',
+ namespace: 'channels',
+ keys: ['adjacent-owner-key', 'caller-key'],
+ })
+ })
+
+ it('uses the default namespace in the write summary', async () => {
+ coreApi.createNamespacedSecret.mockResolvedValue({
+ ...RAW_WRITE_RESULT,
+ metadata: { ...RAW_WRITE_RESULT.metadata, namespace: 'default-ns' },
+ })
+ const result = await svc.createSecret({
+ name: 'credentials',
+ stringData: { 'caller-key': 'caller-sent-value' },
+ })
+ expect((result as { namespace: string }).namespace).toBe('default-ns')
+ })
+
+ it('returns a names-only delete acknowledgement after the apiserver succeeds', async () => {
+ const result = await svc.deleteSecret('credentials', 'channels', {
+ uid: 'uid-1',
+ resourceVersion: '42',
+ })
+ expect(result).toEqual({ name: 'credentials', namespace: 'channels', deleted: true })
+ expect(coreApi.deleteNamespacedSecret.mock.calls[0][0].body.preconditions).toEqual({
+ uid: 'uid-1',
+ resourceVersion: '42',
+ })
+ })
+
+ it('propagates delete failures instead of synthesizing success', async () => {
+ coreApi.deleteNamespacedSecret.mockRejectedValueOnce(new Error('delete rejected'))
+ await expect(svc.deleteSecret('credentials', 'channels')).rejects.toThrow('delete rejected')
+ })
+
+ it('omits annotations from the list projection', async () => {
+ coreApi.listNamespacedSecret.mockResolvedValue({
+ items: [
+ {
+ metadata: {
+ name: 'credentials',
+ namespace: 'channels',
+ labels: { owner: 'platform' },
+ annotations: { 'example.invalid/private': 'do-not-return' },
+ },
+ type: 'Opaque',
+ data: { 'caller-key': SENT_SECRET_VALUE },
+ },
+ ],
+ })
+
+ const result = await svc.listSecrets('channels')
+ expect(result).toEqual([
+ {
+ metadata: {
+ name: 'credentials',
+ namespace: 'channels',
+ labels: { owner: 'platform' },
+ },
+ type: 'Opaque',
+ keys: ['caller-key'],
+ },
+ ])
+ })
+})
+
describe('SecretService — invalid Secret keys never reach the apiserver', () => {
let coreApi: CoreApiMock
let svc: SecretService
diff --git a/scripts/tests/test-minikube-t2-public-boundary.sh b/scripts/tests/test-minikube-t2-public-boundary.sh
index 78ceef2a1..5ce500dc5 100755
--- a/scripts/tests/test-minikube-t2-public-boundary.sh
+++ b/scripts/tests/test-minikube-t2-public-boundary.sh
@@ -47,6 +47,8 @@ diff = Path(sys.argv[1]).read_text(errors="replace")
bad = []
current = ""
safe_source_paths = {
+ "control-api/src/routes/admin/communicationchannelcredentials.ts",
+ "control-api/test/routes.admincommunicationchannelcredentials.test.ts",
"deploy/scripts/lib/gfs-credential-rollout.sh",
"deploy/scripts/lib/gfs-credential-secret.sh",
"deploy/scripts/reconcile-gfs-deploy-credentials.sh",