Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): bind mcp-host control token to Host uid (S-05 F2)
Diego Zacarias31e6b264821f
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.ymlindex aa4b965e1..0c1a426fe 100644--- a/.github/workflows/ci-public.yml+++ b/.github/workflows/ci-public.yml@@ -555,6 +555,7 @@ jobs:services.adminSubscriptionRateLimitMigration.realPostgres.integration.test.ts \pluginWorkloadSdkSteplessQuota.realPostgres.integration.test.ts \entityChangeFeed.realPostgres.integration.test.ts \+ routes.mcp-host.renewal.realPostgres.integration.test.ts \db.realPostgresMigration.integration.test.ts- name: Install gfs-controller dependenciesdiff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 78d615f2c..d6ceb0eae 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.815",+ "version": "0.1.816","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.815",+ "version": "0.1.816","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex bf305cb3a..05de184ba 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.815",+ "version": "0.1.816","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/auth/mcp-host/issue.routes.ts b/control-api/src/routes/auth/mcp-host/issue.routes.tsindex 59f7dcb42..43f6a2de4 100644--- a/control-api/src/routes/auth/mcp-host/issue.routes.ts+++ b/control-api/src/routes/auth/mcp-host/issue.routes.ts@@ -163,7 +163,18 @@ export function createAuthMcpHostIssueRoutes(): Router {})const control = issueMcpHostControlJwt(recipeNamespace, recipeName, hostRefs, {scopes: controlScopes.scopes,+ hccCredential,})+ if (control.scopeStripped) {+ req.log?.warn(+ {+ event: 'oauth_user_token_scope_stripped',+ route: 'issue',+ provisioner: provisioner.iss,+ },+ 'oauth:user-token dropped from a non-HCC control token'+ )+ }req.log?.info({event: 'mcp_host_credentials_issued',diff --git a/control-api/src/routes/mcp-host/index.ts b/control-api/src/routes/mcp-host/index.tsindex 0d46b3aba..b7fd0d4e9 100644--- a/control-api/src/routes/mcp-host/index.ts+++ b/control-api/src/routes/mcp-host/index.ts@@ -13,7 +13,7 @@ export function createMcpHostRoutes(directRunAttributionBindingService: DirectRunAttributionBindingService): Router {const router = Router()- router.use(createMcpHostRenewalRoutes())+ router.use(createMcpHostRenewalRoutes(gateway))router.use(createUserApprovalRequestsRoutes(gateway, directRunAttributionBindingService))router.use(createMcpHostWorkflowRoutes(gateway))router.use(createMcpHostPluginWorkloadSdkRoutes())diff --git a/control-api/src/routes/mcp-host/renewal/hostBinding.ts b/control-api/src/routes/mcp-host/renewal/hostBinding.tsnew file mode 100644index 000000000..53c54c6e0--- /dev/null+++ b/control-api/src/routes/mcp-host/renewal/hostBinding.ts@@ -0,0 +1,61 @@+import { config } from '../../../config.js'+import type { K8sGateway } from '../../../k8s.js'+import { isK8sResourceNotFound } from '../../../services/access/mcpInvocable.js'+import {+ HCC_STANDALONE_RECIPE_NAME,+ MCP_HOST_CREDENTIAL_CAPABILITY,+ type McpHostRefreshClaims,+} from '../../../utils/auth/mcpHostJwtToken.js'++export type RenewalHostGateway = Pick<K8sGateway, 'getResource'>++export type RenewalHostBinding =+ | { kind: 'ok'; hccCredential?: { hostUid: string } }+ | {+ kind: 'denied'+ reason: 'hcc_lineage_without_audience' | 'host_not_found' | 'host_uid_mismatch'+ }+ | { kind: 'unavailable' }++/**+ * Decide whether a verified (not yet consumed) refresh token may be rotated.+ *+ * Only the HCC lineage is bound to a live Host: workflow-recipe chains have no+ * Host. A Host deleted and recreated under the same name gets a new uid, so a+ * chain minted for the old Host stops renewing. Only existence and uid are+ * checked, not deletionTimestamp: a Host being torn down keeps its workflow+ * credential until it is gone.+ */+export async function resolveRenewalHostBinding(+ gateway: RenewalHostGateway,+ claims: McpHostRefreshClaims+): Promise<RenewalHostBinding> {+ const hccQualified = claims.mcpCapabilities.includes(MCP_HOST_CREDENTIAL_CAPABILITY)+ if (!hccQualified) {+ // A hosts-namespace standalone chain without the HCC audience predates+ // host_uid; renewing it would mint a control token that can never be bound+ // to a Host. HCC re-issues such Hosts on contract change.+ if (+ claims.recipeNamespace === config.hostsNamespace &&+ claims.recipeName === HCC_STANDALONE_RECIPE_NAME+ ) {+ return { kind: 'denied', reason: 'hcc_lineage_without_audience' }+ }+ return { kind: 'ok' }+ }++ // validateClaims guarantees host_uid and a single bare Host name on this lineage.+ const hostUid = claims.host_uid as string+ let host: { metadata?: { uid?: unknown } }+ try {+ // Namespace is explicit: without it the gateway falls back to a cluster-wide list.+ host = (await gateway.getResource('hosts', claims.hostRefs[0], config.hostsNamespace)) as {+ metadata?: { uid?: unknown }+ }+ } catch (err) {+ if (isK8sResourceNotFound(err)) return { kind: 'denied', reason: 'host_not_found' }+ return { kind: 'unavailable' }+ }+ if (host?.metadata?.uid !== hostUid) return { kind: 'denied', reason: 'host_uid_mismatch' }+ return { kind: 'ok', hccCredential: { hostUid } }+}diff --git a/control-api/src/routes/mcp-host/renewal/index.ts b/control-api/src/routes/mcp-host/renewal/index.tsindex 84ba11bad..20ee60c39 100644--- a/control-api/src/routes/mcp-host/renewal/index.ts+++ b/control-api/src/routes/mcp-host/renewal/index.ts@@ -1,10 +1,11 @@import { Router } from 'express'+import type { RenewalHostGateway } from './hostBinding.js'import { createMcpHostRefreshRoutes } from './refresh.routes.js'import { createMcpHostReissueRoutes } from './reissue.routes.js'-export function createMcpHostRenewalRoutes(): Router {+export function createMcpHostRenewalRoutes(gateway: RenewalHostGateway): Router {const router = Router()- router.use(createMcpHostRefreshRoutes())- router.use(createMcpHostReissueRoutes())+ router.use(createMcpHostRefreshRoutes(gateway))+ router.use(createMcpHostReissueRoutes(gateway))return router}diff --git a/control-api/src/routes/mcp-host/renewal/refresh.routes.ts b/control-api/src/routes/mcp-host/renewal/refresh.routes.tsindex dddf304cb..8330df358 100644--- a/control-api/src/routes/mcp-host/renewal/refresh.routes.ts+++ b/control-api/src/routes/mcp-host/renewal/refresh.routes.ts@@ -7,16 +7,17 @@ import {mcpHostJwtRefreshTotal,} from '../../../observability/metrics.js'import {- MCP_HOST_CREDENTIAL_CAPABILITY,- consumeMcpHostRefreshJwt,+ consumeRefreshJti,getMcpHostRefreshRateLimitKey,issueMcpHostAccessJwt,issueMcpHostControlJwt,issueMcpHostRefreshJwt,+ verifyMcpHostRefreshJwt,} from '../../../utils/auth/mcpHostJwtToken.js'import { extractBearerToken } from '../../../utils/extractBearerToken.js'+import { type RenewalHostGateway, resolveRenewalHostBinding } from './hostBinding.js'-export function createMcpHostRefreshRoutes(): Router {+export function createMcpHostRefreshRoutes(gateway: RenewalHostGateway): Router {const router = Router()router.post(@@ -47,7 +48,9 @@ export function createMcpHostRefreshRoutes(): Router {return res.status(401).json({ error: 'Unauthorized' })}- const claims = await consumeMcpHostRefreshJwt(token)+ // Verify without consuming: the Host lookup below can fail transiently,+ // and a consumed jti cannot be retried.+ const claims = await verifyMcpHostRefreshJwt(token)if (!claims) {req.log?.info({@@ -60,9 +63,32 @@ export function createMcpHostRefreshRoutes(): Router {return res.status(401).json({ error: 'Unauthorized' })}- const hccCredential = claims.mcpCapabilities.includes(MCP_HOST_CREDENTIAL_CAPABILITY)- ? { hostUid: claims.host_uid! }- : undefined+ const binding = await resolveRenewalHostBinding(gateway, claims)+ if (binding.kind === 'unavailable') {+ req.log?.warn(+ { event: 'host_state_unavailable', route: 'workflow_auth_refresh' },+ 'host lookup failed; refresh token left unconsumed'+ )+ return res.status(503).json({ error: 'host_state_unavailable' })+ }+ if (binding.kind === 'denied') {+ req.log?.info(+ { event: 'auth_denied', reason: binding.reason, route: 'workflow_auth_refresh' },+ 'auth denied'+ )+ return res.status(401).json({ error: 'Unauthorized' })+ }++ const consumed = await consumeRefreshJti(claims.jti, claims.exp)+ if (!consumed) {+ req.log?.info(+ { event: 'auth_denied', reason: 'jti_race_lost', route: 'workflow_auth_refresh' },+ 'auth denied'+ )+ return res.status(401).json({ error: 'Unauthorized' })+ }++ const { hccCredential } = binding// Preserve hostRefs from the incoming refresh token so the host// identity binding (1st-party hostRefs[0]) survives rotation.@@ -82,8 +108,14 @@ export function createMcpHostRefreshRoutes(): Router {claims.recipeNamespace,claims.recipeName,claims.hostRefs,- { scopes: claims.workflowControlScopes }+ { scopes: claims.workflowControlScopes, hccCredential })+ if (control.scopeStripped) {+ req.log?.warn(+ { event: 'oauth_user_token_scope_stripped', route: 'refresh' },+ 'oauth:user-token dropped from a non-HCC control token'+ )+ }resultLabel = 'success'return res.status(200).json({diff --git a/control-api/src/routes/mcp-host/renewal/reissue.routes.ts b/control-api/src/routes/mcp-host/renewal/reissue.routes.tsindex d8d63a46d..bf6f0495c 100644--- a/control-api/src/routes/mcp-host/renewal/reissue.routes.ts+++ b/control-api/src/routes/mcp-host/renewal/reissue.routes.ts@@ -4,8 +4,7 @@ import { mcpHostHttpMetrics } from '../../../middleware/mcpHostHttpMetrics.js'import { rateLimitMiddleware } from '../../../middleware/rateLimitMiddleware.js'import { mcpHostJwtReissueTotal } from '../../../observability/metrics.js'import {- MCP_HOST_CREDENTIAL_CAPABILITY,- consumeExpiredRefreshJti,+ consumeRefreshJti,getMcpHostExpiredRefreshRateLimitKey,issueMcpHostAccessJwt,issueMcpHostControlJwt,@@ -13,8 +12,9 @@ import {verifyExpiredMcpHostRefreshJwtDetailed,} from '../../../utils/auth/mcpHostJwtToken.js'import { extractBearerToken } from '../../../utils/extractBearerToken.js'+import { type RenewalHostGateway, resolveRenewalHostBinding } from './hostBinding.js'-export function createMcpHostReissueRoutes(): Router {+export function createMcpHostReissueRoutes(gateway: RenewalHostGateway): Router {const router = Router()function bodyString(body: unknown, snakeKey: string, camelKey: string): string | undefined {@@ -49,6 +49,9 @@ export function createMcpHostReissueRoutes(): Router {| 'revoked'| 'mismatch'| 'bad_request'+ | 'host_mismatch'+ | 'host_unavailable'+ | 'lineage_without_audience'let resultLabel: ResultLabel = 'invalid_sig'try {const token = extractBearerToken(req)@@ -151,7 +154,33 @@ export function createMcpHostReissueRoutes(): Router {return res.status(401).json({ error: 'Unauthorized' })}- const consumed = await consumeExpiredRefreshJti(claims.jti, claims.exp)+ const binding = await resolveRenewalHostBinding(gateway, claims)+ if (binding.kind === 'unavailable') {+ resultLabel = 'host_unavailable'+ req.log?.warn(+ { event: 'host_state_unavailable', route: 'workflow_auth_reissue', mode },+ 'host lookup failed; refresh token left unconsumed'+ )+ return res.status(503).json({ error: 'host_state_unavailable' })+ }+ if (binding.kind === 'denied') {+ resultLabel =+ binding.reason === 'hcc_lineage_without_audience'+ ? 'lineage_without_audience'+ : 'host_mismatch'+ req.log?.info(+ {+ event: 'auth_denied',+ reason: binding.reason,+ route: 'workflow_auth_reissue',+ mode,+ },+ 'auth denied'+ )+ return res.status(401).json({ error: 'Unauthorized' })+ }++ const consumed = await consumeRefreshJti(claims.jti, claims.exp)if (!consumed) {resultLabel = 'revoked'req.log?.info(@@ -161,9 +190,7 @@ export function createMcpHostReissueRoutes(): Router {return res.status(401).json({ error: 'Unauthorized' })}- const hccCredential = claims.mcpCapabilities.includes(MCP_HOST_CREDENTIAL_CAPABILITY)- ? { hostUid: claims.host_uid! }- : undefined+ const { hccCredential } = binding// Preserve hostRefs from the incoming (expired) refresh token so// the host identity binding survives the recovery re-issue.@@ -183,8 +210,14 @@ export function createMcpHostReissueRoutes(): Router {claims.recipeNamespace,claims.recipeName,claims.hostRefs,- { scopes: claims.workflowControlScopes }+ { scopes: claims.workflowControlScopes, hccCredential })+ if (control.scopeStripped) {+ req.log?.warn(+ { event: 'oauth_user_token_scope_stripped', route: 'reissue' },+ 'oauth:user-token dropped from a non-HCC control token'+ )+ }resultLabel = 'ok'req.log?.info(diff --git a/control-api/src/utils/auth/mcpHostJwtToken.ts b/control-api/src/utils/auth/mcpHostJwtToken.tsindex 052460ee1..04a5873bf 100644--- a/control-api/src/utils/auth/mcpHostJwtToken.ts+++ b/control-api/src/utils/auth/mcpHostJwtToken.ts@@ -24,6 +24,23 @@ export const MCP_HOST_CREDENTIAL_CAPABILITY = 'mcp:credential:read'*/export const MCP_HOST_HCC_ACCESS_MAX_TTL_SECONDS = 600const HCC_HOST_NAME_RE = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/+export const HCC_STANDALONE_RECIPE_NAME = 'standalone'++/** HCC token lineage: the hosts-namespace standalone recipe and one bare Host name. */+function isHccShape(+ recipeNamespace: string,+ recipeName: string,+ hostRefs: string[],+ hostsNamespace: string = config.hostsNamespace+): boolean {+ return (+ recipeNamespace === hostsNamespace &&+ recipeName === HCC_STANDALONE_RECIPE_NAME &&+ hostRefs.length === 1 &&+ hostRefs[0].length <= 63 &&+ HCC_HOST_NAME_RE.test(hostRefs[0])+ )+}type McpHostCredentialLineage = {hostUid: string@@ -75,7 +92,7 @@ async function revokeRefreshJti(jti: string, exp: number): Promise<void> {cacheRevokedRefreshJti(jti)}-async function consumeRefreshJti(jti: string, exp: number): Promise<boolean> {+async function insertRefreshJtiOnce(jti: string, exp: number): Promise<boolean> {if (revokedRefreshJtis.has(jti)) {return false}@@ -198,12 +215,33 @@ export type McpHostControlClaims = {hostRefs: string[]typ: 'service'scopes: McpHostControlScope[]+ host_uid?: stringiss: stringaud: stringjti: stringexp: number}+const BROKER_USER_TOKEN_SCOPE: McpHostControlScope = 'oauth:user-token'++/**+ * Structural shape of a control token minted for a host-context-controller+ * Host: the sentinel standalone recipe in the hosts namespace and exactly one+ * bare Host name. `standalone` itself is rejected because it is the reserved+ * name of the legacy shared principal, not a Host. Deliberately not part of+ * `verifyMcpHostControlJwt`: other verifiers accept workflow-recipe tokens and+ * a Host that happens to be called `standalone`.+ */+export function isHccControlLineage(+ claims: Pick<McpHostControlClaims, 'recipeNamespace' | 'recipeName' | 'hostRefs'>,+ hostsNamespace: string+): boolean {+ return (+ isHccShape(claims.recipeNamespace, claims.recipeName, claims.hostRefs, hostsNamespace) &&+ claims.hostRefs[0] !== HCC_STANDALONE_RECIPE_NAME+ )+}+// Lazy memoized public key — deferred until first verification call so that// tests can mock config.adminJwtPrivateKey before the key is computed.let _workflowJwtPublicKey: string | null = null@@ -316,11 +354,24 @@ export function issueMcpHostControlJwt(recipeNamespace: string,recipeName: string,hostRefs?: string[],- options: { scopes?: McpHostControlScope[] } = {}-): { token: string; expiresInSeconds: number } {+ options: { scopes?: McpHostControlScope[]; hccCredential?: McpHostCredentialLineage } = {}+): { token: string; expiresInSeconds: number; scopeStripped: boolean } {const refs = normalizeIssuedMcpHostHostRefs(recipeNamespace, recipeName, hostRefs)- const scopes = normalizeMcpHostControlScopes(options.scopes ?? [])- if (!scopes) throw new Error('invalid mcp-host control scopes')+ const requestedScopes = normalizeMcpHostControlScopes(options.scopes ?? [])+ if (!requestedScopes) throw new Error('invalid mcp-host control scopes')+ const { hccCredential } = options+ if (hccCredential) {+ assertHccCredentialLineage(recipeNamespace, recipeName, refs, hccCredential)+ }+ // The OAuth broker binds a control token to a live Host through host_uid, so+ // only HCC-lineage tokens may carry the broker scope. Filtering here (not in+ // each route) also covers refresh/reissue of older chains that still list the+ // scope. Access and refresh keep it: they never authorize at the broker, and+ // workflow-recipes compares their scopes against what it requested.+ const scopeStripped = !hccCredential && requestedScopes.includes(BROKER_USER_TOKEN_SCOPE)+ const scopes = scopeStripped+ ? requestedScopes.filter(scope => scope !== BROKER_USER_TOKEN_SCOPE)+ : requestedScopesconst token = jwt.sign({sub: `${recipeNamespace}/${recipeName}`,@@ -329,6 +380,9 @@ export function issueMcpHostControlJwt(hostRefs: refs,typ: 'service',scopes,+ // host_uid only. mcpCapabilities would let this token act as an HCC+ // credential reader; that authority stays on access/refresh.+ ...(hccCredential ? { host_uid: hccCredential.hostUid } : {}),},config.adminJwtPrivateKey,{@@ -340,7 +394,7 @@ export function issueMcpHostControlJwt(})mcpHostJwtIssueTotal.inc({ kind: 'control' }, 1)- return { token, expiresInSeconds: config.mcpHostJwtControlTtlSec }+ return { token, expiresInSeconds: config.mcpHostJwtControlTtlSec, scopeStripped }}function normalizeMcpHostControlScopes(value: unknown): McpHostControlScope[] | null {@@ -387,14 +441,7 @@ function assertHccCredentialLineage(hostRefs: string[],lineage: McpHostCredentialLineage): void {- if (- recipeNamespace !== config.hostsNamespace ||- recipeName !== 'standalone' ||- hostRefs.length !== 1 ||- hostRefs[0].length > 63 ||- !HCC_HOST_NAME_RE.test(hostRefs[0]) ||- !normalizeHostUid(lineage.hostUid)- ) {+ if (!isHccShape(recipeNamespace, recipeName, hostRefs) || !normalizeHostUid(lineage.hostUid)) {throw new Error('invalid HCC mcp-host credential lineage')}}@@ -415,11 +462,7 @@ function validateMcpCredentialLineage(const hostUid = normalizeHostUid(payload.host_uid)const capabilities = payload.mcpCapabilitiesif (- recipeNamespace !== config.hostsNamespace ||- recipeName !== 'standalone' ||- hostRefs.length !== 1 ||- hostRefs[0].length > 63 ||- !HCC_HOST_NAME_RE.test(hostRefs[0]) ||+ !isHccShape(recipeNamespace, recipeName, hostRefs) ||!hostUid ||!Array.isArray(capabilities) ||capabilities.length !== 1 ||@@ -532,6 +575,13 @@ export function verifyMcpHostControlJwt(token: string): McpHostControlClaims | nreturn null}+ let hostUid: string | undefined+ if (payload.host_uid !== undefined) {+ const normalized = normalizeHostUid(payload.host_uid)+ if (!normalized) return null+ hostUid = normalized+ }+return {sub,recipeNamespace,@@ -539,6 +589,7 @@ export function verifyMcpHostControlJwt(token: string): McpHostControlClaims | nhostRefs,typ: 'service',scopes,+ ...(hostUid ? { host_uid: hostUid } : {}),iss: payload.iss as string,aud: 'mcp-host',jti,@@ -663,7 +714,7 @@ export async function verifyMcpHostRefreshJwt(token: string): Promise<McpHostRef* (the caller surfaces an opaque 401 to avoid leaking which check failed).** Does NOT consume the jti — callers that want one-shot semantics must- * invoke `consumeRevokedRefreshJti` separately (see route handler).+ * invoke `consumeRefreshJti` separately (see route handler).*/export async function verifyExpiredMcpHostRefreshJwt(token: string@@ -707,52 +758,23 @@ export async function verifyExpiredMcpHostRefreshJwtDetailed(}/**- * Atomic single-use consumption of an expired refresh jti on the recovery- * path. Same contract as `consumeRefreshJti` but exported so the- * reissue route can close the race between "verify" and "emit new pair":- * if two mcp-host replicas both hold the same expired refresh and both- * hit /reissue simultaneously, only one wins the INSERT and only one- * receives fresh tokens.+ * Atomic single-use consumption of a refresh jti. Callers verify first+ * (`verifyMcpHostRefreshJwt` / `verifyExpiredMcpHostRefreshJwtDetailed`),+ * run every check that can fail transiently, and only then consume: a+ * consumed jti cannot be retried, so consuming before a check that answers+ * 503 would burn the caller's rotation chain. When two requests race on the+ * same jti only one wins the INSERT.*/-export async function consumeExpiredRefreshJti(jti: string, exp: number): Promise<boolean> {- // The expiry cron removes rows where `expires_at < now()`. An expired- // refresh jti (exp in the past) would be reclaimed almost immediately,- // which defeats replay prevention during the short window after reissue.- // Floor the stored expiry at the reissue grace window so the revocation record- // survives long enough to block a replayed token issued in the same- // minute.- const minExp = Math.floor(Date.now() / 1000) + EXPIRED_REFRESH_REISSUE_GRACE_SECONDS- const effectiveExp = Math.max(exp, minExp)- return consumeRefreshJti(jti, effectiveExp)-}--export async function consumeMcpHostRefreshJwt(- token: string-): Promise<McpHostRefreshClaims | null> {- try {- const payload = jwt.verify(token, getWorkflowJwtPublicKey(), {- algorithms: ['RS256'],- issuer: config.adminJwtIssuer,- audience: MCP_HOST_WORKFLOW_AUDIENCE,- }) as jwt.JwtPayload-- const claims = validateClaims(- payload,- 'workflow:approval:refresh'- ) as McpHostRefreshClaims | null- if (!claims) {- return null- }-- const consumed = await consumeRefreshJti(claims.jti, claims.exp)- if (!consumed) {- return null- }-- return claims- } catch {- return null- }+export async function consumeRefreshJti(jti: string, exp: number): Promise<boolean> {+ // Reissue accepts a refresh until `exp + grace`, and the expiry cron deletes+ // rows once `expires_at` passes. The row must therefore outlive the whole+ // reissue window: stored at plain `exp`, the cron could drop it while the+ // consumed token is still reissuable, and after a restart (cold in-memory+ // cache) reissue would accept it a second time. `now + grace` covers a jti+ // consumed on reissue after its exp.+ const now = Math.floor(Date.now() / 1000)+ const replayableUntil = Math.max(exp, now) + EXPIRED_REFRESH_REISSUE_GRACE_SECONDS+ return insertRefreshJtiOnce(jti, replayableUntil)}export function getMcpHostCallerKey(diff --git a/control-api/test/helpers/requestLogCapture.ts b/control-api/test/helpers/requestLogCapture.tsnew file mode 100644index 000000000..683e7bdfb--- /dev/null+++ b/control-api/test/helpers/requestLogCapture.ts@@ -0,0 +1,23 @@+import { vi } from 'vitest'+import { rootLogger } from '../../src/observability/logger.js'++/**+ * Capture route logs. `req.log` is `rootLogger.child(...)` built per request,+ * so a runtime spy on `child` intercepts it without disturbing the module+ * loggers created at import time.+ */+export function captureRequestLogs() {+ const info = vi.fn()+ const warn = vi.fn()+ const fakeChild: Record<string, unknown> = {+ info,+ warn,+ error: vi.fn(),+ debug: vi.fn(),+ trace: vi.fn(),+ fatal: vi.fn(),+ }+ fakeChild.child = () => fakeChild+ const spy = vi.spyOn(rootLogger, 'child').mockReturnValue(fakeChild as never)+ return { info, warn, restore: () => spy.mockRestore() }+}diff --git a/control-api/test/mcpHostJwtToken.hostRefs.test.ts b/control-api/test/mcpHostJwtToken.hostRefs.test.tsindex 530815bd4..97b362834 100644--- a/control-api/test/mcpHostJwtToken.hostRefs.test.ts+++ b/control-api/test/mcpHostJwtToken.hostRefs.test.ts@@ -11,6 +11,7 @@ import {getMcpHostCallerKey,getMcpHostExpiredRefreshRateLimitKey,getMcpHostRefreshRateLimitKey,+ isHccControlLineage,isHostRefAuthorized,issueMcpHostAccessJwt,issueMcpHostControlJwt,@@ -279,6 +280,104 @@ describe('mcpHostJwtToken — hostRefs JWT claim', () => {'invalid mcp-host hostRefs')})++ it('F2a: signs host_uid, never mcpCapabilities, and keeps oauth:user-token for an HCC credential', () => {+ const out = issueMcpHostControlJwt(config.hostsNamespace, 'standalone', ['chatllm'], {+ scopes: ['workflow:list', 'oauth:user-token'],+ hccCredential: { hostUid: 'uid-chatllm-1' },+ })+ const decoded = jwt.decode(out.token) as Record<string, unknown>+ expect(decoded.host_uid).toBe('uid-chatllm-1')+ expect(decoded.mcpCapabilities).toBeUndefined()+ expect(decoded.scopes).toEqual(['workflow:list', 'oauth:user-token'])+ expect(out.scopeStripped).toBe(false)+ })++ it('E1: strips oauth:user-token without an HCC credential and reports it', () => {+ const out = issueMcpHostControlJwt('sandbox-recipes', 'crm', undefined, {+ scopes: ['workflow:list', 'oauth:user-token'],+ })+ const decoded = jwt.decode(out.token) as Record<string, unknown>+ expect(decoded.scopes).toEqual(['workflow:list'])+ expect(decoded.host_uid).toBeUndefined()+ expect(out.scopeStripped).toBe(true)+ expect(out.expiresInSeconds).toBe(config.mcpHostJwtControlTtlSec)+ })++ it('reports no strip when the broker scope was never requested', () => {+ const out = issueMcpHostControlJwt('sandbox-recipes', 'crm', undefined, {+ scopes: ['workflow:list'],+ })+ expect(out.scopeStripped).toBe(false)+ })++ it.each([+ {+ label: 'non-hosts namespace',+ ns: 'sandbox-recipes',+ name: 'standalone',+ refs: ['chatllm'],+ },+ { label: 'non-standalone recipe', ns: 'HOSTS', name: 'crm', refs: ['chatllm'] },+ { label: 'namespaced hostRef', ns: 'HOSTS', name: 'standalone', refs: ['mcp-host/chatllm'] },+ { label: 'two hostRefs', ns: 'HOSTS', name: 'standalone', refs: ['a', 'b'] },+ ])('refuses to sign an HCC credential on a non-HCC lineage ($label)', ({ ns, name, refs }) => {+ const namespace = ns === 'HOSTS' ? config.hostsNamespace : ns+ expect(() =>+ issueMcpHostControlJwt(namespace, name, refs, {+ scopes: ['oauth:user-token'],+ hccCredential: { hostUid: 'uid-1' },+ })+ ).toThrow('invalid HCC mcp-host credential lineage')+ })++ it('refuses to sign a malformed HCC host uid', () => {+ expect(() =>+ issueMcpHostControlJwt(config.hostsNamespace, 'standalone', ['chatllm'], {+ hccCredential: { hostUid: 'bad uid' },+ })+ ).toThrow('invalid HCC mcp-host credential lineage')+ })+ })++ describe('isHccControlLineage', () => {+ const base = { recipeNamespace: config.hostsNamespace, recipeName: 'standalone' }++ it('accepts a single bare Host name in the hosts namespace standalone lineage', () => {+ expect(isHccControlLineage({ ...base, hostRefs: ['chatllm'] }, config.hostsNamespace)).toBe(+ true+ )+ expect(+ isHccControlLineage({ ...base, hostRefs: ['a'.repeat(63)] }, config.hostsNamespace)+ ).toBe(true)+ })++ it.each([+ {+ label: 'wrc recipe binding',+ claims: {+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'crm',+ hostRefs: ['sandbox-recipes/crm'],+ },+ },+ { label: 'legacy namespaced ref', claims: { ...base, hostRefs: ['mcp-host/standalone'] } },+ { label: 'reserved standalone', claims: { ...base, hostRefs: ['standalone'] } },+ { label: 'two hostRefs', claims: { ...base, hostRefs: ['a', 'b'] } },+ {+ label: 'non-standalone recipe',+ claims: { ...base, recipeName: 'other', hostRefs: ['chatllm'] },+ },+ {+ label: 'other namespace',+ claims: { ...base, recipeNamespace: 'elsewhere', hostRefs: ['chatllm'] },+ },+ { label: 'uppercase', claims: { ...base, hostRefs: ['ChatLLM'] } },+ { label: 'over 63 chars', claims: { ...base, hostRefs: ['a'.repeat(64)] } },+ { label: 'empty hostRefs', claims: { ...base, hostRefs: [] as string[] } },+ ])('rejects $label', ({ claims }) => {+ expect(isHccControlLineage(claims, config.hostsNamespace)).toBe(false)+ })})describe('verifyMcpHostAccessJwt — hostRefs validation', () => {@@ -641,9 +740,69 @@ describe('mcpHostJwtToken — hostRefs JWT claim', () => {const claims = verifyMcpHostControlJwt(token)expect(claims).not.toBeNull()expect(claims!.typ).toBe('service')- expect(claims!.scopes).toEqual(ALL_MCP_HOST_CONTROL_SCOPES)+ // Without an HCC credential the broker scope never reaches the control token.+ expect(claims!.scopes).toEqual(+ ALL_MCP_HOST_CONTROL_SCOPES.filter(scope => scope !== 'oauth:user-token')+ )expect(claims!.aud).toBe('mcp-host')expect(claims!.hostRefs).toEqual(['ns1/recipe1', 'ns2/recipe2'])+ expect(claims!.host_uid).toBeUndefined()+ })++ it('F2f: exposes the host_uid of an HCC control token', () => {+ const { token } = issueMcpHostControlJwt(config.hostsNamespace, 'standalone', ['chatllm'], {+ scopes: ['oauth:user-token'],+ hccCredential: { hostUid: 'uid-chatllm-1' },+ })+ const claims = verifyMcpHostControlJwt(token)+ expect(claims?.host_uid).toBe('uid-chatllm-1')+ expect(claims?.scopes).toEqual(['oauth:user-token'])+ })++ it.each([+ { label: 'empty', hostUid: '' },+ { label: 'padded', hostUid: ' uid-1 ' },+ { label: 'illegal characters', hostUid: 'uid/1' },+ { label: 'too long', hostUid: 'u'.repeat(129) },+ { label: 'non-string', hostUid: 42 },+ ])('F2f: rejects a control token whose host_uid is malformed ($label)', ({ hostUid }) => {+ // Forged on purpose: the issuer refuses to sign a malformed uid.+ const token = jwt.sign(+ {+ sub: `${config.hostsNamespace}/standalone`,+ recipeNamespace: config.hostsNamespace,+ recipeName: 'standalone',+ hostRefs: ['chatllm'],+ typ: 'service',+ scopes: ['oauth:user-token'],+ host_uid: hostUid,+ },+ config.adminJwtPrivateKey,+ {+ algorithm: 'RS256',+ issuer: config.adminJwtIssuer,+ audience: 'mcp-host',+ expiresIn: 300,+ jwtid: `malformed-host-uid-${hostUid}`,+ }+ )+ expect(verifyMcpHostControlJwt(token)).toBeNull()+ })++ it('F2f: keeps a control token for a Host named standalone valid (only the broker rejects that lineage)', () => {+ const { token } = issueMcpHostControlJwt(+ config.hostsNamespace,+ 'standalone',+ ['standalone'],+ {+ scopes: ['workflow:read'],+ hccCredential: { hostUid: 'uid-standalone-host' },+ }+ )+ const claims = verifyMcpHostControlJwt(token)+ expect(claims).not.toBeNull()+ expect(claims!.host_uid).toBe('uid-standalone-host')+ expect(isHccControlLineage(claims!, config.hostsNamespace)).toBe(false)})it('rejects a new-format control token with a non-service type', () => {diff --git a/control-api/test/mockGateway.ts b/control-api/test/mockGateway.tsindex 761243898..be70a60fd 100644--- a/control-api/test/mockGateway.ts+++ b/control-api/test/mockGateway.ts@@ -143,6 +143,7 @@ export class MockGateway {private secretWriteFault: MockGatewaySecretWriteFault | null = nullprivate resourceCreateFault: MockGatewayResourceCreateFault | null = nullprivate resourceUpdateFault: MockGatewayResourceUpdateFault | null = null+ private readonly getResourceFailures = new Map<ResourceType, unknown[]>()// Stub for the LLM allowlist ConfigMap materializer. Defaults to a no-op so// CRUD success paths are undisturbed; a test can inject a throwing impl to@@ -250,7 +251,22 @@ export class MockGateway {return rows.filter(row => row.metadata.namespace === namespace)}+ /**+ * Test helper: the next `getResource` on `plural` rejects with `err` (e.g. a+ * K8s-shaped `{ statusCode: 503 }`). Each call queues one failure; later reads+ * go back to the store.+ */+ failGetResource(plural: ResourceType, err: unknown): void {+ const queue = this.getResourceFailures.get(plural) ?? []+ queue.push(err)+ this.getResourceFailures.set(plural, queue)+ }+async getResource(plural: ResourceType, name: string, namespace?: string): Promise<unknown> {+ const queuedFailure = this.getResourceFailures.get(plural)+ if (queuedFailure && queuedFailure.length > 0) {+ throw queuedFailure.shift()+ }const row = this.store[plural].get(this.key(name, namespace))if (!row) {throw new K8sNotFoundError(`${plural}/${name} not found`)diff --git a/control-api/test/oauth.brokerJwt.test.ts b/control-api/test/oauth.brokerJwt.test.tsindex cb9be1994..a7a3df8fd 100644--- a/control-api/test/oauth.brokerJwt.test.ts+++ b/control-api/test/oauth.brokerJwt.test.ts@@ -2,7 +2,6 @@ import { describe, expect, it } from 'vitest'import jwt from 'jsonwebtoken'import { config } from '../src/config.js'import {- consumeMcpHostRefreshJwt,getMcpHostExpiredRefreshRateLimitKey,getMcpHostRefreshRateLimitKey,issueMcpHostControlJwt,@@ -94,10 +93,6 @@ describe('[SEC-2] reverse audience confusion — mcp-host validators reject a brexpect(await verifyExpiredMcpHostRefreshJwt(brokerToken())).toBeNull()})- it('consumeMcpHostRefreshJwt rejects an aud=oauth-broker token (and does not consume a jti)', async () => {- expect(await consumeMcpHostRefreshJwt(brokerToken())).toBeNull()- })-it('getMcpHostRefreshRateLimitKey returns null for an aud=oauth-broker token', () => {expect(getMcpHostRefreshRateLimitKey(brokerToken())).toBeNull()})diff --git a/control-api/test/oauth.remoteSpecCoherence.test.ts b/control-api/test/oauth.remoteSpecCoherence.test.tsindex d0d2f5f70..f03970598 100644--- a/control-api/test/oauth.remoteSpecCoherence.test.ts+++ b/control-api/test/oauth.remoteSpecCoherence.test.ts@@ -656,8 +656,9 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_i}return Promise.resolve({ rows: [], rowCount: 0 })})- const token = issueMcpHostControlJwt('mcp-host', 'standalone', ['mcp-host/standalone'], {+ const token = issueMcpHostControlJwt('mcp-host', 'standalone', ['agent-host'], {scopes: ['oauth:user-token'],+ hccCredential: { hostUid: 'uid-agent-host' },}).tokenconst res = await request(app).post('/api/v1/mcp-oauth/user-token')diff --git a/control-api/test/routes.auth.mcp-host.issue.security.test.ts b/control-api/test/routes.auth.mcp-host.issue.security.test.tsindex 4b6ea4bcb..e38143737 100644--- a/control-api/test/routes.auth.mcp-host.issue.security.test.ts+++ b/control-api/test/routes.auth.mcp-host.issue.security.test.ts@@ -10,12 +10,14 @@ import {MCP_HOST_CREDENTIAL_CAPABILITY,MCP_HOST_HCC_AUDIENCE,MCP_HOST_WORKFLOW_AUDIENCE,+ type McpHostControlScope,issueMcpHostAccessJwt,issueMcpHostRefreshJwt,verifyMcpHostAccessJwt,verifyMcpHostControlJwt,verifyMcpHostRefreshJwt,} from '../src/utils/auth/mcpHostJwtToken.js'+import { captureRequestLogs } from './helpers/requestLogCapture.js'import { MockGateway } from './mockGateway.js'// Mock userApprovalRequestService for all tests@@ -40,11 +42,25 @@ vi.mock('../src/services/notificationEmitter.js', () => ({// is only consumed for NON-rate-limit queries. This keeps each test focused on// its actual invariant instead of having to stub the rate limiter too.const mockPoolQuery = vi.fn<(sql: string, params?: unknown[]) => Promise<unknown>>()+// Refresh-jti revocation table, modelled by SQL shape so the refresh route's+// verify (SELECT) and consume (INSERT ... ON CONFLICT DO NOTHING) see the same+// state a real table would give them.+const consumedRefreshJtis = new Set<string>()const mockPoolQueryDispatch = vi.fn(async (sql: unknown, params?: unknown[]) => {const text = typeof sql === 'string' ? sql : ''if (/rate_limit_buckets/i.test(text)) {return { rows: [{ count: 1 }], rowCount: 1 }}+ if (/workflow_revoked_refresh_jtis/i.test(text)) {+ const jti = Array.isArray(params) && typeof params[0] === 'string' ? params[0] : ''+ if (/^\s*SELECT/i.test(text)) {+ const hit = consumedRefreshJtis.has(jti)+ return { rows: hit ? [{ '?column?': 1 }] : [], rowCount: hit ? 1 : 0 }+ }+ if (consumedRefreshJtis.has(jti)) return { rows: [], rowCount: 0 }+ consumedRefreshJtis.add(jti)+ return { rows: [{ jti }], rowCount: 1 }+ }if (/lifecycle_state/i.test(text)) {return { rows: [{ lifecycle_state: 'active', lifecycle_version: 1 }], rowCount: 1 }}@@ -542,22 +558,47 @@ describe('Security: /auth/mcp-host/:namespace/:name/tokens access control', () =*/describe('Security: Refresh token rotation', () => {let app: ReturnType<typeof createApp>+ let gateway: MockGateway+ const HOST = 'chatllm'beforeEach(() => {vi.clearAllMocks()mockPoolQuery.mockReset()mockPoolQuery.mockResolvedValue({ rows: [], rowCount: 0 })- app = createApp(new MockGateway('mcp-server') as never)- })+ consumedRefreshJtis.clear()+ gateway = new MockGateway('mcp-server')+ app = createApp(gateway as never)+ })++ async function seedHost(name = HOST): Promise<string> {+ const created = (await gateway.createResource(+ 'hosts',+ { metadata: { name }, spec: { host: name, contextRef: 'ctx-a', secretRef: `${name}-llm` } },+ config.hostsNamespace+ )) as { metadata: { uid: string } }+ return created.metadata.uid+ }++ function issueHccRefresh(+ hostUid: string,+ workflowControlScopes: McpHostControlScope[] = ['workflow:list', 'oauth:user-token']+ ): string {+ return issueMcpHostRefreshJwt(config.hostsNamespace, 'standalone', [HOST], {+ workflowControlScopes,+ hccCredential: { hostUid },+ }).token+ }++ function refresh(token: string, body: Record<string, unknown> = {}) {+ return request(app)+ .post('/api/v1/workflow-auth/refresh')+ .set('Authorization', `Bearer ${token}`)+ .send(body)+ }it('issues new tokens with valid refresh token', async () => {const { token: refreshToken } = issueMcpHostRefreshJwt('ns', 'recipe')- // Mock: INSERT revocation row succeeds, so this request wins the one-time-use race.- mockPoolQuery.mockResolvedValueOnce({ rows: [{ jti: 'jti-1' }], rowCount: 1 })- const res = await request(app)- .post('/api/v1/workflow-auth/refresh')- .set('Authorization', `Bearer ${refreshToken}`)- .send()+ const res = await refresh(refreshToken)expect(res.status).toBe(200)expect(res.body.accessToken).toBeDefined()expect(res.body.refreshToken).toBeDefined()@@ -569,31 +610,18 @@ describe('Security: Refresh token rotation', () => {}})- it('preserves signed HCC lineage across ordinary rotation and keeps the control token separate', async () => {+ it('preserves signed HCC lineage across ordinary rotation and binds the control token to the Host uid (F2b)', async () => {const workflowControlScopes = ['workflow:list' as const, 'workflow:read' as const]- const hostRef = 'chatllm'- const hostUid = 'signed-host-uid'- const { token: refreshToken } = issueMcpHostRefreshJwt(- config.hostsNamespace,- 'standalone',- [hostRef],- {- workflowControlScopes,- hccCredential: { hostUid },- }- )- mockPoolQuery.mockResolvedValueOnce({ rows: [{ jti: 'hcc-refresh-jti' }], rowCount: 1 })+ const hostUid = await seedHost()+ const refreshToken = issueHccRefresh(hostUid, workflowControlScopes)- const res = await request(app)- .post('/api/v1/workflow-auth/refresh')- .set('Authorization', `Bearer ${refreshToken}`)- .send({ hostUid: 'body-controlled-uid', mcpCapabilities: [] })+ const res = await refresh(refreshToken, { hostUid: 'body-controlled-uid', mcpCapabilities: [] })expect(res.status).toBe(200)for (const encoded of [res.body.accessToken, res.body.refreshToken]) {const claims = jwt.decode(encoded) as Record<string, unknown>expect(claims.aud).toEqual([MCP_HOST_WORKFLOW_AUDIENCE, MCP_HOST_HCC_AUDIENCE])- expect(claims.hostRefs).toEqual([hostRef])+ expect(claims.hostRefs).toEqual([HOST])expect(claims.host_uid).toBe(hostUid)expect(claims.mcpCapabilities).toEqual([MCP_HOST_CREDENTIAL_CAPABILITY])expect(claims.workflowControlScopes).toEqual(workflowControlScopes)@@ -601,10 +629,11 @@ describe('Security: Refresh token rotation', () => {const control = jwt.decode(res.body.mcpHostControlToken) as Record<string, unknown>expect(control.aud).toBe('mcp-host')- expect(control.hostRefs).toEqual([hostRef])+ expect(control.hostRefs).toEqual([HOST])expect(control.scopes).toEqual(workflowControlScopes)- expect(control.host_uid).toBeUndefined()+ expect(control.host_uid).toBe(hostUid)expect(control.mcpCapabilities).toBeUndefined()+ expect(verifyMcpHostControlJwt(res.body.mcpHostControlToken)?.host_uid).toBe(hostUid)expect(verifyMcpHostAccessJwt(res.body.mcpHostControlToken)).toBeNull()await expect(verifyMcpHostRefreshJwt(res.body.mcpHostControlToken)).resolves.toBeNull()@@ -612,52 +641,118 @@ describe('Security: Refresh token rotation', () => {expect(verifyMcpHostControlJwt(res.body.refreshToken)).toBeNull()})+ it('keeps oauth:user-token on an HCC control token after rotation', async () => {+ const hostUid = await seedHost()+ const res = await refresh(issueHccRefresh(hostUid))+ expect(res.status).toBe(200)+ expect(verifyMcpHostControlJwt(res.body.mcpHostControlToken)?.scopes).toEqual([+ 'workflow:list',+ 'oauth:user-token',+ ])+ })++ it('E2: strips oauth:user-token from the control token of a rotated WRC chain, keeps it on access/refresh', async () => {+ const { token: refreshToken } = issueMcpHostRefreshJwt(+ config.sandboxNamespace,+ 'crm',+ undefined,+ { workflowControlScopes: ['workflow:list', 'oauth:user-token'] }+ )+ const logs = captureRequestLogs()+ let res: Awaited<ReturnType<typeof refresh>>+ try {+ res = await refresh(refreshToken)+ } finally {+ logs.restore()+ }+ expect(res.status).toBe(200)+ expect(verifyMcpHostControlJwt(res.body.mcpHostControlToken)?.scopes).toEqual(['workflow:list'])+ for (const encoded of [res.body.accessToken, res.body.refreshToken]) {+ const claims = jwt.decode(encoded) as Record<string, unknown>+ expect(claims.workflowControlScopes).toEqual(['workflow:list', 'oauth:user-token'])+ }+ expect(logs.warn).toHaveBeenCalledWith(+ expect.objectContaining({ event: 'oauth_user_token_scope_stripped', route: 'refresh' }),+ expect.any(String)+ )+ })++ it('F2c: rejects an HCC refresh whose Host no longer exists', async () => {+ const hostUid = await seedHost()+ const refreshToken = issueHccRefresh(hostUid)+ await gateway.deleteResource('hosts', HOST, config.hostsNamespace)++ const res = await refresh(refreshToken)+ expect(res.status).toBe(401)+ expect(res.body).toEqual({ error: 'Unauthorized' })+ })++ it('F2c: rejects an HCC refresh after the Host was recreated under the same name (uid changed)', async () => {+ const oldUid = await seedHost()+ const refreshToken = issueHccRefresh(oldUid)+ await gateway.deleteResource('hosts', HOST, config.hostsNamespace)+ const newUid = await seedHost()+ expect(newUid).not.toBe(oldUid)++ const res = await refresh(refreshToken)+ expect(res.status).toBe(401)+ expect(res.body).toEqual({ error: 'Unauthorized' })+ })++ it('F2d: answers 503 on a transient Host read error and leaves the refresh token reusable', async () => {+ const hostUid = await seedHost()+ const refreshToken = issueHccRefresh(hostUid)+ gateway.failGetResource(+ 'hosts',+ Object.assign(new Error('apiserver down'), { statusCode: 503 })+ )++ const failed = await refresh(refreshToken)+ expect(failed.status).toBe(503)+ expect(failed.body).toEqual({ error: 'host_state_unavailable' })++ const retried = await refresh(refreshToken)+ expect(retried.status).toBe(200)+ expect(verifyMcpHostControlJwt(retried.body.mcpHostControlToken)?.host_uid).toBe(hostUid)+ })++ it('F2e: rejects a hosts-namespace standalone refresh that lacks the HCC audience', async () => {+ await seedHost()+ // The producer still emits this pre-host_uid shape when called without an+ // HCC credential; only the renewal routes refuse to rotate it.+ const { token: refreshToken } = issueMcpHostRefreshJwt(+ config.hostsNamespace,+ 'standalone',+ [HOST],+ { workflowControlScopes: ['workflow:list'] }+ )+ const res = await refresh(refreshToken, { host_ref: HOST })+ expect(res.status).toBe(401)+ expect(res.body).toEqual({ error: 'Unauthorized' })+ })+it('rejects access token used as refresh token (scope mismatch)', async () => {const { token: accessToken } = issueMcpHostAccessJwt('ns', 'recipe')- const res = await request(app)- .post('/api/v1/workflow-auth/refresh')- .set('Authorization', `Bearer ${accessToken}`)- .send()+ const res = await refresh(accessToken)expect(res.status).toBe(401)})it('rejects reused refresh token (old JTI revoked after rotation)', async () => {const { token: refreshToken } = issueMcpHostRefreshJwt('ns', 'recipe')- // First use - should succeed and consume the old JTI.- mockPoolQuery.mockResolvedValueOnce({ rows: [{ jti: 'jti-1' }], rowCount: 1 })-- const res1 = await request(app)- .post('/api/v1/workflow-auth/refresh')- .set('Authorization', `Bearer ${refreshToken}`)- .send()+ const res1 = await refresh(refreshToken)expect(res1.status).toBe(200)expect(res1.body.refreshToken).toBeDefined()- const res2 = await request(app)- .post('/api/v1/workflow-auth/refresh')- .set('Authorization', `Bearer ${refreshToken}`)- .send()+ const res2 = await refresh(refreshToken)expect(res2.status).toBe(401)})it('allows only one winner when two refresh requests race on the same token', async () => {- const { token: refreshToken } = issueMcpHostRefreshJwt('ns', 'recipe')+ const hostUid = await seedHost()+ const refreshToken = issueHccRefresh(hostUid)- mockPoolQuery- .mockResolvedValueOnce({ rows: [{ jti: 'jti-1' }], rowCount: 1 })- .mockResolvedValueOnce({ rows: [], rowCount: 0 })-- const [res1, res2] = await Promise.all([- request(app)- .post('/api/v1/workflow-auth/refresh')- .set('Authorization', `Bearer ${refreshToken}`)- .send(),- request(app)- .post('/api/v1/workflow-auth/refresh')- .set('Authorization', `Bearer ${refreshToken}`)- .send(),- ])+ const [res1, res2] = await Promise.all([refresh(refreshToken), refresh(refreshToken)])expect([res1.status, res2.status].sort()).toEqual([200, 401])})diff --git a/control-api/test/routes.auth.mcp-host.issue.test.ts b/control-api/test/routes.auth.mcp-host.issue.test.tsindex 1f21cd810..4a23f568c 100644--- a/control-api/test/routes.auth.mcp-host.issue.test.ts+++ b/control-api/test/routes.auth.mcp-host.issue.test.ts@@ -8,9 +8,16 @@ import {MCP_HOST_CREDENTIAL_CAPABILITY,MCP_HOST_HCC_AUDIENCE,MCP_HOST_WORKFLOW_AUDIENCE,+ verifyMcpHostControlJwt,} from '../src/utils/auth/mcpHostJwtToken.js'+import { captureRequestLogs } from './helpers/requestLogCapture.js'import { MockGateway } from './mockGateway.js'+// Every scope except the broker one: what a non-HCC control token may carry.+const NON_BROKER_CONTROL_SCOPES = ALL_MCP_HOST_CONTROL_SCOPES.filter(+ scope => scope !== 'oauth:user-token'+)+vi.mock('../src/services/notificationEmitter.js', () => ({emitNotification: vi.fn().mockResolvedValue(undefined),enqueueApprovalRequestedNotification: vi.fn().mockResolvedValue(undefined),@@ -98,12 +105,61 @@ describe('routes/auth/mcp-host issue', () => {const accessClaims = jwt.decode(res.body.mcpHostAccessToken) as Record<string, unknown>const refreshClaims = jwt.decode(res.body.mcpHostRefreshToken) as Record<string, unknown>expect(controlClaims.typ).toBe('service')- expect(controlClaims.scopes).toEqual(ALL_MCP_HOST_CONTROL_SCOPES)+ // The broker scope is HCC-only; access and refresh keep the requested set.+ expect(controlClaims.scopes).toEqual(NON_BROKER_CONTROL_SCOPES)expect(accessClaims.workflowControlScopes).toEqual(ALL_MCP_HOST_CONTROL_SCOPES)expect(refreshClaims.workflowControlScopes).toEqual(ALL_MCP_HOST_CONTROL_SCOPES)expect(controlClaims.scope).toBeUndefined()expect(controlClaims.aud).toBe('mcp-host')expect(controlClaims.hostRefs).toEqual(['sandbox-recipes/test-recipe'])+ expect(controlClaims.host_uid).toBeUndefined()+ })++ it('E1: strips oauth:user-token from a WRC control token, keeps it on access/refresh, and logs it', async () => {+ const logs = captureRequestLogs()+ try {+ const res = await request(app)+ .post('/api/v1/auth/mcp-host/sandbox-recipes/test-recipe/tokens')+ .set('Authorization', `Bearer ${signInternalControlJwt('wrc')}`)+ .send({+ includeMcpHostControlToken: true,+ workflowControlScopes: ['workflow:list', 'oauth:user-token'],+ })++ expect(res.status).toBe(200)+ const control = verifyMcpHostControlJwt(res.body.mcpHostControlToken)+ expect(control).not.toBeNull()+ expect(control!.scopes).toEqual(['workflow:list'])+ expect(control!.host_uid).toBeUndefined()+ for (const encoded of [res.body.mcpHostAccessToken, res.body.mcpHostRefreshToken]) {+ const claims = jwt.decode(encoded) as Record<string, unknown>+ expect(claims.workflowControlScopes).toEqual(['workflow:list', 'oauth:user-token'])+ }+ expect(logs.warn).toHaveBeenCalledWith(+ expect.objectContaining({ event: 'oauth_user_token_scope_stripped', route: 'issue' }),+ expect.any(String)+ )+ } finally {+ logs.restore()+ }+ })++ it('does not log a scope strip when a WRC control token never asked for oauth:user-token', async () => {+ const logs = captureRequestLogs()+ try {+ const res = await request(app)+ .post('/api/v1/auth/mcp-host/sandbox-recipes/test-recipe/tokens')+ .set('Authorization', `Bearer ${signInternalControlJwt('wrc')}`)+ .send({ includeMcpHostControlToken: true, workflowControlScopes: ['workflow:list'] })++ expect(res.status).toBe(200)+ expect(logs.warn).not.toHaveBeenCalledWith(+ expect.objectContaining({ event: 'oauth_user_token_scope_stripped' }),+ expect.any(String)+ )+ } finally {+ logs.restore()+ }})it('does not expose the old workflow auth issuance route', async () => {@@ -141,8 +197,32 @@ describe('routes/auth/mcp-host issue', () => {expect(claims.mcpCapabilities).toEqual([MCP_HOST_CREDENTIAL_CAPABILITY])expect(claims.hostRefs).toEqual(['trader'])}- expect(controlClaims.host_uid).toBeUndefined()+ // F2a: the control token is bound to the Host uid HCC sent, but never+ // carries the credential-reader capability.+ expect(controlClaims.host_uid).toBe('host-uid-trader')expect(controlClaims.mcpCapabilities).toBeUndefined()+ expect(verifyMcpHostControlJwt(res.body.mcpHostControlToken)?.host_uid).toBe('host-uid-trader')+ })++ it('F2f: a control token for a Host literally named standalone still authenticates on workflow routes', async () => {+ const issued = await request(app)+ .post('/api/v1/auth/mcp-host/mcp-host/standalone/tokens')+ .set('Authorization', `Bearer ${signInternalControlJwt('hcc')}`)+ .send({+ includeMcpHostControlToken: true,+ workflowControlScopes: ['workflow:list'],+ host: 'standalone',+ hostUid: 'host-uid-standalone',+ })+ expect(issued.status).toBe(200)++ const res = await request(app)+ .get('/api/v1/workflows')+ .set('Authorization', `Bearer ${issued.body.mcpHostControlToken}`)++ expect(res.status).not.toBe(401)+ expect(res.status).toBe(200)+ expect(res.body).toEqual({ items: [], count: 0 })})it('uses the workflowControlScopes declared by the trusted provisioner', async () => {diff --git a/control-api/test/routes.mcp-host.renewal.realPostgres.integration.test.ts b/control-api/test/routes.mcp-host.renewal.realPostgres.integration.test.tsnew file mode 100644index 000000000..74226a412--- /dev/null+++ b/control-api/test/routes.mcp-host.renewal.realPostgres.integration.test.ts@@ -0,0 +1,245 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import jwt from 'jsonwebtoken'+import { randomBytes } from 'node:crypto'+import { Pool } from 'pg'+import request from 'supertest'+import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.js'++// Refresh rotation of the HCC lineage against the REAL revocation table+// (`workflow_revoked_refresh_jtis`): the route verifies the refresh, reads the+// Host, and only then consumes the jti. These cases pin what a mocked pool+// cannot show — the atomic INSERT ... ON CONFLICT under concurrency, that a+// transient Host error leaves no row behind, and the expires_at floor the+// expiry cron relies on. Refresh tokens come from the real producer+// (`issueMcpHostRefreshJwt`) and Hosts from MockGateway, which assigns the uid.+// Skipped without CONTROL_API_REAL_PG_ADMIN_URL.++const REISSUE_GRACE_SECONDS = 5 * 60++function jwtDecode(token: string): { jti: string } {+ return jwt.decode(token) as { jti: string }+}++function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+}++const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL+const describeRealPostgres = adminUrl ? describe : describe.skip++describeRealPostgres('mcp-host refresh rotation (real Postgres)', () => {+ const database = `control_api_mcp_host_renewal_${randomBytes(6).toString('hex')}`+ const connectionString = databaseUrl(+ adminUrl ?? 'postgresql://[email protected]/postgres',+ database+ )+ const previousPgEnv = process.env.CONTROL_API_PG_CONNECTION_STRING++ let adminPool: Pool+ let corePool: Pool+ let limiterPool: Pool+ // Loaded dynamically AFTER the env points the module pool at the test DB.+ let mod: {+ createApp: (gateway: unknown) => import('express').Express+ config: typeof import('../src/config.js').config+ jwt: typeof import('../src/utils/auth/mcpHostJwtToken.js')+ MockGateway: typeof import('./mockGateway.js').MockGateway+ }+ let gateway: InstanceType<typeof mod.MockGateway>+ let app: import('express').Express++ beforeAll(async () => {+ adminPool = new Pool({ connectionString: adminUrl })+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)++ process.env.CONTROL_API_PG_CONNECTION_STRING = connectionString++ const dbMod = await import('../src/db.js')+ corePool = dbMod.pool as unknown as Pool+ corePool.on('error', () => {})+ limiterPool = dbMod.rateLimitPool as unknown as Pool+ limiterPool.on('error', () => {})+ const migratePool = new Pool({ connectionString })+ await dbMod.initDb({ connect: () => migratePool.connect() })+ await endPoolAndWaitForClients(migratePool)++ const appMod = await import('../src/app.js')+ const configMod = await import('../src/config.js')+ const jwtMod = await import('../src/utils/auth/mcpHostJwtToken.js')+ const { MockGateway } = await import('./mockGateway.js')+ mod = {+ createApp: appMod.createApp as never,+ config: configMod.config,+ jwt: jwtMod,+ MockGateway,+ }+ }, 60_000)++ afterAll(async () => {+ try {+ if (previousPgEnv === undefined) delete process.env.CONTROL_API_PG_CONNECTION_STRING+ else process.env.CONTROL_API_PG_CONNECTION_STRING = previousPgEnv+ await endPoolAndWaitForClients(corePool).catch(() => {})+ await endPoolAndWaitForClients(limiterPool).catch(() => {})+ if (adminPool) {+ await adminPool.query(+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity+ WHERE datname = $1 AND pid <> pg_backend_pid()`,+ [database]+ )+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)+ }+ } finally {+ await adminPool?.end()+ }+ })++ beforeEach(async () => {+ await corePool.query('DELETE FROM workflow_revoked_refresh_jtis')+ await corePool.query('DELETE FROM rate_limit_buckets')+ gateway = new mod.MockGateway('mcp-server')+ app = mod.createApp(gateway)+ })++ async function seedHost(name: string): Promise<string> {+ const created = (await gateway.createResource(+ 'hosts',+ { metadata: { name }, spec: { host: name, contextRef: 'ctx-a', secretRef: `${name}-llm` } },+ mod.config.hostsNamespace+ )) as { metadata: { uid: string } }+ return created.metadata.uid+ }++ function issueHccRefresh(host: string, hostUid: string): string {+ return mod.jwt.issueMcpHostRefreshJwt(mod.config.hostsNamespace, 'standalone', [host], {+ workflowControlScopes: ['workflow:list', 'oauth:user-token'],+ hccCredential: { hostUid },+ }).token+ }++ function refresh(token: string) {+ return request(app)+ .post('/api/v1/workflow-auth/refresh')+ .set('Authorization', `Bearer ${token}`)+ .send()+ }++ async function revokedRow(jti: string): Promise<{ expires_at: Date } | undefined> {+ const res = await corePool.query<{ expires_at: Date }>(+ 'SELECT expires_at FROM workflow_revoked_refresh_jtis WHERE jti = $1',+ [jti]+ )+ return res.rows[0]+ }++ it('F2g: concurrent refreshes of the same HCC jti yield exactly one 200', async () => {+ const hostUid = await seedHost('race-host')+ const token = issueHccRefresh('race-host', hostUid)++ // Hold every Host read until all requests have passed verify, so they all+ // reach the consume step together and only the table's atomic INSERT can+ // pick the winner (otherwise the first request finishes before the others+ // verify, and the revoked-jti cache answers instead).+ const racers = 3+ const realGet = gateway.getResource.bind(gateway)+ let arrived = 0+ let release!: () => void+ const allArrived = new Promise<void>(resolve => {+ release = resolve+ })+ vi.spyOn(gateway, 'getResource').mockImplementation(async (...args) => {+ arrived += 1+ if (arrived === racers) release()+ await allArrived+ return realGet(...args)+ })++ const results = await Promise.all(Array.from({ length: racers }, () => refresh(token)))+ const statuses = results.map(r => r.status).sort()++ expect(statuses).toEqual([200, 401, 401])+ const winner = results.find(r => r.status === 200)!+ expect(mod.jwt.verifyMcpHostControlJwt(winner.body.mcpHostControlToken)?.host_uid).toBe(hostUid)+ })++ it('F2d: a transient Host error answers 503 and leaves no revocation row; the retry succeeds once', async () => {+ const hostUid = await seedHost('blip-host')+ const token = issueHccRefresh('blip-host', hostUid)+ const { jti } = (await mod.jwt.verifyMcpHostRefreshJwt(token)) as { jti: string }+ gateway.failGetResource(+ 'hosts',+ Object.assign(new Error('apiserver down'), { statusCode: 503 })+ )++ const failed = await refresh(token)+ expect(failed.status).toBe(503)+ expect(failed.body).toEqual({ error: 'host_state_unavailable' })+ expect(await revokedRow(jti)).toBeUndefined()++ const retried = await refresh(token)+ expect(retried.status).toBe(200)+ expect(await revokedRow(jti)).toBeDefined()++ expect((await refresh(token)).status).toBe(401)+ })++ it('F2c: a recreated Host (new uid) gets 401 and the refresh is not consumed', async () => {+ const oldUid = await seedHost('reborn-host')+ const token = issueHccRefresh('reborn-host', oldUid)+ const { jti } = (await mod.jwt.verifyMcpHostRefreshJwt(token)) as { jti: string }+ await gateway.deleteResource('hosts', 'reborn-host', mod.config.hostsNamespace)+ await seedHost('reborn-host')++ const res = await refresh(token)+ expect(res.status).toBe(401)+ expect(await revokedRow(jti)).toBeUndefined()+ })++ it('keeps the revocation row for the whole reissue window: expires_at = exp + reissue grace', async () => {+ const hostUid = await seedHost('floor-host')+ const token = issueHccRefresh('floor-host', hostUid)+ const claims = (await mod.jwt.verifyMcpHostRefreshJwt(token)) as { jti: string; exp: number }+ expect(claims.exp).toBeGreaterThan(Math.floor(Date.now() / 1000))++ const res = await refresh(token)+ expect(res.status).toBe(200)++ // Reissue accepts this refresh until exp + grace, so a row that the expiry+ // cron could delete at plain exp would let it be replayed after a restart.+ const row = await revokedRow(claims.jti)+ expect(row).toBeDefined()+ const storedSeconds = Math.floor(new Date(row!.expires_at).getTime() / 1000)+ expect(storedSeconds).toBe(claims.exp + REISSUE_GRACE_SECONDS)+ })++ it('floors expires_at at now + reissue grace for a refresh consumed on reissue after its exp', async () => {+ const hostUid = await seedHost('late-host')+ const realNow = Date.now()+ // Sign so that exp is 60 s in the past: still inside the reissue grace.+ const clock = vi+ .spyOn(Date, 'now')+ .mockReturnValue(realNow - (mod.config.mcpHostJwtRefreshTtlSec + 60) * 1000)+ let token: string+ try {+ token = issueHccRefresh('late-host', hostUid)+ } finally {+ clock.mockRestore()+ }+ const { jti } = jwtDecode(token)++ const res = await request(app)+ .post('/api/v1/workflow-auth/reissue')+ .set('Authorization', `Bearer ${token}`)+ .send({ host_ref: 'late-host' })+ expect(res.status).toBe(200)++ const row = await revokedRow(jti)+ expect(row).toBeDefined()+ const storedSeconds = Math.floor(new Date(row!.expires_at).getTime() / 1000)+ expect(storedSeconds).toBeGreaterThanOrEqual(+ Math.floor(realNow / 1000) + REISSUE_GRACE_SECONDS - 5+ )+ })+})diff --git a/control-api/test/routes.mcp-host.renewal.refresh.rate-limit.test.ts b/control-api/test/routes.mcp-host.renewal.refresh.rate-limit.test.tsindex 086f972f3..ff2bc5dc7 100644--- a/control-api/test/routes.mcp-host.renewal.refresh.rate-limit.test.ts+++ b/control-api/test/routes.mcp-host.renewal.refresh.rate-limit.test.ts@@ -19,7 +19,7 @@ vi.mock('../src/services/notificationEmitter.js', () => ({// DB pool is now called for TWO things by the refresh endpoint:// 1. rate_limit_buckets INSERT ... RETURNING count (rate limiter middleware)-// 2. workflow_revoked_refresh_jtis INSERT (JTI consumption)+// 2. workflow_revoked_refresh_jtis SELECT / INSERT (JTI verify, then consumption)// The mock dispatches on SQL fragment so each call returns the right shape.const rateLimitCounts = new Map<string, number>()const consumedJtis = new Set<string>()@@ -40,6 +40,11 @@ const mockPoolQuery = vi.fn(async (sql: unknown, params?: unknown[]) => {Array.isArray(params) && typeof params[0] === 'string'? params[0]: `unknown-${mockPoolQuery.mock.calls.length}`+ // The route verifies (SELECT, read-only) before it consumes (INSERT).+ if (/^\s*SELECT/i.test(text)) {+ const hit = consumedJtis.has(jti)+ return { rows: hit ? [{ '?column?': 1 }] : [], rowCount: hit ? 1 : 0 }+ }if (consumedJtis.has(jti)) {return { rows: [], rowCount: 0 }}diff --git a/control-api/test/routes.mcp-host.renewal.reissue.test.ts b/control-api/test/routes.mcp-host.renewal.reissue.test.tsindex aa8ee9870..37839b897 100644--- a/control-api/test/routes.mcp-host.renewal.reissue.test.ts+++ b/control-api/test/routes.mcp-host.renewal.reissue.test.ts@@ -3,12 +3,17 @@ import jwt from 'jsonwebtoken'import request from 'supertest'import { createApp } from '../src/app.js'import { config } from '../src/config.js'+import { mcpHostJwtReissueTotal } from '../src/observability/metrics.js'import {MCP_HOST_CREDENTIAL_CAPABILITY,MCP_HOST_HCC_AUDIENCE,MCP_HOST_WORKFLOW_AUDIENCE,+ type McpHostControlScope,issueMcpHostAccessJwt,+ issueMcpHostRefreshJwt,+ verifyMcpHostControlJwt,} from '../src/utils/auth/mcpHostJwtToken.js'+import { captureRequestLogs } from './helpers/requestLogCapture.js'import { MockGateway } from './mockGateway.js'// Preserve the real mcpHostJwtToken helpers — we want the full RS256 sign@@ -131,8 +136,36 @@ function issueExpiredRefreshToken()}+/**+ * Mint an already-expired refresh token through the real producer by moving+ * the signing clock back past the refresh TTL.+ */+async function reissueCount(result: string): Promise<number> {+ const metric = await mcpHostJwtReissueTotal.get()+ return metric.values.find(v => v.labels.result === result)?.value ?? 0+}++function issueExpiredRefreshFromProducer(+ ns: string,+ recipe: string,+ hostRefs: string[] | undefined,+ options: Parameters<typeof issueMcpHostRefreshJwt>[3],+ expiredSeconds = 60+): string {+ const realNow = Date.now()+ const clock = vi+ .spyOn(Date, 'now')+ .mockReturnValue(realNow - (config.mcpHostJwtRefreshTtlSec + expiredSeconds) * 1000)+ try {+ return issueMcpHostRefreshJwt(ns, recipe, hostRefs, options).token+ } finally {+ clock.mockRestore()+ }+}+describe('POST /api/v1/workflow-auth/reissue', () => {let app: ReturnType<typeof createApp>+ let gateway: MockGatewayafterEach(() => vi.restoreAllMocks())@@ -143,9 +176,29 @@ describe('POST /api/v1/workflow-auth/reissue', () => {consumedJtis.clear()conflictOnInsertJtis.clear()throwOnConsumeInsert = false- app = createApp(new MockGateway('mcp-server') as never)+ gateway = new MockGateway('mcp-server')+ app = createApp(gateway as never)})+ async function seedHost(name = HOST_REF): Promise<string> {+ const created = (await gateway.createResource(+ 'hosts',+ { metadata: { name }, spec: { host: name, contextRef: 'ctx-a', secretRef: `${name}-llm` } },+ config.hostsNamespace+ )) as { metadata: { uid: string } }+ return created.metadata.uid+ }++ function issueExpiredHccRefresh(+ hostUid: string,+ workflowControlScopes: McpHostControlScope[] = ['workflow:list']+ ): string {+ return issueExpiredRefreshFromProducer(HOST_NS, STANDALONE_RECIPE, [HOST_REF], {+ workflowControlScopes,+ hccCredential: { hostUid },+ })+ }+it('mints a fresh pair for a valid-but-expired refresh token', async () => {const token = issueExpiredRefreshToken()const res = await request(app)@@ -175,7 +228,8 @@ describe('POST /api/v1/workflow-auth/reissue', () => {})it('mints a fresh pair for an HCC standalone host using host_ref binding', async () => {- const token = issueExpiredRefreshToken(HOST_NS, STANDALONE_RECIPE, 60, [HOST_REF])+ const hostUid = await seedHost()+ const token = issueExpiredHccRefresh(hostUid)const res = await request(app).post('/api/v1/workflow-auth/reissue').set('Authorization', `Bearer ${token}`)@@ -190,7 +244,8 @@ describe('POST /api/v1/workflow-auth/reissue', () => {})it('also accepts camelCase hostRef field for HCC standalone reissue', async () => {- const token = issueExpiredRefreshToken(HOST_NS, STANDALONE_RECIPE, 60, [HOST_REF])+ const hostUid = await seedHost()+ const token = issueExpiredHccRefresh(hostUid)const res = await request(app).post('/api/v1/workflow-auth/reissue').set('Authorization', `Bearer ${token}`)@@ -199,15 +254,29 @@ describe('POST /api/v1/workflow-auth/reissue', () => {expect(res.status).toBe(200)})- it('preserves HCC audience, Host UID, and capability through bounded reissue', async () => {- const token = issueExpiredRefreshToken(- HOST_NS,- STANDALONE_RECIPE,- 60,- [HOST_REF],- ['workflow:list'],- { hostUid: 'signed-host-uid' }- )+ it('F2e: rejects a hosts-namespace standalone refresh that lacks the HCC audience', async () => {+ await seedHost()+ // Pre-host_uid chain shape: the producer still emits it without an HCC credential.+ const token = issueExpiredRefreshFromProducer(HOST_NS, STANDALONE_RECIPE, [HOST_REF], {+ workflowControlScopes: ['workflow:list'],+ })+ const lineageBefore = await reissueCount('lineage_without_audience')+ const mismatchBefore = await reissueCount('host_mismatch')+ const res = await request(app)+ .post('/api/v1/workflow-auth/reissue')+ .set('Authorization', `Bearer ${token}`)+ .send({ host_ref: HOST_REF })++ expect(res.status).toBe(401)+ expect(res.body).toEqual({ error: 'Unauthorized' })+ expect(consumedJtis.size).toBe(0)+ expect(await reissueCount('lineage_without_audience')).toBe(lineageBefore + 1)+ expect(await reissueCount('host_mismatch')).toBe(mismatchBefore)+ })++ it('preserves HCC audience, Host UID, and capability through bounded reissue (F2b)', async () => {+ const hostUid = await seedHost()+ const token = issueExpiredHccRefresh(hostUid)const res = await request(app).post('/api/v1/workflow-auth/reissue').set('Authorization', `Bearer ${token}`)@@ -221,9 +290,95 @@ describe('POST /api/v1/workflow-auth/reissue', () => {for (const encoded of [res.body.accessToken, res.body.refreshToken]) {const claims = jwt.decode(encoded) as Record<string, unknown>expect(claims.aud).toEqual([MCP_HOST_WORKFLOW_AUDIENCE, MCP_HOST_HCC_AUDIENCE])- expect(claims.host_uid).toBe('signed-host-uid')+ expect(claims.host_uid).toBe(hostUid)expect(claims.mcpCapabilities).toEqual([MCP_HOST_CREDENTIAL_CAPABILITY])}+ const control = jwt.decode(res.body.mcpHostControlToken) as Record<string, unknown>+ expect(control.host_uid).toBe(hostUid)+ expect(control.mcpCapabilities).toBeUndefined()+ expect(verifyMcpHostControlJwt(res.body.mcpHostControlToken)?.host_uid).toBe(hostUid)+ })++ it('F2c: rejects an HCC reissue whose Host no longer exists, without consuming the jti', async () => {+ const hostUid = await seedHost()+ const token = issueExpiredHccRefresh(hostUid)+ await gateway.deleteResource('hosts', HOST_REF, config.hostsNamespace)+ const mismatchBefore = await reissueCount('host_mismatch')++ const res = await request(app)+ .post('/api/v1/workflow-auth/reissue')+ .set('Authorization', `Bearer ${token}`)+ .send({ host_ref: HOST_REF })++ expect(res.status).toBe(401)+ expect(res.body).toEqual({ error: 'Unauthorized' })+ expect(consumedJtis.size).toBe(0)+ expect(await reissueCount('host_mismatch')).toBe(mismatchBefore + 1)+ })++ it('F2c: rejects an HCC reissue after the Host was recreated under the same name', async () => {+ const oldUid = await seedHost()+ const token = issueExpiredHccRefresh(oldUid)+ await gateway.deleteResource('hosts', HOST_REF, config.hostsNamespace)+ expect(await seedHost()).not.toBe(oldUid)++ const res = await request(app)+ .post('/api/v1/workflow-auth/reissue')+ .set('Authorization', `Bearer ${token}`)+ .send({ host_ref: HOST_REF })++ expect(res.status).toBe(401)+ expect(res.body).toEqual({ error: 'Unauthorized' })+ })++ it('answers 503 on a transient Host read error and leaves the expired refresh reusable', async () => {+ const hostUid = await seedHost()+ const token = issueExpiredHccRefresh(hostUid)+ gateway.failGetResource(+ 'hosts',+ Object.assign(new Error('apiserver down'), { statusCode: 503 })+ )++ const failed = await request(app)+ .post('/api/v1/workflow-auth/reissue')+ .set('Authorization', `Bearer ${token}`)+ .send({ host_ref: HOST_REF })+ expect(failed.status).toBe(503)+ expect(failed.body).toEqual({ error: 'host_state_unavailable' })+ expect(consumedJtis.size).toBe(0)++ const retried = await request(app)+ .post('/api/v1/workflow-auth/reissue')+ .set('Authorization', `Bearer ${token}`)+ .send({ host_ref: HOST_REF })+ expect(retried.status).toBe(200)+ })++ it('E2: strips oauth:user-token from the control token of a reissued WRC chain and logs it', async () => {+ const token = issueExpiredRefreshFromProducer(NS, RECIPE, undefined, {+ workflowControlScopes: ['workflow:list', 'oauth:user-token'],+ })+ const logs = captureRequestLogs()+ let res: request.Response+ try {+ res = await request(app)+ .post('/api/v1/workflow-auth/reissue')+ .set('Authorization', `Bearer ${token}`)+ .send({ recipe_name: RECIPE })+ } finally {+ logs.restore()+ }++ expect(res.status).toBe(200)+ expect(verifyMcpHostControlJwt(res.body.mcpHostControlToken)?.scopes).toEqual(['workflow:list'])+ for (const encoded of [res.body.accessToken, res.body.refreshToken]) {+ const claims = jwt.decode(encoded) as Record<string, unknown>+ expect(claims.workflowControlScopes).toEqual(['workflow:list', 'oauth:user-token'])+ }+ expect(logs.warn).toHaveBeenCalledWith(+ expect.objectContaining({ event: 'oauth_user_token_scope_stripped', route: 'reissue' }),+ expect.any(String)+ )})it('returns 401 when the Authorization header is missing', async () => {diff --git a/control-api/test/routes.mcp-host.user-approval-requests.test.ts b/control-api/test/routes.mcp-host.user-approval-requests.test.tsindex 192aeb533..c8d863a16 100644--- a/control-api/test/routes.mcp-host.user-approval-requests.test.ts+++ b/control-api/test/routes.mcp-host.user-approval-requests.test.ts@@ -48,25 +48,38 @@ vi.mock('../src/services/workflowApprovalMediumTeamsVerificationService.js', ()vi.mock('../src/services/workflowApprovalTelegramChannelGateService.js', () => ({verifyTelegramOperationalChannelBinding: vi.fn(),}))-vi.mock('../src/utils/auth/mcpHostJwtToken.js', async () => {- const actual = await vi.importActual<typeof import('../src/utils/auth/mcpHostJwtToken.js')>(- '../src/utils/auth/mcpHostJwtToken.js'- )- return {- ...actual,- consumeMcpHostRefreshJwt: vi.fn(),- }-})vi.mock('../src/services/notificationEmitter.js', () => ({emitNotification: vi.fn().mockResolvedValue(undefined),enqueueApprovalRequestedNotification: vi.fn().mockResolvedValue(undefined),enqueueApprovalUpdatedNotification: vi.fn().mockResolvedValue(undefined),}))-// Mock DB pool — refresh token revocation now uses DB-backed storage+// Mock DB pool — refresh token revocation now uses DB-backed storage. The+// refresh-jti table is modelled by SQL shape (SELECT = revoked?, INSERT ... ON+// CONFLICT DO NOTHING = consume) so the real verify-then-consume path runs.+const consumedRefreshJtis = new Set<string>()+let failNextRefreshJtiInsert: Error | null = nullvi.mock('../src/db.js', () => ({pool: {- query: vi.fn().mockResolvedValue({ rows: [], rowCount: 0 }),+ query: vi.fn(async (sql: unknown, params?: unknown[]) => {+ const text = typeof sql === 'string' ? sql : ''+ if (/workflow_revoked_refresh_jtis/i.test(text)) {+ const jti = Array.isArray(params) && typeof params[0] === 'string' ? params[0] : ''+ if (/^\s*SELECT/i.test(text)) {+ const hit = consumedRefreshJtis.has(jti)+ return { rows: hit ? [{ '?column?': 1 }] : [], rowCount: hit ? 1 : 0 }+ }+ if (failNextRefreshJtiInsert) {+ const err = failNextRefreshJtiInsert+ failNextRefreshJtiInsert = null+ throw err+ }+ if (consumedRefreshJtis.has(jti)) return { rows: [], rowCount: 0 }+ consumedRefreshJtis.add(jti)+ return { rows: [{ jti }], rowCount: 1 }+ }+ return { rows: [], rowCount: 0 }+ }),connect: vi.fn(),},withTransaction: vi.fn(),@@ -120,9 +133,8 @@ describe('User Approval Request Routes', () => {beforeEach(async () => {vi.clearAllMocks()- vi.mocked(mcpHostJwt.consumeMcpHostRefreshJwt).mockImplementation(async token =>- mcpHostJwt.verifyMcpHostRefreshJwt(token)- )+ consumedRefreshJtis.clear()+ failNextRefreshJtiInsert = nullvi.mocked(userApprovalRequestService.parseWorkflowTriggerIntent).mockImplementation((payload: unknown) => {const record =@@ -206,19 +218,6 @@ describe('User Approval Request Routes', () => {describe('POST /api/v1/workflow-auth/refresh', () => {it('issues new tokens with valid refresh token', async () => {const { refreshToken } = issueTestTokens()- vi.mocked(mcpHostJwt.consumeMcpHostRefreshJwt).mockResolvedValueOnce({- sub: `${NS}/${RECIPE}`,- recipeNamespace: NS,- recipeName: RECIPE,- hostRefs: [`${NS}/${RECIPE}`],- scope: 'workflow:approval:refresh',- workflowControlScopes: ['workflow:list', 'workflow:read'],- mcpCapabilities: [],- iss: 'test-issuer',- aud: 'workflow-approvals',- jti: 'jti-1',- exp: Math.floor(Date.now() / 1000) + 3600,- })const res = await request(app).post('/api/v1/workflow-auth/refresh').set('Authorization', `Bearer ${refreshToken}`)@@ -231,21 +230,21 @@ describe('User Approval Request Routes', () => {})it('preserves HCC authority only from verified refresh lineage and ignores body upgrades', async () => {- const { refreshToken } = issueTestTokens()- vi.mocked(mcpHostJwt.consumeMcpHostRefreshJwt).mockResolvedValueOnce({- sub: 'mcp-host/standalone',- recipeNamespace: 'mcp-host',- recipeName: 'standalone',- hostRefs: ['chatllm'],- host_uid: 'signed-host-uid',- scope: 'workflow:approval:refresh',- workflowControlScopes: ['workflow:list'],- mcpCapabilities: [mcpHostJwt.MCP_HOST_CREDENTIAL_CAPABILITY],- iss: 'control-api',- aud: [mcpHostJwt.MCP_HOST_WORKFLOW_AUDIENCE, mcpHostJwt.MCP_HOST_HCC_AUDIENCE],- jti: 'hcc-refresh-jti',- exp: Math.floor(Date.now() / 1000) + 3600,- })+ const host = (await gateway.createResource(+ 'hosts',+ {+ metadata: { name: SHARED_HOST },+ spec: { host: SHARED_HOST, contextRef: 'ctx-a', secretRef: `${SHARED_HOST}-llm` },+ },+ SHARED_HOST_NS+ )) as { metadata: { uid: string } }+ const hostUid = host.metadata.uid+ const refreshToken = mcpHostJwt.issueMcpHostRefreshJwt(+ SHARED_HOST_NS,+ 'standalone',+ [SHARED_HOST],+ { workflowControlScopes: ['workflow:list'], hccCredential: { hostUid } }+ ).tokenconst res = await request(app).post('/api/v1/workflow-auth/refresh')@@ -259,16 +258,17 @@ describe('User Approval Request Routes', () => {mcpHostJwt.MCP_HOST_WORKFLOW_AUDIENCE,mcpHostJwt.MCP_HOST_HCC_AUDIENCE,])- expect(claims.host_uid).toBe('signed-host-uid')+ expect(claims.host_uid).toBe(hostUid)expect(claims.mcpCapabilities).toEqual([mcpHostJwt.MCP_HOST_CREDENTIAL_CAPABILITY])}+ // The control token is bound to the Host uid but never carries the+ // credential-reader capability.const control = jwt.decode(res.body.mcpHostControlToken) as Record<string, unknown>- expect(control.host_uid).toBeUndefined()+ expect(control.host_uid).toBe(hostUid)expect(control.mcpCapabilities).toBeUndefined()})it('rejects invalid refresh token', async () => {- vi.mocked(mcpHostJwt.consumeMcpHostRefreshJwt).mockResolvedValueOnce(null)const res = await request(app).post('/api/v1/workflow-auth/refresh').set('Authorization', 'Bearer invalid-token')@@ -283,11 +283,12 @@ describe('User Approval Request Routes', () => {})it('propagates refresh-token consumption errors to the error handler', async () => {- vi.mocked(mcpHostJwt.consumeMcpHostRefreshJwt).mockRejectedValueOnce(new Error('db down'))+ const { refreshToken } = issueTestTokens()+ failNextRefreshJtiInsert = new Error('db down')const res = await request(app).post('/api/v1/workflow-auth/refresh')- .set('Authorization', 'Bearer syntactically-present')+ .set('Authorization', `Bearer ${refreshToken}`).send()expect(res.status).toBe(500)@@ -296,7 +297,6 @@ describe('User Approval Request Routes', () => {it('rejects access token used as refresh', async () => {const { accessToken } = issueTestTokens()- vi.mocked(mcpHostJwt.consumeMcpHostRefreshJwt).mockResolvedValueOnce(null)const res = await request(app).post('/api/v1/workflow-auth/refresh').set('Authorization', `Bearer ${accessToken}`)diff --git a/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts b/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.tsindex 2b24080b8..2b2b58f3e 100644--- a/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts+++ b/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts@@ -91,8 +91,9 @@ const USER = 'alice'type Flavor = 'user' | 'context'function controlToken(): string {- return issueMcpHostControlJwt('mcp-host', 'standalone', ['mcp-host/standalone'], {+ return issueMcpHostControlJwt('mcp-host', 'standalone', ['agent-host'], {scopes: ['oauth:user-token'],+ hccCredential: { hostUid: 'uid-agent-host' },}).token}diff --git a/control-api/test/routes.mcpOauth.test.ts b/control-api/test/routes.mcpOauth.test.tsindex 696caeded..51da560f2 100644--- a/control-api/test/routes.mcpOauth.test.ts+++ b/control-api/test/routes.mcpOauth.test.ts@@ -70,9 +70,13 @@ async function liveUid(gateway: MockGateway, name: string): Promise<string> {return cr.metadata.uid}-// Control JWT derived from the REAL minter (T1) — no hand-forged token.+// Control JWT derived from the REAL minter (T1) — no hand-forged token. Only an+// HCC-lineage control token may carry oauth:user-token, so it is minted for a Host.function controlToken(scopes: Array<'oauth:user-token'> = ['oauth:user-token']): string {- return issueMcpHostControlJwt('mcp-host', 'standalone', ['mcp-host/standalone'], { scopes }).token+ return issueMcpHostControlJwt('mcp-host', 'standalone', ['agent-host'], {+ scopes,+ hccCredential: { hostUid: 'uid-agent-host' },+ }).token}function nonExpiredUserGrantRow(userId: string, expiresAt: Date) {@@ -131,9 +135,11 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {const tokenA = issueMcpHostControlJwt('mcp-host', 'standalone', ['host-a'], {scopes: ['oauth:user-token'],+ hccCredential: { hostUid: 'uid-host-a' },}).tokenconst tokenB = issueMcpHostControlJwt('mcp-host', 'standalone', ['host-b'], {scopes: ['oauth:user-token'],+ hccCredential: { hostUid: 'uid-host-b' },}).tokenawait request(app)