Skip to content

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

TypeScript

fix(control-api): make admin secret-write responses names-only (stop leaking Secret values)

Alfredo Lopez6c3e8cdf0ce7
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index cb0f7a33b..1bf20ca32 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.392",
+ "version": "0.1.393",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.392",
+ "version": "0.1.393",
"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 6d18bd0d2..1376f982e 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.392",
+ "version": "0.1.393",
"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 e7dfdfd11..ab233500a 100644
--- a/control-api/src/k8s.ts
+++ b/control-api/src/k8s.ts
@@ -7,7 +7,7 @@ import {
LlmAllowedModelsConfigMapWriter,
} from './services/llmAllowedModelsConfigMap.js'
import { ResourceService, mergeAnnotationsForReplace } from './services/resourceService.js'
-import { SecretService } from './services/secretService.js'
+import { SecretService, type SecretSummary } from './services/secretService.js'
import { ClerumResourceType, HostOverview, SecretUpsertRequest } from './types.js'
/**
@@ -390,23 +390,33 @@ export class K8sGateway {
return this.secrets.getSecret(name, namespace)
}
- async createSecret(req: SecretUpsertRequest): Promise<unknown> {
+ // Write ops return a names-only summary (never the k8s Secret's `.data`), so no
+ // route can leak secret values by echoing the return — and a future cast to
+ // V1Secret is now a compile error. Reads (getSecret) stay full-fat.
+ async createSecret(req: SecretUpsertRequest): Promise<SecretSummary> {
return this.secrets.createSecret(req)
}
- async updateSecret(req: SecretUpsertRequest): Promise<unknown> {
+ async updateSecret(req: SecretUpsertRequest): Promise<SecretSummary> {
return this.secrets.updateSecret(req)
}
- 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)
}
- async deleteSecret(name: string, namespace?: string): Promise<unknown> {
+ async deleteSecret(
+ name: string,
+ namespace?: string
+ ): Promise<{ name: string; namespace: string; deleted: true }> {
return this.secrets.deleteSecret(name, namespace)
}
diff --git a/control-api/src/routes/admin/communicationChannelCredentials.ts b/control-api/src/routes/admin/communicationChannelCredentials.ts
index 401b22cab..56c4c93b3 100644
--- a/control-api/src/routes/admin/communicationChannelCredentials.ts
+++ b/control-api/src/routes/admin/communicationChannelCredentials.ts
@@ -69,18 +69,24 @@ export function registerCommunicationChannelCredentialsRoutes(
}
const existingSecretName = cc.spec?.credentialsSecretRef?.name
if (existingSecretName) {
- const merged = await gateway.mergeSecret({
+ await gateway.mergeSecret({
name: existingSecretName,
namespace: ns,
type: 'Opaque',
stringData: data,
})
+ // Names-only response (mirrors routes/admin/secrets.ts, PR #223 policy):
+ // respond with only the rotated key NAMES, never secret values. The write
+ // result is not echoed — a merge-patch touches the whole Secret (including
+ // keys the caller did not send), so echoing raw k8s data would leak values
+ // into the HTTP response body (logs/proxies/error-trackers). `rotatedKeys`
+ // reflects exactly the keys this request wrote.
res.status(200).json({
name,
secretName: existingSecretName,
namespace: ns,
rotated: true,
- result: merged,
+ rotatedKeys: Object.keys(data),
})
return
}
@@ -96,18 +102,17 @@ export function registerCommunicationChannelCredentialsRoutes(
...(cc.spec ?? {}),
credentialsSecretRef: { name: secretName },
}
- const updated = await gateway.updateResource(
- 'communicationchannels',
- name,
- { spec: nextSpec },
- ns
- )
+ await gateway.updateResource('communicationchannels', name, { spec: nextSpec }, ns)
+ // Names-only for consistency with the rotated:true branch and the #223
+ // policy. `updated` is the CommunicationChannel CRD (only
+ // credentialsSecretRef, no secret values), but we still avoid echoing the
+ // raw CRD and return only the written key NAMES.
res.status(200).json({
name,
secretName,
namespace: ns,
rotated: false,
- result: updated,
+ rotatedKeys: Object.keys(data),
})
})
)
diff --git a/control-api/src/services/secretService.ts b/control-api/src/services/secretService.ts
index 0fd214a4c..eb83635c0 100644
--- a/control-api/src/services/secretService.ts
+++ b/control-api/src/services/secretService.ts
@@ -1,6 +1,29 @@
import * as k8s from '@kubernetes/client-node'
import { SecretUpsertRequest } from '../types.js'
+// A write-side summary of a Secret — NEVER carries `.data` values. Every admin
+// secret-write route echoes this, so secret values cannot leave the Secret store
+// via an HTTP response body (mirrors the names-only policy in
+// routes/admin/secrets.ts). Reads that legitimately need values use `getSecret`,
+// which deliberately stays full-fat.
+export interface SecretSummary {
+ name: string
+ namespace: string
+ keys: string[]
+}
+
+// Trim a k8s write response to a names-only summary. `name`/`namespace` come from
+// the request (always defined); `keys` from the returned Secret's data — for a
+// merge-patch this is the merged WHOLE keyset, but still only NAMES, never values.
+function summarizeSecret(result: unknown, name: string, namespace: string): SecretSummary {
+ const data = (result as k8s.V1Secret | undefined)?.data
+ return {
+ name,
+ namespace,
+ keys: Object.keys(data ?? {}).sort((a, b) => a.localeCompare(b)),
+ }
+}
+
export class SecretService {
constructor(
private readonly coreApi: k8s.CoreV1Api,
@@ -29,13 +52,14 @@ export class SecretService {
return this.coreApi.readNamespacedSecret({ namespace, name })
}
- async createSecret(req: SecretUpsertRequest): Promise<unknown> {
+ async createSecret(req: SecretUpsertRequest): Promise<SecretSummary> {
+ 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,
},
@@ -44,10 +68,9 @@ export class SecretService {
stringData: req.stringData,
}
- return this.coreApi.createNamespacedSecret({
- namespace: req.namespace || this.defaultNamespace,
- body,
- })
+ // Names-only return: never surface the created Secret's `.data` to callers.
+ const created = await this.coreApi.createNamespacedSecret({ namespace: ns, body })
+ return summarizeSecret(created, req.name, ns)
}
/**
@@ -61,7 +84,7 @@ export class SecretService {
* inter-service token rotation. For multi-owner Secrets where individual
* keys must survive a partial update, use `mergeSecret` instead.
*/
- async updateSecret(req: SecretUpsertRequest): Promise<unknown> {
+ async updateSecret(req: SecretUpsertRequest): Promise<SecretSummary> {
const ns = req.namespace || this.defaultNamespace
const existing = await this.coreApi.readNamespacedSecret({ namespace: ns, name: req.name })
@@ -80,7 +103,13 @@ export class SecretService {
stringData: req.stringData,
}
- return this.coreApi.replaceNamespacedSecret({ namespace: ns, name: req.name, body })
+ // Names-only return: never surface the replaced Secret's `.data` to callers.
+ const updated = await this.coreApi.replaceNamespacedSecret({
+ namespace: ns,
+ name: req.name,
+ body,
+ })
+ return summarizeSecret(updated, req.name, ns)
}
/**
@@ -100,7 +129,7 @@ export class SecretService {
* `control-api-communication-channels` Role. Do NOT call this from
* routes that target other namespaces unless their Role has been updated.
*/
- async mergeSecret(req: SecretUpsertRequest): Promise<unknown> {
+ async mergeSecret(req: SecretUpsertRequest): Promise<SecretSummary> {
const ns = req.namespace || this.defaultNamespace
const body: Partial<k8s.V1Secret> = {}
@@ -112,7 +141,9 @@ export class SecretService {
if (req.labels !== undefined) body.metadata = { labels: req.labels }
if (req.type !== undefined) body.type = req.type
- return this.coreApi.patchNamespacedSecret(
+ // Names-only return: the patch response is the merged WHOLE Secret (all keys,
+ // including ones the caller did not send) — return only the key NAMES.
+ const merged = await this.coreApi.patchNamespacedSecret(
{
namespace: ns,
name: req.name,
@@ -122,13 +153,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> {
const ns = req.namespace || this.defaultNamespace
const body = { data: { [req.key]: null } } as unknown as Partial<k8s.V1Secret>
- return this.coreApi.patchNamespacedSecret(
+ // Names-only return: never surface the patched Secret's remaining `.data`.
+ const patched = await this.coreApi.patchNamespacedSecret(
{
namespace: ns,
name: req.name,
@@ -138,12 +175,15 @@ export class SecretService {
middleware: [k8s.setHeaderMiddleware('Content-Type', 'application/merge-patch+json')],
}
)
+ return summarizeSecret(patched, req.name, ns)
}
- async deleteSecret(name: string, namespace?: string): Promise<unknown> {
- return this.coreApi.deleteNamespacedSecret({
- namespace: namespace || this.defaultNamespace,
- name,
- })
+ async deleteSecret(
+ name: string,
+ namespace?: string
+ ): Promise<{ name: string; namespace: string; deleted: true }> {
+ const ns = namespace || this.defaultNamespace
+ await this.coreApi.deleteNamespacedSecret({ namespace: ns, name })
+ return { name, namespace: ns, deleted: true }
}
}
diff --git a/control-api/test/routes.adminCommunicationChannelCredentials.test.ts b/control-api/test/routes.adminCommunicationChannelCredentials.test.ts
index c0adbd0d6..06deb028f 100644
--- a/control-api/test/routes.adminCommunicationChannelCredentials.test.ts
+++ b/control-api/test/routes.adminCommunicationChannelCredentials.test.ts
@@ -238,19 +238,96 @@ describe('admin communicationchannels — credentials cascade', () => {
expect(gatewayMock.updateResource).not.toHaveBeenCalled()
})
+ it('SECURITY: PUT credentials (rotated:true) response is names-only and leaks no secret VALUE', async () => {
+ // Regression for a pre-existing confidentiality leak (blame 5d663a4): the
+ // rotated:true branch used to respond `result: merged`, and `merged` is the
+ // full k8s Secret returned by patchNamespacedSecret — its `.data` carries
+ // the base64 VALUES of every stored key, INCLUDING keys the caller never
+ // sent. Those values then travel in the HTTP response body into surfaces
+ // that don't protect secrets (access logs, proxies, error trackers,
+ // DevTools). The route must mirror the #223 policy (secrets.ts): names-only.
+ //
+ // Mutation guard: mock mergeSecret to return exactly such a populated Secret
+ // and assert NO secret value appears at any depth. This test goes RED if the
+ // handler ever echoes the Secret object again (e.g. `result: merged`).
+ gatewayMock.getResource.mockResolvedValue({
+ metadata: { name: 'foo', namespace: 'channels' },
+ spec: { hostRef: 'h1', credentialsSecretRef: { name: 'cc-foo-credentials' } },
+ })
+ const NEW_TOKEN_PLAIN = 'tg-new-token'
+ const SLACK_TOKEN_PLAIN = 'xoxb-super-secret'
+ const EMAIL_PW_PLAIN = 'hunter2'
+ const NEW_TOKEN_B64 = Buffer.from(NEW_TOKEN_PLAIN, 'utf8').toString('base64')
+ const SLACK_TOKEN_B64 = Buffer.from(SLACK_TOKEN_PLAIN, 'utf8').toString('base64')
+ const EMAIL_PW_B64 = Buffer.from(EMAIL_PW_PLAIN, 'utf8').toString('base64')
+ gatewayMock.mergeSecret.mockResolvedValue({
+ apiVersion: 'v1',
+ kind: 'Secret',
+ metadata: { name: 'cc-foo-credentials', namespace: 'channels' },
+ type: 'Opaque',
+ data: {
+ 'telegram-bot-token': NEW_TOKEN_B64,
+ // Keys the caller did NOT send — over-return must never bring these back.
+ 'slack-bot-token': SLACK_TOKEN_B64,
+ 'email-password': EMAIL_PW_B64,
+ },
+ })
+
+ const res = await request(makeApp())
+ .put('/admin/communication-channels/foo/credentials')
+ .send({ 'telegram-bot-token': NEW_TOKEN_PLAIN })
+
+ expect(res.status).toBe(200)
+ // Names-only contract: metadata + the rotated key NAMES the caller sent.
+ expect(res.body).toEqual({
+ name: 'foo',
+ secretName: 'cc-foo-credentials',
+ namespace: 'channels',
+ rotated: true,
+ rotatedKeys: ['telegram-bot-token'],
+ })
+ expect(res.body).not.toHaveProperty('result')
+ // Belt-and-suspenders: no secret value (base64 or plaintext) at ANY depth,
+ // including the caller-sent token in either encoding.
+ const serialized = JSON.stringify(res.body)
+ for (const needle of [
+ NEW_TOKEN_B64,
+ NEW_TOKEN_PLAIN,
+ SLACK_TOKEN_B64,
+ EMAIL_PW_B64,
+ SLACK_TOKEN_PLAIN,
+ EMAIL_PW_PLAIN,
+ ]) {
+ expect(serialized).not.toContain(needle)
+ }
+ })
+
it('PUT credentials on CC without credentialsSecretRef creates Secret + patches CC', async () => {
gatewayMock.getResource.mockResolvedValue({
metadata: { name: 'foo', namespace: 'channels' },
spec: { hostRef: 'h1' },
})
gatewayMock.createSecret.mockResolvedValue({})
- gatewayMock.updateResource.mockResolvedValue({})
+ gatewayMock.updateResource.mockResolvedValue({
+ metadata: { name: 'foo', namespace: 'channels' },
+ spec: { hostRef: 'h1', credentialsSecretRef: { name: 'cc-foo-credentials' } },
+ })
const res = await request(makeApp())
.put('/admin/communication-channels/foo/credentials')
.send({ 'telegram-bot-token': 'tok' })
expect(res.status).toBe(200)
+ // Names-only for the rotated:false branch too: return the written key NAMES,
+ // never the raw CRD object.
+ expect(res.body).toEqual({
+ name: 'foo',
+ secretName: 'cc-foo-credentials',
+ namespace: 'channels',
+ rotated: false,
+ rotatedKeys: ['telegram-bot-token'],
+ })
+ expect(res.body).not.toHaveProperty('result')
expect(gatewayMock.createSecret).toHaveBeenCalledWith(
expect.objectContaining({
name: 'cc-foo-credentials',
diff --git a/control-api/test/routes.secretsNamesOnly.integration.test.ts b/control-api/test/routes.secretsNamesOnly.integration.test.ts
new file mode 100644
index 000000000..42dc87242
--- /dev/null
+++ b/control-api/test/routes.secretsNamesOnly.integration.test.ts
@@ -0,0 +1,144 @@
+import { describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { createAdminSecretsRouter } from '../src/routes/admin/secrets.js'
+import { SecretService } from '../src/services/secretService.js'
+
+// Integration guard for the names-only write contract (SECURITY). Unlike the
+// unit route tests (which mock the K8sGateway and so bypass the trim), this wires
+// the REAL SecretService behind the REAL admin secrets router and mocks ONLY the
+// external Kubernetes CoreV1Api — the correct boundary to mock. The mocked k8s
+// client returns FULL V1Secrets with base64 `.data`, so the ONLY reason the HTTP
+// response is names-only is the SecretService trim. These tests go RED if the
+// service ever stops trimming (i.e. the leak returns), even though no route code
+// changed for the sibling endpoints.
+
+const b64 = (s: string): string => Buffer.from(s, 'utf8').toString('base64')
+
+const LEAK = 'leak-me-please'
+const OTHER = 'other-provider-secret'
+
+function fullSecret(
+ name: string,
+ namespace: string,
+ data: Record<string, string>,
+ labels: Record<string, string> = {}
+): Record<string, unknown> {
+ return {
+ apiVersion: 'v1',
+ kind: 'Secret',
+ metadata: { name, namespace, resourceVersion: '7', labels },
+ type: 'Opaque',
+ data,
+ }
+}
+
+function makeApp(opts: {
+ existing?: Record<string, unknown> | null
+ written: Record<string, unknown>
+}): { app: express.Express; core: Record<string, ReturnType<typeof vi.fn>> } {
+ const core = {
+ createNamespacedSecret: vi.fn(async () => opts.written),
+ readNamespacedSecret: vi.fn(async () => {
+ if (opts.existing == null) {
+ throw Object.assign(new Error('not found'), { statusCode: 404 })
+ }
+ return opts.existing
+ }),
+ replaceNamespacedSecret: vi.fn(async () => opts.written),
+ patchNamespacedSecret: vi.fn(async () => opts.written),
+ deleteNamespacedSecret: vi.fn(async () => ({ kind: 'Status', status: 'Success' })),
+ listNamespacedSecret: vi.fn(async () => ({ items: [] })),
+ }
+ const svc = new SecretService(core as never, 'mcp-host')
+ // Minimal gateway facade delegating secret ops to the REAL service; only the
+ // methods the routes under test touch are provided.
+ const gateway = {
+ listSecrets: (ns?: string) => svc.listSecrets(ns),
+ getSecret: (n: string, ns?: string) => svc.getSecret(n, ns),
+ createSecret: (r: never) => svc.createSecret(r),
+ updateSecret: (r: never) => svc.updateSecret(r),
+ deleteSecret: (n: string, ns?: string) => svc.deleteSecret(n, ns),
+ listResource: vi.fn(async () => []),
+ }
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminSecretsRouter(gateway as never))
+ return { app, core }
+}
+
+// Asserts an HTTP body carries no secret value at any depth and no `.data` field.
+function expectNoSecretValues(body: unknown): void {
+ const serialized = JSON.stringify(body)
+ for (const needle of [LEAK, OTHER, b64(LEAK), b64(OTHER)]) {
+ expect(serialized).not.toContain(needle)
+ }
+ expect((body as { data?: unknown }).data).toBeUndefined()
+}
+
+describe('SECURITY (integration): admin secret-write responses are names-only', () => {
+ it('POST /admin/secrets does not echo the created Secret .data', async () => {
+ const { app } = makeApp({
+ written: fullSecret('svc-token', 'mcp-host', { token: b64(LEAK) }),
+ })
+ const res = await request(app)
+ .post('/admin/secrets')
+ .send({ name: 'svc-token', stringData: { token: LEAK } })
+ .expect(201)
+
+ expect(res.body).toMatchObject({ name: 'svc-token', keys: ['token'] })
+ expect(res.body).not.toHaveProperty('data')
+ expectNoSecretValues(res.body)
+ })
+
+ it('PUT /admin/secrets (full-replace) does not echo the replaced Secret .data', async () => {
+ const { app } = makeApp({
+ // getSecret (validation-only label read) + updateSecret read-then-replace.
+ existing: fullSecret('svc-token', 'mcp-host', { token: b64('old') }),
+ written: fullSecret('svc-token', 'mcp-host', { token: b64(LEAK) }),
+ })
+ const res = await request(app)
+ .put('/admin/secrets')
+ .send({ name: 'svc-token', stringData: { token: LEAK } })
+ .expect(200)
+
+ expect(res.body).toMatchObject({ name: 'svc-token', keys: ['token'] })
+ expectNoSecretValues(res.body)
+ })
+
+ it('PUT /admin/recipe-secrets does not echo merged .data (incl. keys the caller did not send)', async () => {
+ const { app } = makeApp({
+ // Existing recipe secret carries a key the caller does NOT send this time;
+ // the merge-patch response would include it — only its NAME may surface.
+ existing: fullSecret(
+ 'r1',
+ 'sandbox-recipes',
+ { EXISTING: b64(OTHER) },
+ { 'clerum.io/recipe-secret': 'true', 'clerum.io/shared': 'true' }
+ ),
+ written: fullSecret(
+ 'r1',
+ 'sandbox-recipes',
+ { EXISTING: b64(OTHER), TOKEN: b64(LEAK) },
+ { 'clerum.io/recipe-secret': 'true', 'clerum.io/shared': 'true' }
+ ),
+ })
+ const res = await request(app)
+ .put('/admin/recipe-secrets')
+ .send({ name: 'r1', data: { TOKEN: LEAK } })
+ .expect(200)
+
+ expect(res.body).toMatchObject({ name: 'r1' })
+ expect(Array.isArray(res.body.keys)).toBe(true)
+ expectNoSecretValues(res.body)
+ })
+
+ it('DELETE /admin/secrets/:name returns a names-only summary, not a Secret body', async () => {
+ const { app } = makeApp({
+ written: fullSecret('svc-token', 'mcp-host', { token: b64(LEAK) }),
+ })
+ const res = await request(app).delete('/admin/secrets/svc-token').expect(200)
+ expect(res.body).toMatchObject({ name: 'svc-token', deleted: true })
+ expectNoSecretValues(res.body)
+ })
+})
diff --git a/control-api/test/services.secretService.test.ts b/control-api/test/services.secretService.test.ts
new file mode 100644
index 000000000..98fa43b09
--- /dev/null
+++ b/control-api/test/services.secretService.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, it, vi } from 'vitest'
+import { SecretService } from '../src/services/secretService.js'
+
+// SECURITY (names-only write boundary): the k8s API returns the FULL Secret from
+// create/replace/patch — its `.data` carries the base64 VALUES of every key,
+// including keys the caller never sent (merge-patch returns the merged whole).
+// SecretService's write ops MUST NOT surface those values to callers; they return
+// a `{name, namespace, keys}` summary so no admin route can leak values by echoing
+// the return. `getSecret` deliberately stays full-fat (internal consumers need
+// `.data`) and is not covered here. These tests go RED if any write op returns the
+// raw k8s Secret again.
+
+const b64 = (s: string): string => Buffer.from(s, 'utf8').toString('base64')
+
+// A fully-populated V1Secret as the k8s apiserver would return it from a write:
+// metadata + type + `.data` with base64 values for EVERY stored key.
+function fullSecret(
+ name: string,
+ namespace: string,
+ data: Record<string, string>
+): Record<string, unknown> {
+ return {
+ apiVersion: 'v1',
+ kind: 'Secret',
+ metadata: { name, namespace, resourceVersion: '42', uid: 'uid-1' },
+ type: 'Opaque',
+ data,
+ }
+}
+
+// The secret values that must NEVER appear in any write-op return value.
+const SENT_VALUE = b64('sk-caller-sent')
+const OTHER_VALUE = b64('xoxb-not-sent-by-caller')
+const RETURNED = fullSecret('cc-foo-credentials', 'channels', {
+ 'telegram-bot-token': SENT_VALUE,
+ // A key the caller did NOT send — merge-patch echoes the merged whole.
+ 'slack-bot-token': OTHER_VALUE,
+})
+
+function makeCoreApi(): Record<string, ReturnType<typeof vi.fn>> {
+ return {
+ createNamespacedSecret: vi.fn(async () => RETURNED),
+ readNamespacedSecret: vi.fn(async () => RETURNED),
+ replaceNamespacedSecret: vi.fn(async () => RETURNED),
+ patchNamespacedSecret: vi.fn(async () => RETURNED),
+ deleteNamespacedSecret: vi.fn(async () => ({ kind: 'Status', status: 'Success' })),
+ }
+}
+
+function makeService(): { svc: SecretService; core: Record<string, ReturnType<typeof vi.fn>> } {
+ const core = makeCoreApi()
+ const svc = new SecretService(core as never, 'default-ns')
+ return { svc, core }
+}
+
+// Asserts a write-op result is names-only: exact shape + no value at any depth.
+function expectNamesOnly(result: unknown, name: string, namespace: string, keys: string[]): void {
+ expect(result).toEqual({ name, namespace, keys })
+ const serialized = JSON.stringify(result)
+ for (const needle of [SENT_VALUE, OTHER_VALUE, 'sk-caller-sent', 'xoxb-not-sent-by-caller']) {
+ expect(serialized).not.toContain(needle)
+ }
+ // Defensive: no `.data` field survived.
+ expect((result as { data?: unknown }).data).toBeUndefined()
+}
+
+describe('SecretService — write ops return names-only summaries (no secret values)', () => {
+ it('createSecret returns {name, namespace, keys}, never the Secret .data', async () => {
+ const { svc } = makeService()
+ const result = await svc.createSecret({
+ name: 'cc-foo-credentials',
+ namespace: 'channels',
+ type: 'Opaque',
+ stringData: { 'telegram-bot-token': 'plaintext' },
+ })
+ // keys come from the returned Secret's data (sorted), never the values.
+ expectNamesOnly(result, 'cc-foo-credentials', 'channels', [
+ 'slack-bot-token',
+ 'telegram-bot-token',
+ ])
+ })
+
+ it('updateSecret (full-replace) returns names-only', async () => {
+ const { svc } = makeService()
+ const result = await svc.updateSecret({
+ name: 'cc-foo-credentials',
+ namespace: 'channels',
+ type: 'Opaque',
+ stringData: { 'telegram-bot-token': 'plaintext' },
+ })
+ expectNamesOnly(result, 'cc-foo-credentials', 'channels', [
+ 'slack-bot-token',
+ 'telegram-bot-token',
+ ])
+ })
+
+ it('mergeSecret returns names-only INCLUDING keys the caller did not send', async () => {
+ const { svc } = makeService()
+ const result = await svc.mergeSecret({
+ name: 'cc-foo-credentials',
+ namespace: 'channels',
+ type: 'Opaque',
+ stringData: { 'telegram-bot-token': 'plaintext' },
+ })
+ // The merged Secret carries slack-bot-token too; only its NAME may surface.
+ expectNamesOnly(result, 'cc-foo-credentials', 'channels', [
+ 'slack-bot-token',
+ 'telegram-bot-token',
+ ])
+ })
+
+ it('removeSecretKey returns names-only', async () => {
+ const { svc } = makeService()
+ const result = await svc.removeSecretKey({
+ name: 'cc-foo-credentials',
+ namespace: 'channels',
+ key: 'telegram-bot-token',
+ })
+ expectNamesOnly(result, 'cc-foo-credentials', 'channels', [
+ 'slack-bot-token',
+ 'telegram-bot-token',
+ ])
+ })
+
+ it('deleteSecret returns {name, namespace, deleted:true}, never a Secret body', async () => {
+ const { svc } = makeService()
+ const result = await svc.deleteSecret('cc-foo-credentials', 'channels')
+ expect(result).toEqual({ name: 'cc-foo-credentials', namespace: 'channels', deleted: true })
+ expect((result as { data?: unknown }).data).toBeUndefined()
+ })
+
+ it('deleteSecret fails loud: a k8s delete error propagates (never a synthetic success)', async () => {
+ const { svc, core } = makeService()
+ core.deleteNamespacedSecret.mockRejectedValueOnce(
+ Object.assign(new Error('forbidden'), { statusCode: 403 })
+ )
+ // The synthetic {deleted:true} must be reachable ONLY after a successful k8s
+ // delete — a failure must reject, not be swallowed into a fake success.
+ await expect(svc.deleteSecret('cc-foo-credentials', 'channels')).rejects.toThrow('forbidden')
+ })
+
+ it('namespace falls back to the service default when omitted', async () => {
+ const { svc } = makeService()
+ const result = (await svc.createSecret({
+ name: 'x',
+ type: 'Opaque',
+ stringData: { k: 'v' },
+ })) as { namespace: string }
+ expect(result.namespace).toBe('default-ns')
+ })
+})