Skip to content

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

TypeScript

fix(plugin-sdk): enforce just-in-time provider credentials

Alfredo Lopez574a45761724
diff --git a/charts/clerum-crds/crds/workflowrecipe.yaml b/charts/clerum-crds/crds/workflowrecipe.yaml
index 9a563eba6..3ef975b18 100644
--- a/charts/clerum-crds/crds/workflowrecipe.yaml
+++ b/charts/clerum-crds/crds/workflowrecipe.yaml
@@ -2130,7 +2130,7 @@ spec:
properties:
state:
type: string
- enum: [validated, disabled]
+ enum: [validated, disabled, degraded]
promptBridge:
type: boolean
clientNotifications:
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index ad1b0ca0b..7c4fc7168 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -7,6 +7,7 @@ import {
import { config } from './config.js'
import { applyMemberRegistrationCredentialsSchema } from './services/memberRegistrationCredentialsSchema.js'
import {
+ addPluginWorkloadSdkJitCredentialTicketColumns,
addPluginWorkloadSdkPromptTargetPolicyColumns,
addPluginWorkloadSdkProviderColumn,
applyPluginWorkloadSdkSchema,
@@ -1375,6 +1376,8 @@ async function applyUsageTrackingBaseline(db: DbClient): Promise<void> {
ON usage_events (llm_secret_name, ts) WHERE llm_secret_name IS NOT NULL;
ALTER TABLE usage_events
ADD COLUMN IF NOT EXISTS team_id TEXT;
+ ALTER TABLE usage_events
+ ADD COLUMN IF NOT EXISTS prompt_bridge_metadata JSONB;
CREATE INDEX IF NOT EXISTS usage_events_team_id_ts_idx
ON usage_events (team_id, ts) WHERE team_id IS NOT NULL;
@@ -1497,6 +1500,14 @@ async function applyUsageTrackingBaseline(db: DbClient): Promise<void> {
`)
}
+/** Adds bounded promptBridge target attribution to the raw usage ledger. */
+async function addPromptBridgeUsageMetadataColumn(db: DbClient): Promise<void> {
+ await db.query(`
+ ALTER TABLE usage_events
+ ADD COLUMN IF NOT EXISTS prompt_bridge_metadata JSONB;
+ `)
+}
+
async function applyWorkflowUsageAttributionSchema(db: DbClient): Promise<void> {
await db.query(`
ALTER TABLE workflow_runs
@@ -5029,6 +5040,14 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
version: '0075_plugin_workload_sdk_prompt_target_policy',
apply: addPluginWorkloadSdkPromptTargetPolicyColumns,
},
+ {
+ version: '0076_plugin_workload_sdk_jit_credential_tickets',
+ apply: addPluginWorkloadSdkJitCredentialTicketColumns,
+ },
+ {
+ version: '0077_plugin_workload_sdk_usage_attribution',
+ apply: addPromptBridgeUsageMetadataColumn,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.ts
index 5b6231ccc..5ecbeac5d 100644
--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts
+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts
@@ -1,5 +1,5 @@
import { type Response, Router } from 'express'
-import { PROVIDER_CREDENTIAL_SLOTS, isLlmProviderId } from '@clerum/llm-providers'
+import { isCredentialSlotOwnedByProvider, isLlmProviderId } from '@clerum/llm-providers'
import { asyncHandler } from '../../http/asyncHandler.js'
import type { UiAuthedRequest } from '../../middleware/controlUIAuth.js'
import { listEnabledModelNamesForProvider } from '../../services/llmAllowedModels.js'
@@ -145,15 +145,10 @@ function parseModelPolicies(
}
function credentialSlotBelongsToProvider(provider: string, credentialSlot: string): boolean {
- if (!isLlmProviderId(provider)) return false
- const canonicalSlots = PROVIDER_CREDENTIAL_SLOTS[provider].map(slot => slot.dataKey)
- // Extra slots are created by the additive secrets editor and remain owned by
- // their provider. A target only carries the key identity; this route never
- // reads the Secret or returns a value.
- return (
- canonicalSlots.some(slot => credentialSlot === slot || credentialSlot.startsWith(`${slot}-`)) ||
- credentialSlot.startsWith(`${provider}-`)
- )
+ // This shares the exact slot-ownership rule with the runtime broker. A
+ // target only carries the key identity; this route never reads the Secret or
+ // returns a value.
+ return isCredentialSlotOwnedByProvider(provider, credentialSlot)
}
function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPromptTarget[] | null {
diff --git a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
index 8211bee2b..a95104038 100644
--- a/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
+++ b/control-api/src/routes/mcp-host/plugin-workload-sdk.routes.ts
@@ -9,6 +9,7 @@ import {
authorizeClientNotification,
authorizeListRecipients,
authorizePromptBridge,
+ reissuePromptBridgeCredentialTicket,
} from '../../services/pluginWorkloadSdkAuthorizer.js'
import { verifyPluginWorkloadSdkCredentialTicket } from '../../services/pluginWorkloadSdkCredentialTicket.js'
import {
@@ -27,6 +28,7 @@ import {
getInvocationById,
hashPromptTargetPolicy,
listInvocations,
+ redeemPluginWorkloadSdkCredentialTicketJti,
resolveRecipientProfiles,
} from '../../services/pluginWorkloadSdkDb.js'
import { markInvocationStatus } from '../../services/pluginWorkloadSdkInvocationAuditor.js'
@@ -40,6 +42,7 @@ import { isPlainObject } from '../../utils/isPlainObject.js'
//
// POST /mcp-host/plugin-workload-sdk/prompt-bridge
// POST /mcp-host/plugin-workload-sdk/client-notification
+// POST /mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket
// GET /mcp-host/plugin-workload-sdk/invocations/:recipeRef
const IDEMPOTENCY_KEY_RE = new RegExp(DEFAULT_IDEMPOTENCY_KEY_PATTERN)
@@ -392,6 +395,38 @@ function parseClientNotificationBody(
export function createMcpHostPluginWorkloadSdkRoutes(): Router {
const router = Router()
+ router.post(
+ // JIT fallback-ticket contract for mcp-host:
+ // - call only after the prior provider attempt has failed;
+ // - provide invocationId + next targetRef, never a credential identity;
+ // - redeem the returned ticket once, immediately before WRC reads the slot.
+ // The server derives caller and allowed suffix from the persisted
+ // invocation, verifies current policy, and emits a new one-shot jti.
+ '/mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket',
+ requireMcpHostJwt,
+ asyncHandler(async (req, res) => {
+ const claims = req.mcpHostJwt!
+ const body = isPlainObject(req.body) ? req.body : {}
+ if (!checkRecipeBinding(body, claims, res)) return
+ const invocationId = typeof body.invocationId === 'string' ? body.invocationId.trim() : ''
+ const targetRef = typeof body.targetRef === 'string' ? body.targetRef.trim() : ''
+ if (!invocationId || !targetRef || targetRef.length > MAX_TARGET_REF_LENGTH) {
+ res.status(400).json({ error: 'invocationId and targetRef are required' })
+ return
+ }
+ const result = await reissuePromptBridgeCredentialTicket({
+ claims,
+ invocationId,
+ targetRef,
+ })
+ if (!result.ok) {
+ sendAuthzError(res, result)
+ return
+ }
+ res.status(201).json(result.value)
+ })
+ )
+
router.post(
'/mcp-host/plugin-workload-sdk/prompt-bridge',
requireMcpHostJwt,
@@ -439,7 +474,6 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
authorizedTargets: result.value.authorizedTargets,
policyRevision: result.value.policyRevision,
policyHash: result.value.policyHash,
- authorizedTargetTickets: result.value.authorizedTargetTickets,
maxOutputTokens: result.value.maxOutputTokens,
})
})
@@ -557,6 +591,7 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
const ticket = typeof body.credentialTicket === 'string' ? body.credentialTicket : ''
const invocationId = typeof body.invocationId === 'string' ? body.invocationId : ''
const targetRef = typeof body.targetRef === 'string' ? body.targetRef : ''
+ const redeem = body.redeem === true
if (!ticket || !invocationId || !targetRef) {
res.status(400).json({ error: 'credentialTicket, invocationId and targetRef are required' })
return
@@ -578,7 +613,13 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
!invocation ||
invocation.recipeNamespace !== claims.recipeNamespace ||
invocation.recipeName !== claims.recipeName ||
- invocation.method !== 'promptBridge'
+ invocation.method !== 'promptBridge' ||
+ invocation.status !== 'in_progress' ||
+ invocation.authorizationDecision !== 'authorized' ||
+ !invocation.promptAuthorization ||
+ !invocation.promptAuthorization.authorizedTargetRefs.includes(targetRef) ||
+ invocation.promptAuthorization.policyRevision !== ticketClaims.policyRevision ||
+ invocation.promptAuthorization.policyHash !== ticketClaims.policyHash
) {
res.status(403).json({ error: 'provider_policy_denied', retryable: false })
return
@@ -597,6 +638,19 @@ export function createMcpHostPluginWorkloadSdkRoutes(): Router {
res.status(403).json({ error: 'provider_policy_denied', retryable: false })
return
}
+ if (redeem) {
+ const redeemed = await redeemPluginWorkloadSdkCredentialTicketJti({
+ jti: ticketClaims.jti,
+ recipeNamespace: claims.recipeNamespace,
+ recipeName: claims.recipeName,
+ invocationId,
+ targetRef,
+ })
+ if (!redeemed) {
+ res.status(403).json({ error: 'provider_policy_denied', retryable: false })
+ return
+ }
+ }
res.status(200).json({ active: true })
})
)
diff --git a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
index fec5ea5ea..8b82492fa 100644
--- a/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
+++ b/control-api/src/services/pluginWorkloadSdkAuthorizer.ts
@@ -1,13 +1,18 @@
import { pluginWorkloadSdkAuthDecisionsTotal } from '../observability/metrics.js'
import type { McpHostAccessClaims } from '../utils/auth/mcpHostJwtToken.js'
-import { issuePluginWorkloadSdkCredentialTicket } from './pluginWorkloadSdkCredentialTicket.js'
+import {
+ PLUGIN_SDK_CREDENTIAL_TICKET_TTL_SECONDS,
+ issuePluginWorkloadSdkCredentialTicketWithClaims,
+} from './pluginWorkloadSdkCredentialTicket.js'
import {
type PluginWorkloadSdkErrorCode,
type PluginWorkloadSdkGrant,
type PluginWorkloadSdkModelPolicy,
type PluginWorkloadSdkPromptTarget,
findGrant,
+ getInvocationById,
hashPromptTargetPolicy,
+ registerPluginWorkloadSdkCredentialTicketJti,
} from './pluginWorkloadSdkDb.js'
import { markInvocationStatus, recordInvocation } from './pluginWorkloadSdkInvocationAuditor.js'
import { checkRateLimit, consumeQuota } from './pluginWorkloadSdkQuotaTracker.js'
@@ -108,31 +113,9 @@ export interface AuthorizedPromptBridge {
authorizedTargets: PluginWorkloadSdkPromptTarget[]
policyRevision: number
policyHash: string
- /** One short-lived signed authorization artifact per eligible target. */
- authorizedTargetTickets: Array<{ targetRef: string; credentialTicket: string }>
maxOutputTokens: number | null
}
-function issueTargetTickets(
- claims: McpHostAccessClaims,
- invocationId: string,
- targets: PluginWorkloadSdkPromptTarget[],
- policyRevision: number,
- policyHash: string
-): Array<{ targetRef: string; credentialTicket: string }> {
- return targets.map(target => ({
- targetRef: target.targetRef,
- credentialTicket: issuePluginWorkloadSdkCredentialTicket({
- recipeNamespace: claims.recipeNamespace,
- recipeName: claims.recipeName,
- invocationId,
- target,
- policyRevision,
- policyHash,
- }),
- }))
-}
-
type PromptTargetResolution =
| { ok: true; selectedIndex: number; modelPolicy: PluginWorkloadSdkModelPolicy | null }
| { ok: false; error: PluginWorkloadSdkAuthzError }
@@ -322,6 +305,11 @@ async function authorizePromptBridgeInner(
payload: params.payload,
status: 'in_progress',
authorizationDecision: 'authorized',
+ promptAuthorization: {
+ policyRevision: grant.policyRevision,
+ policyHash: resolvedPolicyHash,
+ authorizedTargetRefs: authorizedTargets.map(target => target.targetRef),
+ },
})
if (recorded.kind === 'conflict') {
return deny('idempotency_conflict', 'idempotency key was already used with a different payload')
@@ -350,13 +338,6 @@ async function authorizePromptBridgeInner(
authorizedTargets,
policyRevision: grant.policyRevision,
policyHash: resolvedPolicyHash,
- authorizedTargetTickets: issueTargetTickets(
- claims,
- recorded.invocation.id,
- authorizedTargets,
- grant.policyRevision,
- resolvedPolicyHash
- ),
maxOutputTokens: grant.quotaLimits.maxOutputTokens ?? null,
},
}
@@ -405,18 +386,122 @@ async function authorizePromptBridgeInner(
authorizedTargets,
policyRevision: grant.policyRevision,
policyHash: resolvedPolicyHash,
- authorizedTargetTickets: issueTargetTickets(
- claims,
- recorded.invocation.id,
- authorizedTargets,
- grant.policyRevision,
- resolvedPolicyHash
- ),
maxOutputTokens: grant.quotaLimits.maxOutputTokens ?? null,
},
}
}
+export interface ReissuePromptBridgeCredentialTicketParams {
+ claims: McpHostAccessClaims
+ invocationId: string
+ targetRef: string
+}
+
+export type ReissuedPromptBridgeCredentialTicket = {
+ invocationId: string
+ targetRef: string
+ credentialTicket: string
+ policyRevision: number
+ policyHash: string
+ expiresInSeconds: number
+}
+
+/**
+ * Mints one short-lived ticket immediately before a fallback attempt. The
+ * target is accepted only when it was in the original, persisted suffix and
+ * the live policy still has exactly that revision/hash and caller authority.
+ * This route accepts no credential slot, model, provider, or caller from the
+ * workload, so it cannot turn a fallback request into a selector bypass.
+ */
+export async function reissuePromptBridgeCredentialTicket(
+ params: ReissuePromptBridgeCredentialTicketParams
+): Promise<PluginWorkloadSdkAuthzResult<ReissuedPromptBridgeCredentialTicket>> {
+ const scopeError = checkScope(params.claims)
+ if (scopeError) return scopeError
+
+ const invocation = await getInvocationById(params.invocationId)
+ if (
+ !invocation ||
+ invocation.recipeNamespace !== params.claims.recipeNamespace ||
+ invocation.recipeName !== params.claims.recipeName ||
+ invocation.method !== 'promptBridge' ||
+ invocation.status !== 'in_progress' ||
+ invocation.authorizationDecision !== 'authorized' ||
+ !invocation.promptAuthorization
+ ) {
+ return deny(
+ 'provider_policy_denied',
+ 'promptBridge invocation is not eligible for ticket reissue'
+ )
+ }
+
+ const authorization = invocation.promptAuthorization
+ if (!authorization.authorizedTargetRefs.includes(params.targetRef)) {
+ return deny('target_not_allowed', 'target was not authorized for this invocation')
+ }
+
+ const grant = await findGrant(
+ params.claims.recipeNamespace,
+ params.claims.recipeName,
+ 'promptBridge'
+ )
+ if (!grant || checkCaller(grant, invocation.callerRef)) {
+ return deny(
+ 'provider_policy_denied',
+ 'promptBridge policy no longer authorizes this invocation'
+ )
+ }
+ const policyHash = hashPromptTargetPolicy(grant)
+ if (
+ grant.policyRevision !== authorization.policyRevision ||
+ policyHash !== authorization.policyHash
+ ) {
+ return deny(
+ 'provider_policy_denied',
+ 'promptBridge policy changed after the original authorization'
+ )
+ }
+ const target = grant.promptTargets.find(candidate => candidate.targetRef === params.targetRef)
+ if (!target) {
+ return deny('target_not_allowed', 'target is not in the current promptBridge policy')
+ }
+
+ const issued = issuePluginWorkloadSdkCredentialTicketWithClaims({
+ recipeNamespace: params.claims.recipeNamespace,
+ recipeName: params.claims.recipeName,
+ invocationId: invocation.id,
+ target,
+ policyRevision: grant.policyRevision,
+ policyHash,
+ })
+ const registered = await registerPluginWorkloadSdkCredentialTicketJti({
+ jti: issued.claims.jti,
+ recipeNamespace: params.claims.recipeNamespace,
+ recipeName: params.claims.recipeName,
+ invocationId: invocation.id,
+ targetRef: target.targetRef,
+ expiresAt: new Date(Date.now() + PLUGIN_SDK_CREDENTIAL_TICKET_TTL_SECONDS * 1_000),
+ })
+ if (!registered) {
+ return deny(
+ 'provider_unavailable',
+ 'credential ticket issuance is temporarily unavailable',
+ true
+ )
+ }
+ return {
+ ok: true,
+ value: {
+ invocationId: invocation.id,
+ targetRef: target.targetRef,
+ credentialTicket: issued.credentialTicket,
+ policyRevision: grant.policyRevision,
+ policyHash,
+ expiresInSeconds: PLUGIN_SDK_CREDENTIAL_TICKET_TTL_SECONDS,
+ },
+ }
+}
+
// ─── clientNotifications ─────────────────────────────────────────────────
export interface AuthorizeClientNotificationParams {
diff --git a/control-api/src/services/pluginWorkloadSdkCredentialTicket.ts b/control-api/src/services/pluginWorkloadSdkCredentialTicket.ts
index 2d09712a8..59a841133 100644
--- a/control-api/src/services/pluginWorkloadSdkCredentialTicket.ts
+++ b/control-api/src/services/pluginWorkloadSdkCredentialTicket.ts
@@ -7,9 +7,12 @@ import type { PluginWorkloadSdkPromptTarget } from './pluginWorkloadSdkDb.js'
// already-authorized target to one invocation so mcp-host cannot be tricked
// into resolving a different slot from a caller-supplied policy response.
export const PLUGIN_SDK_CREDENTIAL_TICKET_AUDIENCE = 'plugin-sdk-credential-broker'
-const CREDENTIAL_TICKET_TTL_SECONDS = 60
+/** Short-lived by design: fallbacks receive a new ticket just before use. */
+export const PLUGIN_SDK_CREDENTIAL_TICKET_TTL_SECONDS = 60
export type PluginWorkloadSdkCredentialTicketClaims = {
+ /** Unique ticket identity, generated by the issuer rather than the caller. */
+ jti: string
sub: string
recipeNamespace: string
recipeName: string
@@ -23,6 +26,11 @@ export type PluginWorkloadSdkCredentialTicketClaims = {
typ: 'plugin-sdk-credential-ticket'
}
+export type IssuedPluginWorkloadSdkCredentialTicket = {
+ credentialTicket: string
+ claims: PluginWorkloadSdkCredentialTicketClaims
+}
+
export function issuePluginWorkloadSdkCredentialTicket(input: {
recipeNamespace: string
recipeName: string
@@ -31,7 +39,24 @@ export function issuePluginWorkloadSdkCredentialTicket(input: {
policyRevision: number
policyHash: string
}): string {
+ return issuePluginWorkloadSdkCredentialTicketWithClaims(input).credentialTicket
+}
+
+/**
+ * Issues a ticket plus its issuer-generated identity so control-api can record
+ * exactly one future redemption. This is internal control-plane data; callers
+ * must never choose the jti.
+ */
+export function issuePluginWorkloadSdkCredentialTicketWithClaims(input: {
+ recipeNamespace: string
+ recipeName: string
+ invocationId: string
+ target: PluginWorkloadSdkPromptTarget
+ policyRevision: number
+ policyHash: string
+}): IssuedPluginWorkloadSdkCredentialTicket {
const claims: PluginWorkloadSdkCredentialTicketClaims = {
+ jti: randomUUID(),
sub: `${input.recipeNamespace}/${input.recipeName}`,
recipeNamespace: input.recipeNamespace,
recipeName: input.recipeName,
@@ -44,13 +69,15 @@ export function issuePluginWorkloadSdkCredentialTicket(input: {
policyHash: input.policyHash,
typ: 'plugin-sdk-credential-ticket',
}
- return jwt.sign(claims, config.adminJwtPrivateKey, {
- algorithm: 'RS256',
- issuer: config.adminJwtIssuer,
- audience: PLUGIN_SDK_CREDENTIAL_TICKET_AUDIENCE,
- jwtid: randomUUID(),
- expiresIn: CREDENTIAL_TICKET_TTL_SECONDS,
- })
+ return {
+ credentialTicket: jwt.sign(claims, config.adminJwtPrivateKey, {
+ algorithm: 'RS256',
+ issuer: config.adminJwtIssuer,
+ audience: PLUGIN_SDK_CREDENTIAL_TICKET_AUDIENCE,
+ expiresIn: PLUGIN_SDK_CREDENTIAL_TICKET_TTL_SECONDS,
+ }),
+ claims,
+ }
}
export function verifyPluginWorkloadSdkCredentialTicket(
@@ -69,6 +96,8 @@ export function verifyPluginWorkloadSdkCredentialTicket(
if (typeof verified !== 'object' || verified === null) return null
const claims = verified as jwt.JwtPayload
if (
+ typeof claims.jti !== 'string' ||
+ claims.jti.length === 0 ||
typeof claims.sub !== 'string' ||
typeof claims.recipeNamespace !== 'string' ||
typeof claims.recipeName !== 'string' ||
diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.ts
index fcabee050..56bc2864f 100644
--- a/control-api/src/services/pluginWorkloadSdkDb.ts
+++ b/control-api/src/services/pluginWorkloadSdkDb.ts
@@ -102,6 +102,17 @@ export interface PluginWorkloadSdkPromptTarget {
credentialSlot: string
}
+/**
+ * Non-secret snapshot of the originally authorized ordered suffix. It is the
+ * authority for JIT fallback-ticket issuance; a request body never supplies
+ * this list.
+ */
+export interface PluginWorkloadSdkPromptAuthorization {
+ policyRevision: number
+ policyHash: string
+ authorizedTargetRefs: string[]
+}
+
export interface PluginWorkloadSdkGrant {
id: string
recipeNamespace: string
@@ -144,6 +155,7 @@ export interface PluginWorkloadSdkInvocationRecord {
status: PluginWorkloadSdkInvocationStatus
quotaConsumed: boolean
authorizationDecision: string
+ promptAuthorization: PluginWorkloadSdkPromptAuthorization | null
createdAt: string
completedAt: string | null
}
@@ -268,12 +280,35 @@ function mapInvocationRow(row: Record<string, unknown>): PluginWorkloadSdkInvoca
status: row.status as PluginWorkloadSdkInvocationStatus,
quotaConsumed: row.quota_consumed === true,
authorizationDecision: String(row.authorization_decision),
+ promptAuthorization: promptAuthorization(row.prompt_authorization),
createdAt: new Date(row.created_at as string).toISOString(),
completedAt:
row.completed_at === null ? null : new Date(row.completed_at as string).toISOString(),
}
}
+function promptAuthorization(value: unknown): PluginWorkloadSdkPromptAuthorization | null {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return null
+ const record = value as Record<string, unknown>
+ if (
+ typeof record.policyRevision !== 'number' ||
+ !Number.isInteger(record.policyRevision) ||
+ record.policyRevision < 1 ||
+ typeof record.policyHash !== 'string' ||
+ !/^[a-f0-9]{64}$/.test(record.policyHash) ||
+ !Array.isArray(record.authorizedTargetRefs) ||
+ record.authorizedTargetRefs.length === 0 ||
+ !record.authorizedTargetRefs.every(ref => typeof ref === 'string' && ref.length > 0)
+ ) {
+ return null
+ }
+ return {
+ policyRevision: record.policyRevision,
+ policyHash: record.policyHash,
+ authorizedTargetRefs: [...record.authorizedTargetRefs],
+ }
+}
+
// ─── Grants ──────────────────────────────────────────────────────────────
export async function findGrant(
@@ -552,6 +587,7 @@ export interface InsertInvocationParams {
payloadHash: string
status: PluginWorkloadSdkInvocationStatus
authorizationDecision: string
+ promptAuthorization?: PluginWorkloadSdkPromptAuthorization
}
export type InsertInvocationResult =
@@ -575,8 +611,8 @@ export async function insertInvocation(
const inserted = await pool.query(
`INSERT INTO plugin_workload_sdk_invocations
(recipe_namespace, recipe_name, caller_ref, correlation_id, method, detail, purpose,
- idempotency_key_hash, payload_hash, status, authorization_decision)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
+ idempotency_key_hash, payload_hash, status, authorization_decision, prompt_authorization)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
ON CONFLICT (recipe_namespace, recipe_name, method, idempotency_key_hash) DO NOTHING
RETURNING *`,
[
@@ -591,6 +627,7 @@ export async function insertInvocation(
params.payloadHash,
params.status,
params.authorizationDecision,
+ params.promptAuthorization ? JSON.stringify(params.promptAuthorization) : null,
]
)
const insertedRow = inserted.rows[0] as Record<string, unknown> | undefined
@@ -626,6 +663,59 @@ export async function getInvocationById(
return row ? mapInvocationRow(row) : null
}
+export async function registerPluginWorkloadSdkCredentialTicketJti(input: {
+ jti: string
+ recipeNamespace: string
+ recipeName: string
+ invocationId: string
+ targetRef: string
+ expiresAt: Date
+}): Promise<boolean> {
+ // Opportunistic cleanup bounds the one-shot registry without retaining any
+ // credentials or ticket bodies.
+ await pool.query(
+ `DELETE FROM plugin_workload_sdk_credential_ticket_jtis WHERE expires_at <= now()`
+ )
+ const result = await pool.query(
+ `INSERT INTO plugin_workload_sdk_credential_ticket_jtis
+ (jti, recipe_namespace, recipe_name, invocation_id, target_ref, expires_at)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (jti) DO NOTHING`,
+ [
+ input.jti,
+ input.recipeNamespace,
+ input.recipeName,
+ input.invocationId,
+ input.targetRef,
+ input.expiresAt,
+ ]
+ )
+ return (result.rowCount ?? 0) === 1
+}
+
+/** Atomically consumes a ticket identity after all binding/policy checks pass. */
+export async function redeemPluginWorkloadSdkCredentialTicketJti(input: {
+ jti: string
+ recipeNamespace: string
+ recipeName: string
+ invocationId: string
+ targetRef: string
+}): Promise<boolean> {
+ const result = await pool.query(
+ `UPDATE plugin_workload_sdk_credential_ticket_jtis
+ SET redeemed_at = now()
+ WHERE jti = $1
+ AND recipe_namespace = $2
+ AND recipe_name = $3
+ AND invocation_id = $4
+ AND target_ref = $5
+ AND redeemed_at IS NULL
+ AND expires_at > now()`,
+ [input.jti, input.recipeNamespace, input.recipeName, input.invocationId, input.targetRef]
+ )
+ return (result.rowCount ?? 0) === 1
+}
+
export async function updateInvocationStatus(
id: string,
status: PluginWorkloadSdkInvocationStatus,
diff --git a/control-api/src/services/pluginWorkloadSdkInvocationAuditor.ts b/control-api/src/services/pluginWorkloadSdkInvocationAuditor.ts
index 2d899c4bb..ef967c94b 100644
--- a/control-api/src/services/pluginWorkloadSdkInvocationAuditor.ts
+++ b/control-api/src/services/pluginWorkloadSdkInvocationAuditor.ts
@@ -2,6 +2,7 @@ import {
type InsertInvocationResult,
type PluginWorkloadSdkFamily,
type PluginWorkloadSdkInvocationStatus,
+ type PluginWorkloadSdkPromptAuthorization,
hashIdempotencyKey,
hashPayload,
insertInvocation,
@@ -35,6 +36,7 @@ export interface RecordInvocationParams {
payload: unknown
status: PluginWorkloadSdkInvocationStatus
authorizationDecision: string
+ promptAuthorization?: PluginWorkloadSdkPromptAuthorization
}
export async function recordInvocation(
@@ -52,6 +54,7 @@ export async function recordInvocation(
payloadHash: hashPayload(params.payload),
status: params.status,
authorizationDecision: params.authorizationDecision,
+ promptAuthorization: params.promptAuthorization,
})
}
diff --git a/control-api/src/services/pluginWorkloadSdkSchema.ts b/control-api/src/services/pluginWorkloadSdkSchema.ts
index 2af3791b8..c7fccf76d 100644
--- a/control-api/src/services/pluginWorkloadSdkSchema.ts
+++ b/control-api/src/services/pluginWorkloadSdkSchema.ts
@@ -48,10 +48,25 @@ export async function applyPluginWorkloadSdkSchema(db: DbClient): Promise<void>
status TEXT NOT NULL CHECK (status IN ('in_progress','complete','failed','provider_unavailable','accepted','delivered')),
quota_consumed BOOLEAN NOT NULL DEFAULT true,
authorization_decision TEXT NOT NULL,
+ -- Persisted, non-secret prompt authorization snapshot used to mint a
+ -- fresh fallback ticket without trusting caller-supplied target lists.
+ prompt_authorization JSONB NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
completed_at TIMESTAMPTZ NULL
);
+ CREATE TABLE IF NOT EXISTS plugin_workload_sdk_credential_ticket_jtis (
+ jti UUID PRIMARY KEY,
+ recipe_namespace TEXT NOT NULL,
+ recipe_name TEXT NOT NULL,
+ invocation_id UUID NOT NULL,
+ target_ref TEXT NOT NULL,
+ expires_at TIMESTAMPTZ NOT NULL,
+ redeemed_at TIMESTAMPTZ NULL
+ );
+ CREATE INDEX IF NOT EXISTS plugin_workload_sdk_credential_ticket_jtis_expiry
+ ON plugin_workload_sdk_credential_ticket_jtis (expires_at);
+
-- Idempotency uniqueness scoped per recipe + method (OQ-5). Rows older
-- than the 24h TTL are pruned by prunePluginWorkloadSdkExpiredIdempotency
-- so keys become reusable in a new invocation period.
@@ -107,3 +122,26 @@ export async function addPluginWorkloadSdkPromptTargetPolicyColumns(db: DbClient
ADD COLUMN IF NOT EXISTS policy_revision INTEGER NOT NULL DEFAULT 1;
`)
}
+
+/**
+ * Persists the original target suffix for JIT fallback ticket issuance and
+ * makes every ticket jti redeemable exactly once at credential introspection.
+ */
+export async function addPluginWorkloadSdkJitCredentialTicketColumns(db: DbClient): Promise<void> {
+ await db.query(`
+ ALTER TABLE plugin_workload_sdk_invocations
+ ADD COLUMN IF NOT EXISTS prompt_authorization JSONB NULL;
+
+ CREATE TABLE IF NOT EXISTS plugin_workload_sdk_credential_ticket_jtis (
+ jti UUID PRIMARY KEY,
+ recipe_namespace TEXT NOT NULL,
+ recipe_name TEXT NOT NULL,
+ invocation_id UUID NOT NULL,
+ target_ref TEXT NOT NULL,
+ expires_at TIMESTAMPTZ NOT NULL,
+ redeemed_at TIMESTAMPTZ NULL
+ );
+ CREATE INDEX IF NOT EXISTS plugin_workload_sdk_credential_ticket_jtis_expiry
+ ON plugin_workload_sdk_credential_ticket_jtis (expires_at);
+ `)
+}
diff --git a/control-api/src/services/usageEvents.ts b/control-api/src/services/usageEvents.ts
index c01401900..0cb04e485 100644
--- a/control-api/src/services/usageEvents.ts
+++ b/control-api/src/services/usageEvents.ts
@@ -26,6 +26,12 @@ export type LlmUsageEvent = {
cache_read_tokens: number
cache_write_tokens: number
cache_tokens_reported: boolean
+ prompt_bridge_metadata: {
+ target_ref: string
+ credential_slot: string
+ fallback_used: boolean
+ attempt_count: number
+ } | null
}
export type UsageIngestResult = {
@@ -71,6 +77,35 @@ function intOrNull(value: unknown): number | null {
return value
}
+function promptBridgeMetadata(value: unknown): LlmUsageEvent['prompt_bridge_metadata'] {
+ if (value === undefined || value === null) return null
+ if (typeof value !== 'object' || Array.isArray(value)) return null
+ const record = value as Record<string, unknown>
+ const targetRef = typeof record.target_ref === 'string' ? record.target_ref.trim() : ''
+ const credentialSlot =
+ typeof record.credential_slot === 'string' ? record.credential_slot.trim() : ''
+ const fallbackUsed = record.fallback_used
+ const attemptCount = intOrNull(record.attempt_count)
+ if (
+ !targetRef ||
+ targetRef.length > 256 ||
+ !credentialSlot ||
+ credentialSlot.length > 256 ||
+ typeof fallbackUsed !== 'boolean' ||
+ attemptCount === null ||
+ attemptCount < 1 ||
+ attemptCount > 64
+ ) {
+ return null
+ }
+ return {
+ target_ref: targetRef,
+ credential_slot: credentialSlot,
+ fallback_used: fallbackUsed,
+ attempt_count: attemptCount,
+ }
+}
+
export function validateUsageEvent(raw: unknown): LlmUsageEvent | null {
if (!raw || typeof raw !== 'object') return null
const r = raw as Record<string, unknown>
@@ -115,6 +150,15 @@ export function validateUsageEvent(raw: unknown): LlmUsageEvent | null {
if (cache_read_raw === null || cache_write_raw === null) return null
if (cache_read_raw < 0 || cache_write_raw < 0) return null
+ const prompt_bridge_metadata = promptBridgeMetadata(r.prompt_bridge_metadata)
+ if (
+ r.prompt_bridge_metadata !== undefined &&
+ r.prompt_bridge_metadata !== null &&
+ !prompt_bridge_metadata
+ ) {
+ return null
+ }
+
const recipe_name = trimOrNull(r.recipe_name)
const llm_secret_name = trimOrNull(r.llm_secret_name)
const task_id = trimOrNull(r.task_id)
@@ -149,10 +193,11 @@ export function validateUsageEvent(raw: unknown): LlmUsageEvent | null {
cache_read_tokens: cache_read_raw,
cache_write_tokens: cache_write_raw,
cache_tokens_reported,
+ prompt_bridge_metadata,
}
}
-const COLUMNS_PER_EVENT = 22
+const COLUMNS_PER_EVENT = 23
function buildInsertSql(rowCount: number): string {
const placeholders: string[] = []
@@ -167,7 +212,7 @@ function buildInsertSql(rowCount: number): string {
request_id, ts, run_id, host_ref, context_ref, team_id, provider, model, llm_secret_name,
source_kind, user_id, sender, channel_type, recipe_name, cron_job_id,
task_id, iteration, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
- cache_tokens_reported
+ cache_tokens_reported, prompt_bridge_metadata
)
VALUES ${placeholders.join(',')}
ON CONFLICT (request_id) DO NOTHING
@@ -200,7 +245,8 @@ function buildInsertParams(events: LlmUsageEvent[]): unknown[] {
e.output_tokens,
e.cache_read_tokens,
e.cache_write_tokens,
- e.cache_tokens_reported
+ e.cache_tokens_reported,
+ e.prompt_bridge_metadata
)
}
return params
diff --git a/control-api/test/db.ready.test.ts b/control-api/test/db.ready.test.ts
index a440a8a53..40464ce29 100644
--- a/control-api/test/db.ready.test.ts
+++ b/control-api/test/db.ready.test.ts
@@ -1,5 +1,7 @@
import { describe, expect, it, vi } from 'vitest'
-import { assertDbReady } from '../src/db.js'
+import { CONTROL_API_MIGRATIONS, assertDbReady } from '../src/db.js'
+
+const LATEST_MIGRATION = CONTROL_API_MIGRATIONS.at(-1)!.version
describe('assertDbReady', () => {
it('accepts a database migrated through the authoritative GFS runtime role contract', async () => {
@@ -7,7 +9,7 @@ describe('assertDbReady', () => {
await expect(assertDbReady({ query })).resolves.toBeUndefined()
expect(query).toHaveBeenCalledWith(expect.stringContaining('schema_migrations'), [
- '0075_plugin_workload_sdk_prompt_target_policy',
+ LATEST_MIGRATION,
])
})
@@ -15,7 +17,7 @@ describe('assertDbReady', () => {
const query = vi.fn().mockResolvedValue({ rows: [{ ready: false }], rowCount: 1 })
await expect(assertDbReady({ query })).rejects.toThrow(
- 'migration 0075_plugin_workload_sdk_prompt_target_policy is required'
+ `migration ${LATEST_MIGRATION} is required`
)
})
})
diff --git a/control-api/test/gfsReadiness.realPostgres.integration.test.ts b/control-api/test/gfsReadiness.realPostgres.integration.test.ts
index 669c2ec7e..7efce15e9 100644
--- a/control-api/test/gfsReadiness.realPostgres.integration.test.ts
+++ b/control-api/test/gfsReadiness.realPostgres.integration.test.ts
@@ -3,7 +3,7 @@ import { randomBytes } from 'node:crypto'
import { Pool } from 'pg'
import type { PoolClient } from 'pg'
import { createPermissionStoreProbe } from '../../gfs-controller/src/authz/storeProbe.js'
-import { assertDbReady, initDb } from '../src/db.js'
+import { CONTROL_API_MIGRATIONS, assertDbReady, initDb } from '../src/db.js'
const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
const describeRealPostgres = adminUrl ? describe : describe.skip
@@ -19,6 +19,7 @@ function quoteIdent(value: string): string {
}
describeRealPostgres('GFS Phase 0 real PostgreSQL readiness', () => {
+ const latestMigration = CONTROL_API_MIGRATIONS.at(-1)!.version
const database = `gfs_readiness_${randomBytes(6).toString('hex')}`
const connectionString = databaseUrl(
adminUrl ?? 'postgresql://[email protected]/postgres',
@@ -73,12 +74,8 @@ describeRealPostgres('GFS Phase 0 real PostgreSQL readiness', () => {
const client = await pool.connect()
try {
await client.query('BEGIN')
- await client.query(
- `DELETE FROM schema_migrations WHERE version='0075_plugin_workload_sdk_prompt_target_policy'`
- )
- await expect(assertDbReady(client)).rejects.toThrow(
- /0075_plugin_workload_sdk_prompt_target_policy/
- )
+ await client.query(`DELETE FROM schema_migrations WHERE version=$1`, [latestMigration])
+ await expect(assertDbReady(client)).rejects.toThrow(new RegExp(latestMigration))
} finally {
await client.query('ROLLBACK').catch(() => undefined)
client.release()
diff --git a/control-api/test/llmProviders.test.ts b/control-api/test/llmProviders.test.ts
index fb8aea9e5..ac82486ed 100644
--- a/control-api/test/llmProviders.test.ts
+++ b/control-api/test/llmProviders.test.ts
@@ -4,6 +4,7 @@ import {
PROVIDER_DISPLAY_LABELS,
PROVIDER_IDS,
PROVIDER_NON_SECRET_ENV,
+ isCredentialSlotOwnedByProvider,
isLlmProviderId,
} from '@clerum/llm-providers'
@@ -104,6 +105,17 @@ describe('credential slots', () => {
])
expect(PROVIDER_CREDENTIAL_SLOTS.bedrock.every(s => s.required)).toBe(true)
})
+
+ it('uses one ownership rule for additive and structured provider slots', () => {
+ expect(isCredentialSlotOwnedByProvider('openai', 'openai-api-key-fallback-a')).toBe(true)
+ expect(isCredentialSlotOwnedByProvider('zai', 'zai-api-key-fallback-a')).toBe(true)
+ expect(isCredentialSlotOwnedByProvider('bedrock', 'aws-access-key-id-fallback')).toBe(false)
+ expect(isCredentialSlotOwnedByProvider('bedrock', 'aws-access-key-id')).toBe(true)
+ expect(isCredentialSlotOwnedByProvider('vertex', 'vertex-service-account-json-fallback')).toBe(
+ false
+ )
+ expect(isCredentialSlotOwnedByProvider('vertex', 'vertex-service-account-json')).toBe(true)
+ })
})
describe('non-secret per-Host env', () => {
diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
index 3a7b5aa20..9193f2d50 100644
--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts
+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
@@ -242,6 +242,54 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
)
})
+ it('rejects additive slots for multi-slot or multiline providers before persisting policy', async () => {
+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g-bedrock' } as never)
+ vi.mocked(pool.query).mockResolvedValue({
+ rows: [{ model: 'claude-3-7-sonnet' }],
+ rowCount: 1,
+ } as never)
+
+ const bedrock = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send({
+ ...validGrantBody,
+ provider: 'bedrock',
+ allowedModels: ['claude-3-7-sonnet'],
+ promptTargets: [
+ {
+ targetRef: 'bedrock-fallback-slot',
+ provider: 'bedrock',
+ model: 'claude-3-7-sonnet',
+ credentialSlot: 'aws-access-key-id-fallback',
+ },
+ ],
+ defaultTargetRef: 'bedrock-fallback-slot',
+ })
+ expect(bedrock.status).toBe(400)
+ expect(bedrock.body.error).toContain('credentialSlot')
+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
+
+ const vertex = await request(buildApp())
+ .post('/admin/plugin-workload-sdk/grants')
+ .send({
+ ...validGrantBody,
+ provider: 'vertex',
+ allowedModels: ['gemini-2.5-pro'],
+ promptTargets: [
+ {
+ targetRef: 'vertex-fallback-slot',
+ provider: 'vertex',
+ model: 'gemini-2.5-pro',
+ credentialSlot: 'vertex-service-account-json-fallback',
+ },
+ ],
+ defaultTargetRef: 'vertex-fallback-slot',
+ })
+ expect(vertex.status).toBe(400)
+ expect(vertex.body.error).toContain('credentialSlot')
+ expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
+ })
+
it('does not require a provider for clientNotifications grants', async () => {
vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g2' } as never)
const res = await request(buildApp())
diff --git a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
index 9c818b331..37280ad65 100644
--- a/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
+++ b/control-api/test/routes.mcp-host.plugin-workload-sdk.test.ts
@@ -4,6 +4,7 @@ import request from 'supertest'
import { createMcpHostPluginWorkloadSdkRoutes } from '../src/routes/mcp-host/plugin-workload-sdk.routes.js'
import * as notificationEmitter from '../src/services/notificationEmitter.js'
import * as authorizer from '../src/services/pluginWorkloadSdkAuthorizer.js'
+import { issuePluginWorkloadSdkCredentialTicket } from '../src/services/pluginWorkloadSdkCredentialTicket.js'
import * as sdkDb from '../src/services/pluginWorkloadSdkDb.js'
import * as auditor from '../src/services/pluginWorkloadSdkInvocationAuditor.js'
import * as mcpHostJwt from '../src/utils/auth/mcpHostJwtToken.js'
@@ -30,7 +31,9 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {
return {
...actual,
getInvocationById: vi.fn(),
+ findGrant: vi.fn(),
listInvocations: vi.fn(),
+ redeemPluginWorkloadSdkCredentialTicketJti: vi.fn(),
resolveRecipientProfiles: vi.fn(),
}
})
@@ -44,6 +47,7 @@ vi.mock('../src/services/pluginWorkloadSdkAuthorizer.js', async () => {
authorizePromptBridge: vi.fn(),
authorizeClientNotification: vi.fn(),
authorizeListRecipients: vi.fn(),
+ reissuePromptBridgeCredentialTicket: vi.fn(),
}
})
@@ -98,13 +102,17 @@ const validNotificationBody = {
beforeEach(() => {
vi.mocked(authorizer.authorizePromptBridge).mockReset()
+ vi.mocked(authorizer.reissuePromptBridgeCredentialTicket).mockReset()
vi.mocked(authorizer.authorizeClientNotification).mockReset()
vi.mocked(sdkDb.listInvocations).mockReset()
vi.mocked(auditor.markInvocationStatus).mockReset().mockResolvedValue(true)
vi.mocked(sdkDb.getInvocationById).mockReset()
+ vi.mocked(sdkDb.findGrant).mockReset()
+ vi.mocked(sdkDb.redeemPluginWorkloadSdkCredentialTicketJti).mockReset()
vi.mocked(notificationEmitter.enqueuePluginWorkloadSdkNotification)
.mockReset()
.mockResolvedValue(undefined)
+ vi.mocked(sdkDb.redeemPluginWorkloadSdkCredentialTicketJti).mockResolvedValue(true)
vi.mocked(authorizer.authorizePromptBridge).mockResolvedValue({
ok: true,
value: {
@@ -129,10 +137,20 @@ beforeEach(() => {
],
policyRevision: 1,
policyHash: 'policy-hash',
- authorizedTargetTickets: [{ targetRef: 'primary-zai', credentialTicket: 'signed-ticket' }],
maxOutputTokens: null,
},
})
+ vi.mocked(authorizer.reissuePromptBridgeCredentialTicket).mockResolvedValue({
+ ok: true,
+ value: {
+ invocationId: 'inv-1',
+ targetRef: 'openai-fallback',
+ credentialTicket: 'signed-fresh-ticket',
+ policyRevision: 1,
+ policyHash: 'policy-hash',
+ expiresInSeconds: 60,
+ },
+ })
vi.mocked(authorizer.authorizeClientNotification).mockResolvedValue({
ok: true,
value: { notificationId: 'not-1', replay: false, status: 'accepted' },
@@ -246,8 +264,8 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
expect(res.body).toMatchObject({ invocationId: 'inv-1', replay: false, model: 'glm-4.7' })
expect(res.body).toMatchObject({
selectedTarget: { targetRef: 'primary-zai', credentialSlot: 'zai-api-key' },
- authorizedTargetTickets: [{ targetRef: 'primary-zai' }],
})
+ expect(JSON.stringify(res.body)).not.toContain('credentialTicket')
})
it('forwards an exact provider/model selector without accepting a raw credential', async () => {
@@ -304,7 +322,6 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
],
policyRevision: 1,
policyHash: 'policy-hash',
- authorizedTargetTickets: [{ targetRef: 'primary-zai', credentialTicket: 'signed-ticket' }],
maxOutputTokens: null,
},
})
@@ -317,6 +334,50 @@ describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge', () => {
})
})
+describe('POST /mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket', () => {
+ const body = {
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ invocationId: 'inv-1',
+ targetRef: 'openai-fallback',
+ }
+
+ it('requires the runtime JWT and recipe binding', async () => {
+ await request(buildApp())
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket')
+ .send(body)
+ .expect(401)
+ const res = await request(buildApp())
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket')
+ .set('Authorization', `Bearer ${issueSdkToken()}`)
+ .send({ ...body, recipeName: 'other-recipe' })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('recipe_binding_mismatch')
+ expect(authorizer.reissuePromptBridgeCredentialTicket).not.toHaveBeenCalled()
+ })
+
+ it('forwards only the bound invocation and target, never a caller or credential slot', async () => {
+ const res = await request(buildApp())
+ .post('/mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket')
+ .set('Authorization', `Bearer ${issueSdkToken()}`)
+ .send({ ...body, callerRef: 'attacker', credentialSlot: 'other-provider-key' })
+ expect(res.status).toBe(201)
+ expect(res.body).toEqual({
+ invocationId: 'inv-1',
+ targetRef: 'openai-fallback',
+ credentialTicket: 'signed-fresh-ticket',
+ policyRevision: 1,
+ policyHash: 'policy-hash',
+ expiresInSeconds: 60,
+ })
+ expect(authorizer.reissuePromptBridgeCredentialTicket).toHaveBeenCalledWith({
+ claims: expect.objectContaining({ recipeNamespace: NS, recipeName: RECIPE }),
+ invocationId: 'inv-1',
+ targetRef: 'openai-fallback',
+ })
+ })
+})
+
describe('POST /mcp-host/plugin-workload-sdk/client-notification', () => {
it('returns 400 when both target and userRef are present', async () => {
const res = await request(buildApp())
@@ -636,4 +697,94 @@ describe('POST /mcp-host/plugin-workload-sdk/credential-ticket/introspect', () =
expect(res.body).toEqual({ error: 'provider_policy_denied', retryable: false })
expect(JSON.stringify(res.body)).not.toContain('credentialSlot')
})
+
+ it('consumes a valid jti exactly once after all policy and invocation checks', async () => {
+ const target = {
+ targetRef: 'primary-zai',
+ provider: 'zai',
+ model: 'glm-4.7',
+ credentialSlot: 'zai-api-key',
+ }
+ const policyHash = sdkDb.hashPromptTargetPolicy({
+ policyRevision: 1,
+ defaultTargetRef: 'primary-zai',
+ promptTargets: [target],
+ })
+ const ticket = issuePluginWorkloadSdkCredentialTicket({
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ invocationId: 'inv-1',
+ target,
+ policyRevision: 1,
+ policyHash,
+ })
+ vi.mocked(sdkDb.getInvocationById).mockResolvedValue({
+ id: 'inv-1',
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ callerRef: 'api',
+ correlationId: null,
+ method: 'promptBridge',
+ detail: 'glm-4.7',
+ purpose: 'summarization',
+ idempotencyKeyHash: 'hash',
+ payloadHash: 'payload-hash',
+ status: 'in_progress',
+ quotaConsumed: true,
+ authorizationDecision: 'authorized',
+ promptAuthorization: {
+ policyRevision: 1,
+ policyHash,
+ authorizedTargetRefs: ['primary-zai'],
+ },
+ createdAt: '2026-08-02T00:00:00.000Z',
+ completedAt: null,
+ })
+ vi.mocked(sdkDb.findGrant).mockResolvedValue({
+ id: 'grant-1',
+ recipeNamespace: NS,
+ recipeName: RECIPE,
+ capabilityFamily: 'promptBridge',
+ provider: 'zai',
+ allowedModels: ['glm-4.7'],
+ allowedEventTypes: [],
+ allowedTargetRefs: [],
+ allowedUserRefs: [],
+ allowedCallers: ['api'],
+ quotaLimits: {},
+ modelPolicies: {},
+ promptTargets: [target],
+ defaultTargetRef: 'primary-zai',
+ policyRevision: 1,
+ createdAt: '2026-08-02T00:00:00.000Z',
+ updatedAt: '2026-08-02T00:00:00.000Z',
+ })
+
+ const body = {
+ credentialTicket: ticket,
+ invocationId: 'inv-1',
+ targetRef: 'primary-zai',
+ redeem: true,
+ }
+ await request(buildApp())
+ .post('/mcp-host/plugin-workload-sdk/credential-ticket/introspect')
+ .set('Authorization', `Bearer ${issueSdkToken()}`)
+ .send(body)
+ .expect(200)
+ expect(sdkDb.redeemPluginWorkloadSdkCredentialTicketJti).toHaveBeenCalledWith(
+ expect.objectContaining({
+ invocationId: 'inv-1',
+ targetRef: 'primary-zai',
+ jti: expect.any(String),
+ })
+ )
+
+ vi.mocked(sdkDb.redeemPluginWorkloadSdkCredentialTicketJti).mockResolvedValue(false)
+ const replay = await request(buildApp())
+ .post('/mcp-host/plugin-workload-sdk/credential-ticket/introspect')
+ .set('Authorization', `Bearer ${issueSdkToken()}`)
+ .send(body)
+ expect(replay.status).toBe(403)
+ expect(replay.body).toEqual({ error: 'provider_policy_denied', retryable: false })
+ })
})
diff --git a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts
index 00af72e4b..a6d4c725d 100644
--- a/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkAuthorizer.test.ts
@@ -1,8 +1,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import jwt from 'jsonwebtoken'
import {
authorizeClientNotification,
authorizeListRecipients,
authorizePromptBridge,
+ reissuePromptBridgeCredentialTicket,
} from '../src/services/pluginWorkloadSdkAuthorizer.js'
import * as sdkDb from '../src/services/pluginWorkloadSdkDb.js'
import type { McpHostAccessClaims } from '../src/utils/auth/mcpHostJwtToken.js'
@@ -26,6 +28,8 @@ vi.mock('../src/services/pluginWorkloadSdkDb.js', async () => {
updateInvocationStatus: vi.fn(),
consumePeriodQuota: vi.fn(),
countRecentInvocations: vi.fn(),
+ getInvocationById: vi.fn(),
+ registerPluginWorkloadSdkCredentialTicketJti: vi.fn(),
}
})
@@ -98,6 +102,7 @@ function invocation(
authorizationDecision: 'authorized',
createdAt: '2026-06-09T00:00:00.000Z',
completedAt: null,
+ promptAuthorization: null,
...overrides,
}
}
@@ -124,8 +129,11 @@ beforeEach(() => {
vi.mocked(sdkDb.updateInvocationStatus).mockReset()
vi.mocked(sdkDb.consumePeriodQuota).mockReset()
vi.mocked(sdkDb.countRecentInvocations).mockReset()
+ vi.mocked(sdkDb.getInvocationById).mockReset()
+ vi.mocked(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).mockReset()
vi.mocked(sdkDb.countRecentInvocations).mockResolvedValue(0)
vi.mocked(sdkDb.consumePeriodQuota).mockResolvedValue(true)
+ vi.mocked(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).mockResolvedValue(true)
vi.mocked(sdkDb.insertInvocation).mockResolvedValue({
kind: 'inserted',
invocation: invocation(),
@@ -229,6 +237,35 @@ describe('authorizePromptBridge', () => {
})
})
+ it('returns only the ordered policy and defers credential tickets to each attempt', async () => {
+ vi.mocked(sdkDb.findGrant).mockResolvedValue(
+ grant({
+ promptTargets: [
+ {
+ targetRef: 'zai-primary',
+ provider: 'zai',
+ model: 'glm-4.7',
+ credentialSlot: 'zai-api-key',
+ },
+ {
+ targetRef: 'openai-fallback',
+ provider: 'openai',
+ model: 'gpt-5.4',
+ credentialSlot: 'openai-api-key',
+ },
+ ],
+ defaultTargetRef: 'zai-primary',
+ })
+ )
+
+ const result = await authorizePromptBridge({ claims: claims(), ...basePromptParams })
+ expect(result).toMatchObject({ ok: true })
+ if (!result.ok) return
+ expect(result.value.authorizedTargets).toHaveLength(2)
+ expect(result.value).not.toHaveProperty('authorizedTargetTickets')
+ expect(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).not.toHaveBeenCalled()
+ })
+
it('rejects a bare model shared by two authorized providers before recording an invocation', async () => {
vi.mocked(sdkDb.findGrant).mockResolvedValue(
grant({
@@ -528,6 +565,120 @@ describe('authorizePromptBridge', () => {
})
})
+describe('reissuePromptBridgeCredentialTicket', () => {
+ const authorizedSuffix = {
+ policyRevision: 1,
+ policyHash: 'a'.repeat(64),
+ authorizedTargetRefs: ['primary-zai', 'openai-fallback'],
+ }
+
+ const twoTargetGrant = () =>
+ grant({
+ promptTargets: [
+ {
+ targetRef: 'primary-zai',
+ provider: 'zai',
+ model: 'glm-4.7',
+ credentialSlot: 'zai-api-key',
+ },
+ {
+ targetRef: 'openai-fallback',
+ provider: 'openai',
+ model: 'gpt-5.4',
+ credentialSlot: 'openai-api-key',
+ },
+ ],
+ defaultTargetRef: 'primary-zai',
+ })
+
+ it('issues a fresh short-lived ticket only for the persisted fallback suffix', async () => {
+ const policy = twoTargetGrant()
+ authorizedSuffix.policyHash = sdkDb.hashPromptTargetPolicy(policy)
+ vi.mocked(sdkDb.findGrant).mockResolvedValue(policy)
+ vi.mocked(sdkDb.getInvocationById).mockResolvedValue(
+ invocation({ promptAuthorization: { ...authorizedSuffix } })
+ )
+
+ const result = await reissuePromptBridgeCredentialTicket({
+ claims: claims(),
+ invocationId: 'inv-1',
+ targetRef: 'openai-fallback',
+ })
+
+ expect(result).toMatchObject({
+ ok: true,
+ value: {
+ invocationId: 'inv-1',
+ targetRef: 'openai-fallback',
+ policyRevision: 1,
+ policyHash: authorizedSuffix.policyHash,
+ expiresInSeconds: 60,
+ },
+ })
+ if (!result.ok) return
+ const claimsFromTicket = jwt.decode(result.value.credentialTicket) as jwt.JwtPayload
+ expect(claimsFromTicket).toMatchObject({
+ invocationId: 'inv-1',
+ targetRef: 'openai-fallback',
+ policyHash: authorizedSuffix.policyHash,
+ policyRevision: 1,
+ })
+ expect(typeof claimsFromTicket.jti).toBe('string')
+ expect(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).toHaveBeenCalledWith(
+ expect.objectContaining({ invocationId: 'inv-1', targetRef: 'openai-fallback' })
+ )
+ expect(JSON.stringify(result.value)).not.toContain('secret-value')
+ })
+
+ it('fails closed for a body target outside the original authorization suffix', async () => {
+ vi.mocked(sdkDb.getInvocationById).mockResolvedValue(
+ invocation({
+ promptAuthorization: { ...authorizedSuffix, authorizedTargetRefs: ['primary-zai'] },
+ })
+ )
+ const result = await reissuePromptBridgeCredentialTicket({
+ claims: claims(),
+ invocationId: 'inv-1',
+ targetRef: 'openai-fallback',
+ })
+ expect(result).toMatchObject({ ok: false, error: 'target_not_allowed' })
+ expect(sdkDb.findGrant).not.toHaveBeenCalled()
+ expect(sdkDb.registerPluginWorkloadSdkCredentialTicketJti).not.toHaveBeenCalled()
+ })
+
+ it('fails closed when policy changes or the invocation is terminal', async () => {
+ const policy = twoTargetGrant()
+ authorizedSuffix.policyHash = sdkDb.hashPromptTargetPolicy(policy)
+ vi.mocked(sdkDb.findGrant).mockResolvedValue(
+ grant({
+ ...twoTargetGrant(),
+ policyRevision: 2,
+ })
+ )
+ vi.mocked(sdkDb.getInvocationById).mockResolvedValue(
+ invocation({ promptAuthorization: { ...authorizedSuffix } })
+ )
+ await expect(
+ reissuePromptBridgeCredentialTicket({
+ claims: claims(),
+ invocationId: 'inv-1',
+ targetRef: 'openai-fallback',
+ })
+ ).resolves.toMatchObject({ ok: false, error: 'provider_policy_denied' })
+
+ vi.mocked(sdkDb.getInvocationById).mockResolvedValue(
+ invocation({ status: 'failed', promptAuthorization: { ...authorizedSuffix } })
+ )
+ await expect(
+ reissuePromptBridgeCredentialTicket({
+ claims: claims(),
+ invocationId: 'inv-1',
+ targetRef: 'openai-fallback',
+ })
+ ).resolves.toMatchObject({ ok: false, error: 'provider_policy_denied' })
+ })
+})
+
describe('authorizeClientNotification', () => {
const notificationGrant = (overrides: Partial<sdkDb.PluginWorkloadSdkGrant> = {}) =>
grant({
diff --git a/control-api/test/services.pluginWorkloadSdkCredentialTicket.test.ts b/control-api/test/services.pluginWorkloadSdkCredentialTicket.test.ts
index 3c3db5492..8f582f753 100644
--- a/control-api/test/services.pluginWorkloadSdkCredentialTicket.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkCredentialTicket.test.ts
@@ -1,13 +1,18 @@
-import { describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import jwt from 'jsonwebtoken'
import { createPublicKey } from 'node:crypto'
import { config } from '../src/config.js'
import {
PLUGIN_SDK_CREDENTIAL_TICKET_AUDIENCE,
issuePluginWorkloadSdkCredentialTicket,
+ verifyPluginWorkloadSdkCredentialTicket,
} from '../src/services/pluginWorkloadSdkCredentialTicket.js'
describe('plugin workload SDK credential ticket', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
it('binds one authorized target without exposing any credential value', () => {
const ticket = issuePluginWorkloadSdkCredentialTicket({
recipeNamespace: 'sandbox-recipes',
@@ -42,6 +47,63 @@ describe('plugin workload SDK credential ticket', () => {
policyRevision: 7,
typ: 'plugin-sdk-credential-ticket',
})
+ expect(typeof claims.jti).toBe('string')
+ expect(claims.jti).not.toHaveLength(0)
expect(JSON.stringify(claims)).not.toContain('secret-value')
})
+
+ it('expires before a default-duration primary attempt can reach a fallback', () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-08-02T12:00:00.000Z'))
+ const ticket = issuePluginWorkloadSdkCredentialTicket({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ invocationId: 'invocation-slow-primary',
+ target: {
+ targetRef: 'openai-fallback',
+ provider: 'openai',
+ model: 'gpt-5.4',
+ credentialSlot: 'openai-api-key-fb1',
+ },
+ policyRevision: 7,
+ policyHash: 'policy-hash',
+ })
+
+ // Fallbacks must request a new JIT ticket. A ticket carried from initial
+ // authorization intentionally cannot survive the 120s primary timeout.
+ vi.advanceTimersByTime(120_000)
+ expect(verifyPluginWorkloadSdkCredentialTicket(ticket)).toBeNull()
+ })
+
+ it('reissues a fresh jti without changing the invocation or policy binding', () => {
+ const input = {
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'prompt-notify',
+ invocationId: 'invocation-1',
+ target: {
+ targetRef: 'openai-fallback',
+ provider: 'openai',
+ model: 'gpt-5.4',
+ credentialSlot: 'openai-api-key-fb1',
+ },
+ policyRevision: 7,
+ policyHash: 'policy-hash',
+ }
+ const original = verifyPluginWorkloadSdkCredentialTicket(
+ issuePluginWorkloadSdkCredentialTicket(input)
+ )
+ const reissued = verifyPluginWorkloadSdkCredentialTicket(
+ issuePluginWorkloadSdkCredentialTicket(input)
+ )
+
+ expect(original).not.toBeNull()
+ expect(reissued).not.toBeNull()
+ expect(reissued).toMatchObject({
+ invocationId: original!.invocationId,
+ targetRef: original!.targetRef,
+ policyRevision: original!.policyRevision,
+ policyHash: original!.policyHash,
+ })
+ expect(reissued!.jti).not.toBe(original!.jti)
+ })
})
diff --git a/control-api/test/services.pluginWorkloadSdkDb.test.ts b/control-api/test/services.pluginWorkloadSdkDb.test.ts
index 36d3871b3..ffc7d413c 100644
--- a/control-api/test/services.pluginWorkloadSdkDb.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkDb.test.ts
@@ -3,6 +3,8 @@ import { pool } from '../src/db.js'
import {
consumePeriodQuota,
deleteGrant,
+ redeemPluginWorkloadSdkCredentialTicketJti,
+ registerPluginWorkloadSdkCredentialTicketJti,
resolveRecipientProfiles,
upsertGrant,
} from '../src/services/pluginWorkloadSdkDb.js'
@@ -71,6 +73,56 @@ describe('consumePeriodQuota — SQL bind parameter contract', () => {
})
})
+describe('JIT credential ticket jti registry', () => {
+ beforeEach(() => {
+ vi.mocked(pool.query).mockReset()
+ })
+
+ it('registers a non-secret, invocation-bound jti and reports insertion conflicts', async () => {
+ vi.mocked(pool.query)
+ .mockResolvedValueOnce({ rows: [], rowCount: 0 } as never)
+ .mockResolvedValueOnce({ rows: [], rowCount: 1 } as never)
+ await expect(
+ registerPluginWorkloadSdkCredentialTicketJti({
+ jti: '11111111-1111-4111-8111-111111111111',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'sdk-recipe',
+ invocationId: '22222222-2222-4222-8222-222222222222',
+ targetRef: 'openai-fallback',
+ expiresAt: new Date('2026-08-02T12:01:00.000Z'),
+ })
+ ).resolves.toBe(true)
+ const [sql, params] = vi.mocked(pool.query).mock.calls[1] as unknown as [string, unknown[]]
+ expect(sql).toContain('plugin_workload_sdk_credential_ticket_jtis')
+ expect(sql).toContain('ON CONFLICT (jti) DO NOTHING')
+ expect(params).toHaveLength(6)
+ expect(JSON.stringify(params)).not.toContain('secret-value')
+ })
+
+ it('redeems a jti atomically once and binds every identifying field in SQL', async () => {
+ vi.mocked(pool.query).mockResolvedValue({ rows: [], rowCount: 1 } as never)
+ await expect(
+ redeemPluginWorkloadSdkCredentialTicketJti({
+ jti: '11111111-1111-4111-8111-111111111111',
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'sdk-recipe',
+ invocationId: '22222222-2222-4222-8222-222222222222',
+ targetRef: 'openai-fallback',
+ })
+ ).resolves.toBe(true)
+ const [sql, params] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]
+ expect(sql).toContain('redeemed_at IS NULL')
+ expect(sql).toContain('expires_at > now()')
+ expect(params).toEqual([
+ '11111111-1111-4111-8111-111111111111',
+ 'sandbox-recipes',
+ 'sdk-recipe',
+ '22222222-2222-4222-8222-222222222222',
+ 'openai-fallback',
+ ])
+ })
+})
+
describe('upsertGrant — provider column (R1)', () => {
const grantRow = {
id: 'g1',
diff --git a/control-api/test/services.pluginWorkloadSdkSchema.test.ts b/control-api/test/services.pluginWorkloadSdkSchema.test.ts
index ff2a77d99..ae40ba097 100644
--- a/control-api/test/services.pluginWorkloadSdkSchema.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkSchema.test.ts
@@ -51,4 +51,16 @@ describe('pluginWorkloadSdkSchema', () => {
expect(grantsCreate).not.toMatch(/super_admin_approved/)
expect(source).toMatch(/DROP COLUMN IF EXISTS super_admin_approved/)
})
+
+ it('persists JIT ticket authorization and one-shot ticket identities on fresh and upgraded schemas', () => {
+ const schemaPath = join(
+ dirname(fileURLToPath(import.meta.url)),
+ '../src/services/pluginWorkloadSdkSchema.ts'
+ )
+ const source = readFileSync(schemaPath, 'utf8')
+ expect(source).toMatch(/prompt_authorization JSONB NULL/)
+ expect(source).toMatch(/plugin_workload_sdk_credential_ticket_jtis/)
+ expect(source).toMatch(/redeemed_at TIMESTAMPTZ NULL/)
+ expect(source).toMatch(/addPluginWorkloadSdkJitCredentialTicketColumns/)
+ })
})
diff --git a/control-api/test/services.usageEvents.test.ts b/control-api/test/services.usageEvents.test.ts
index 60930701e..b62640cc9 100644
--- a/control-api/test/services.usageEvents.test.ts
+++ b/control-api/test/services.usageEvents.test.ts
@@ -30,6 +30,7 @@ const VALID_EVENT = {
output_tokens: 80,
cache_read_tokens: 40,
cache_write_tokens: 10,
+ prompt_bridge_metadata: null,
}
describe('validateUsageEvent', () => {
@@ -151,6 +152,30 @@ describe('validateUsageEvent', () => {
expect(validateUsageEvent({ ...VALID_EVENT, cache_read_tokens: 1.5 })).toBeNull()
expect(validateUsageEvent({ ...VALID_EVENT, cache_write_tokens: 1.5 })).toBeNull()
})
+
+ it('accepts bounded promptBridge target attribution and rejects malformed metadata', () => {
+ const ev = validateUsageEvent({
+ ...VALID_EVENT,
+ prompt_bridge_metadata: {
+ target_ref: 'zai-primary',
+ credential_slot: 'zai-api-key',
+ fallback_used: true,
+ attempt_count: 2,
+ },
+ })
+ expect(ev?.prompt_bridge_metadata).toEqual({
+ target_ref: 'zai-primary',
+ credential_slot: 'zai-api-key',
+ fallback_used: true,
+ attempt_count: 2,
+ })
+ expect(
+ validateUsageEvent({
+ ...VALID_EVENT,
+ prompt_bridge_metadata: { target_ref: 'zai-primary', fallback_used: true },
+ })
+ ).toBeNull()
+ })
})
describe('ingestUsageEvents', () => {
@@ -207,9 +232,10 @@ describe('ingestUsageEvents', () => {
expect(params).toContain(VALID_EVENT.input_tokens)
expect(params).toContain(VALID_EVENT.cache_read_tokens)
expect(params).toContain(VALID_EVENT.cache_write_tokens)
- expect(params.at(-1)).toBe(true)
- // 22 columns per event (single event => 22 bound params).
- expect(params).toHaveLength(22)
+ expect(params.at(-2)).toBe(true)
+ expect(params.at(-1)).toBeNull()
+ // 23 columns per event (single event => 23 bound params).
+ expect(params).toHaveLength(23)
})
it('mixes valid + invalid + duplicate accounting in a single call', async () => {
diff --git a/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.ts b/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.ts
index 95c382abe..2af799592 100644
--- a/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.ts
+++ b/control-ui/e2e/plugin-workload-sdk-operator-journey.spec.ts
@@ -29,7 +29,9 @@ const REGISTRY_BASE = process.env.REGISTRY_URL || 'http://localhost:8085'
const ADMIN_USER = process.env.ADMIN_USER || 'admin'
const ADMIN_PASS = process.env.ADMIN_PASS || 'changeme123!'
const PROVIDER = process.env.E2E_WORKFLOW_MODEL_PROVIDER || 'zai'
-const MODEL = process.env.E2E_WORKFLOW_MODEL_NAME || 'glm-5.1'
+const MODEL = process.env.E2E_WORKFLOW_MODEL_NAME || 'glm-4.7'
+const FALLBACK_PROVIDER = process.env.E2E_PROMPT_FALLBACK_PROVIDER || 'openai'
+const FALLBACK_MODEL = process.env.E2E_PROMPT_FALLBACK_MODEL || 'gpt-5.4-mini'
const RECIPE_NS = 'sandbox-recipes'
const EVENT_TYPE = 'e2e.test.notification'
const USER_EMAIL = process.env.E2E_DESKTOP_USER_EMAIL || '[email protected]'
@@ -237,7 +239,9 @@ test.describe('Plugin Workload SDK — operator journey (Marketplace → install
// 3. The eager mcp-host self-validates the SDK capability (regression path).
await waitForSdkValidated(token, installedRecipeName)
- // 4. promptBridge grant — configured through the grant page UI.
+ // 4. promptBridge grant — configured through the grant page UI. Add the
+ // fallback first, then the bootstrap target, and reorder it visibly so
+ // the saved policy proves both providers plus an explicit default/order.
// Navigate through the visible application shell so this test proves the
// operator journey rather than jumping directly to the grant route.
await page.getByRole('link', { name: 'Plugins', exact: true }).click()
@@ -256,10 +260,30 @@ test.describe('Plugin Workload SDK — operator journey (Marketplace → install
await expect(page.locator('#sdk-family')).toHaveValue('promptBridge')
await page.locator('#sdk-callers').fill('sdk-caller')
const saveGrantButton = page.getByRole('button', { name: 'Save grant' })
- await expect(page.locator('#sdk-target-model')).toHaveValue(MODEL)
+
+ await page.locator('#sdk-provider').selectOption(FALLBACK_PROVIDER)
+ await page.locator('#sdk-target-model').selectOption(FALLBACK_MODEL)
+ await page.locator('#sdk-credential-slot').selectOption(`${FALLBACK_PROVIDER}-api-key`)
+ await page.locator('#sdk-target-ref').fill(`fallback-${FALLBACK_PROVIDER}`)
+ await page.getByRole('button', { name: 'Add target' }).click()
+
+ await page.locator('#sdk-provider').selectOption(PROVIDER)
+ await page.locator('#sdk-target-model').selectOption(MODEL)
await page.locator('#sdk-credential-slot').selectOption(`${PROVIDER}-api-key`)
await page.locator('#sdk-target-ref').fill(`primary-${PROVIDER}`)
await page.getByRole('button', { name: 'Add target' }).click()
+
+ const orderedTargets = page.getByLabel('Ordered promptBridge targets')
+ const primaryTargetRow = orderedTargets
+ .locator('div.cu-sdk-custom-model-row')
+ .filter({
+ hasText: `primary-${PROVIDER}:`,
+ })
+ .first()
+ await expect(primaryTargetRow).toContainText(`fallback 1 · primary-${PROVIDER}`)
+ await primaryTargetRow.getByRole('button', { name: 'Up' }).click()
+ await expect(orderedTargets).toContainText(`default · primary-${PROVIDER}`)
+ await expect(orderedTargets).toContainText(`fallback 1 · fallback-${FALLBACK_PROVIDER}`)
await expect(saveGrantButton).toBeEnabled()
await saveGrantButton.click()
const promptRow = page.locator('tr', { hasText: installedRecipeName }).filter({
@@ -314,12 +338,41 @@ test.describe('Plugin Workload SDK — operator journey (Marketplace → install
const grants = (list.data.data ?? list.data.items ?? list.data.grants ?? []) as Array<{
capabilityFamily?: string
allowedModels?: string[]
+ provider?: string
+ defaultTargetRef?: string
+ promptTargets?: Array<{
+ targetRef?: string
+ provider?: string
+ model?: string
+ credentialSlot?: string
+ }>
+ policyRevision?: number
}>
const families = grants.map(g => g.capabilityFamily)
expect(families).toContain('promptBridge')
expect(families).toContain('clientNotifications')
const promptGrant = grants.find(g => g.capabilityFamily === 'promptBridge')
expect(promptGrant?.allowedModels).toContain(MODEL)
+ expect(promptGrant).toMatchObject({
+ provider: PROVIDER,
+ defaultTargetRef: `primary-${PROVIDER}`,
+ promptTargets: [
+ {
+ targetRef: `primary-${PROVIDER}`,
+ provider: PROVIDER,
+ model: MODEL,
+ credentialSlot: `${PROVIDER}-api-key`,
+ },
+ {
+ targetRef: `fallback-${FALLBACK_PROVIDER}`,
+ provider: FALLBACK_PROVIDER,
+ model: FALLBACK_MODEL,
+ credentialSlot: `${FALLBACK_PROVIDER}-api-key`,
+ },
+ ],
+ policyRevision: expect.any(Number),
+ })
+ expect(JSON.stringify(promptGrant)).not.toMatch(/secret|token/i)
} finally {
if (installedRecipeName) {
await api(
diff --git a/deploy/scripts/control-api-runtime-access-profiles.tsv b/deploy/scripts/control-api-runtime-access-profiles.tsv
index 827f74e50..3bc0610dd 100644
--- a/deploy/scripts/control-api-runtime-access-profiles.tsv
+++ b/deploy/scripts/control-api-runtime-access-profiles.tsv
@@ -32,6 +32,7 @@ llm_model_prices legacy_dml
member_registration_credentials upsert
notification_deliveries legacy_dml
oauth_grants legacy_dml
+plugin_workload_sdk_credential_ticket_jtis legacy_dml
plugin_workload_sdk_grants legacy_dml
plugin_workload_sdk_invocations legacy_dml
plugin_workload_sdk_quota_counters legacy_dml
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 5021ed01a..d196b6df8 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.324",
+ "version": "0.1.325",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.324",
+ "version": "0.1.325",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index 4e86e78c8..96f27f76d 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.324",
+ "version": "0.1.325",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index a46feca02..cdd7a71a4 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -237,7 +237,7 @@ export type WorkflowInputContractSchema = {
export type WorkflowInputValues = Record<string, string | number | boolean>
export type PluginWorkloadSdkCapabilityStatus = {
- state: 'validated' | 'disabled'
+ state: 'validated' | 'disabled' | 'degraded'
promptBridge: boolean
clientNotifications: boolean
message?: string
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 0058b389b..f66055f0e 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
@@ -153,53 +153,111 @@ async function embeddedValue(
)
}
-async function clickEmbedded(
+async function embeddedActiveControl(
app: ElectronApplication,
webContentsId: number,
selector: string
+): Promise<boolean> {
+ return app.evaluate(
+ async ({ webContents }, args) => {
+ const contents = webContents.fromId(args.webContentsId)
+ if (!contents || contents.isDestroyed()) return false
+ const script = `document.activeElement?.matches(${JSON.stringify(args.selector)}) === true`
+ return Boolean(await contents.executeJavaScript(script))
+ },
+ { webContentsId, selector }
+ )
+}
+
+async function embeddedActiveSignature(
+ app: ElectronApplication,
+ webContentsId: number
+): Promise<string> {
+ return app.evaluate(async ({ webContents }, webContentsId) => {
+ const contents = webContents.fromId(webContentsId)
+ if (!contents || contents.isDestroyed()) return 'destroyed'
+ return String(
+ await contents.executeJavaScript(`(() => {
+ const el = document.activeElement;
+ if (!el) return 'none';
+ return [el.tagName, el.id || '', el.getAttribute('name') || ''].join('#');
+ })()`)
+ )
+ }, webContentsId)
+}
+
+async function sendEmbeddedKey(
+ app: ElectronApplication,
+ webContentsId: number,
+ keyCode: string
): Promise<void> {
- const rect = await embeddedRect(app, webContentsId, selector)
- if (!rect) throw new Error(`Embedded control ${selector} is missing or not visible.`)
- const point = { x: Math.round(rect.x + rect.width / 2), y: Math.round(rect.y + rect.height / 2) }
await app.evaluate(
({ webContents }, args) => {
const contents = webContents.fromId(args.webContentsId)
if (!contents || contents.isDestroyed()) throw new Error('Embedded WebContentsView closed')
- contents.sendInputEvent({ type: 'mouseMove', x: args.x, y: args.y })
- contents.sendInputEvent({
- type: 'mouseDown',
- x: args.x,
- y: args.y,
- button: 'left',
- clickCount: 1,
- })
- contents.sendInputEvent({
- type: 'mouseUp',
- x: args.x,
- y: args.y,
- button: 'left',
- clickCount: 1,
- })
+ contents.focus()
+ contents.sendInputEvent({ type: 'keyDown', keyCode: args.keyCode })
+ if (args.keyCode === 'Enter') {
+ contents.sendInputEvent({ type: 'char', keyCode: '\r' })
+ }
+ contents.sendInputEvent({ type: 'keyUp', keyCode: args.keyCode })
},
- { webContentsId, ...point }
+ { webContentsId, keyCode }
)
}
+async function focusEmbeddedControl(
+ app: ElectronApplication,
+ webContentsId: number,
+ selector: string
+): Promise<void> {
+ // WebContentsView controls below the fold cannot be clicked with coordinates
+ // returned by getBoundingClientRect(): Chromium drops pointer events whose
+ // target point is outside the view. Tab traversal is the native keyboard
+ // path a user takes and scrolls each focused control into view without DOM
+ // focus()/scrollIntoView() shortcuts.
+ for (let attempt = 0; attempt < 16; attempt += 1) {
+ if (await embeddedActiveControl(app, webContentsId, selector)) return
+ const activeBefore = await embeddedActiveSignature(app, webContentsId)
+ await sendEmbeddedKey(app, webContentsId, 'Tab')
+ await expect
+ .poll(() => embeddedActiveSignature(app, webContentsId), {
+ timeout: 2_000,
+ intervals: [10, 25, 50],
+ })
+ .not.toBe(activeBefore)
+ }
+ throw new Error(`Embedded control ${selector} did not receive native keyboard focus.`)
+}
+
async function typeEmbedded(
app: ElectronApplication,
webContentsId: number,
selector: string,
value: string
): Promise<void> {
- await clickEmbedded(app, webContentsId, selector)
+ await focusEmbeddedControl(app, webContentsId, selector)
await app.evaluate(
({ webContents }, args) => {
const contents = webContents.fromId(args.webContentsId)
if (!contents || contents.isDestroyed()) throw new Error('Embedded WebContentsView closed')
- contents.insertText(args.value)
+ contents.focus()
+ for (const character of args.value) {
+ contents.sendInputEvent({ type: 'char', keyCode: character })
+ }
},
{ webContentsId, value }
)
+ await expect.poll(() => embeddedValue(app, webContentsId, selector)).toBe(value)
+}
+
+async function activateEmbedded(
+ app: ElectronApplication,
+ webContentsId: number,
+ selector: string
+): Promise<void> {
+ await focusEmbeddedControl(app, webContentsId, selector)
+ await sendEmbeddedKey(app, webContentsId, 'Enter')
}
test('Desktop Apps executes promptBridge and clientNotifications inside the real WebContentsView', async ({}, testInfo) => {
@@ -236,7 +294,9 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the real
embedded = await findPromptNotifyContents(app!)
return embedded?.url ?? ''
})
- .toContain('/api/v1/sandbox-ui/')
+ .toContain(
+ `/api/v1/sandbox-ui/${encodeURIComponent(RECIPE_NAMESPACE)}/${encodeURIComponent(RECIPE_NAME)}/view/`
+ )
const webContentsId = embedded!.id
await expect.poll(() => embeddedRect(app!, webContentsId, '#run')).not.toBeNull()
@@ -247,7 +307,7 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the real
'#prompt',
`Reply with a short confirmation for test marker ${marker}.`
)
- await clickEmbedded(app, webContentsId, '#run')
+ await activateEmbedded(app, webContentsId, '#run')
await expect
.poll(() => embeddedText(app!, webContentsId, '#prompt-out'), { timeout: 120_000 })
.not.toMatch(/^(?:|Running…|Enter a prompt first\.)$/)
@@ -261,10 +321,16 @@ test('Desktop Apps executes promptBridge and clientNotifications inside the real
.not.toBe('')
await typeEmbedded(app, webContentsId, '#title', `Evenfire E2E ${marker}`)
await typeEmbedded(app, webContentsId, '#message', 'Plugin Workload SDK Desktop validation.')
- await clickEmbedded(app, webContentsId, '#notify')
+ await expect
+ .poll(() => embeddedValue(app!, webContentsId, '#title'))
+ .toBe(`Evenfire E2E ${marker}`)
+ await expect
+ .poll(() => embeddedValue(app!, webContentsId, '#message'))
+ .toBe('Plugin Workload SDK Desktop validation.')
+ await activateEmbedded(app, webContentsId, '#notify')
await expect
.poll(() => embeddedText(app!, webContentsId, '#notify-out'), { timeout: 30_000 })
- .toMatch(/notificationId|accepted|delivered/i)
+ .toMatch(/"notificationId"\s*:\s*"[0-9a-f-]{36}"/i)
// Renderer chrome + native view both remain alive after the two backend
// operations, proving the Desktop Apps path rather than a direct proxy call.
diff --git a/mcp-host/src/pluginWorkloadSdk/domain/errors.ts b/mcp-host/src/pluginWorkloadSdk/domain/errors.ts
index 90cd3e15c..acb2453b8 100644
--- a/mcp-host/src/pluginWorkloadSdk/domain/errors.ts
+++ b/mcp-host/src/pluginWorkloadSdk/domain/errors.ts
@@ -24,6 +24,19 @@ export const PLUGIN_WORKLOAD_ERROR_CODES = [
] as const
export type PluginWorkloadErrorCode = (typeof PLUGIN_WORKLOAD_ERROR_CODES)[number]
+/** Safe, closed diagnostic classes for provider_unavailable responses. */
+export const PLUGIN_WORKLOAD_ERROR_REASONS = [
+ 'rate_limited',
+ 'insufficient_quota',
+ 'auth',
+ 'provider_unavailable',
+ 'credential_unavailable',
+ 'configuration',
+ 'timeout',
+ 'network',
+] as const
+export type PluginWorkloadErrorReason = (typeof PLUGIN_WORKLOAD_ERROR_REASONS)[number]
+
const ERROR_HTTP_STATUS: Record<PluginWorkloadErrorCode, number> = {
capability_not_declared: 403,
caller_not_allowed: 403,
@@ -41,25 +54,49 @@ const ERROR_HTTP_STATUS: Record<PluginWorkloadErrorCode, number> = {
}
const ERROR_CODE_SET = new Set<string>(PLUGIN_WORKLOAD_ERROR_CODES)
+const ERROR_REASON_SET = new Set<string>(PLUGIN_WORKLOAD_ERROR_REASONS)
export class PluginWorkloadError extends Error {
readonly code: PluginWorkloadErrorCode
readonly retryable: boolean
readonly httpStatus: number
+ readonly reason?: PluginWorkloadErrorReason
- constructor(code: PluginWorkloadErrorCode, message: string, retryable = false) {
+ constructor(
+ code: PluginWorkloadErrorCode,
+ message: string,
+ retryable = false,
+ reason?: PluginWorkloadErrorReason
+ ) {
super(message)
this.name = 'PluginWorkloadError'
this.code = code
this.retryable = retryable
this.httpStatus = ERROR_HTTP_STATUS[code]
+ this.reason = reason
}
- toBody(): { error: PluginWorkloadErrorCode; message: string; retryable: boolean } {
- return { error: this.code, message: this.message, retryable: this.retryable }
+ toBody(): {
+ error: PluginWorkloadErrorCode
+ message: string
+ retryable: boolean
+ reason?: PluginWorkloadErrorReason
+ } {
+ return {
+ error: this.code,
+ message: this.message,
+ retryable: this.retryable,
+ ...(this.reason ? { reason: this.reason } : {}),
+ }
}
}
export function isKnownPluginWorkloadErrorCode(code: string): code is PluginWorkloadErrorCode {
return ERROR_CODE_SET.has(code)
}
+
+export function isKnownPluginWorkloadErrorReason(
+ reason: string
+): reason is PluginWorkloadErrorReason {
+ return ERROR_REASON_SET.has(reason)
+}
diff --git a/mcp-host/src/pluginWorkloadSdk/metrics.test.ts b/mcp-host/src/pluginWorkloadSdk/metrics.test.ts
index e390ec990..f6c63a353 100644
--- a/mcp-host/src/pluginWorkloadSdk/metrics.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/metrics.test.ts
@@ -33,7 +33,6 @@ function makeHandler(recipeName: string, complete?: ReturnType<typeof vi.fn>) {
modelPolicy: null,
selectedTarget: target,
authorizedTargets: [target],
- authorizedTargetTickets: [{ targetRef: target.targetRef, credentialTicket: 'ticket' }],
policyRevision: 1,
policyHash: 'a'.repeat(64),
maxOutputTokens: null,
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
index f19637d76..0eacc63bb 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts
@@ -27,7 +27,6 @@ function authorizedBody(invocationId: string) {
modelPolicy: null,
selectedTarget: target,
authorizedTargets: [target],
- authorizedTargetTickets: [{ targetRef: target.targetRef, credentialTicket: 'signed-ticket' }],
policyRevision: 2,
policyHash: 'a'.repeat(64),
maxOutputTokens: null,
@@ -77,12 +76,12 @@ describe('PluginWorkloadSdkControlApiClient', () => {
expect(fetchImpl).toHaveBeenCalledTimes(1) // 4xx is not retried
})
- it('fails closed when authorization omits target tickets', async () => {
- const { authorizedTargetTickets: _omitted, ...missingTickets } = authorizedBody('inv-1')
- const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(201, missingTickets))
+ it('accepts a policy-only authorization envelope and leaves ticket issuance to the attempt path', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(201, authorizedBody('inv-1')))
const client = makeClient(fetchImpl as unknown as typeof fetch)
- await expect(client.authorizePromptBridge(promptBody)).rejects.toMatchObject({
- code: 'provider_unavailable',
+ await expect(client.authorizePromptBridge(promptBody)).resolves.toMatchObject({
+ invocationId: 'inv-1',
+ authorizedTargets: [target],
})
})
@@ -103,6 +102,66 @@ describe('PluginWorkloadSdkControlApiClient', () => {
})
})
+ it('reissues a ticket bound to the authorized recipe, invocation, target, and policy snapshot', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue(
+ jsonResponse(201, {
+ invocationId: 'inv-1',
+ targetRef: target.targetRef,
+ credentialTicket: 'fresh-signed-ticket',
+ policyRevision: 2,
+ policyHash: 'a'.repeat(64),
+ expiresInSeconds: 60,
+ })
+ )
+ const client = makeClient(fetchImpl as unknown as typeof fetch)
+
+ await expect(
+ client.reissuePromptBridgeCredentialTicket({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'r1',
+ invocationId: 'inv-1',
+ target,
+ policyRevision: 2,
+ policyHash: 'a'.repeat(64),
+ })
+ ).resolves.toMatchObject({ credentialTicket: 'fresh-signed-ticket' })
+
+ const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]
+ expect(url).toBe(
+ 'http://gateway:8092/api/v1/mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket'
+ )
+ expect(JSON.parse(String(init.body))).toEqual({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'r1',
+ invocationId: 'inv-1',
+ targetRef: target.targetRef,
+ })
+ })
+
+ it('rejects a reissued ticket that does not match the original authorization snapshot', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue(
+ jsonResponse(201, {
+ invocationId: 'inv-1',
+ targetRef: 'different-target',
+ credentialTicket: 'fresh-signed-ticket',
+ policyRevision: 2,
+ policyHash: 'a'.repeat(64),
+ expiresInSeconds: 60,
+ })
+ )
+ const client = makeClient(fetchImpl as unknown as typeof fetch)
+ await expect(
+ client.reissuePromptBridgeCredentialTicket({
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'r1',
+ invocationId: 'inv-1',
+ target,
+ policyRevision: 2,
+ policyHash: 'a'.repeat(64),
+ })
+ ).rejects.toMatchObject({ code: 'provider_unavailable', retryable: false })
+ })
+
it('retries 5xx and returns provider_unavailable after exhausting retries', async () => {
const fetchImpl = vi.fn().mockResolvedValue(jsonResponse(503, {}))
const client = makeClient(fetchImpl as unknown as typeof fetch)
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
index 99a4571da..878bb2999 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
@@ -1,5 +1,9 @@
import { CircuitBreaker } from '../domain/circuitBreaker'
-import { PluginWorkloadError, isKnownPluginWorkloadErrorCode } from '../domain/errors'
+import {
+ PluginWorkloadError,
+ isKnownPluginWorkloadErrorCode,
+ isKnownPluginWorkloadErrorReason,
+} from '../domain/errors'
import type { PromptBridgeTarget } from '../domain/types'
/**
@@ -41,12 +45,20 @@ export interface AuthorizePromptBridgeResponse {
modelPolicy: { provider: string; model: string; temperature?: number; maxCostUsd?: number } | null
selectedTarget: PromptBridgeTarget
authorizedTargets: PromptBridgeTarget[]
- authorizedTargetTickets: Array<{ targetRef: string; credentialTicket: string }>
policyRevision: number
policyHash: string
maxOutputTokens: number | null
}
+export interface ReissuedPromptBridgeCredentialTicket {
+ invocationId: string
+ targetRef: string
+ credentialTicket: string
+ policyRevision: number
+ policyHash: string
+ expiresInSeconds: number
+}
+
export interface SubmitClientNotificationResponse {
notificationId: string
replay: boolean
@@ -83,15 +95,6 @@ function isAuthorizePromptBridgeResponse(v: unknown): v is AuthorizePromptBridge
Array.isArray(r.authorizedTargets) &&
r.authorizedTargets.length > 0 &&
r.authorizedTargets.every(isPromptBridgeTarget) &&
- Array.isArray(r.authorizedTargetTickets) &&
- r.authorizedTargetTickets.length === r.authorizedTargets.length &&
- r.authorizedTargetTickets.every(
- ticket =>
- typeof ticket === 'object' &&
- ticket !== null &&
- typeof (ticket as Record<string, unknown>).targetRef === 'string' &&
- typeof (ticket as Record<string, unknown>).credentialTicket === 'string'
- ) &&
Number.isInteger(r.policyRevision) &&
(r.policyRevision as number) >= 1 &&
typeof r.policyHash === 'string' &&
@@ -100,6 +103,25 @@ function isAuthorizePromptBridgeResponse(v: unknown): v is AuthorizePromptBridge
)
}
+function isReissuedPromptBridgeCredentialTicket(
+ value: unknown
+): value is ReissuedPromptBridgeCredentialTicket {
+ if (typeof value !== 'object' || value === null) return false
+ const ticket = value as Record<string, unknown>
+ return (
+ typeof ticket.invocationId === 'string' &&
+ typeof ticket.targetRef === 'string' &&
+ typeof ticket.credentialTicket === 'string' &&
+ ticket.credentialTicket.length > 0 &&
+ Number.isInteger(ticket.policyRevision) &&
+ (ticket.policyRevision as number) >= 1 &&
+ typeof ticket.policyHash === 'string' &&
+ /^[a-f0-9]{64}$/.test(ticket.policyHash) &&
+ Number.isInteger(ticket.expiresInSeconds) &&
+ (ticket.expiresInSeconds as number) > 0
+ )
+}
+
function isPromptBridgeTarget(value: unknown): value is PromptBridgeTarget {
if (typeof value !== 'object' || value === null) return false
const target = value as Record<string, unknown>
@@ -255,13 +277,17 @@ export class PluginWorkloadSdkControlApiClient {
error?: unknown
message?: unknown
retryable?: unknown
+ reason?: unknown
}
const code = typeof errorBody.error === 'string' ? errorBody.error : ''
if (isKnownPluginWorkloadErrorCode(code)) {
throw new PluginWorkloadError(
code,
typeof errorBody.message === 'string' ? errorBody.message : `request denied (${code})`,
- errorBody.retryable === true
+ errorBody.retryable === true,
+ typeof errorBody.reason === 'string' && isKnownPluginWorkloadErrorReason(errorBody.reason)
+ ? errorBody.reason
+ : undefined
)
}
if (response.status === 401) {
@@ -306,6 +332,50 @@ export class PluginWorkloadSdkControlApiClient {
return result
}
+ /**
+ * Obtain a one-shot credential ticket immediately before a single target's
+ * credential resolution. The caller binds the original authorization
+ * snapshot; the gateway independently derives the credential identity.
+ */
+ async reissuePromptBridgeCredentialTicket(body: {
+ recipeNamespace: string
+ recipeName: string
+ invocationId: string
+ target: PromptBridgeTarget
+ policyRevision: number
+ policyHash: string
+ }): Promise<ReissuedPromptBridgeCredentialTicket> {
+ const result = await this.post(
+ '/api/v1/mcp-host/plugin-workload-sdk/prompt-bridge/credential-ticket',
+ {
+ recipeNamespace: body.recipeNamespace,
+ recipeName: body.recipeName,
+ invocationId: body.invocationId,
+ targetRef: body.target.targetRef,
+ }
+ )
+ if (!isReissuedPromptBridgeCredentialTicket(result)) {
+ throw new PluginWorkloadError(
+ 'provider_unavailable',
+ 'control-api returned an unexpected response shape for credential-ticket reissue',
+ true
+ )
+ }
+ if (
+ result.invocationId !== body.invocationId ||
+ result.targetRef !== body.target.targetRef ||
+ result.policyRevision !== body.policyRevision ||
+ result.policyHash !== body.policyHash
+ ) {
+ throw new PluginWorkloadError(
+ 'provider_unavailable',
+ 'control-api returned a credential ticket for a different authorization',
+ false
+ )
+ }
+ return result
+ }
+
async reportInvocationStatus(
invocationId: string,
recipeNamespace: string,
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.ts
index 21c379437..12c271a4a 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/credentialBrokerClient.ts
@@ -29,6 +29,7 @@ export class PluginWorkloadSdkCredentialBrokerClient {
invocationId: string
target: PromptBridgeTarget
credentialTicket: string
+ timeoutMs?: number
}): Promise<BrokeredCredential> {
const fetchImpl = this.opts.fetchImpl ?? fetch
const url = `${this.opts.baseUrl.replace(/\/+$/, '')}/api/v1/workflow/${encodeURIComponent(
@@ -37,6 +38,10 @@ export class PluginWorkloadSdkCredentialBrokerClient {
let response: Response
try {
+ const signal =
+ input.timeoutMs === undefined
+ ? undefined
+ : AbortSignal.timeout(Math.max(1, input.timeoutMs))
response = await fetchImpl(url, {
method: 'POST',
headers: {
@@ -49,6 +54,7 @@ export class PluginWorkloadSdkCredentialBrokerClient {
target: input.target,
credentialTicket: input.credentialTicket,
}),
+ signal,
})
} catch {
throw unavailable()
@@ -99,6 +105,7 @@ function unavailable(): PluginWorkloadError {
return new PluginWorkloadError(
'provider_unavailable',
'authorized provider credentials are unavailable',
- false
+ false,
+ 'credential_unavailable'
)
}
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
index d068afb0f..f585b620a 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.test.ts
@@ -32,10 +32,6 @@ function authorization(overrides: Record<string, unknown> = {}) {
modelPolicy: null,
selectedTarget: primary,
authorizedTargets: [primary, fallback],
- authorizedTargetTickets: [
- { targetRef: primary.targetRef, credentialTicket: 'ticket-primary' },
- { targetRef: fallback.targetRef, credentialTicket: 'ticket-fallback' },
- ],
policyRevision: 7,
policyHash: 'a'.repeat(64),
maxOutputTokens: 2048,
@@ -60,6 +56,7 @@ function makeDeps(
model: fallback.model,
servedTarget: fallback,
fallbackUsed: true,
+ attemptCount: 2,
llmSecretName: 'provider-secret',
content: 'summary text',
usage: { inputTokens: 10, outputTokens: 5 },
@@ -149,10 +146,7 @@ describe('PromptBridgeHandler', () => {
expect.objectContaining({
invocationId: 'inv-1',
maxTokens: 2048,
- targets: [
- { target: primary, credentialTicket: 'ticket-primary' },
- { target: fallback, credentialTicket: 'ticket-fallback' },
- ],
+ targets: [{ target: primary }, { target: fallback }],
})
)
expect(result).toMatchObject({
@@ -171,26 +165,11 @@ describe('PromptBridgeHandler', () => {
servedTarget: fallback,
fallbackUsed: true,
llmSecretName: 'provider-secret',
+ attemptCount: 2,
})
)
})
- it('fails closed on inconsistent tickets before credential or provider access', async () => {
- const authorize = vi.fn().mockResolvedValue(
- authorization({
- authorizedTargetTickets: [
- { targetRef: primary.targetRef, credentialTicket: 'ticket-primary' },
- ],
- })
- )
- const { handler, complete } = makeDeps({ authorize })
- await expect(handler.handle(validBody, 'api')).rejects.toMatchObject({
- code: 'provider_unavailable',
- retryable: false,
- })
- expect(complete).not.toHaveBeenCalled()
- })
-
it('does not repeat a provider charge for an existing non-failed replay', async () => {
const authorize = vi.fn().mockResolvedValue(authorization({ replay: true, status: 'complete' }))
const { handler, complete } = makeDeps({ authorize })
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
index 921069852..066dc7789 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/handler.ts
@@ -47,6 +47,7 @@ export interface PromptBridgeHandlerDeps {
model: string
servedTarget: PromptBridgeTarget
fallbackUsed: boolean
+ attemptCount: number
llmSecretName: string
inputTokens: number
outputTokens: number
@@ -241,24 +242,24 @@ export class PromptBridgeHandler {
if (!selected || !sameTarget(selected, authorized.selectedTarget)) {
throw unexpectedAuthorizationResponse()
}
- const ticketByTarget = new Map(
- authorized.authorizedTargetTickets.map(ticket => [ticket.targetRef, ticket.credentialTicket])
- )
- if (
- ticketByTarget.size !== authorized.authorizedTargets.length ||
- authorized.authorizedTargets.some(target => !ticketByTarget.has(target.targetRef))
- ) {
- throw unexpectedAuthorizationResponse()
- }
-
try {
const completion = await this.deps.llmBridge.complete({
invocationId: authorized.invocationId,
- targets: authorized.authorizedTargets.map(target => ({
- target,
- credentialTicket: ticketByTarget.get(target.targetRef)!,
- })),
+ targets: authorized.authorizedTargets.map(target => ({ target })),
messages: request.messages,
+ policyRevision: authorized.policyRevision,
+ policyHash: authorized.policyHash,
+ credentialTicketIssuer: {
+ issue: async input =>
+ this.deps.controlApiClient.reissuePromptBridgeCredentialTicket({
+ recipeNamespace: this.deps.recipeNamespace,
+ recipeName: this.deps.recipeName,
+ invocationId: input.invocationId,
+ target: input.target,
+ policyRevision: input.policyRevision,
+ policyHash: input.policyHash,
+ }),
+ },
maxTokens: clampMaxTokens(request.maxTokens, authorized.maxOutputTokens),
temperature: request.temperature ?? authorized.modelPolicy?.temperature,
timeoutMs: this.deps.promptTimeoutMs,
@@ -269,6 +270,7 @@ export class PromptBridgeHandler {
model: completion.model,
servedTarget: completion.servedTarget,
fallbackUsed: completion.fallbackUsed,
+ attemptCount: completion.attemptCount,
llmSecretName: completion.llmSecretName,
inputTokens: completion.usage.inputTokens,
outputTokens: completion.usage.outputTokens,
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
index e1cd5010a..ab3977eb0 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts
@@ -77,10 +77,14 @@ function makeBridge(
const request = {
invocationId: 'inv-1',
- targets: [
- { target: primary, credentialTicket: 'ticket-primary' },
- { target: fallback, credentialTicket: 'ticket-fallback' },
- ],
+ targets: [{ target: primary }, { target: fallback }],
+ policyRevision: 1,
+ policyHash: 'a'.repeat(64),
+ credentialTicketIssuer: {
+ issue: vi.fn(async ({ target }: { target: PromptBridgeTarget }) => ({
+ credentialTicket: `fresh-${target.targetRef}`,
+ })),
+ },
messages: [{ role: 'user' as const, content: 'hi' }],
timeoutMs: 5_000,
}
@@ -106,6 +110,7 @@ describe('LlmBridge authorized multi-provider fallback', () => {
fallbackUsed: true,
model: fallback.model,
usage: { inputTokens: 3, outputTokens: 4 },
+ attemptCount: 2,
})
})
@@ -127,6 +132,62 @@ describe('LlmBridge authorized multi-provider fallback', () => {
expect(providerCalls).toEqual([])
})
+ it('reissues a fresh target-bound ticket immediately before each credential resolution', async () => {
+ const first = new FakeProvider(() => Promise.reject(new Error('provider response')))
+ const second = new FakeProvider(() => Promise.resolve(OK))
+ const issue = vi.fn(async ({ target }: { target: PromptBridgeTarget }) => ({
+ credentialTicket: `fresh-${target.targetRef}`,
+ }))
+ const resolve = vi.fn(async ({ target, credentialTicket }) => {
+ expect(credentialTicket).toBe(`fresh-${target.targetRef}`)
+ return {
+ target,
+ keys: {
+ [target.provider]: { [`${target.provider}-api-key`]: 'provider-secret' },
+ } as ApiKeys,
+ llmSecretName: 'provider-secret',
+ }
+ })
+ const { bridge } = makeBridge({ [primary.model]: first, [fallback.model]: second }, resolve)
+
+ await bridge.complete({ ...request, credentialTicketIssuer: { issue } })
+
+ expect(issue).toHaveBeenNthCalledWith(1, {
+ invocationId: 'inv-1',
+ target: primary,
+ policyRevision: 1,
+ policyHash: 'a'.repeat(64),
+ })
+ expect(issue).toHaveBeenNthCalledWith(2, {
+ invocationId: 'inv-1',
+ target: fallback,
+ policyRevision: 1,
+ policyHash: 'a'.repeat(64),
+ })
+ expect(resolve).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not fall back when JIT ticket issuance fails', async () => {
+ const issue = vi.fn(async () => {
+ throw new PluginWorkloadError('provider_unavailable', 'ticket unavailable', true)
+ })
+ const { bridge, credentialCalls } = makeBridge({})
+ await expect(
+ bridge.complete({ ...request, credentialTicketIssuer: { issue } })
+ ).rejects.toMatchObject({ code: 'provider_unavailable', retryable: true })
+ expect(issue).toHaveBeenCalledOnce()
+ expect(credentialCalls).toEqual([])
+ })
+
+ it('bounds JIT ticket issuance to the request deadline', async () => {
+ const issue = vi.fn(() => new Promise<{ credentialTicket: string }>(() => undefined))
+ const { bridge, credentialCalls } = makeBridge({})
+ await expect(
+ bridge.complete({ ...request, timeoutMs: 5, credentialTicketIssuer: { issue } })
+ ).rejects.toMatchObject({ code: 'provider_unavailable', retryable: true })
+ expect(credentialCalls).toEqual([])
+ })
+
it('does not fallback on a provider error outside triggerOn', async () => {
const first = new FakeProvider(() => Promise.reject(new Error('429')))
const second = new FakeProvider(() => Promise.resolve(OK))
@@ -141,6 +202,32 @@ describe('LlmBridge authorized multi-provider fallback', () => {
expect(providerCalls).toEqual([`${primary.provider}/${primary.model}`])
})
+ it('surfaces only a safe provider reason and never the provider body', async () => {
+ const failing = new FakeProvider(() =>
+ Promise.reject(new Error('provider secret response body must stay private'))
+ )
+ const { bridge } = makeBridge({ [primary.model]: failing })
+
+ await expect(
+ bridge.complete({ ...request, targets: [{ target: primary }] })
+ ).rejects.toMatchObject({ code: 'provider_unavailable', reason: 'rate_limited' })
+
+ try {
+ await bridge.complete({ ...request, targets: [{ target: primary }] })
+ } catch (error) {
+ expect(error).toBeInstanceOf(PluginWorkloadError)
+ expect((error as PluginWorkloadError).toBody()).toEqual({
+ error: 'provider_unavailable',
+ message: 'LLM provider error: LLM_RATE_LIMITED',
+ retryable: true,
+ reason: 'rate_limited',
+ })
+ expect(JSON.stringify((error as PluginWorkloadError).toBody())).not.toContain(
+ 'provider secret'
+ )
+ }
+ })
+
it('fails terminally when an authorized target cannot construct its provider', async () => {
const { bridge } = makeBridge({})
await expect(bridge.complete(request)).rejects.toMatchObject({
@@ -232,7 +319,7 @@ describe('LlmBridge authorized multi-provider fallback', () => {
bridge.complete({
...request,
invocationId: `metric-${attempt}`,
- targets: [{ target, credentialTicket: `ticket-${attempt}` }],
+ targets: [{ target }],
})
).rejects.toMatchObject({ code: 'provider_unavailable' })
}
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
index 1f0c3cbcf..530f641ff 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
@@ -32,12 +32,25 @@ export interface PromptBridgeCredentialResolver {
invocationId: string
target: PromptBridgeTarget
credentialTicket: string
+ timeoutMs?: number
}): Promise<BrokeredCredential>
}
+export interface PromptBridgeCredentialTicketIssuer {
+ issue(input: {
+ invocationId: string
+ target: PromptBridgeTarget
+ policyRevision: number
+ policyHash: string
+ }): Promise<{ credentialTicket: string }>
+}
+
export interface LlmBridgeRequest {
invocationId: string
- targets: Array<{ target: PromptBridgeTarget; credentialTicket: string }>
+ targets: Array<{ target: PromptBridgeTarget }>
+ policyRevision: number
+ policyHash: string
+ credentialTicketIssuer: PromptBridgeCredentialTicketIssuer
messages: Array<{ role: 'system' | 'user' | 'assistant'; content: string }>
maxTokens?: number
temperature?: number
@@ -49,6 +62,7 @@ export interface LlmBridgeResult {
model: string
servedTarget: PromptBridgeTarget
fallbackUsed: boolean
+ attemptCount: number
llmSecretName: string
content: string
usage: { inputTokens: number; outputTokens: number }
@@ -57,6 +71,47 @@ export interface LlmBridgeResult {
const DEFAULT_MAX_LLM_RESPONSE_BYTES = 1024 * 1024
+function remainingTimeoutMs(deadlineAt: number): number {
+ return deadlineAt - Date.now()
+}
+
+async function withinDeadline<T>(
+ operation: () => Promise<T>,
+ timeoutMs: number,
+ reason: 'timeout' | 'provider_unavailable' = 'timeout'
+): Promise<T> {
+ if (timeoutMs <= 0) {
+ throw new PluginWorkloadError(
+ 'provider_unavailable',
+ 'promptBridge request deadline elapsed before provider attempt',
+ true,
+ reason
+ )
+ }
+ let timeout: NodeJS.Timeout | undefined
+ try {
+ return await Promise.race([
+ operation(),
+ new Promise<never>((_, reject) => {
+ timeout = setTimeout(
+ () =>
+ reject(
+ new PluginWorkloadError(
+ 'provider_unavailable',
+ 'promptBridge request deadline elapsed before provider attempt',
+ true,
+ reason
+ )
+ ),
+ timeoutMs
+ )
+ }),
+ ])
+ } finally {
+ if (timeout) clearTimeout(timeout)
+ }
+}
+
function mapFinishReason(reason: FinishReason): LlmBridgeResult['finishReason'] {
if (reason === FinishReason.Length) return 'length'
if (reason === FinishReason.ContentFilter) return 'content_filter'
@@ -109,9 +164,15 @@ export class LlmBridge {
async complete(request: LlmBridgeRequest): Promise<LlmBridgeResult> {
if (request.targets.length === 0) {
- throw new PluginWorkloadError('provider_unavailable', 'no authorized provider target', false)
+ throw new PluginWorkloadError(
+ 'provider_unavailable',
+ 'no authorized provider target',
+ false,
+ 'configuration'
+ )
}
const triggerOn = new Set(request.triggerOn ?? ALL_FAILOVER_CLASSES)
+ const deadlineAt = Date.now() + request.timeoutMs
let lastProviderError: ClassifiedProviderError | null = null
for (const [index, authorized] of request.targets.entries()) {
@@ -119,7 +180,8 @@ export class LlmBridge {
throw new PluginWorkloadError(
'provider_unavailable',
'authorized provider configuration is unavailable',
- false
+ false,
+ 'configuration'
)
}
@@ -130,7 +192,8 @@ export class LlmBridge {
new PluginWorkloadError(
'provider_unavailable',
'LLM provider is temporarily unavailable',
- true
+ true,
+ 'provider_unavailable'
)
)
lastProviderError = error
@@ -145,18 +208,40 @@ export class LlmBridge {
// Ticket redemption is deliberately inside the attempt loop. This value
// is held only for the provider call and is never exposed in SDK output.
- const credential = await this.credentials.resolve({
- invocationId: request.invocationId,
- target: authorized.target,
- credentialTicket: authorized.credentialTicket,
- })
+ const ticket = await withinDeadline(
+ () =>
+ request.credentialTicketIssuer.issue({
+ invocationId: request.invocationId,
+ target: authorized.target,
+ policyRevision: request.policyRevision,
+ policyHash: request.policyHash,
+ }),
+ remainingTimeoutMs(deadlineAt),
+ 'timeout'
+ )
+ const credential = await withinDeadline(
+ () =>
+ this.credentials.resolve({
+ invocationId: request.invocationId,
+ target: authorized.target,
+ credentialTicket: ticket.credentialTicket,
+ timeoutMs: remainingTimeoutMs(deadlineAt),
+ }),
+ remainingTimeoutMs(deadlineAt),
+ 'timeout'
+ )
try {
- const completion = await this.attempt(credential, request, breaker)
+ const completion = await this.attempt(
+ credential,
+ { ...request, timeoutMs: remainingTimeoutMs(deadlineAt) },
+ breaker
+ )
return {
...completion,
servedTarget: authorized.target,
fallbackUsed: index > 0,
+ attemptCount: index + 1,
llmSecretName: credential.llmSecretName,
}
} catch (error) {
@@ -173,7 +258,12 @@ export class LlmBridge {
throw (
lastProviderError?.toPluginWorkloadError() ??
- new PluginWorkloadError('provider_unavailable', 'authorized providers are unavailable', true)
+ new PluginWorkloadError(
+ 'provider_unavailable',
+ 'authorized providers are unavailable',
+ true,
+ 'provider_unavailable'
+ )
)
}
@@ -182,13 +272,22 @@ export class LlmBridge {
request: LlmBridgeRequest,
breaker: CircuitBreaker
): Promise<Pick<LlmBridgeResult, 'model' | 'content' | 'usage' | 'finishReason'>> {
+ if (request.timeoutMs <= 0) {
+ throw new PluginWorkloadError(
+ 'provider_unavailable',
+ 'promptBridge request deadline elapsed before provider attempt',
+ true,
+ 'timeout'
+ )
+ }
const factory = this.opts.createProvider ?? createLLMProvider
const providerId = credential.target.provider
if (!isLlmProvider(providerId)) {
throw new PluginWorkloadError(
'provider_unavailable',
'authorized provider configuration is unavailable',
- false
+ false,
+ 'configuration'
)
}
const provider: SingleTurnProvider | null = factory(credential.keys, {
@@ -199,7 +298,8 @@ export class LlmBridge {
throw new PluginWorkloadError(
'provider_unavailable',
'authorized provider credentials are unavailable',
- false
+ false,
+ 'credential_unavailable'
)
}
@@ -225,7 +325,8 @@ export class LlmBridge {
throw new PluginWorkloadError(
'provider_unavailable',
'provider returned invalid usage',
- false
+ false,
+ 'provider_unavailable'
)
}
return {
@@ -243,17 +344,21 @@ export class LlmBridge {
new PluginWorkloadError(
'provider_unavailable',
'LLM provider did not respond within the request timeout',
- true
+ true,
+ 'timeout'
)
)
}
const classified = provider.classifyError(error)
+ const reason =
+ classifyFailoverClass(classified.code, classified.retryable) ?? 'provider_unavailable'
throw new ClassifiedProviderError(
{ code: classified.code, retryable: classified.retryable },
new PluginWorkloadError(
'provider_unavailable',
`LLM provider error: ${classified.code}`,
- classified.retryable
+ classified.retryable,
+ reason
)
)
} finally {
diff --git a/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts b/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts
index a1b044a2d..303d3ffe2 100644
--- a/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/securityInvariants.test.ts
@@ -50,9 +50,6 @@ describe('Plugin Workload SDK — §6.2 response-shape security invariants', ()
modelPolicy: { provider: 'zai', model: 'glm-4.7', apiKey: 'sk-provider-secret' },
selectedTarget: target,
authorizedTargets: [target],
- authorizedTargetTickets: [
- { targetRef: target.targetRef, credentialTicket: 'signed-ticket' },
- ],
policyRevision: 1,
policyHash: 'a'.repeat(64),
maxOutputTokens: null,
diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.test.ts b/mcp-host/src/pluginWorkloadSdk/server/index.test.ts
index c89bfd1bd..f5b58520e 100644
--- a/mcp-host/src/pluginWorkloadSdk/server/index.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/server/index.test.ts
@@ -57,4 +57,38 @@ describe('PluginWorkloadSdk server usage attribution', () => {
output_tokens: 5,
})
})
+
+ it('records actual promptBridge target attribution without credential values', () => {
+ const event = buildPromptBridgeUsageEvent({
+ binding: {
+ hostRef: 'plugin-workload-sdk/sandbox-app',
+ recipeNamespace: 'sandbox-apps',
+ recipeName: 'prompt-notify',
+ },
+ provider: 'openai',
+ model: 'gpt-5.4-mini',
+ inputTokens: 10,
+ outputTokens: 5,
+ callerRef: 'backend-worker',
+ promptBridgeMetadata: {
+ targetRef: 'fallback-openai',
+ credentialSlot: 'openai-api-key',
+ fallbackUsed: true,
+ attemptCount: 2,
+ },
+ })
+
+ expect(event).toMatchObject({
+ provider: 'openai',
+ model: 'gpt-5.4-mini',
+ prompt_bridge_metadata: {
+ target_ref: 'fallback-openai',
+ credential_slot: 'openai-api-key',
+ fallback_used: true,
+ attempt_count: 2,
+ },
+ })
+ expect(JSON.stringify(event)).not.toContain('credentialTicket')
+ expect(JSON.stringify(event)).not.toContain('secret-')
+ })
})
diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.ts b/mcp-host/src/pluginWorkloadSdk/server/index.ts
index c4bbf54de..74971ab8d 100644
--- a/mcp-host/src/pluginWorkloadSdk/server/index.ts
+++ b/mcp-host/src/pluginWorkloadSdk/server/index.ts
@@ -46,6 +46,12 @@ export function buildPromptBridgeUsageEvent(input: {
inputTokens: number
outputTokens: number
callerRef: string
+ promptBridgeMetadata?: {
+ targetRef: string
+ credentialSlot: string
+ fallbackUsed: boolean
+ attemptCount: number
+ }
metadata?: Record<string, unknown>
}): LlmUsageEvent | null {
const isWorkflowRecipe = input.binding.recipeNamespace === WORKFLOW_RECIPE_NAMESPACE
@@ -70,6 +76,16 @@ export function buildPromptBridgeUsageEvent(input: {
iteration: null,
input_tokens: input.inputTokens,
output_tokens: input.outputTokens,
+ ...(input.promptBridgeMetadata
+ ? {
+ prompt_bridge_metadata: {
+ target_ref: input.promptBridgeMetadata.targetRef,
+ credential_slot: input.promptBridgeMetadata.credentialSlot,
+ fallback_used: input.promptBridgeMetadata.fallbackUsed,
+ attempt_count: input.promptBridgeMetadata.attemptCount,
+ },
+ }
+ : {}),
}
}
@@ -107,6 +123,16 @@ export function buildPromptBridgeUsageEvent(input: {
iteration: null,
input_tokens: input.inputTokens,
output_tokens: input.outputTokens,
+ ...(input.promptBridgeMetadata
+ ? {
+ prompt_bridge_metadata: {
+ target_ref: input.promptBridgeMetadata.targetRef,
+ credential_slot: input.promptBridgeMetadata.credentialSlot,
+ fallback_used: input.promptBridgeMetadata.fallbackUsed,
+ attempt_count: input.promptBridgeMetadata.attemptCount,
+ },
+ }
+ : {}),
}
}
@@ -251,6 +277,12 @@ export function maybeCreatePluginWorkloadSdkServer(
inputTokens: usage.inputTokens,
outputTokens: usage.outputTokens,
callerRef: usage.callerRef,
+ promptBridgeMetadata: {
+ targetRef: usage.servedTarget.targetRef,
+ credentialSlot: usage.servedTarget.credentialSlot,
+ fallbackUsed: usage.fallbackUsed,
+ attemptCount: usage.attemptCount,
+ },
metadata: { ...usage.metadata, llmSecretName: usage.llmSecretName },
})
if (event) usageReporter.enqueue(event)
diff --git a/mcp-host/src/usage/usageReporter.ts b/mcp-host/src/usage/usageReporter.ts
index 4c6788cbb..5e8a2d257 100644
--- a/mcp-host/src/usage/usageReporter.ts
+++ b/mcp-host/src/usage/usageReporter.ts
@@ -39,6 +39,18 @@ export type LlmUsageEvent = {
*/
cache_read_tokens?: number
cache_write_tokens?: number
+ /**
+ * Sanitized attribution for a Plugin Workload SDK promptBridge call. The
+ * values are policy identities and bounded execution metadata only; raw
+ * credentials, bearer tokens, and provider responses never enter this
+ * event.
+ */
+ prompt_bridge_metadata?: {
+ target_ref: string
+ credential_slot: string
+ fallback_used: boolean
+ attempt_count: number
+ }
}
export type UsageReporterOptions = {
diff --git a/packages/llm-providers/index.cjs b/packages/llm-providers/index.cjs
index 5de98d467..c25299b2e 100644
--- a/packages/llm-providers/index.cjs
+++ b/packages/llm-providers/index.cjs
@@ -182,10 +182,30 @@ function isLlmProviderId(s) {
return typeof s === 'string' && Object.prototype.hasOwnProperty.call(PROVIDER_CREDENTIAL_SLOTS, s)
}
+/**
+ * Whether a policy credentialSlot is a valid operator-owned slot for a
+ * provider. Single, single-line API-key providers may use additive suffixed
+ * slots (for example `openai-api-key-fallback-a`); multi-slot providers and
+ * multiline credentials must use one of their canonical slots exactly.
+ */
+function isCredentialSlotOwnedByProvider(provider, credentialSlot) {
+ if (!isLlmProviderId(provider) || typeof credentialSlot !== 'string') return false
+ const slots = PROVIDER_CREDENTIAL_SLOTS[provider]
+ const canonical = slots.map(slot => slot.dataKey)
+ const singleSlotProvider = slots.length === 1 && slots[0].multiline !== true
+ if (singleSlotProvider) {
+ return canonical.some(
+ dataKey => credentialSlot === dataKey || credentialSlot.startsWith(`${dataKey}-`)
+ )
+ }
+ return canonical.includes(credentialSlot)
+}
+
module.exports = {
PROVIDER_IDS,
PROVIDER_CREDENTIAL_SLOTS,
PROVIDER_DISPLAY_LABELS,
PROVIDER_NON_SECRET_ENV,
+ isCredentialSlotOwnedByProvider,
isLlmProviderId,
}
diff --git a/packages/llm-providers/index.d.ts b/packages/llm-providers/index.d.ts
index 1d5e217c5..fbf9030cd 100644
--- a/packages/llm-providers/index.d.ts
+++ b/packages/llm-providers/index.d.ts
@@ -69,3 +69,13 @@ export declare const PROVIDER_NON_SECRET_ENV: Record<LlmProviderId, readonly Non
/** Own-property (prototype-safe) guard for the canonical provider ids. */
export declare function isLlmProviderId(s: unknown): s is LlmProviderId
+
+/**
+ * Returns whether a policy credential slot belongs to the provider. Additive
+ * suffixed slots are valid only for single, single-line API-key providers;
+ * multi-slot and multiline providers accept canonical slots only.
+ */
+export declare function isCredentialSlotOwnedByProvider(
+ provider: string,
+ credentialSlot: string,
+): boolean
diff --git a/scripts/e2e/e2e-plugin-workload-sdk.sh b/scripts/e2e/e2e-plugin-workload-sdk.sh
index d51273eb1..299d901ac 100755
--- a/scripts/e2e/e2e-plugin-workload-sdk.sh
+++ b/scripts/e2e/e2e-plugin-workload-sdk.sh
@@ -23,6 +23,7 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export RECIPE_NS="${RECIPE_NS:-sandbox-recipes}"
+# shellcheck source=e2e-lib.sh
source "${SCRIPT_DIR}/e2e-lib.sh"
require_safe_kube_context
@@ -32,6 +33,18 @@ EVENT_TYPE="e2e.test.notification"
E2E_DESKTOP_USER_EMAIL="${E2E_DESKTOP_USER_EMAIL:-${E2E_DEV_LOGIN_EMAIL:[email protected]}}"
E2E_WORKFLOW_MODEL_PROVIDER="${E2E_WORKFLOW_MODEL_PROVIDER:-${CLERUM_MODEL_PROVIDER:-zai}}"
E2E_WORKFLOW_MODEL_NAME="${E2E_WORKFLOW_MODEL_NAME:-${CLERUM_MODEL_NAME:-glm-5.1}}"
+# promptBridge grants are an ordered, credential-bound policy. The target
+# reference is not a credential value; operators can override both values for
+# a non-default, provider-owned Secret data key without exposing its contents.
+# The gate deliberately carries two distinct providers so selector authorization
+# and ordered fallback are exercised independently of whether either paid
+# provider is available in the local cluster.
+E2E_PROMPT_TARGET_REF="${E2E_PROMPT_TARGET_REF:-primary}"
+E2E_PROMPT_CREDENTIAL_SLOT="${E2E_PROMPT_CREDENTIAL_SLOT:-${E2E_WORKFLOW_CREDENTIAL_SLOT:-}}"
+E2E_PROMPT_FALLBACK_PROVIDER="${E2E_PROMPT_FALLBACK_PROVIDER:-openai}"
+E2E_PROMPT_FALLBACK_MODEL="${E2E_PROMPT_FALLBACK_MODEL:-gpt-5.4-mini}"
+E2E_PROMPT_FALLBACK_TARGET_REF="${E2E_PROMPT_FALLBACK_TARGET_REF:-fallback-${E2E_PROMPT_FALLBACK_PROVIDER}}"
+E2E_PROMPT_FALLBACK_CREDENTIAL_SLOT="${E2E_PROMPT_FALLBACK_CREDENTIAL_SLOT:-}"
E2E_ADMIN_TOKEN="${E2E_ADMIN_TOKEN:-}"
# Seeded by scripts/e2e/seed-e2e-data.sh (copies ADMIN_PASSWORD into test users).
E2E_DESKTOP_PASSWORD="${E2E_DESKTOP_PASSWORD:-${ADMIN_PASSWORD:-changeme123!}}"
@@ -62,6 +75,47 @@ E2E_WAIT_CALLER_MARKER="${E2E_WAIT_CALLER_MARKER:-180}"
E2E_WAIT_CALLER_DONE="${E2E_WAIT_CALLER_DONE:-180}"
E2E_WAIT_NOTIFICATION_ROW="${E2E_WAIT_NOTIFICATION_ROW:-60}"
+default_prompt_credential_slot() {
+ case "$1" in
+ openai) printf '%s\n' 'openai-api-key' ;;
+ claude) printf '%s\n' 'claude-api-key' ;;
+ zai) printf '%s\n' 'zai-api-key' ;;
+ bailian) printf '%s\n' 'bailian-api-key' ;;
+ vertex) printf '%s\n' 'vertex-service-account-json' ;;
+ bedrock) printf '%s\n' 'aws-access-key-id' ;;
+ openrouter) printf '%s\n' 'openrouter-api-key' ;;
+ gemini) printf '%s\n' 'gemini-api-key' ;;
+ deepseek) printf '%s\n' 'deepseek-api-key' ;;
+ groq) printf '%s\n' 'groq-api-key' ;;
+ together) printf '%s\n' 'together-api-key' ;;
+ fireworks) printf '%s\n' 'fireworks-api-key' ;;
+ mistral) printf '%s\n' 'mistral-api-key' ;;
+ xai) printf '%s\n' 'xai-api-key' ;;
+ cerebras) printf '%s\n' 'cerebras-api-key' ;;
+ deepinfra) printf '%s\n' 'deepinfra-api-key' ;;
+ perplexity) printf '%s\n' 'perplexity-api-key' ;;
+ moonshot) printf '%s\n' 'moonshot-api-key' ;;
+ nebius) printf '%s\n' 'nebius-api-key' ;;
+ novita) printf '%s\n' 'novita-api-key' ;;
+ azure) printf '%s\n' 'azure-openai-api-key' ;;
+ *) return 1 ;;
+ esac
+}
+
+if [ -z "$E2E_PROMPT_CREDENTIAL_SLOT" ]; then
+ E2E_PROMPT_CREDENTIAL_SLOT="$(default_prompt_credential_slot "$E2E_WORKFLOW_MODEL_PROVIDER")" \
+ || { printf 'Unsupported promptBridge provider %q; set E2E_PROMPT_CREDENTIAL_SLOT explicitly\n' "$E2E_WORKFLOW_MODEL_PROVIDER" >&2; exit 2; }
+fi
+if [ -z "$E2E_PROMPT_FALLBACK_CREDENTIAL_SLOT" ]; then
+ E2E_PROMPT_FALLBACK_CREDENTIAL_SLOT="$(default_prompt_credential_slot "$E2E_PROMPT_FALLBACK_PROVIDER")" \
+ || { printf 'Unsupported promptBridge fallback provider %q; set E2E_PROMPT_FALLBACK_CREDENTIAL_SLOT explicitly\n' "$E2E_PROMPT_FALLBACK_PROVIDER" >&2; exit 2; }
+fi
+if [ "$E2E_WORKFLOW_MODEL_PROVIDER" = "$E2E_PROMPT_FALLBACK_PROVIDER" ]; then
+ printf 'promptBridge E2E requires two distinct providers; got %q for both primary and fallback\n' \
+ "$E2E_WORKFLOW_MODEL_PROVIDER" >&2
+ exit 2
+fi
+
gate_assert_deadline() {
local phase=${1:-gate}
if [ $((SECONDS - E2E_GATE_STARTED_AT)) -ge "$E2E_GATE_MAX_SECONDS" ]; then
@@ -159,6 +213,7 @@ cleanup_sdk_recipe() {
return "$cleanup_status"
}
+# shellcheck disable=SC2329 # Registered below through the EXIT trap.
cleanup_on_exit() {
local status=$?
if [ "${e2e_total:-0}" -gt 0 ] && [ "${E2E_SUPPRESS_RESULTS:-0}" != "1" ]; then
@@ -396,13 +451,34 @@ obtain_desktop_session_token() {
create_grant() {
local family=$1 payload
if [ "$family" = "promptBridge" ]; then
- payload='{"recipeNamespace":"sandbox-recipes","recipeName":"'"$RECIPE_NAME"'","capabilityFamily":"promptBridge","provider":"'"$E2E_WORKFLOW_MODEL_PROVIDER"'","allowedModels":["'"$E2E_WORKFLOW_MODEL_NAME"'"],"allowedCallers":["'"$WORKLOAD_ID"'"],"quotaLimits":{"maxRequestsPerRun":3}}'
+ payload="$(prompt_grant_payload "$WORKLOAD_ID")"
else
payload='{"recipeNamespace":"sandbox-recipes","recipeName":"'"$RECIPE_NAME"'","capabilityFamily":"clientNotifications","allowedEventTypes":["'"$EVENT_TYPE"'"],"allowedUserRefs":["'"$USER_REF"'"],"allowedCallers":["'"$WORKLOAD_ID"'"],"quotaLimits":{"maxNotificationsPerRun":10}}'
fi
admin_curl POST "/api/v1/admin/plugin-workload-sdk/grants" "$payload"
}
+# The admin API validates the policy; jq is used here solely to serialize E2E
+# configuration safely, never to carry credential values. `allowedModels` is
+# retained for the compatibility/bootstrap contract, while `promptTargets` is
+# the authorization policy and `defaultTargetRef` must select its first target.
+prompt_grant_payload() {
+ local caller=$1
+ jq -cn \
+ --arg namespace "$RECIPE_NS" \
+ --arg recipe "$RECIPE_NAME" \
+ --arg provider "$E2E_WORKFLOW_MODEL_PROVIDER" \
+ --arg model "$E2E_WORKFLOW_MODEL_NAME" \
+ --arg targetRef "$E2E_PROMPT_TARGET_REF" \
+ --arg credentialSlot "$E2E_PROMPT_CREDENTIAL_SLOT" \
+ --arg fallbackProvider "$E2E_PROMPT_FALLBACK_PROVIDER" \
+ --arg fallbackModel "$E2E_PROMPT_FALLBACK_MODEL" \
+ --arg fallbackTargetRef "$E2E_PROMPT_FALLBACK_TARGET_REF" \
+ --arg fallbackCredentialSlot "$E2E_PROMPT_FALLBACK_CREDENTIAL_SLOT" \
+ --arg caller "$caller" \
+ '{recipeNamespace:$namespace,recipeName:$recipe,capabilityFamily:"promptBridge",provider:$provider,allowedModels:[$model,$fallbackModel],promptTargets:[{targetRef:$targetRef,provider:$provider,model:$model,credentialSlot:$credentialSlot},{targetRef:$fallbackTargetRef,provider:$fallbackProvider,model:$fallbackModel,credentialSlot:$fallbackCredentialSlot}],defaultTargetRef:$targetRef,allowedCallers:[$caller],quotaLimits:{maxRequestsPerRun:3}}'
+}
+
# ─── prerequisites ───────────────────────────────────────────────────────
header "Plugin Workload SDK E2E — prerequisites"
@@ -569,25 +645,58 @@ fi
header "Admin grant guardrails"
-wildcard_payload='{"recipeNamespace":"'"$RECIPE_NS"'","recipeName":"'"$RECIPE_NAME"'","capabilityFamily":"promptBridge","allowedModels":["*"],"allowedCallers":["'"$WORKLOAD_ID"'"]}'
+wildcard_payload="$(jq -cn \
+ --arg namespace "$RECIPE_NS" \
+ --arg recipe "$RECIPE_NAME" \
+ --arg provider "$E2E_WORKFLOW_MODEL_PROVIDER" \
+ --arg model "$E2E_WORKFLOW_MODEL_NAME" \
+ --arg targetRef "$E2E_PROMPT_TARGET_REF" \
+ --arg credentialSlot "$E2E_PROMPT_CREDENTIAL_SLOT" \
+ --arg caller "$WORKLOAD_ID" \
+ '{recipeNamespace:$namespace,recipeName:$recipe,capabilityFamily:"promptBridge",provider:$provider,allowedModels:["*"],promptTargets:[{targetRef:$targetRef,provider:$provider,model:$model,credentialSlot:$credentialSlot}],defaultTargetRef:$targetRef,allowedCallers:[$caller]}')"
admin_curl POST "/api/v1/admin/plugin-workload-sdk/grants" "$wildcard_payload" >/dev/null || true
wildcard_status="$ADMIN_CURL_HTTP_STATUS"
wildcard_body="$ADMIN_CURL_BODY"
if [ "$wildcard_status" = "400" ] && printf '%s' "$wildcard_body" | grep -q 'wildcard_not_allowed'; then
ok "admin API rejects wildcard allowlists with wildcard_not_allowed"
else
- fail "wildcard grant was not rejected as expected (status=${wildcard_status}, body=${wildcard_body})"
- exit 1
-fi
-
-empty_models_payload='{"recipeNamespace":"'"$RECIPE_NS"'","recipeName":"'"$RECIPE_NAME"'","capabilityFamily":"promptBridge","allowedModels":[],"allowedCallers":["'"$WORKLOAD_ID"'"]}'
-admin_curl POST "/api/v1/admin/plugin-workload-sdk/grants" "$empty_models_payload" >/dev/null || true
-empty_models_status="$ADMIN_CURL_HTTP_STATUS"
-empty_models_body="$ADMIN_CURL_BODY"
-if [ "$empty_models_status" = "400" ] && printf '%s' "$empty_models_body" | grep -q 'allowedModels must be non-empty'; then
- ok "admin API rejects promptBridge grants without an explicit model"
+ fail "wildcard grant was not rejected as expected (HTTP ${wildcard_status:-unknown}; response body redacted)"
+ exit 1
+fi
+
+missing_policy_payload="$(jq -cn \
+ --arg namespace "$RECIPE_NS" \
+ --arg recipe "$RECIPE_NAME" \
+ --arg provider "$E2E_WORKFLOW_MODEL_PROVIDER" \
+ --arg model "$E2E_WORKFLOW_MODEL_NAME" \
+ --arg caller "$WORKLOAD_ID" \
+ '{recipeNamespace:$namespace,recipeName:$recipe,capabilityFamily:"promptBridge",provider:$provider,allowedModels:[$model],allowedCallers:[$caller]}')"
+admin_curl POST "/api/v1/admin/plugin-workload-sdk/grants" "$missing_policy_payload" >/dev/null || true
+missing_policy_status="$ADMIN_CURL_HTTP_STATUS"
+missing_policy_body="$ADMIN_CURL_BODY"
+if [ "$missing_policy_status" = "400" ] && printf '%s' "$missing_policy_body" | grep -q 'promptTargets must be a non-empty array'; then
+ ok "admin API rejects promptBridge grants without ordered promptTargets"
else
- fail "empty-model promptBridge grant was not rejected as expected (status=${empty_models_status}, body=${empty_models_body})"
+ fail "promptBridge grant without promptTargets was not rejected as expected (HTTP ${missing_policy_status:-unknown}; response body redacted)"
+ exit 1
+fi
+
+missing_default_payload="$(jq -cn \
+ --arg namespace "$RECIPE_NS" \
+ --arg recipe "$RECIPE_NAME" \
+ --arg provider "$E2E_WORKFLOW_MODEL_PROVIDER" \
+ --arg model "$E2E_WORKFLOW_MODEL_NAME" \
+ --arg targetRef "$E2E_PROMPT_TARGET_REF" \
+ --arg credentialSlot "$E2E_PROMPT_CREDENTIAL_SLOT" \
+ --arg caller "$WORKLOAD_ID" \
+ '{recipeNamespace:$namespace,recipeName:$recipe,capabilityFamily:"promptBridge",provider:$provider,allowedModels:[$model],promptTargets:[{targetRef:$targetRef,provider:$provider,model:$model,credentialSlot:$credentialSlot}],allowedCallers:[$caller]}')"
+admin_curl POST "/api/v1/admin/plugin-workload-sdk/grants" "$missing_default_payload" >/dev/null || true
+missing_default_status="$ADMIN_CURL_HTTP_STATUS"
+missing_default_body="$ADMIN_CURL_BODY"
+if [ "$missing_default_status" = "400" ] && printf '%s' "$missing_default_body" | grep -q 'defaultTargetRef is required'; then
+ ok "admin API rejects promptBridge grants without defaultTargetRef"
+else
+ fail "promptBridge grant without defaultTargetRef was not rejected as expected (HTTP ${missing_default_status:-unknown}; response body redacted)"
exit 1
fi
@@ -602,8 +711,45 @@ if ! stop_sdk_caller_fixture; then
fi
ok "paused sdk-caller fixture before authorization probes (run=${E2E_PROBE_RUN_ID})"
-create_grant promptBridge >/dev/null && ok "created promptBridge grant" || { fail "promptBridge grant creation failed"; exit 1; }
-create_grant clientNotifications >/dev/null && ok "created clientNotifications grant" || { fail "clientNotifications grant creation failed"; exit 1; }
+if create_grant promptBridge >/dev/null; then
+ ok "created promptBridge grant"
+else
+ fail "promptBridge grant creation failed"
+ exit 1
+fi
+if create_grant clientNotifications >/dev/null; then
+ ok "created clientNotifications grant"
+else
+ fail "clientNotifications grant creation failed"
+ exit 1
+fi
+
+# Read back only the persisted policy metadata. This proves the operator's
+# two-provider order/default contract without ever logging a Secret value,
+# bearer token, or credential ticket.
+prompt_grant_readback="$(admin_curl GET "/api/v1/admin/plugin-workload-sdk/grants?recipeNamespace=${RECIPE_NS}&recipeName=${RECIPE_NAME}" || true)"
+if [ "$ADMIN_CURL_HTTP_STATUS" = "200" ] &&
+ printf '%s' "$prompt_grant_readback" | jq -e \
+ --arg provider "$E2E_WORKFLOW_MODEL_PROVIDER" \
+ --arg model "$E2E_WORKFLOW_MODEL_NAME" \
+ --arg targetRef "$E2E_PROMPT_TARGET_REF" \
+ --arg credentialSlot "$E2E_PROMPT_CREDENTIAL_SLOT" \
+ --arg fallbackProvider "$E2E_PROMPT_FALLBACK_PROVIDER" \
+ --arg fallbackModel "$E2E_PROMPT_FALLBACK_MODEL" \
+ --arg fallbackTargetRef "$E2E_PROMPT_FALLBACK_TARGET_REF" \
+ --arg fallbackCredentialSlot "$E2E_PROMPT_FALLBACK_CREDENTIAL_SLOT" \
+ '(.items // []) | map(select(.capabilityFamily == "promptBridge")) | .[0] as $grant |
+ ($grant.provider == $provider) and
+ ($grant.defaultTargetRef == $targetRef) and
+ (($grant.promptTargets // []) | length == 2) and
+ ($grant.promptTargets[0] == {targetRef:$targetRef,provider:$provider,model:$model,credentialSlot:$credentialSlot}) and
+ ($grant.promptTargets[1] == {targetRef:$fallbackTargetRef,provider:$fallbackProvider,model:$fallbackModel,credentialSlot:$fallbackCredentialSlot}) and
+ ((($grant | tojson) | test("secret|token"; "i")) | not)' >/dev/null; then
+ ok "persisted promptBridge policy contains ordered primary + fallback providers without credential material"
+else
+ fail "persisted promptBridge policy did not match the two-provider order/default contract (HTTP ${ADMIN_CURL_HTTP_STATUS:-unknown}; response body redacted)"
+ exit 1
+fi
# Recipients read endpoint (grant-driven picker): the clientNotifications grant
# just created carries allowedUserRefs=[USER_REF]. GET /v1/client-notifications/
@@ -654,10 +800,33 @@ else
exit 1
fi
-narrow_payload='{"recipeNamespace":"'"$RECIPE_NS"'","recipeName":"'"$RECIPE_NAME"'","capabilityFamily":"promptBridge","provider":"'"$E2E_WORKFLOW_MODEL_PROVIDER"'","allowedModels":["'"$E2E_WORKFLOW_MODEL_NAME"'"],"allowedCallers":["e2e-unlisted-caller"],"quotaLimits":{"maxRequestsPerRun":3}}'
+unauthorized_target="$(kctl exec "$caller_pod" -n "$SANDBOX_NS" -- env "E2E_PROBE_RUN_ID=${E2E_PROBE_RUN_ID}" node -e '
+fetch(process.env.PLUGIN_WORKLOAD_SDK_ENDPOINT + "/v1/prompt-bridge", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: "Bearer " + process.env.PLUGIN_WORKLOAD_SDK_TOKEN,
+ },
+ body: JSON.stringify({
+ purpose: "summarization",
+ targetRef: "unauthorized-third-provider",
+ idempotencyKey: "e2e-deny-target-" + process.env.E2E_PROBE_RUN_ID,
+ messages: [{ role: "user", content: "x" }],
+ }),
+}).then(async r => { const b = await r.json().catch(() => ({})); console.log(r.status + ":" + (b.error || "")); process.exit(0) })
+ .catch(() => { console.log("ERR"); process.exit(0) })
+' 2>/dev/null || true)"
+if printf "%s" "$unauthorized_target" | grep -q 'target_not_allowed'; then
+ ok "selector outside the two-provider policy is denied with target_not_allowed"
+else
+ fail "unauthorized provider target was not denied as expected (got '${unauthorized_target}')"
+ exit 1
+fi
+
+narrow_payload="$(prompt_grant_payload 'e2e-unlisted-caller')"
admin_curl POST "/api/v1/admin/plugin-workload-sdk/grants" "$narrow_payload" >/dev/null || true
if [ "$ADMIN_CURL_HTTP_STATUS" != "200" ]; then
- fail "failed to narrow promptBridge grant for caller_not_allowed probe (status=${ADMIN_CURL_HTTP_STATUS}, body=${ADMIN_CURL_BODY})"
+ fail "failed to narrow promptBridge grant for caller_not_allowed probe (HTTP ${ADMIN_CURL_HTTP_STATUS:-unknown}; response body redacted)"
exit 1
fi
@@ -708,14 +877,14 @@ logs="$(wait_for_caller_logs_matching E2E_SDK_CLIENT_NOTIFICATION_OK "$E2E_WAIT_
if printf "%s" "$logs" | grep -q E2E_SDK_PROMPT_BRIDGE_OK; then
ok "sdk-caller promptBridge call was authorized (invocationId returned)"
else
- fail "sdk-caller promptBridge call did not succeed within ${E2E_WAIT_CALLER_MARKER}s: $(printf '%s' "$logs" | grep E2E_SDK_PROMPT_BRIDGE || true)"
+ fail "sdk-caller promptBridge call did not succeed within ${E2E_WAIT_CALLER_MARKER}s (fixture marker missing; caller logs redacted)"
exit 1
fi
if printf "%s" "$logs" | grep -q E2E_SDK_CLIENT_NOTIFICATION_OK; then
ok "sdk-caller clientNotifications call was accepted (notificationId returned)"
else
- fail "sdk-caller clientNotifications call did not succeed within ${E2E_WAIT_CALLER_MARKER}s: $(printf '%s' "$logs" | grep E2E_SDK_CLIENT_NOTIFICATION || true)"
+ fail "sdk-caller clientNotifications call did not succeed within ${E2E_WAIT_CALLER_MARKER}s (fixture marker missing; caller logs redacted)"
exit 1
fi
@@ -777,7 +946,7 @@ header "Notification preferences PUT contract"
desktop_session_token="$(obtain_desktop_session_token "$E2E_DESKTOP_USER_EMAIL" "$E2E_DESKTOP_PASSWORD" || true)"
if [ -z "$desktop_session_token" ]; then
- fail "could not obtain desktop session token for ${E2E_DESKTOP_USER_EMAIL} (HTTP ${ADMIN_CURL_HTTP_STATUS} via ${E2E_EXTERNAL_REST_API_URL}: ${ADMIN_CURL_BODY})"
+ fail "could not obtain desktop session token for ${E2E_DESKTOP_USER_EMAIL} (HTTP ${ADMIN_CURL_HTTP_STATUS:-unknown} via ${E2E_EXTERNAL_REST_API_URL}; response body redacted)"
exit 1
fi
ok "obtained desktop session token for notification-preferences checks"
@@ -787,7 +956,7 @@ if [ "$ADMIN_CURL_HTTP_STATUS" = "400" ] &&
printf '%s' "$ADMIN_CURL_BODY" | grep -q 'invalid_channel_fallback_enabled'; then
ok "partial PUT without channelFallbackEnabled is rejected with invalid_channel_fallback_enabled"
else
- fail "partial notification-preferences PUT was not rejected as expected (status=${ADMIN_CURL_HTTP_STATUS}, body=${ADMIN_CURL_BODY})"
+ fail "partial notification-preferences PUT was not rejected as expected (HTTP ${ADMIN_CURL_HTTP_STATUS:-unknown}; response body redacted)"
exit 1
fi
@@ -796,13 +965,13 @@ if [ "$ADMIN_CURL_HTTP_STATUS" = "400" ] &&
printf '%s' "$ADMIN_CURL_BODY" | grep -q 'invalid_preferred_medium'; then
ok "partial PUT without preferredMedium is rejected with invalid_preferred_medium"
else
- fail "partial notification-preferences PUT without preferredMedium was not rejected as expected (status=${ADMIN_CURL_HTTP_STATUS}, body=${ADMIN_CURL_BODY})"
+ fail "partial notification-preferences PUT without preferredMedium was not rejected as expected (HTTP ${ADMIN_CURL_HTTP_STATUS:-unknown}; response body redacted)"
exit 1
fi
session_curl PUT "/external/me/notification-preferences" "$desktop_session_token" '{"preferredMedium":null,"channelFallbackEnabled":false}' >/dev/null || true
if [ "$ADMIN_CURL_HTTP_STATUS" != "200" ]; then
- fail "full notification-preferences PUT expected HTTP 200, got ${ADMIN_CURL_HTTP_STATUS}: ${ADMIN_CURL_BODY}"
+ fail "full notification-preferences PUT expected HTTP 200, got ${ADMIN_CURL_HTTP_STATUS:-unknown} (response body redacted)"
exit 1
fi
@@ -831,7 +1000,7 @@ fi
if printf "%s" "$logs" | grep -q E2E_SDK_IDEMPOTENCY_OK; then
ok "idempotency replay returned same invocationId (no extra quota consumed)"
else
- fail "idempotency replay did not return same invocationId: $(printf '%s' "$logs" | grep E2E_SDK_IDEMPOTENCY || true)"
+ fail "idempotency replay did not return the first invocationId (fixture marker missing; caller logs redacted)"
exit 1
fi
@@ -839,7 +1008,7 @@ fi
if printf "%s" "$logs" | grep -q E2E_SDK_QUOTA_EXCEEDED_OK; then
ok "quota enforcement correctly rejected call after 3/3 requests consumed"
else
- fail "quota enforcement did not reject excess call: $(printf '%s' "$logs" | grep E2E_SDK_QUOTA_EXCEEDED || true)"
+ fail "quota enforcement did not reject the excess call (fixture marker missing; caller logs redacted)"
exit 1
fi
diff --git a/scripts/e2e/seed-e2e-data.sh b/scripts/e2e/seed-e2e-data.sh
index 3f4c8393a..eb22d650f 100755
--- a/scripts/e2e/seed-e2e-data.sh
+++ b/scripts/e2e/seed-e2e-data.sh
@@ -6,7 +6,11 @@
# desktop-app/test/e2e/* and scripts/e2e/*.sh suites require. User/team and
# access bindings use the admin API contract. Minikube additionally gets local
# Desktop password-login credentials, plus optional Plugin Workload SDK demo
-# grants for the grant-driven sandbox-ui notification recipe.
+# grants for the grant-driven sandbox-ui notification recipe. When the recipe
+# is already installed, the same seed also gives the E2E users direct
+# WorkflowRecipe trigger access so the Desktop Apps picker can list its
+# `spec.ui` app. SDK capability grants and Sandbox UI trigger grants are
+# separate authorization contracts.
#
# Idempotent: safe to run on every deploy. Re-runs preserve existing state
# (admin user/team lookup is create-if-missing, PUT /admin/users/:id/
@@ -39,6 +43,9 @@
# E2E_PLUGIN_SDK_DEMO_EVENT_TYPE notification event type (default: fullstack.prompt.notify)
# E2E_PLUGIN_SDK_DEMO_CALLER_REF allowed caller ref (default: backend)
# E2E_PLUGIN_SDK_DEMO_MODEL_NAME promptBridge model grant (default: E2E/CLERUM model)
+# E2E_PLUGIN_SDK_DEMO_PROVIDER promptBridge provider (default: E2E/CLERUM provider)
+# E2E_PLUGIN_SDK_DEMO_TARGET_REF ordered policy target id (default: primary)
+# E2E_PLUGIN_SDK_DEMO_CREDENTIAL_SLOT Secret data key owned by provider (derived when omitted)
# ADMIN_USERNAME admin user (default: admin)
# ADMIN_EMAIL bootstrap email (default: [email protected])
# ADMIN_PASSWORD admin pass (REQUIRED — bootstrap or rotated)
@@ -93,6 +100,9 @@ PLUGIN_SDK_DEMO_RECIPE_NAME="${E2E_PLUGIN_SDK_DEMO_RECIPE_NAME:-${E2E_SANDBOX_UI
PLUGIN_SDK_DEMO_EVENT_TYPE="${E2E_PLUGIN_SDK_DEMO_EVENT_TYPE:-fullstack.prompt.notify}"
PLUGIN_SDK_DEMO_CALLER_REF="${E2E_PLUGIN_SDK_DEMO_CALLER_REF:-backend}"
PLUGIN_SDK_DEMO_MODEL_NAME="${E2E_PLUGIN_SDK_DEMO_MODEL_NAME:-${E2E_WORKFLOW_MODEL_NAME:-${CLERUM_MODEL_NAME:-glm-4.7}}}"
+PLUGIN_SDK_DEMO_PROVIDER="${E2E_PLUGIN_SDK_DEMO_PROVIDER:-${CLERUM_MODEL_PROVIDER:-zai}}"
+PLUGIN_SDK_DEMO_TARGET_REF="${E2E_PLUGIN_SDK_DEMO_TARGET_REF:-primary}"
+PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="${E2E_PLUGIN_SDK_DEMO_CREDENTIAL_SLOT:-}"
PLUGIN_SDK_DEMO_PROMPT_MAX="${E2E_PLUGIN_SDK_DEMO_PROMPT_MAX_REQUESTS:-50}"
PLUGIN_SDK_DEMO_NOTIFICATION_MAX="${E2E_PLUGIN_SDK_DEMO_MAX_NOTIFICATIONS:-25}"
@@ -108,6 +118,33 @@ ok() { echo -e " ${GREEN}OK${NC} — $*"; }
warn() { echo -e " ${YELLOW}WARN${NC} — $*"; }
die() { echo -e " ${RED}ERROR${NC} — $*" >&2; exit 1; }
+if [ -z "$PLUGIN_SDK_DEMO_CREDENTIAL_SLOT" ]; then
+ case "$PLUGIN_SDK_DEMO_PROVIDER" in
+ openai) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="openai-api-key" ;;
+ claude) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="claude-api-key" ;;
+ zai) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="zai-api-key" ;;
+ bailian) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="bailian-api-key" ;;
+ vertex) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="vertex-service-account-json" ;;
+ bedrock) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="aws-access-key-id" ;;
+ openrouter) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="openrouter-api-key" ;;
+ gemini) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="gemini-api-key" ;;
+ deepseek) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="deepseek-api-key" ;;
+ groq) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="groq-api-key" ;;
+ together) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="together-api-key" ;;
+ fireworks) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="fireworks-api-key" ;;
+ mistral) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="mistral-api-key" ;;
+ xai) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="xai-api-key" ;;
+ cerebras) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="cerebras-api-key" ;;
+ deepinfra) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="deepinfra-api-key" ;;
+ perplexity) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="perplexity-api-key" ;;
+ moonshot) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="moonshot-api-key" ;;
+ nebius) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="nebius-api-key" ;;
+ novita) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="novita-api-key" ;;
+ azure) PLUGIN_SDK_DEMO_CREDENTIAL_SLOT="azure-openai-api-key" ;;
+ *) die "Cannot derive a credential slot for provider '$PLUGIN_SDK_DEMO_PROVIDER'; set E2E_PLUGIN_SDK_DEMO_CREDENTIAL_SLOT explicitly" ;;
+ esac
+fi
+
is_branch_scoped_minikube_context() {
case "$CONTEXT" in
clerum-codex-*|clerum-cursor-*|clerum-detached-*)
@@ -239,9 +276,12 @@ seed_plugin_sdk_demo_grants_if_enabled() {
--arg ns "$PLUGIN_SDK_DEMO_RECIPE_NS" \
--arg n "$PLUGIN_SDK_DEMO_RECIPE_NAME" \
--arg caller "$PLUGIN_SDK_DEMO_CALLER_REF" \
+ --arg provider "$PLUGIN_SDK_DEMO_PROVIDER" \
+ --arg target "$PLUGIN_SDK_DEMO_TARGET_REF" \
+ --arg credentialSlot "$PLUGIN_SDK_DEMO_CREDENTIAL_SLOT" \
--arg model "$PLUGIN_SDK_DEMO_MODEL_NAME" \
--argjson max "$PLUGIN_SDK_DEMO_PROMPT_MAX" \
- '{recipeNamespace:$ns,recipeName:$n,capabilityFamily:"promptBridge",allowedModels:[$model],allowedCallers:[$caller],quotaLimits:{maxRequestsPerRun:$max}}')" \
+ '{recipeNamespace:$ns,recipeName:$n,capabilityFamily:"promptBridge",provider:$provider,allowedModels:[$model],promptTargets:[{targetRef:$target,provider:$provider,model:$model,credentialSlot:$credentialSlot}],defaultTargetRef:$target,allowedCallers:[$caller],quotaLimits:{maxRequestsPerRun:$max}}')" \
"POST /admin/plugin-workload-sdk/grants promptBridge"
admin_post "$CAPI_BASE/admin/plugin-workload-sdk/grants" \
@@ -256,6 +296,18 @@ seed_plugin_sdk_demo_grants_if_enabled() {
'{recipeNamespace:$ns,recipeName:$n,capabilityFamily:"clientNotifications",allowedEventTypes:[$ev],allowedUserRefs:[$u1,$u2],allowedCallers:[$caller],quotaLimits:{maxNotificationsPerRun:$max}}')" \
"POST /admin/plugin-workload-sdk/grants clientNotifications"
+ # Sandbox UI discovery is governed by WorkflowRecipe trigger grants, not by
+ # Plugin Workload SDK capability grants. Seed this only when the target
+ # recipe is already installed; full-stack setup invokes this script before
+ # optional application recipes are applied.
+ if $KC -n "$PLUGIN_SDK_DEMO_RECIPE_NS" get workflowrecipe "$PLUGIN_SDK_DEMO_RECIPE_NAME" >/dev/null 2>&1; then
+ admin_put "$CAPI_BASE/admin/workflows/${PLUGIN_SDK_DEMO_RECIPE_NS}/${PLUGIN_SDK_DEMO_RECIPE_NAME}/grants" \
+ "$(jq -cn --arg u1 "$USER_ID" --arg u2 "$USER_ID_2" '{userIds:[$u1,$u2]}')" \
+ "PUT /admin/workflows/${PLUGIN_SDK_DEMO_RECIPE_NS}/${PLUGIN_SDK_DEMO_RECIPE_NAME}/grants"
+ else
+ log "Skipping Sandbox UI trigger grant: ${PLUGIN_SDK_DEMO_RECIPE_NS}/${PLUGIN_SDK_DEMO_RECIPE_NAME} is not installed yet"
+ fi
+
ok "Plugin Workload SDK demo grants seeded for $DEV_EMAIL and $DEV_EMAIL_2"
}
@@ -442,6 +494,19 @@ admin_post() {
fi
}
+admin_put() {
+ local url="$1" body="$2" label="$3"
+ local resp code
+ resp="$(curl -sS -w '\n%{http_code}' -X PUT "${url}" "${AUTH_CURL[@]}" -d "${body}" || true)"
+ code="$(echo "${resp}" | tail -n1)"
+ if [[ "${code}" =~ ^2 ]]; then
+ ADMIN_PUT_BODY="$(echo "${resp}" | sed '$d')"
+ ok "${label} → ${code}"
+ else
+ die "${label} → ${code} body=$(echo "${resp}" | sed '$d')"
+ fi
+}
+
put_json() {
local url="$1" body="$2" label="$3"
local resp code
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index a4d0a0b62..1748c4b47 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.257",
+ "version": "0.1.258",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.257",
+ "version": "0.1.258",
"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 e225b0095..1a2ff461c 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.257",
+ "version": "0.1.258",
"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 d27b3fcc5..d7294f9ae 100644
--- a/workflow-recipes/src/mcp/server.pluginSdkBroker.test.ts
+++ b/workflow-recipes/src/mcp/server.pluginSdkBroker.test.ts
@@ -43,6 +43,27 @@ describe('WRC Plugin SDK credential ticket TOCTOU revalidation', () => {
})
})
+ it('marks the post-read revalidation as the one-shot redemption boundary', async () => {
+ const fetchImpl = vi.fn().mockResolvedValue(response(200, { active: true }))
+ await expect(
+ revalidatePluginSdkCredentialTicket({
+ runtimeToken: 'runtime-jwt',
+ credentialTicket: 'signed-ticket',
+ invocationId: 'inv-1',
+ targetRef: 'fallback-openai',
+ redeem: true,
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ })
+ ).resolves.toBe(true)
+ const [, init] = fetchImpl.mock.calls[0] as [string, RequestInit]
+ expect(JSON.parse(String(init.body))).toEqual({
+ credentialTicket: 'signed-ticket',
+ invocationId: 'inv-1',
+ targetRef: 'fallback-openai',
+ redeem: true,
+ })
+ })
+
it.each([
[200, { active: false }],
[403, { error: 'provider_policy_denied' }],
diff --git a/workflow-recipes/src/mcp/server.ts b/workflow-recipes/src/mcp/server.ts
index 707f0834a..5db61eeb3 100644
--- a/workflow-recipes/src/mcp/server.ts
+++ b/workflow-recipes/src/mcp/server.ts
@@ -47,6 +47,8 @@ export async function revalidatePluginSdkCredentialTicket(input: {
credentialTicket: string
invocationId: string
targetRef: string
+ /** Consume the control-plane jti after the Secret read, not during preflight. */
+ redeem?: boolean
fetchImpl?: typeof fetch
controlApiBaseUrl?: string
}): Promise<boolean> {
@@ -64,6 +66,7 @@ export async function revalidatePluginSdkCredentialTicket(input: {
credentialTicket: input.credentialTicket,
invocationId: input.invocationId,
targetRef: input.targetRef,
+ ...(input.redeem ? { redeem: true } : {}),
}),
}
)
@@ -478,6 +481,7 @@ export class ClerumMcpServer {
credentialTicket: body.credentialTicket,
invocationId: body.invocationId,
targetRef: target.targetRef,
+ redeem: true,
})
if (!ticketStillActiveAfterResolve) {
res.writeHead(403, { 'Content-Type': 'application/json' })
diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts
index 55d2df0c4..54ff86acc 100644
--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts
+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.test.ts
@@ -281,6 +281,32 @@ describe('buildPluginWorkloadSdkStatus', () => {
})
})
+ it('projects provider_unavailable separately from a validated capability declaration', () => {
+ const projection = buildPluginWorkloadSdkStatus({
+ spec: baseSpec({ promptBridge: {} }),
+ existingConditions: undefined,
+ phase: 'degraded',
+ featureFlagEnabled: true,
+ providerUnavailable: true,
+ now: NOW,
+ })
+ expect(projection.conditions).toEqual([
+ {
+ type: PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,
+ status: 'False',
+ reason: 'ProviderUnavailable',
+ message: 'Capability validated, but the configured provider is unavailable',
+ lastTransitionTime: NOW,
+ },
+ ])
+ expect(projection.capability).toEqual({
+ state: 'degraded',
+ promptBridge: true,
+ clientNotifications: false,
+ message: 'Capability validated, but the configured provider is unavailable',
+ })
+ })
+
it('carries forward existing owned conditions when reconcile failed', () => {
const existing = {
type: PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,
diff --git a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts
index 886cf0a78..2c724d781 100644
--- a/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts
+++ b/workflow-recipes/src/reconciler/pluginWorkloadSdkValidator.ts
@@ -20,6 +20,8 @@ export const DEFAULT_IDEMPOTENCY_KEY_PATTERN = '^[a-zA-Z0-9_-]{1,128}$'
/** Condition type owned by the Plugin Workload SDK reconcile pass. */
export const PLUGIN_WORKLOAD_SDK_CONDITION_TYPE = 'PluginWorkloadSdkCapability'
+export const PLUGIN_WORKLOAD_SDK_PROVIDER_UNAVAILABLE_CONDITION_TYPE =
+ 'PluginWorkloadSdkProviderUnavailable'
/**
* WorkflowRecipe remains the CRD that carries Plugin Workload SDK, but an SDK
@@ -169,9 +171,10 @@ export function buildPluginWorkloadSdkStatus(args: {
existingConditions: StatusCondition[] | undefined
phase: RecipePhase
featureFlagEnabled: boolean
+ providerUnavailable?: boolean
now: string
}): PluginWorkloadSdkStatusProjection {
- const { spec, existingConditions, phase, featureFlagEnabled, now } = args
+ const { spec, existingConditions, phase, featureFlagEnabled, providerUnavailable, now } = args
const sdk = spec.pluginWorkloadSdk
if (!sdk) {
@@ -209,6 +212,27 @@ export function buildPluginWorkloadSdkStatus(args: {
return { conditions: carried, capability: undefined }
}
+ if (providerUnavailable) {
+ const message = 'Capability validated, but the configured provider is unavailable'
+ return {
+ conditions: [
+ {
+ type: PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,
+ status: 'False',
+ reason: 'ProviderUnavailable',
+ message,
+ lastTransitionTime: now,
+ },
+ ],
+ capability: {
+ state: 'degraded',
+ promptBridge,
+ clientNotifications,
+ message,
+ },
+ }
+ }
+
const families = [
promptBridge ? 'promptBridge' : undefined,
clientNotifications ? 'clientNotifications' : undefined,
diff --git a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
index ae233097b..c524a7da7 100644
--- a/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
+++ b/workflow-recipes/src/reconciler/workflowRecipeReconciler.ts
@@ -80,6 +80,7 @@ import {
import { issueOAuthBrokerToken } from './oauthBrokerTokenIssuerClient'
import {
PLUGIN_WORKLOAD_SDK_CONDITION_TYPE,
+ PLUGIN_WORKLOAD_SDK_PROVIDER_UNAVAILABLE_CONDITION_TYPE,
buildPluginWorkloadSdkStatus,
validatePluginWorkloadSdkSpec,
} from './pluginWorkloadSdkValidator'
@@ -486,6 +487,8 @@ export interface ReconcileResult {
* UI/API-consumable reasons that should not be inferred from free-form messages.
*/
workloadConditions?: StatusCondition[]
+ /** SDK-only eager-host provider health, kept separate from workflow phase. */
+ pluginWorkloadSdkProviderUnavailable?: boolean
workflowPhase?: import('../workflow/types').WorkflowPhase
clearWorkflowExecution?: boolean
/** When true, the caller should NOT patch the CRD status — the phase hasn't changed. */
@@ -1201,6 +1204,7 @@ export class WorkflowRecipeReconciler {
const name = recipe.metadata.name
const ns = recipe.metadata.namespace
const currentPhase = recipe.status?.phase ?? 'candidate'
+ let sdkOnlyProviderUnavailable = false
// Defense-in-depth: the VAP + admin-API already enforce this invariant,
// but a manually-applied CRD in another namespace must not be reconciled.
@@ -2302,6 +2306,7 @@ export class WorkflowRecipeReconciler {
const sdkOnlyRuntime = isSdkOnly
? await this.reconcilePluginWorkloadSdkOnly(recipe)
: undefined
+ sdkOnlyProviderUnavailable = sdkOnlyRuntime?.phase === 'provider_unavailable'
if (sdkOnlyRuntime?.phase === 'failed') {
return {
phase: 'failed',
@@ -2358,6 +2363,7 @@ export class WorkflowRecipeReconciler {
internalDependencyConditions,
secretOwnershipConditions: secretOwnership.conditions,
workloadConditions,
+ pluginWorkloadSdkProviderUnavailable: sdkOnlyProviderUnavailable,
// Issue #637 — requeue if a denied workload's teardown failed (deniedTeardownFailed),
// so the revocation is retried rather than left to the next event.
requeueAfterMs:
@@ -5731,15 +5737,22 @@ export class WorkflowRecipeReconciler {
recipe.status?.conditions,
result.workloadConditions
)
- // Plugin Workload SDK conditions are derived here (not threaded through
- // ReconcileResult) so every status patch carries a consistent projection
- // of spec.pluginWorkloadSdk + feature flag, regardless of which reconcile
- // return path produced the result.
+ // Plugin Workload SDK conditions are derived here so every status patch
+ // carries a consistent projection of spec.pluginWorkloadSdk + feature flag,
+ // while the SDK-only provider health bit is propagated explicitly through
+ // ReconcileResult rather than inferred from a free-form phase/message.
const pluginSdkProjection = buildPluginWorkloadSdkStatus({
spec: recipe.spec,
existingConditions: recipe.status?.conditions,
phase: result.phase,
featureFlagEnabled: this.config.pluginWorkloadSdkEnabled,
+ providerUnavailable:
+ result.pluginWorkloadSdkProviderUnavailable === true ||
+ (result.workflowConditions ?? []).some(
+ condition =>
+ condition.type === PLUGIN_WORKLOAD_SDK_PROVIDER_UNAVAILABLE_CONDITION_TYPE &&
+ condition.status === 'True'
+ ),
now,
})
const pluginSdkMergedConditions = mergePluginWorkloadSdkConditions(
diff --git a/workflow-recipes/src/types.ts b/workflow-recipes/src/types.ts
index 83e27e524..873265e9c 100644
--- a/workflow-recipes/src/types.ts
+++ b/workflow-recipes/src/types.ts
@@ -536,7 +536,7 @@ export interface PluginWorkloadSdkSnippetConfig {
* actually has active (vs merely declared in spec).
*/
export interface PluginWorkloadSdkCapabilityStatus {
- state: 'validated' | 'disabled'
+ state: 'validated' | 'disabled' | 'degraded'
promptBridge: boolean
clientNotifications: boolean
message?: string
diff --git a/workflow-recipes/src/workflow/modelConfigHandler.ts b/workflow-recipes/src/workflow/modelConfigHandler.ts
index d91cfe526..89ec43607 100644
--- a/workflow-recipes/src/workflow/modelConfigHandler.ts
+++ b/workflow-recipes/src/workflow/modelConfigHandler.ts
@@ -9,7 +9,11 @@
* SDK bootstrap is identity-only; its prompt credentials stay behind the
* per-attempt broker.
*/
-import { PROVIDER_CREDENTIAL_SLOTS, isLlmProviderId } from '@clerum/llm-providers'
+import {
+ PROVIDER_CREDENTIAL_SLOTS,
+ isCredentialSlotOwnedByProvider,
+ isLlmProviderId,
+} from '@clerum/llm-providers'
import { createLogger } from '../observability/logger'
// ─── Types ──────────────────────────────────────────────────────────────
@@ -232,16 +236,8 @@ export class ModelConfigHandler {
}
const slots = PROVIDER_CREDENTIAL_SLOTS[target.provider]
- const canonicalDataKeys = slots.map(slot => slot.dataKey)
- const singleSlotProvider = slots.length === 1
- const slotBelongsToProvider = canonicalDataKeys.some(
- dataKey =>
- target.credentialSlot === dataKey || target.credentialSlot.startsWith(`${dataKey}-`)
- )
- if (
- !slotBelongsToProvider ||
- (!singleSlotProvider && !canonicalDataKeys.includes(target.credentialSlot))
- ) {
+ const singleSlotProvider = slots.length === 1 && slots[0].multiline !== true
+ if (!isCredentialSlotOwnedByProvider(target.provider, target.credentialSlot)) {
return { status: 400, body: { error: 'Invalid credential target' } }
}