Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): reject enabling a provider without its credentials (#312)
Jose Ramirez9bba22bd9d31
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 4f27babd1..31b8ca7a5 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.435",+ "version": "0.1.436","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.435",+ "version": "0.1.436","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.jsonindex 1c47faa52..c73ab25e9 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.435",+ "version": "0.1.436","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/resources.ts b/control-api/src/routes/admin/resources.tsindex 544704dc7..26033dfed 100644--- a/control-api/src/routes/admin/resources.ts+++ b/control-api/src/routes/admin/resources.ts@@ -6,6 +6,7 @@ import { validateCommunicationChannelSpec } from '../../http/validateCommunicatiimport { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec.js'import { K8sGateway } from '../../k8s.js'import { K8sConflictError } from '../../services/resourceService.js'+import { secretKeyNames } from '../../services/secretKeyNames.js'import { ClerumResourceType } from '../../types.js'import {registerCommunicationChannelCredentialsRoutes,@@ -211,6 +212,68 @@ function missingCreateCredentialKey(return null}+const PROVIDER_REQUIRED_KEYS: Record<string, string[]> = {+ telegram: ['telegram-bot-token'],+ slack: ['slack-bot-token', 'slack-signing-secret'],+ teams: ['teams-app-password'],+ email: ['email-username', 'email-password'],+}++function providersEnabled(spec: Record<string, unknown> | null): Set<string> {+ const enabled = new Set<string>()+ if (!spec) return enabled+ if (ccSpecHasTelegramProvider(spec)) enabled.add('telegram')+ if (ccSpecHasSlackProvider(spec)) enabled.add('slack')+ if (ccSpecHasTeamsProvider(spec)) enabled.add('teams')+ if (Array.isArray(spec.email) && spec.email.length > 0) enabled.add('email')+ return enabled+}++/**+ * Validate providers that go absent -> present. Returns an error message, or null.+ *+ * Deliberately scoped to the transition: a channel already missing keys in a+ * cluster stays editable, and enabling a NEW provider without its credentials is+ * refused. Presence of `credentialsSecretRef` proves nothing, which is why the+ * pre-existing POST guard missed this entirely — the channel that motivated this+ * (#312) already had a ref, holding only its Telegram token, and still accepted a+ * Slack App Name.+ *+ * Fails CLOSED: an unreadable Secret rejects the write. Refusing a write on a+ * read failure is safe; assuming the keys are there is how a channel ends up+ * advertising a provider it cannot serve.+ */+async function providerTransitionError(+ gateway: K8sGateway,+ nextSpec: Record<string, unknown>,+ previousSpec: Record<string, unknown> | null,+ credentials: Record<string, string> | undefined,+ namespace: string+): Promise<string | null> {+ const previouslyEnabled = providersEnabled(previousSpec)+ const added = [...providersEnabled(nextSpec)].filter(p => !previouslyEnabled.has(p))+ if (added.length === 0) return null++ const secretName = (nextSpec.credentialsSecretRef as { name?: string } | undefined)?.name?.trim()+ let existingKeys: string[] = []+ if (secretName) {+ try {+ existingKeys = await secretKeyNames(gateway, secretName, namespace)+ } catch {+ return `Cannot read the credentials Secret "${secretName}" to validate the new provider. Fix access to that Secret, or supply the credentials with this request.`+ }+ }++ for (const provider of added) {+ for (const key of PROVIDER_REQUIRED_KEYS[provider] || []) {+ if (!credentials?.[key] && !existingKeys.includes(key)) {+ return `credentials["${key}"] is required to enable the ${provider} provider on this CommunicationChannel`+ }+ }+ }+ return null+}+// workflowrecipes is handled by recipes.ts (canonical sandbox-recipes route).// workflowrecipepolicies is read inline by the recipes policy-invariant// helper and does not need generic admin CRUD routing.@@ -329,6 +392,21 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {})return}++ // Every declared provider is new on create, so the whole spec is the+ // transition. A credentialsSecretRef satisfies the guard above without+ // proving the Secret behind it holds this provider's keys.+ const transitionError = await providerTransitionError(+ gateway,+ body.spec,+ null,+ body.credentials,+ ns+ )+ if (transitionError) {+ res.status(400).json({ error: transitionError })+ return+ }}if (plural === 'communicationchannels' && body.credentials) {@@ -516,6 +594,23 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {),}: body+ if (isCommunicationChannelUpdate) {+ // updateBody.spec, not body.spec: the ref the write will actually carry+ // is the preserved one, and that is the Secret whose keys decide whether+ // a newly enabled provider can work. Reuses the snapshot already loaded+ // above — no second fetch.+ const transitionError = await providerTransitionError(+ gateway,+ updateBody.spec,+ previousCommunicationChannelSpec?.spec ?? null,+ undefined,+ ns+ )+ if (transitionError) {+ res.status(400).json({ error: transitionError })+ return+ }+ }try {const updated = await gateway.updateResource(plural, req.params.name, updateBody, ns)if (plural === 'communicationchannels' && body.spec) {diff --git a/control-api/test/routes.adminCommunicationChannelCredentials.test.ts b/control-api/test/routes.adminCommunicationChannelCredentials.test.tsindex c0adbd0d6..a75e3ea0d 100644--- a/control-api/test/routes.adminCommunicationChannelCredentials.test.ts+++ b/control-api/test/routes.adminCommunicationChannelCredentials.test.ts@@ -78,6 +78,9 @@ describe('admin communicationchannels — credentials cascade', () => {it('B4: POST provider CC (telegram) WITH credentialsSecretRef already in spec → ok (no 400)', async () => {// A user may pre-create the Secret and supply credentialsSecretRef directly.+ // The Secret must actually hold the provider's key: since #312 a ref alone+ // no longer proves the provider can work (routes.providerTransition.test.ts).+ gatewayMock.getSecret.mockResolvedValue({ data: { 'telegram-bot-token': 'dGc=' } })gatewayMock.createResource.mockResolvedValue({metadata: { name: 'bot', namespace: 'channels' },spec: { hostRef: 'h1', credentialsSecretRef: { name: 'my-existing-secret' } },@@ -119,7 +122,13 @@ describe('admin communicationchannels — credentials cascade', () => {// BUT the conventional cc-<name>-credentials Secret EXISTS.const e404 = Object.assign(new Error('not found'), { statusCode: 404 })gatewayMock.getResource.mockRejectedValue(e404) // existing CC 404 → no existing ref- gatewayMock.getSecret.mockResolvedValue({ metadata: { name: 'cc-bot-credentials' } })+ // Holds the Telegram key, so enabling telegram on a channel that had no+ // provider before passes the #312 transition check and the assertion under+ // test stays about ref re-injection.+ gatewayMock.getSecret.mockResolvedValue({+ metadata: { name: 'cc-bot-credentials' },+ data: { 'telegram-bot-token': 'dGc=' },+ })gatewayMock.updateResource.mockResolvedValue({metadata: { name: 'bot', namespace: 'channels' },spec: { hostRef: 'h1', credentialsSecretRef: { name: 'cc-bot-credentials' } },diff --git a/control-api/test/routes.providerTransition.test.ts b/control-api/test/routes.providerTransition.test.tsnew file mode 100644index 000000000..a38725d2d--- /dev/null+++ b/control-api/test/routes.providerTransition.test.ts@@ -0,0 +1,204 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import express from 'express'+import { ApiException } from '@kubernetes/client-node'+import request from 'supertest'+import type { K8sGateway } from '../src/k8s.js'+import { createAdminResourcesRouter } from '../src/routes/admin/resources.js'++// Same hand-crafted gateway double as routes.adminCommunicationChannelCredentials.test.ts:+// only the K8sGateway methods the CC write paths touch.+const gatewayMock = {+ 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(gatewayMock as unknown as K8sGateway))+ return app+}++/** The jose-tg channel as the cluster holds it: Telegram only, with a credentials Secret. */+const TELEGRAM_SPEC = {+ hostRef: 'h1',+ telegram: [{ channelId: '-1001', chatType: 'group', userIds: ['123'] }],+ telegramSettings: { botHandle: '@jose_tg_bot' },+}++const SECRET_REF = { credentialsSecretRef: { name: 'cc-jose-tg-credentials' } }++function persistedChannel(spec: Record<string, unknown>): Record<string, unknown> {+ return {+ metadata: { name: 'jose-tg', namespace: 'channels', resourceVersion: 'rv-1' },+ spec,+ }+}++describe('admin communicationchannels — provider transition validation (#312)', () => {+ beforeEach(() => {+ Object.values(gatewayMock).forEach(fn => fn.mockReset())+ // Echo the written spec back, the way the API server does when the CRD is+ // current. Anything less trips the pruned-provider-setting 409 instead.+ gatewayMock.updateResource.mockImplementation(+ async (_plural: string, name: string, body: { spec: Record<string, unknown> }) => ({+ metadata: { name, namespace: 'channels', resourceVersion: 'rv-2' },+ spec: body.spec,+ })+ )+ gatewayMock.createResource.mockImplementation(+ async (+ _plural: string,+ body: { metadata: { name: string }; spec: Record<string, unknown> }+ ) => ({+ metadata: { name: body.metadata.name, namespace: 'channels' },+ spec: body.spec,+ })+ )+ gatewayMock.createSecret.mockResolvedValue({})+ })++ // ── BLOCKING ─────────────────────────────────────────────────────────────++ it('PUT enabling Slack on a Telegram channel whose Secret holds only telegram-bot-token → 400', async () => {+ // The #312 regression: an operator typed a Slack App Name into an existing+ // Telegram channel. The channel already had a credentialsSecretRef, so the+ // pre-existing "no envelope and no ref" guard never fired, and the channel+ // went on to answer every Slack request with slack_signing_secret_missing.+ gatewayMock.getResource.mockResolvedValue(persistedChannel({ ...TELEGRAM_SPEC, ...SECRET_REF }))+ gatewayMock.getSecret.mockResolvedValue({ data: { 'telegram-bot-token': 'dGc=' } })++ const res = await request(makeApp())+ .put('/admin/communicationchannels/jose-tg')+ .send({ spec: { ...TELEGRAM_SPEC, slackSettings: { botHandle: 'Jose Bot' } } })++ expect(res.status).toBe(400)+ expect(res.body.error).toMatch(/slack-bot-token|slack-signing-secret/)+ expect(gatewayMock.updateResource).not.toHaveBeenCalled()+ })++ it('POST declaring Slack with a credentialsSecretRef whose Secret lacks the Slack keys → 400', async () => {+ // A ref proves a Secret is named, not that it holds Slack credentials.+ gatewayMock.getSecret.mockResolvedValue({ data: { 'telegram-bot-token': 'dGc=' } })++ const res = await request(makeApp())+ .post('/admin/communicationchannels')+ .send({+ metadata: { name: 'jose-slack' },+ spec: {+ hostRef: 'h1',+ slackSettings: { botHandle: 'Jose Bot' },+ credentialsSecretRef: { name: 'shared-secret' },+ },+ })++ expect(res.status).toBe(400)+ expect(res.body.error).toMatch(/slack-bot-token|slack-signing-secret/)+ expect(gatewayMock.createResource).not.toHaveBeenCalled()+ })++ // ── ALLOWING ─────────────────────────────────────────────────────────────+ // Without these, a validator that reads nothing at all still passes every+ // blocking case above.++ it('PUT enabling Slack where the referenced Secret ALREADY holds both Slack keys → 200', async () => {+ gatewayMock.getResource.mockResolvedValue(persistedChannel({ ...TELEGRAM_SPEC, ...SECRET_REF }))+ gatewayMock.getSecret.mockResolvedValue({+ data: {+ 'telegram-bot-token': 'dGc=',+ 'slack-bot-token': 'eG94Yi0x',+ 'slack-signing-secret': 'c2ln',+ },+ })++ const res = await request(makeApp())+ .put('/admin/communicationchannels/jose-tg')+ .send({ spec: { ...TELEGRAM_SPEC, slackSettings: { botHandle: 'Jose Bot' } } })++ expect(res.status).toBe(200)+ // The request body carries no credentialsSecretRef (the UI never sends one),+ // so the keys can only have come from the preserved ref being read.+ expect(gatewayMock.getSecret).toHaveBeenCalledWith('cc-jose-tg-credentials', 'channels')+ expect(gatewayMock.updateResource).toHaveBeenCalled()+ })++ it('POST declaring Slack with both keys in the credentials envelope → 201', async () => {+ const res = await request(makeApp())+ .post('/admin/communicationchannels')+ .send({+ metadata: { name: 'jose-slack' },+ spec: { hostRef: 'h1', slackSettings: { botHandle: 'Jose Bot' } },+ credentials: { 'slack-bot-token': 'xoxb-1', 'slack-signing-secret': 'sig-1' },+ })++ expect(res.status).toBe(201)+ expect(gatewayMock.createResource).toHaveBeenCalled()+ // Envelope-supplied keys need no Secret read at all.+ expect(gatewayMock.getSecret).not.toHaveBeenCalled()+ })++ it('PUT editing a channel whose Secret LACKS the provider keys, with no NEW provider → 200', async () => {+ // present -> present. Validation is scoped to the transition, so a channel+ // already missing credentials in the cluster stays editable.+ const slackSpec = { hostRef: 'h1', slackSettings: { botHandle: 'Jose Bot' } }+ gatewayMock.getResource.mockResolvedValue(persistedChannel({ ...slackSpec, ...SECRET_REF }))+ gatewayMock.getSecret.mockResolvedValue({ data: {} })++ const res = await request(makeApp())+ .put('/admin/communicationchannels/jose-tg')+ .send({ spec: { ...slackSpec, access: { users: ['user-1'], teams: [] } } })++ expect(res.status).toBe(200)+ expect(gatewayMock.updateResource).toHaveBeenCalled()+ })++ it('PUT REMOVING a provider from a channel with an empty Secret → 200', async () => {+ gatewayMock.getResource.mockResolvedValue(+ persistedChannel({+ ...TELEGRAM_SPEC,+ slackSettings: { botHandle: 'Jose Bot' },+ ...SECRET_REF,+ })+ )+ gatewayMock.getSecret.mockResolvedValue({ data: {} })++ const res = await request(makeApp())+ .put('/admin/communicationchannels/jose-tg')+ .send({ spec: { ...TELEGRAM_SPEC } })++ expect(res.status).toBe(200)+ expect(gatewayMock.updateResource).toHaveBeenCalled()+ })++ // ── FAIL CLOSED ──────────────────────────────────────────────────────────++ it('PUT enabling Slack when the Secret read fails with 403 → 400, never a silent 200', async () => {+ // A real @kubernetes/client-node ApiException: it sets `.code`, not+ // `.statusCode`. A hand-rolled error shape would not exercise the+ // status extraction that decides rethrow-vs-"no keys".+ gatewayMock.getResource.mockResolvedValue(persistedChannel({ ...TELEGRAM_SPEC, ...SECRET_REF }))+ gatewayMock.getSecret.mockRejectedValue(+ new ApiException(+ 403,+ 'Forbidden',+ { message: 'secrets "cc-jose-tg-credentials" is forbidden' },+ {}+ )+ )++ const res = await request(makeApp())+ .put('/admin/communicationchannels/jose-tg')+ .send({ spec: { ...TELEGRAM_SPEC, slackSettings: { botHandle: 'Jose Bot' } } })++ expect(res.status).toBe(400)+ expect(res.body.error).toMatch(/Cannot read the credentials Secret/)+ expect(gatewayMock.updateResource).not.toHaveBeenCalled()+ })+})diff --git a/control-api/test/routes.resourcesCommunicationChannelTransportUserIds.test.ts b/control-api/test/routes.resourcesCommunicationChannelTransportUserIds.test.tsindex b4b1fb2da..efd34047f 100644--- a/control-api/test/routes.resourcesCommunicationChannelTransportUserIds.test.ts+++ b/control-api/test/routes.resourcesCommunicationChannelTransportUserIds.test.ts@@ -58,6 +58,12 @@ describe('routes/resources CommunicationChannel Telegram transport userIds', (){ metadata: { name: 'agent-a-telegram' }, spec: { hostRef: 'agent-a' } },'channels')+ // The PUT turns telegram on (the stored CC has no provider yet), which since+ // #312 requires the provider's key to exist. Seeding the conventional Secret+ // keeps this test about userIds, not credentials.+ gateway.seedSecret('cc-agent-a-telegram-credentials', 'channels', {+ data: { 'telegram-bot-token': 'dGc=' },+ })const updateSpy = vi.spyOn(gateway, 'updateResource')const res = await request(makeApp(gateway))