Skip to content

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

TypeScript

fix: harden stepless Plugin Workload SDK runtime

Alfredo Lopezdd8363016c81
diff --git a/Makefile b/Makefile
index cbff3b060..7e067945e 100644
--- a/Makefile
+++ b/Makefile
@@ -784,6 +784,22 @@ test-e2e-plugin-workload-sdk: ## Run Plugin Workload SDK E2E gate (minikube only
fi
KUBECONTEXT="$${KUBECONTEXT:-$(E2E_KUBECONTEXT)}" bash scripts/e2e/e2e-plugin-workload-sdk.sh
+.PHONY: test-e2e-plugin-workload-sdk-desktop
+test-e2e-plugin-workload-sdk-desktop: ## Run the explicit opt-in Electron/WebContentsView Plugin Workload SDK gate
+ @set -eu; \
+ ctx="$${KUBECONTEXT:-$(E2E_KUBECONTEXT)}"; \
+ test -n "$$ctx" || { echo "Refusing Desktop Plugin Workload SDK E2E: explicit Kubernetes context is required" >&2; exit 1; }; \
+ test "$${E2E_PLUGIN_SDK_WRITE_CONFIRM:-}" = 1 || { echo "Refusing Desktop Plugin Workload SDK E2E: set E2E_PLUGIN_SDK_WRITE_CONFIRM=1" >&2; exit 1; }; \
+ test -n "$${CONTROL_UI_BASE_URL:-}" || { echo "CONTROL_UI_BASE_URL must be set to the branch-owned random port" >&2; exit 1; }; \
+ test -n "$${CONTROL_API_BASE_URL:-}" || { echo "CONTROL_API_BASE_URL must be set to the branch-owned random port" >&2; exit 1; }; \
+ test -n "$${EXTERNAL_REST_API_BASE_URL:-}" || { echo "EXTERNAL_REST_API_BASE_URL must be set to the branch-owned random port" >&2; exit 1; }; \
+ test -n "$${RPC_PROXY_BASE_URL:-}" || { echo "RPC_PROXY_BASE_URL must be set to the branch-owned random port" >&2; exit 1; }; \
+ . scripts/e2e/e2e-lib.sh; \
+ require_branch_profile_urls "$$ctx" "$${CLERUM_PROFILE_PORTS_ENV:-$${E2E_PROFILE_PORTS_ENV:-}}"; \
+ echo "[E2E-GUARD] Desktop Plugin Workload SDK gate: context=$$ctx; URLs supplied by the branch profile"; \
+ cd desktop-app && KUBECONTEXT="$$ctx" E2E_K8S_CONTEXT="$$ctx" E2E_PLUGIN_SDK_DESKTOP=1 npm run build && \
+ KUBECONTEXT="$$ctx" E2E_K8S_CONTEXT="$$ctx" E2E_PLUGIN_SDK_DESKTOP=1 ./node_modules/.bin/playwright test --config test/e2e-playwright/playwright.config.ts plugin-workload-sdk-sandbox-ui.spec.ts
+
.PHONY: test-e2e-cron-tab-validation
test-e2e-cron-tab-validation: ## Run recipe cron tab E2E (set E2E_CRON_TAB_FIX_REQUIRED=1 when the fix must be present)
@echo "Running cron tab validation E2E gate..."
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 99ec05d68..51b58b5b0 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.405",
+ "version": "0.1.406",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.405",
+ "version": "0.1.406",
"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 890187c21..47ddfe7f6 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.405",
+ "version": "0.1.406",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/middleware/pluginWorkloadSdkRateLimits.ts b/control-api/src/middleware/pluginWorkloadSdkRateLimits.ts
index cf1f7434c..ca33a0067 100644
--- a/control-api/src/middleware/pluginWorkloadSdkRateLimits.ts
+++ b/control-api/src/middleware/pluginWorkloadSdkRateLimits.ts
@@ -1,4 +1,5 @@
import type { RequestHandler } from 'express'
+import type { UiAuthedRequest } from './controlUIAuth.js'
import { rateLimitMiddleware } from './rateLimitMiddleware.js'
/**
@@ -33,3 +34,20 @@ export function createPluginWorkloadSdkInternalRateLimit(): RequestHandler {
},
})
}
+
+/**
+ * Operator grant/quota/audit routes are authenticated, but they still need a
+ * principal-scoped distributed abuse budget. Use a sentinel for an unexpected
+ * missing claim so a middleware ordering regression cannot silently bypass the
+ * limiter.
+ */
+export function createPluginWorkloadSdkAdminRateLimit(): RequestHandler {
+ return rateLimitMiddleware({
+ bucketType: 'plugin_workload_sdk_admin',
+ maxPerMinute: 120,
+ getBucketKey: req => {
+ const sub = (req as UiAuthedRequest).adminAuth?.sub
+ return `plugin_workload_sdk_admin:${sub || 'unauthenticated'}`
+ },
+ })
+}
diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.ts
index f3898236c..c2500aece 100644
--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts
+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts
@@ -6,6 +6,7 @@ import {
} from '@clerum/llm-providers'
import { asyncHandler } from '../../http/asyncHandler.js'
import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'
+import { createPluginWorkloadSdkAdminRateLimit } from '../../middleware/pluginWorkloadSdkRateLimits.js'
import { listEnabledModelNamesForProvider } from '../../services/llmAllowedModels.js'
import {
MAX_ALLOWLIST_ENTRY_LENGTH,
@@ -251,6 +252,7 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPro
export function createAdminPluginWorkloadSdkRouter(): Router {
const router = Router()
+ router.use('/admin/plugin-workload-sdk', createPluginWorkloadSdkAdminRateLimit())
router.get(
'/admin/plugin-workload-sdk/grants',
diff --git a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
index 075b92548..5d860e46d 100644
--- a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
+++ b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
@@ -156,6 +156,25 @@ function resolvePromptTarget(
}
}
+ // The HTTP parser rejects provider-only selectors, but the authorizer is
+ // also called by internal mcp-host paths and tests. Keep the invariant at
+ // the authority boundary so a provider cannot implicitly choose its first
+ // model/credential slot.
+ if (
+ params.provider !== undefined &&
+ params.model === undefined &&
+ params.targetRef === undefined &&
+ params.modelPolicyRef === undefined
+ ) {
+ return {
+ ok: false,
+ error: deny(
+ 'provider_policy_denied',
+ 'provider requires model, targetRef, or modelPolicyRef'
+ ),
+ }
+ }
+
let candidates: Array<{ target: PluginWorkloadSdkPromptTarget; index: number }> =
grant.promptTargets.map((target, index) => ({ target, index }))
let modelPolicy: PluginWorkloadSdkModelPolicy | null = null
@@ -625,8 +644,7 @@ export async function reissuePromptBridgeCredentialTicket(
})
return deny(
'provider_unavailable',
- 'credential ticket issuance is temporarily unavailable',
- true
+ 'credential ticket issuance failed after reserving a provider attempt; retry is not safe for this attempt'
)
}
return {
diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
index 7d31d9775..e545f53d4 100644
--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts
+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
@@ -4,6 +4,11 @@ import request from 'supertest'
import { pool } from '../src/db.js'
import { createAdminPluginWorkloadSdkRouter } from '../src/routes/admin/pluginWorkloadSdk.js'
import * as sdkDb from '../src/services/pluginWorkloadSdkDb.js'
+import { checkAndIncrement } from '../src/services/rateLimiterService.js'
+
+vi.mock('../src/services/rateLimiterService.js', () => ({
+ checkAndIncrement: vi.fn(),
+}))
vi.mock('../src/db.js', () => ({
pool: {
@@ -28,13 +33,13 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {
}
})
-function buildApp() {
+const DEFAULT_ADMIN_SUB = '11111111-1111-4111-8111-111111111111'
+
+function buildApp(sub: string | null = DEFAULT_ADMIN_SUB) {
const app = express()
app.use(express.json())
app.use((req, _res, next) => {
- ;(req as unknown as { adminAuth: { sub: string } }).adminAuth = {
- sub: '11111111-1111-4111-8111-111111111111',
- }
+ ;(req as unknown as { adminAuth: { sub?: string } }).adminAuth = sub === null ? {} : { sub }
next()
})
app.use(createAdminPluginWorkloadSdkRouter())
@@ -66,6 +71,14 @@ beforeEach(() => {
vi.mocked(sdkDb.getQuotaCounters).mockReset()
vi.mocked(sdkDb.getPluginWorkloadSdkLegacyGrantInventory).mockReset()
vi.mocked(sdkDb.listInvocations).mockReset()
+ vi.mocked(checkAndIncrement).mockReset()
+ vi.mocked(checkAndIncrement).mockResolvedValue({
+ allowed: true,
+ remaining: 119,
+ resetMs: Date.now() + 60_000,
+ windowStartMs: Date.now(),
+ count: 1,
+ })
// R3 allowlist cross-check (listEnabledModelNamesForProvider) queries pool.
// Default to the seed model so the valid-grant success paths pass; individual
// tests override to simulate a disallowed model.
@@ -74,6 +87,34 @@ beforeEach(() => {
})
describe('routes/admin/pluginWorkloadSdk — grants', () => {
+ it('applies a principal-scoped admin rate limit before grant reads', async () => {
+ vi.mocked(sdkDb.listGrants).mockResolvedValue([])
+
+ const res = await request(buildApp()).get('/admin/plugin-workload-sdk/grants')
+
+ expect(res.status).toBe(200)
+ expect(checkAndIncrement).toHaveBeenCalledWith(
+ 'plugin_workload_sdk_admin:11111111-1111-4111-8111-111111111111',
+ 120
+ )
+ })
+
+ it('keeps separate admin principals in separate rate-limit buckets', async () => {
+ vi.mocked(sdkDb.listGrants).mockResolvedValue([])
+
+ await request(buildApp('admin-a')).get('/admin/plugin-workload-sdk/grants')
+ await request(buildApp('admin-b')).get('/admin/plugin-workload-sdk/grants')
+ await request(buildApp(null)).get('/admin/plugin-workload-sdk/grants')
+
+ expect(checkAndIncrement).toHaveBeenNthCalledWith(1, 'plugin_workload_sdk_admin:admin-a', 120)
+ expect(checkAndIncrement).toHaveBeenNthCalledWith(2, 'plugin_workload_sdk_admin:admin-b', 120)
+ expect(checkAndIncrement).toHaveBeenNthCalledWith(
+ 3,
+ 'plugin_workload_sdk_admin:unauthenticated',
+ 120
+ )
+ })
+
it('lists grants with optional recipe filters', async () => {
vi.mocked(sdkDb.listGrants).mockResolvedValue([])
const res = await request(buildApp()).get(
diff --git a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts
index 48812c76d..6a20cb4b7 100644
--- a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts
@@ -370,6 +370,18 @@ describe('authorizePromptBridge', () => {
expect(sdkDb.insertInvocation).not.toHaveBeenCalled()
})
+ it('rejects a provider-only selector at the authorizer boundary', async () => {
+ vi.mocked(sdkDb.findGrant).mockResolvedValue(grant())
+ const result = await authorizePromptBridge({
+ claims: claims(),
+ ...basePromptParams,
+ provider: 'zai',
+ model: undefined,
+ })
+ expect(result).toMatchObject({ ok: false, error: 'provider_policy_denied' })
+ expect(sdkDb.insertInvocation).not.toHaveBeenCalled()
+ })
+
it('does not treat a legacy wildcard allowedModels entry as routing authority', async () => {
vi.mocked(sdkDb.findGrant).mockResolvedValue(grant({ allowedModels: ['*'] }))
const result = await authorizePromptBridge({
@@ -733,6 +745,32 @@ describe('reissuePromptBridgeCredentialTicket', () => {
expect(JSON.stringify(result.value)).not.toContain('secret-value')
})
+ it('marks a reserved attempt terminal when ticket-jti registration fails', async () => {
+ const policy = twoTargetGrant()
+ authorizedSuffix.policyHash = sdkDb.hashPromptTargetPolicy(policy)
+ vi.mocked(sdkDb.findGrant).mockResolvedValue(policy)
+ vi.mocked(sdkDb.getInvocationById).mockResolvedValue(
+ invocation({ promptAuthorization: { ...authorizedSuffix } })
+ )
+ vi.mocked(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).mockResolvedValue(false)
+
+ const result = await reissuePromptBridgeCredentialTicket({
+ claims: claims(),
+ invocationId: 'inv-1',
+ targetRef: 'openai-fallback',
+ attemptGeneration: 1,
+ })
+
+ expect(result).toMatchObject({
+ ok: false,
+ error: 'provider_unavailable',
+ retryable: false,
+ })
+ expect(sdkDb.markPluginWorkloadSdkProviderAttemptStatus).toHaveBeenCalledWith(
+ expect.objectContaining({ status: 'failed', invocationId: 'inv-1' })
+ )
+ })
+
it('fails closed for a body target outside the original authorization suffix', async () => {
vi.mocked(sdkDb.getInvocationById).mockResolvedValue(
invocation({
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 961298c21..18c7e81bc 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.333",
+ "version": "0.1.334",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.333",
+ "version": "0.1.334",
"license": "MPL-2.0",
"dependencies": {
"@clerum/desktop-app-links": "file:../packages/desktop-app-links",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index f95c2947a..734fef64c 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.333",
+ "version": "0.1.334",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts b/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts
index 2bc91ef57..70cd7eb74 100644
--- a/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts
+++ b/desktop-app/test/e2e-playwright/plugin-workload-sdk-sandbox-ui.spec.ts
@@ -453,8 +453,8 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the real
'E2E_PLUGIN_SDK_WRITE_CONFIRM',
'This journey performs one paid promptBridge call and sends one test notification.'
)
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
// Read-only setup assertion. Every functional action that follows is through
// the real Desktop UI and its native WebContentsView.
assertSteplessSdkRecipePrecondition()
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-agents.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-agents.spec.ts
index 1d09e286b..5003756e7 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-agents.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-agents.spec.ts
@@ -23,8 +23,8 @@ import {
// targets up front. See docs/testing/optional-playwright-qa-recorder.md.
test('optional QA recorder: Desktop agents journey — fleet', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
const hostRef = configuredHostRef()
@@ -54,8 +54,8 @@ test('optional QA recorder: Desktop agents journey — fleet', async ({}, testIn
})
test('optional QA recorder: Desktop agents journey — chat workspace', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
const hostRef = configuredHostRef()
@@ -88,8 +88,8 @@ test('optional QA recorder: Desktop agents journey — chat workspace', async ({
})
test('optional QA recorder: Desktop agents journey — workspace routes', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
const hostRef = configuredHostRef()
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-apps.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-apps.spec.ts
index b48ae614c..af88a607a 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-apps.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-apps.spec.ts
@@ -24,8 +24,8 @@ import {
// specific app name, because none is guaranteed by the fixture set.
//
test('optional QA recorder: Desktop apps journey', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-auth.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-auth.spec.ts
index 54e0c110e..48dd84dcb 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-auth.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-auth.spec.ts
@@ -17,8 +17,8 @@ import {
// starting state and there is no carryover between tests.
test('optional QA recorder: Desktop auth and session journey — sign-in screen', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
@@ -63,8 +63,8 @@ test('optional QA recorder: Desktop auth and session journey — sign-in screen'
})
test('optional QA recorder: Desktop auth and session journey — authenticated shell', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
@@ -108,8 +108,8 @@ test('optional QA recorder: Desktop auth and session journey — authenticated s
})
test('optional QA recorder: Desktop auth and session journey — logout', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-chat.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-chat.spec.ts
index 5965da400..76437e6bf 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-chat.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-chat.spec.ts
@@ -24,8 +24,8 @@ test('optional QA recorder: Desktop chat composer, thread, and task progress jou
'QA_RECORDER_CONFIRM_CHAT',
'This journey sends a real chat message and may incur model cost.'
)
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
const hostRef = configuredHostRef()
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-connectors.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-connectors.spec.ts
index 0fe3f21bc..2737b60d9 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-connectors.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-connectors.spec.ts
@@ -14,8 +14,8 @@ import {
// Read-only journey: no requireRecorderConfirm flag. The loopback + health
// guard still runs for both targets at the top of the test.
test('optional QA recorder: Desktop connectors journey', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-contexts.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-contexts.spec.ts
index b4ad3452e..9c9ae6c0f 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-contexts.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-contexts.spec.ts
@@ -15,8 +15,8 @@ import {
// No chat, no writes, no paid calls — so no confirm flag is required. The
// loopback + health guard still runs for both targets.
test('optional QA recorder: Desktop contexts list and detail journey', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts b/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts
index 4f64286e6..e5a2d7b0a 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-helpers.ts
@@ -48,7 +48,7 @@ export function requireRecorderConfirm(flag: string, description: string): void
}
/** Refuse non-loopback targets unless the operator explicitly allowed a remote QA env. */
-export function assertAllowedTarget(label: string, rawUrl: string): void {
+export async function assertAllowedTarget(label: string, rawUrl: string): Promise<void> {
let url: URL
try {
url = new URL(rawUrl)
@@ -63,7 +63,7 @@ export function assertAllowedTarget(label: string, rawUrl: string): void {
if (LOOPBACK_HOSTS.has(url.hostname) && process.env.QA_RECORDER_ALLOW_REMOTE !== '1') {
// Target is local — assert the endpoints are healthy right now so a recorder
// run fails fast with a clear message instead of a slow Electron timeout.
- void assertHealthy(rawUrl, label)
+ await assertHealthy(rawUrl, label)
}
}
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-inbox-search.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-inbox-search.spec.ts
index e48ae5618..b39284777 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-inbox-search.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-inbox-search.spec.ts
@@ -24,8 +24,8 @@ import {
// We deliberately do NOT click Approve/Deny (those mutate the backend).
test('optional QA recorder: Desktop inbox and search journey — inbox', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
@@ -69,8 +69,8 @@ test('optional QA recorder: Desktop inbox and search journey — inbox', async (
})
test('optional QA recorder: Desktop inbox and search journey — global search', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-navigation.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-navigation.spec.ts
index 17de70fa3..c82bab7a4 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-navigation.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-navigation.spec.ts
@@ -18,8 +18,8 @@ import {
// No confirm flag is required: nothing here writes, messages, or pays.
test('optional QA recorder: Desktop navigation journey — primary sidebar', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
@@ -56,8 +56,8 @@ test('optional QA recorder: Desktop navigation journey — primary sidebar', asy
})
test('optional QA recorder: Desktop navigation journey — footer settings menu', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
@@ -102,8 +102,8 @@ test('optional QA recorder: Desktop navigation journey — footer settings menu'
})
test('optional QA recorder: Desktop navigation journey — resources pages', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-plugins.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-plugins.spec.ts
index e8f14b4dd..a196dc048 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-plugins.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-plugins.spec.ts
@@ -26,8 +26,8 @@ import {
// the `.input-contract-form`, and the `Trigger`/`Triggering...` button.
test('optional QA recorder: Desktop plugins journey', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-settings-chat.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-settings-chat.spec.ts
index fcc2ef4f0..672103c63 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-settings-chat.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-settings-chat.spec.ts
@@ -21,8 +21,8 @@ test('optional QA recorder: Desktop settings and chat journey', async ({}, testI
'QA_RECORDER_CONFIRM_CHAT',
'This journey sends a real chat message and may incur model cost.'
)
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
const hostRef = configuredHostRef()
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-settings.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-settings.spec.ts
index d06112ff2..f4731b1bd 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-settings.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-settings.spec.ts
@@ -22,8 +22,8 @@ import {
// of the always-on read-only journey without a confirm flag.
test('optional QA recorder: Desktop settings journey — appearance and notifications', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
@@ -87,8 +87,8 @@ test('optional QA recorder: Desktop settings journey — appearance and notifica
})
test('optional QA recorder: Desktop settings journey — information and configuration', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-shared-files.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-shared-files.spec.ts
index cb64be2d3..1e2b9953b 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-shared-files.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-shared-files.spec.ts
@@ -27,8 +27,8 @@ import {
} from './qa-recorder-helpers'
test('optional QA recorder: Desktop shared files browser journey', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
diff --git a/desktop-app/test/e2e-playwright/qa-recorder-teams.spec.ts b/desktop-app/test/e2e-playwright/qa-recorder-teams.spec.ts
index fb763d762..6cbab6d27 100644
--- a/desktop-app/test/e2e-playwright/qa-recorder-teams.spec.ts
+++ b/desktop-app/test/e2e-playwright/qa-recorder-teams.spec.ts
@@ -15,8 +15,8 @@ import {
// No chat, no writes, no paid calls — so no confirm flag is required. The
// loopback + health guard still runs for both targets.
test('optional QA recorder: Desktop teams journey', async ({}, testInfo) => {
- assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
- assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
+ await assertAllowedTarget('EXTERNAL_REST_API_BASE_URL', EXTERNAL_REST_API_BASE_URL)
+ await assertAllowedTarget('RPC_PROXY_BASE_URL', RPC_PROXY_BASE_URL)
const credentials = desktopCredentials()
let app: ElectronApplication | undefined
diff --git a/desktop-app/test/qaRecorderHelpers.test.ts b/desktop-app/test/qaRecorderHelpers.test.ts
new file mode 100644
index 000000000..17942bd18
--- /dev/null
+++ b/desktop-app/test/qaRecorderHelpers.test.ts
@@ -0,0 +1,34 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { assertAllowedTarget } from './e2e-playwright/qa-recorder-helpers'
+
+describe('QA recorder target guard', () => {
+ const previousRemoteOptIn = process.env.QA_RECORDER_ALLOW_REMOTE
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ if (previousRemoteOptIn === undefined) delete process.env.QA_RECORDER_ALLOW_REMOTE
+ else process.env.QA_RECORDER_ALLOW_REMOTE = previousRemoteOptIn
+ })
+
+ it('awaits loopback health and fails before the journey when it is unavailable', async () => {
+ delete process.env.QA_RECORDER_ALLOW_REMOTE
+ const fetchMock = vi.fn().mockRejectedValue(new Error('connection refused'))
+ vi.stubGlobal('fetch', fetchMock)
+
+ await expect(
+ assertAllowedTarget('CONTROL_API_BASE_URL', 'http://127.0.0.1:36238')
+ ).rejects.toThrow(/CONTROL_API_BASE_URL not healthy/)
+ expect(fetchMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('only returns after the loopback health check succeeds', async () => {
+ delete process.env.QA_RECORDER_ALLOW_REMOTE
+ const fetchMock = vi.fn().mockResolvedValue({ status: 200 })
+ vi.stubGlobal('fetch', fetchMock)
+
+ await expect(
+ assertAllowedTarget('CONTROL_API_BASE_URL', 'http://127.0.0.1:36238')
+ ).resolves.toBeUndefined()
+ expect(fetchMock).toHaveBeenCalledWith('http://127.0.0.1:36238/health')
+ })
+})
diff --git a/docs/testing/optional-playwright-qa-recorder.md b/docs/testing/optional-playwright-qa-recorder.md
index 1aa80742d..6cbfbe647 100644
--- a/docs/testing/optional-playwright-qa-recorder.md
+++ b/docs/testing/optional-playwright-qa-recorder.md
@@ -68,39 +68,65 @@ launch/login/proof plumbing in `qa-recorder-helpers.ts`, uses the exact QA
identity from `.env.qa-recorder` (no first-available fallback), and records a
WebM + PNG under `.local-notes/qa-recorder/runs/desktop-app/`.
-| Journey | Spec | Notes |
-| --- | --- | --- |
-| Auth & session | `qa-recorder-auth.spec.ts` | Sign-in, authenticated shell, logout. Read-only. |
-| Navigation | `qa-recorder-navigation.spec.ts` | Sidebar, footer Settings/Resources menus, page shells. Read-only. |
-| Agents | `qa-recorder-agents.spec.ts` | Fleet, exact `chatllm` row, workspace routes. Read-only. |
-| Connectors | `qa-recorder-connectors.spec.ts` | MCP/connector health inventory. Read-only. |
-| Contexts | `qa-recorder-contexts.spec.ts` | List + detail tabs (`development`/`moneymaking`). Read-only. |
-| Shared files | `qa-recorder-shared-files.spec.ts` | Filesystem + directory browser. Read-only. |
-| Teams | `qa-recorder-teams.spec.ts` | Teams directory + detail tabs. Read-only. |
-| Plugins | `qa-recorder-plugins.spec.ts` | Inventory, detail, runs/artifacts. Trigger gated by `QA_RECORDER_CONFIRM_MUTATIONS`. |
-| Apps | `qa-recorder-apps.spec.ts` | Catalog + embedded session. Read-only. |
-| Settings | `qa-recorder-settings.spec.ts` | Appearance, notifications, configuration. Endpoint switch gated by `QA_RECORDER_CONFIRM_MUTATIONS`. |
-| Inbox & search | `qa-recorder-inbox-search.spec.ts` | Inbox, notifications, global search. Read-only. |
-| Chat | `qa-recorder-chat.spec.ts` | Composer, thread, task progress. Requires `QA_RECORDER_CONFIRM_CHAT=1`. |
+| Journey | Spec | Notes |
+| -------------- | ---------------------------------- | --------------------------------------------------------------------------------------------------- |
+| Auth & session | `qa-recorder-auth.spec.ts` | Sign-in, authenticated shell, logout. Read-only. |
+| Navigation | `qa-recorder-navigation.spec.ts` | Sidebar, footer Settings/Resources menus, page shells. Read-only. |
+| Agents | `qa-recorder-agents.spec.ts` | Fleet, exact `chatllm` row, workspace routes. Read-only. |
+| Connectors | `qa-recorder-connectors.spec.ts` | MCP/connector health inventory. Read-only. |
+| Contexts | `qa-recorder-contexts.spec.ts` | List + detail tabs (`development`/`moneymaking`). Read-only. |
+| Shared files | `qa-recorder-shared-files.spec.ts` | Filesystem + directory browser. Read-only. |
+| Teams | `qa-recorder-teams.spec.ts` | Teams directory + detail tabs. Read-only. |
+| Plugins | `qa-recorder-plugins.spec.ts` | Inventory, detail, runs/artifacts. Trigger gated by `QA_RECORDER_CONFIRM_MUTATIONS`. |
+| Apps | `qa-recorder-apps.spec.ts` | Catalog + embedded session. Read-only. |
+| Settings | `qa-recorder-settings.spec.ts` | Appearance, notifications, configuration. Endpoint switch gated by `QA_RECORDER_CONFIRM_MUTATIONS`. |
+| Inbox & search | `qa-recorder-inbox-search.spec.ts` | Inbox, notifications, global search. Read-only. |
+| Chat | `qa-recorder-chat.spec.ts` | Composer, thread, task progress. Requires `QA_RECORDER_CONFIRM_CHAT=1`. |
The combined `qa-recorder-settings-chat.spec.ts` smoke (Settings tabs + one chat
message) is unchanged. Read-only journeys need no confirmation flag; every
journey still calls the loopback health guard on both API URLs. Run one journey
with its namespaced command (below) or all of them with `npm run qa:recorder:all`.
+### Plugin Workload SDK Desktop gate
+
+`plugin-workload-sdk-sandbox-ui.spec.ts` is an explicit, manual-only gate. The
+normal Desktop Playwright suite intentionally skips it unless
+`E2E_PLUGIN_SDK_DESKTOP=1`; a skipped optional recorder is not a green SDK
+validation result. Run the dedicated Make target only after the branch-owned
+profile port map is exported and the operator has approved the one real
+prompt/notification journey:
+
+```bash
+E2E_PLUGIN_SDK_WRITE_CONFIRM=1 \
+CONTROL_UI_BASE_URL=http://127.0.0.1:<random-control-ui-port> \
+CONTROL_API_BASE_URL=http://127.0.0.1:<random-control-api-port> \
+EXTERNAL_REST_API_BASE_URL=http://127.0.0.1:<random-external-rest-port> \
+RPC_PROXY_BASE_URL=http://127.0.0.1:<random-rpc-port> \
+KUBECONTEXT=<branch-profile-context> \
+make test-e2e-plugin-workload-sdk-desktop
+```
+
+The target sets the opt-in flag only for this spec, requires non-default
+branch-owned URLs, and compares them with the exact `ports.env` generated for
+the selected branch profile. It runs the actual Electron/WebContentsView
+journey and fails before building if the profile map is missing or belongs to a
+different context. It does not start Minikube or create grants; those
+prerequisites must already be provided by the T2/T3 profile lane.
+
## Repository isolation
The recorder adds new commands; it does not alter any existing command:
-| Package | Optional command | Purpose |
-| ------------- | ----------------------------------- | ------------------------------------- |
-| `control-ui` | `npm run qa:recorder:install` | Download recorder-only Chromium |
-| `control-ui` | `npm run qa:recorder:agent-create` | Record the agent creation journey |
+| Package | Optional command | Purpose |
+| ------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `control-ui` | `npm run qa:recorder:install` | Download recorder-only Chromium |
+| `control-ui` | `npm run qa:recorder:agent-create` | Record the agent creation journey |
| `control-ui` | `npm run qa:recorder:<journey>` | Record one headful journey (`login`, `navigation`, `agents`, `contexts`, `connectors`, `external-channels`, `llm-models`, `users-teams`, `cost-usage`, `traces`, `settings`, `marketplace`) |
-| `control-ui` | `npm run qa:recorder:all` | Record every Control UI recorder journey |
-| `desktop-app` | `npm run qa:recorder:settings-chat` | Build and record the Settings+Chat Electron journey |
-| `desktop-app` | `npm run qa:recorder:<journey>` | Build and record one headful journey (`auth`, `navigation`, `agents`, `connectors`, `contexts`, `shared-files`, `teams`, `plugins`, `apps`, `settings`, `inbox-search`, `chat`) |
-| `desktop-app` | `npm run qa:recorder:all` | Build and record every Desktop recorder journey |
+| `control-ui` | `npm run qa:recorder:all` | Record every Control UI recorder journey |
+| `desktop-app` | `npm run qa:recorder:settings-chat` | Build and record the Settings+Chat Electron journey |
+| `desktop-app` | `npm run qa:recorder:<journey>` | Build and record one headful journey (`auth`, `navigation`, `agents`, `connectors`, `contexts`, `shared-files`, `teams`, `plugins`, `apps`, `settings`, `inbox-search`, `chat`) |
+| `desktop-app` | `npm run qa:recorder:all` | Build and record every Desktop recorder journey |
The normal `test`, `build`, `test:e2e:playwright`, and `test:e2e:all` commands
retain their existing behavior. The dedicated configs match only their
diff --git a/scripts/e2e/e2e-lib.sh b/scripts/e2e/e2e-lib.sh
index bb05580fa..3eead4061 100755
--- a/scripts/e2e/e2e-lib.sh
+++ b/scripts/e2e/e2e-lib.sh
@@ -43,6 +43,52 @@ is_branch_scoped_e2e_context() {
printf "%s\n" "$context" | grep -Eq '^clerum-[a-z0-9][a-z0-9-]*-[0-9a-f]{8}$'
}
+# A branch-scoped context is only valid with the port-forward map generated by
+# clerum/.local-notes/minikube-profiles/branch.mk for that exact context. A
+# non-empty URL is not sufficient: another profile can be healthy on the same
+# machine and would otherwise make a Desktop run appear to validate the wrong
+# cluster.
+require_branch_profile_urls() {
+ local context="$1"
+ local ports_env="${2:-${HOME}/.cache/clerum/minikube-profiles/${context}/ports.env}"
+ if ! is_branch_scoped_e2e_context "$context"; then
+ return 0
+ fi
+ if [[ ! -f "$ports_env" ]]; then
+ echo "Refusing E2E for branch context ${context}: profile ports.env is missing at ${ports_env}" >&2
+ return 1
+ fi
+
+ profile_url() {
+ local key="$1"
+ awk -F= -v expected_key="$key" '$1 == expected_key { sub(/^[^=]*=/, ""); print; exit }' "$ports_env"
+ }
+ normalize_url() {
+ local value="$1"
+ printf '%s' "${value%/}"
+ }
+
+ local pair name expected_key actual expected
+ for pair in \
+ 'CONTROL_UI_BASE_URL CONTROL_UI_URL' \
+ 'CONTROL_API_BASE_URL CONTROL_API_URL' \
+ 'EXTERNAL_REST_API_BASE_URL EXTERNAL_REST_API_URL' \
+ 'RPC_PROXY_BASE_URL RPC_PROXY_URL'; do
+ name="${pair%% *}"
+ expected_key="${pair#* }"
+ actual="${!name:-}"
+ expected="$(profile_url "$expected_key")"
+ if [[ -z "$expected" ]]; then
+ echo "Refusing E2E for branch context ${context}: ${expected_key} is missing from ${ports_env}" >&2
+ return 1
+ fi
+ if [[ "$(normalize_url "$actual")" != "$(normalize_url "$expected")" ]]; then
+ echo "Refusing E2E for branch context ${context}: ${name}=${actual} does not match ${expected_key} from ${ports_env}" >&2
+ return 1
+ fi
+ done
+}
+
is_allowed_e2e_context() {
local context=$1
case ",${E2E_ALLOWED_CONTEXTS}," in
diff --git a/scripts/tests/test-branch-profile-port-guard.sh b/scripts/tests/test-branch-profile-port-guard.sh
new file mode 100755
index 000000000..de614b3b8
--- /dev/null
+++ b/scripts/tests/test-branch-profile-port-guard.sh
@@ -0,0 +1,37 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)"
+source "${ROOT_DIR}/scripts/e2e/e2e-lib.sh"
+
+tmp_dir="$(mktemp -d)"
+trap 'rm -rf "$tmp_dir"' EXIT
+
+context='clerum-codex-port-guard-deadbeef'
+ports_env="${tmp_dir}/ports.env"
+cat >"${ports_env}" <<'EOF_PORTS'
+CONTROL_UI_URL=http://127.0.0.1:36148
+CONTROL_API_URL=http://127.0.0.1:36238
+EXTERNAL_REST_API_URL=http://127.0.0.1:36239
+RPC_PROXY_URL=http://127.0.0.1:36242
+EOF_PORTS
+
+export CONTROL_UI_BASE_URL=http://127.0.0.1:36148
+export CONTROL_API_BASE_URL=http://127.0.0.1:36238
+export EXTERNAL_REST_API_BASE_URL=http://127.0.0.1:36239
+export RPC_PROXY_BASE_URL=http://127.0.0.1:36242
+
+require_branch_profile_urls "$context" "$ports_env"
+
+CONTROL_API_BASE_URL=http://127.0.0.1:36239
+if require_branch_profile_urls "$context" "$ports_env" >/dev/null 2>&1; then
+ echo 'FAIL: accepted a URL belonging to a different profile' >&2
+ exit 1
+fi
+
+if require_branch_profile_urls "$context" "${tmp_dir}/missing.env" >/dev/null 2>&1; then
+ echo 'FAIL: accepted a branch profile without ports.env' >&2
+ exit 1
+fi
+
+echo 'PASS: branch profile URL guard requires the exact generated ports.env mapping'
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index c0726c802..e458ac12e 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.274",
+ "version": "0.1.275",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.274",
+ "version": "0.1.275",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index f22f46a34..640c1c818 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.274",
+ "version": "0.1.275",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/mcp/server.pluginSdkBroker.test.ts b/workflow-recipes/src/mcp/server.pluginSdkBroker.test.ts
index 0d594b6ce..501931387 100644
--- a/workflow-recipes/src/mcp/server.pluginSdkBroker.test.ts
+++ b/workflow-recipes/src/mcp/server.pluginSdkBroker.test.ts
@@ -1,7 +1,9 @@
import { describe, expect, it, vi } from 'vitest'
+import { PassThrough } from 'node:stream'
import {
ClerumMcpServer,
bindPluginSdkCredentialTarget,
+ parseJsonBody,
pluginSdkCredentialTargetEchoMatches,
revalidatePluginSdkCredentialTicket,
} from './server'
@@ -13,6 +15,29 @@ function response(status: number, body: unknown): Response {
})
}
+async function parseBody(body: string) {
+ const request = new PassThrough()
+ const parsed = parseJsonBody(request as never)
+ request.end(body)
+ return parsed
+}
+
+describe('WRC JSON body boundary', () => {
+ it.each(['null', '[]', '"scalar"', '42', 'true'])(
+ 'rejects JSON %s because the endpoint contract requires an object',
+ async body => {
+ await expect(parseBody(body)).resolves.toEqual({ ok: false, reason: 'invalid_json' })
+ }
+ )
+
+ it('accepts a JSON object', async () => {
+ await expect(parseBody('{"messages":[]}')).resolves.toEqual({
+ ok: true,
+ body: { messages: [] },
+ })
+ })
+})
+
describe('WRC Plugin SDK credential ticket TOCTOU revalidation', () => {
it('denies a body target mismatch before the resolver and returns only signed claims', () => {
const signedTarget = {
diff --git a/workflow-recipes/src/mcp/server.ts b/workflow-recipes/src/mcp/server.ts
index ff481f441..c6e03e593 100644
--- a/workflow-recipes/src/mcp/server.ts
+++ b/workflow-recipes/src/mcp/server.ts
@@ -125,7 +125,7 @@ type ParseResult =
| { ok: true; body: Record<string, unknown> }
| { ok: false; reason: 'too_large' | 'invalid_json' | 'stream_error' }
-function parseJsonBody(req: http.IncomingMessage): Promise<ParseResult> {
+export function parseJsonBody(req: http.IncomingMessage): Promise<ParseResult> {
return new Promise(resolve => {
let data = ''
let size = 0
@@ -145,7 +145,12 @@ function parseJsonBody(req: http.IncomingMessage): Promise<ParseResult> {
if (settled) return
settled = true
try {
- resolve({ ok: true, body: JSON.parse(data) })
+ const parsed: unknown = JSON.parse(data)
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
+ resolve({ ok: false, reason: 'invalid_json' })
+ return
+ }
+ resolve({ ok: true, body: parsed as Record<string, unknown> })
} catch {
resolve({ ok: false, reason: 'invalid_json' })
}
diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts
index 2279f555a..073afcb9d 100644
--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts
+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts
@@ -92,8 +92,20 @@ describe('validatePluginWorkloadSdkSpec', () => {
const errors = validatePluginWorkloadSdkSpec(
baseSpec({ promptBridge: {}, allowedCallers: ['api'] }, { workloads: undefined })
)
- expect(errors).toHaveLength(1)
- expect(errors[0]).toContain('"api" does not reference any spec.workloads[].id')
+ expect(errors).toHaveLength(2)
+ expect(errors).toContain(
+ 'pluginWorkloadSdk SDK-only recipes require at least one spec.workloads entry'
+ )
+ expect(
+ errors.some(error => error.includes('"api" does not reference any spec.workloads[].id'))
+ ).toBe(true)
+ })
+
+ it('rejects SDK-only recipes with an explicitly empty workloads list', () => {
+ const errors = validatePluginWorkloadSdkSpec(baseSpec({ promptBridge: {} }, { workloads: [] }))
+ expect(errors).toEqual([
+ 'pluginWorkloadSdk SDK-only recipes require at least one spec.workloads entry',
+ ])
})
it('rejects wildcard entries in allowedEventTypes', () => {
@@ -275,6 +287,15 @@ describe('buildPluginWorkloadSdkStatus', () => {
promptBridge: true,
clientNotifications: false,
message: 'Disabled (feature flag off)',
+ validatedAt: null,
+ bootstrapContractVersion: null,
+ bootstrapPodUid: null,
+ bootstrapProvider: null,
+ bootstrapModel: null,
+ policyRevision: null,
+ policyHash: null,
+ defaultTargetRef: null,
+ verifiedAt: null,
})
})
@@ -358,6 +379,15 @@ describe('buildPluginWorkloadSdkStatus', () => {
promptBridge: true,
clientNotifications: false,
message: 'Capability validated, but the configured provider is unavailable',
+ validatedAt: null,
+ bootstrapContractVersion: null,
+ bootstrapPodUid: null,
+ bootstrapProvider: null,
+ bootstrapModel: null,
+ policyRevision: null,
+ policyHash: null,
+ defaultTargetRef: null,
+ verifiedAt: null,
})
})
@@ -401,6 +431,58 @@ describe('buildPluginWorkloadSdkStatus', () => {
state: 'awaiting_policy',
promptBridge: true,
clientNotifications: false,
+ validatedAt: null,
+ policyRevision: null,
+ policyHash: null,
+ defaultTargetRef: null,
+ })
+ })
+
+ it('clears validated metadata when the capability degrades after a prior validation', () => {
+ const validated = buildPluginWorkloadSdkStatus({
+ spec: baseSpec({ promptBridge: {} }),
+ existingConditions: undefined,
+ phase: 'active',
+ featureFlagEnabled: true,
+ bootstrapProof: {
+ ready: true,
+ contractVersion: 2,
+ podUid: 'old-pod',
+ provider: 'openai',
+ model: 'gpt-5.4-mini',
+ policyRevision: 7,
+ policyHash: 'b'.repeat(64),
+ defaultTargetRef: 'primary-openai',
+ verifiedAt: NOW,
+ },
+ now: NOW,
+ })
+ expect(validated.capability).toMatchObject({
+ state: 'validated',
+ policyRevision: 7,
+ policyHash: 'b'.repeat(64),
+ defaultTargetRef: 'primary-openai',
+ })
+
+ const degraded = buildPluginWorkloadSdkStatus({
+ spec: baseSpec({ promptBridge: {} }),
+ existingConditions: undefined,
+ phase: 'degraded',
+ featureFlagEnabled: true,
+ providerUnavailable: true,
+ now: NOW,
+ })
+ expect(degraded.capability).toMatchObject({
+ state: 'degraded',
+ validatedAt: null,
+ bootstrapContractVersion: null,
+ bootstrapPodUid: null,
+ bootstrapProvider: null,
+ bootstrapModel: null,
+ policyRevision: null,
+ policyHash: null,
+ defaultTargetRef: null,
+ verifiedAt: null,
})
})
diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts
index a5991d51c..7367e23a9 100644
--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts
+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts
@@ -71,6 +71,9 @@ export function validatePluginWorkloadSdkSpec(spec: WorkflowRecipeSpec): string[
const hasWorkflowSteps = (spec.steps?.length ?? 0) > 0
if (!hasWorkflowSteps) {
+ if (!Array.isArray(spec.workloads) || spec.workloads.length === 0) {
+ errors.push('pluginWorkloadSdk SDK-only recipes require at least one spec.workloads entry')
+ }
const configuredWorkflowFields = SDK_ONLY_WORKFLOW_FIELDS.filter(field => {
switch (field) {
case 'triggers':
@@ -196,6 +199,23 @@ export interface PluginWorkloadSdkBootstrapProofInput {
verifiedAt: string
}
+/**
+ * JSON merge-patch preserves omitted object members. Keep the status
+ * projection's derived metadata explicit so a validated record cannot leave
+ * stale bootstrap/policy identity behind after a degraded transition.
+ */
+const CLEARED_PLUGIN_WORKLOAD_SDK_METADATA = {
+ validatedAt: null,
+ bootstrapContractVersion: null,
+ bootstrapPodUid: null,
+ bootstrapProvider: null,
+ bootstrapModel: null,
+ policyRevision: null,
+ policyHash: null,
+ defaultTargetRef: null,
+ verifiedAt: null,
+} as const
+
/**
* Project `spec.pluginWorkloadSdk` + feature flag + reconcile outcome into
* the status condition and capability record.
@@ -270,6 +290,7 @@ export function buildPluginWorkloadSdkStatus(args: {
promptBridge,
clientNotifications,
message,
+ ...CLEARED_PLUGIN_WORKLOAD_SDK_METADATA,
},
}
}
@@ -298,6 +319,7 @@ export function buildPluginWorkloadSdkStatus(args: {
promptBridge,
clientNotifications,
message,
+ ...CLEARED_PLUGIN_WORKLOAD_SDK_METADATA,
},
}
}
@@ -329,6 +351,7 @@ export function buildPluginWorkloadSdkStatus(args: {
promptBridge,
clientNotifications,
message,
+ ...CLEARED_PLUGIN_WORKLOAD_SDK_METADATA,
...(bootstrapProof
? {
bootstrapContractVersion: bootstrapProof.contractVersion,
@@ -359,6 +382,7 @@ export function buildPluginWorkloadSdkStatus(args: {
promptBridge,
clientNotifications,
message,
+ ...CLEARED_PLUGIN_WORKLOAD_SDK_METADATA,
},
}
}
@@ -385,6 +409,7 @@ export function buildPluginWorkloadSdkStatus(args: {
promptBridge,
clientNotifications,
message: `Capability validated (${families})`,
+ ...CLEARED_PLUGIN_WORKLOAD_SDK_METADATA,
validatedAt: now,
...(bootstrapProof
? {
diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
index 4d70fac3e..952dd8862 100644
--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
@@ -772,11 +772,14 @@ export class WorkflowRecipeReconciler {
* disabled keeps a stale host/token reachable only behind an explicit
* requeue, until the cleanup dependency is available and converges.
*/
- private async cleanupPluginWorkloadSdkOrThrow(recipeName: string): Promise<void> {
+ private async cleanupPluginWorkloadSdkOrThrow(
+ recipeName: string,
+ options: { preserveWorkflowRuntime?: boolean } = {}
+ ): Promise<void> {
if (!this.workflowReconciler) {
throw new Error('workflow subsystem is not initialized; SDK cleanup cannot be confirmed')
}
- await this.workflowReconciler.cleanupPluginWorkloadSdk(recipeName)
+ await this.workflowReconciler.cleanupPluginWorkloadSdk(recipeName, options)
}
private async waitForTransportNetworkReadiness(
@@ -1263,7 +1266,9 @@ export class WorkflowRecipeReconciler {
// intentionally restricted to the stepless adapter.
if (!isWorkflow && recipe.spec.pluginWorkloadSdk && !this.config.pluginWorkloadSdkEnabled) {
try {
- await this.cleanupPluginWorkloadSdkOrThrow(name)
+ await this.cleanupPluginWorkloadSdkOrThrow(name, {
+ preserveWorkflowRuntime: isWorkflow,
+ })
} catch (error) {
return {
phase: 'failed' as RecipePhase,
@@ -1293,7 +1298,9 @@ export class WorkflowRecipeReconciler {
// only after this fail-closed cleanup succeeds.
if (!recipe.spec.pluginWorkloadSdk && recipe.status?.pluginWorkloadSdk) {
try {
- await this.cleanupPluginWorkloadSdkOrThrow(name)
+ await this.cleanupPluginWorkloadSdkOrThrow(name, {
+ preserveWorkflowRuntime: isWorkflow,
+ })
} catch (error) {
return {
phase: 'failed' as RecipePhase,
@@ -3196,7 +3203,7 @@ export class WorkflowRecipeReconciler {
// the shared mcp-host/token resources. Hybrid recipes must not bypass
// broker revocation merely because they also have coordinator state.
if (recipe.spec.pluginWorkloadSdk || recipe.status?.pluginWorkloadSdk) {
- await this.cleanupPluginWorkloadSdkOrThrow(name)
+ await this.cleanupPluginWorkloadSdkOrThrow(name, { preserveWorkflowRuntime: true })
}
await this.workflowReconciler.reconcileDelete(name, recipe.metadata.namespace, recipe.spec)
await this.cleanupDelegationIfNeeded(recipe)
diff --git a/workflow-recipes/src/types.ts b/workflow-recipes/src/types.ts
index b14b06bb7..0e26a2edb 100644
--- a/workflow-recipes/src/types.ts
+++ b/workflow-recipes/src/types.ts
@@ -540,15 +540,18 @@ export interface PluginWorkloadSdkCapabilityStatus {
promptBridge: boolean
clientNotifications: boolean
message?: string
- validatedAt?: string
- bootstrapContractVersion?: 2
- bootstrapPodUid?: string
- bootstrapProvider?: string
- bootstrapModel?: string
- policyRevision?: number
- policyHash?: string
- defaultTargetRef?: string
- verifiedAt?: string
+ // These fields are merge-patch clearable. A non-validated projection must
+ // explicitly send null so a previous validated record cannot survive a
+ // later degraded/awaiting-policy transition.
+ validatedAt?: string | null
+ bootstrapContractVersion?: 2 | null
+ bootstrapPodUid?: string | null
+ bootstrapProvider?: string | null
+ bootstrapModel?: string | null
+ policyRevision?: number | null
+ policyHash?: string | null
+ defaultTargetRef?: string | null
+ verifiedAt?: string | null
}
// ─── WorkflowRecipe CRD ─────────────────────────────────────────────────
diff --git a/workflow-recipes/src/workflow/networkPolicyFactory.gfs.test.ts b/workflow-recipes/src/workflow/networkPolicyFactory.gfs.test.ts
index fdb80f533..17d2ed201 100644
--- a/workflow-recipes/src/workflow/networkPolicyFactory.gfs.test.ts
+++ b/workflow-recipes/src/workflow/networkPolicyFactory.gfs.test.ts
@@ -73,6 +73,20 @@ describe('workflow GFS NetworkPolicy', () => {
expect(names).toContain('daily-report-workload-to-mcp-host-sdk-ingress')
})
+ it('allows public runtime egress only over HTTPS', () => {
+ const policies = buildWorkflowNetworkPolicies({
+ ...baseConfig,
+ coordinatorPublicHttpEgress: true,
+ coordinatorPublicHttpEgressClass: 'public-web',
+ })
+ const policy = policies.find(np => np.metadata?.name === 'daily-report-coord-to-wrc')
+ const publicRule = policy?.spec?.egress?.find(rule =>
+ rule.to?.some(destination => destination.ipBlock !== undefined)
+ )
+
+ expect(publicRule?.ports).toEqual([{ port: 443, protocol: 'TCP' }])
+ })
+
it('opens coordinator egress to gfsc only when workflow output publishing is enabled', () => {
const withoutPublish = buildWorkflowNetworkPolicies({ ...baseConfig, includeMcpHost: false })
expect(withoutPublish.some(np => np.metadata?.name === 'daily-report-coordinator-to-gfs')).toBe(
diff --git a/workflow-recipes/src/workflow/networkPolicyFactory.ts b/workflow-recipes/src/workflow/networkPolicyFactory.ts
index eb1928722..9b7e8f9fd 100644
--- a/workflow-recipes/src/workflow/networkPolicyFactory.ts
+++ b/workflow-recipes/src/workflow/networkPolicyFactory.ts
@@ -164,10 +164,9 @@ function buildPublicHttpEgressRule(cidrs?: string[]): k8s.V1NetworkPolicyEgressR
if (exactCidrs.length > 0) {
return {
to: exactCidrs.map(cidr => ({ ipBlock: { cidr } })),
- ports: [
- { port: 443, protocol: 'TCP' },
- { port: 80, protocol: 'TCP' },
- ],
+ // Public runtime egress is HTTPS-only. Plain HTTP would allow a
+ // compromised workload to exfiltrate credentials or prompt content.
+ ports: [{ port: 443, protocol: 'TCP' }],
}
}
@@ -180,10 +179,7 @@ function buildPublicHttpEgressRule(cidrs?: string[]): k8s.V1NetworkPolicyEgressR
},
},
],
- ports: [
- { port: 443, protocol: 'TCP' },
- { port: 80, protocol: 'TCP' },
- ],
+ ports: [{ port: 443, protocol: 'TCP' }],
}
}
diff --git a/workflow-recipes/src/workflow/workflowReconciler.test.ts b/workflow-recipes/src/workflow/workflowReconciler.test.ts
index 9e1da1bb6..d0231a17e 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.test.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.test.ts
@@ -1628,6 +1628,38 @@ describe('WorkflowReconciler — Plugin Workload SDK eager mcp-host', () => {
expect(mockCoreApi.createNamespacedPod).not.toHaveBeenCalled()
})
+ it('removes only SDK-owned authority from a hybrid workflow runtime', async () => {
+ const reconciler = new WorkflowReconciler(makeDeps())
+
+ await expect(
+ reconciler.cleanupPluginWorkloadSdk('hybrid', { preserveWorkflowRuntime: true })
+ ).resolves.toBeUndefined()
+
+ expect(mockCoreApi.deleteNamespacedSecret).toHaveBeenCalledWith({
+ name: 'wf-hybrid-plugin-workload-sdk-token',
+ namespace: sandboxNamespace,
+ })
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'hybrid-workload-to-mcp-host-sdk-ingress',
+ namespace: sandboxNamespace,
+ })
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'hybrid-workload-to-mcp-host-sdk-egress',
+ namespace: sandboxNamespace,
+ })
+ expect(mockNetworkingApi.deleteNamespacedNetworkPolicy).toHaveBeenCalledWith({
+ name: 'hybrid-mcp-host-to-wrc-sdk-broker',
+ namespace: sandboxNamespace,
+ })
+ expect(mockCoreApi.deleteNamespacedService).not.toHaveBeenCalled()
+ expect(mockCoreApi.deleteNamespacedPod).not.toHaveBeenCalled()
+ expect(mockCoreApi.deleteNamespacedSecret).not.toHaveBeenCalledWith({
+ name: 'wf-hybrid-mcp-host-runtime-tokens',
+ namespace: sandboxNamespace,
+ })
+ expect(mockNetworkingApi.listNamespacedNetworkPolicy).not.toHaveBeenCalled()
+ })
+
it('fails closed before physical cleanup when the Control API revocation client is absent', async () => {
const deps = makeDeps() as unknown as { pluginWorkloadSdkRevocationClient?: unknown }
delete deps.pluginWorkloadSdkRevocationClient
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index 8496c74c1..3eef01263 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -170,6 +170,16 @@ type ExternalWorkflowOutputPvcState =
| 'wrc-managed-conflict'
| 'unauthorized'
+export interface PluginWorkloadSdkCleanupOptions {
+ /**
+ * Hybrid workflow recipes share their mcp-host, runtime token Secret and
+ * workflow network policies with the SDK lane. Remove only SDK-owned
+ * authority when the capability is edited out; the workflow reconciler
+ * remains the owner of shared runtime resources.
+ */
+ preserveWorkflowRuntime?: boolean
+}
+
export const WORKFLOW_OUTPUT_CONDITION_TYPES = new Set([
'WorkflowOutputRwoCompatibility',
'WorkflowOutputWrcManagedLifecycle',
@@ -952,18 +962,27 @@ export class WorkflowReconciler {
* coordinator teardown so both SDK-only and hybrid recipes share the same
* authorization-fencing invariant.
*/
- async cleanupPluginWorkloadSdk(recipeName: string): Promise<void> {
+ async cleanupPluginWorkloadSdk(
+ recipeName: string,
+ options: PluginWorkloadSdkCleanupOptions = {}
+ ): Promise<void> {
const ns = this.deps.config.sandboxNamespace
+ const preserveWorkflowRuntime = options.preserveWorkflowRuntime === true
this.pluginWorkloadSdkProvisioner.clearRecipeState(recipeName)
- const networkPolicyNames = [
+ const sdkNetworkPolicyNames = [
`${recipeName}-workload-to-mcp-host-sdk-ingress`,
`${recipeName}-workload-to-mcp-host-sdk-egress`,
`${recipeName}-mcp-host-to-wrc-sdk-broker`,
+ ]
+ const sharedNetworkPolicyNames = [
`${recipeName}-mcp-host-to-servers`,
`${recipeName}-mcp-host-to-llm-api`,
`${recipeName}-mcp-host-to-gfs`,
`${recipeName}-mcp-host-to-approval-gateway`,
]
+ const networkPolicyNames = preserveWorkflowRuntime
+ ? sdkNetworkPolicyNames
+ : [...sdkNetworkPolicyNames, ...sharedNetworkPolicyNames]
let revocationReceipt: PluginWorkloadSdkRevocationReceipt | null = null
const revocationClient = this.deps.pluginWorkloadSdkRevocationClient
if (!revocationClient) {
@@ -991,62 +1010,82 @@ export class WorkflowReconciler {
// token Secrets. This ordering is the revocation boundary: a live pod
// cannot keep receiving broker traffic while its credentials are being
// deleted, and a failed delete is requeued instead of reported as disabled.
- await this.teardownDelete(() =>
- this.deps.coreApi.deleteNamespacedService({
- name: buildMcpHostServiceName(recipeName),
- namespace: ns,
- })
- )
+ if (!preserveWorkflowRuntime) {
+ await this.teardownDelete(() =>
+ this.deps.coreApi.deleteNamespacedService({
+ name: buildMcpHostServiceName(recipeName),
+ namespace: ns,
+ })
+ )
+ }
await Promise.all([
- ...networkPolicyNames.map(name =>
+ ...sdkNetworkPolicyNames.map(name =>
this.teardownDelete(() =>
this.deps.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace: ns })
)
),
+ ...(preserveWorkflowRuntime
+ ? []
+ : sharedNetworkPolicyNames.map(name =>
+ this.teardownDelete(() =>
+ this.deps.networkingApi.deleteNamespacedNetworkPolicy({ name, namespace: ns })
+ )
+ )),
// Older SDK-only reconciles used the shared workflow policy factory and
// left coordinator-shaped policies behind. Sweep the complete recipe
// label set so upgrades and dynamic policy names cannot retain a stale
// isolation lane. The selector is recipe-scoped and only matches WRC-
// managed policies, never the namespace-wide baseline policies.
- this.teardownDelete(() =>
- this.deleteNetworkPoliciesByLabelSelector(
- ns,
- `clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`
- )
- ),
- this.teardownDelete(() =>
- this.deleteNetworkPoliciesByLabelSelector(
- this.deps.config.mcpServerNamespace,
- `clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`
- )
- ),
+ ...(preserveWorkflowRuntime
+ ? []
+ : [
+ this.teardownDelete(() =>
+ this.deleteNetworkPoliciesByLabelSelector(
+ ns,
+ `clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`
+ )
+ ),
+ this.teardownDelete(() =>
+ this.deleteNetworkPoliciesByLabelSelector(
+ this.deps.config.mcpServerNamespace,
+ `clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`
+ )
+ ),
+ ]),
])
- await this.teardownDelete(() =>
- this.deps.coreApi.deleteNamespacedPod({
- name: `${recipeName}-mcp-host`,
- namespace: ns,
- propagationPolicy: 'Background',
- })
- )
- await Promise.all([
- this.teardownDelete(() =>
- this.deps.coreApi.deleteNamespacedSecret({
- name: buildPluginWorkloadSdkTokenSecretName(recipeName),
+ if (!preserveWorkflowRuntime) {
+ await this.teardownDelete(() =>
+ this.deps.coreApi.deleteNamespacedPod({
+ name: `${recipeName}-mcp-host`,
namespace: ns,
+ propagationPolicy: 'Background',
})
- ),
- // The runtime JWT Secret is created for eager SDK hosts as well as
- // workflow hosts. A capability removal must revoke it with the host;
- // leaving it behind would allow a deleted workload to replay broker
- // requests until token expiry.
+ )
+ }
+ await Promise.all([
this.teardownDelete(() =>
this.deps.coreApi.deleteNamespacedSecret({
- name: `wf-${recipeName}-mcp-host-runtime-tokens`,
+ name: buildPluginWorkloadSdkTokenSecretName(recipeName),
namespace: ns,
})
),
+ ...(preserveWorkflowRuntime
+ ? []
+ : [
+ // The runtime JWT Secret is created for eager SDK hosts as well as
+ // workflow hosts. SDK-only capability removal must revoke it with
+ // the host; hybrid workflow cleanup owns the shared Secret.
+ this.teardownDelete(() =>
+ this.deps.coreApi.deleteNamespacedSecret({
+ name: `wf-${recipeName}-mcp-host-runtime-tokens`,
+ namespace: ns,
+ })
+ ),
+ ]),
])
- await this.assertPluginWorkloadSdkResourcesAbsent(recipeName, ns, networkPolicyNames)
+ await this.assertPluginWorkloadSdkResourcesAbsent(recipeName, ns, networkPolicyNames, {
+ preserveWorkflowRuntime,
+ })
if (revocationReceipt.state === 'revoking') {
if (!revocationReceipt.revocationId) {
throw new Error(`Plugin Workload SDK revocation receipt for ${recipeName} has no epoch`)
@@ -1071,48 +1110,53 @@ export class WorkflowReconciler {
private async assertPluginWorkloadSdkResourcesAbsent(
recipeName: string,
namespace: string,
- networkPolicyNames: string[]
+ networkPolicyNames: string[],
+ options: PluginWorkloadSdkCleanupOptions = {}
): Promise<void> {
- const podGone = await waitForPodDeletion(
- this.deps.coreApi,
- `${recipeName}-mcp-host`,
- namespace,
- {
- timeoutMs: 5_000,
- pollIntervalMs: 250,
- }
- )
- if (!podGone)
- throw new Error(`Plugin Workload SDK pod for ${recipeName} still exists after teardown`)
const checks: Array<Promise<unknown>> = [
this.deps.coreApi.readNamespacedSecret({
name: buildPluginWorkloadSdkTokenSecretName(recipeName),
namespace,
}),
- this.deps.coreApi.readNamespacedSecret({
- name: `wf-${recipeName}-mcp-host-runtime-tokens`,
- namespace,
- }),
- this.deps.coreApi.readNamespacedService({
- name: buildMcpHostServiceName(recipeName),
- namespace,
- }),
- this.deps.coreApi.readNamespacedEndpoints({
- name: buildMcpHostServiceName(recipeName),
- namespace,
- }),
...networkPolicyNames.map(name =>
this.deps.networkingApi.readNamespacedNetworkPolicy({ name, namespace })
),
- this.deps.networkingApi.listNamespacedNetworkPolicy({
- namespace,
- labelSelector: `clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`,
- }),
- this.deps.networkingApi.listNamespacedNetworkPolicy({
- namespace: this.deps.config.mcpServerNamespace,
- labelSelector: `clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`,
- }),
]
+ if (!options.preserveWorkflowRuntime) {
+ const podGone = await waitForPodDeletion(
+ this.deps.coreApi,
+ `${recipeName}-mcp-host`,
+ namespace,
+ {
+ timeoutMs: 5_000,
+ pollIntervalMs: 250,
+ }
+ )
+ if (!podGone)
+ throw new Error(`Plugin Workload SDK pod for ${recipeName} still exists after teardown`)
+ checks.push(
+ this.deps.coreApi.readNamespacedSecret({
+ name: `wf-${recipeName}-mcp-host-runtime-tokens`,
+ namespace,
+ }),
+ this.deps.coreApi.readNamespacedService({
+ name: buildMcpHostServiceName(recipeName),
+ namespace,
+ }),
+ this.deps.coreApi.readNamespacedEndpoints({
+ name: buildMcpHostServiceName(recipeName),
+ namespace,
+ }),
+ this.deps.networkingApi.listNamespacedNetworkPolicy({
+ namespace,
+ labelSelector: `clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`,
+ }),
+ this.deps.networkingApi.listNamespacedNetworkPolicy({
+ namespace: this.deps.config.mcpServerNamespace,
+ labelSelector: `clerum.io/recipe=${recipeName},clerum.io/managed-by=wrc`,
+ })
+ )
+ }
const results = await Promise.allSettled(checks)
const unexpected = results.find(result => {
if (result.status !== 'fulfilled') return false