Skip to content

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

TypeScript

test: close NP-08 validation gaps

Alfredo Lopez7924c91e1b5c
diff --git a/Makefile b/Makefile
index b92b177d7..26f191fc8 100644
--- a/Makefile
+++ b/Makefile
@@ -434,6 +434,9 @@ minikube-t2: ## Run the local development T0, Real PostgreSQL T1, and exact-head
@MINIKUBE_PROFILE="$(MINIKUBE_PROFILE)" CONTROL_API_REAL_PG_CONTEXT="$(CONTROL_API_REAL_PG_CONTEXT)" \
scripts/minikube/t2.sh
+.PHONY: minikube-t2-np08-hcc-authorization
+minikube-t2-np08-hcc-authorization: minikube-t2 ## Run canonical T2 including the required deployed NP-08 Host-to-HCC authorization journey
+
.PHONY: minikube-t2-real-postgres
minikube-t2-real-postgres: ## Run the explicit local Real PostgreSQL lane without changing CI's DSN contract
@MINIKUBE_PROFILE="$(MINIKUBE_PROFILE)" CONTROL_API_REAL_PG_CONTEXT="$(CONTROL_API_REAL_PG_CONTEXT)" \
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 94317002b..45c93ac23 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.470",
+ "version": "0.1.471",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.470",
+ "version": "0.1.471",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index 32f95cd2f..d4f9cf5ff 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.470",
+ "version": "0.1.471",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/test/mcpHostJwtToken.hostRefs.test.ts b/control-api/test/mcpHostJwtToken.hostRefs.test.ts
index ac31aebcf..9bc462266 100644
--- a/control-api/test/mcpHostJwtToken.hostRefs.test.ts
+++ b/control-api/test/mcpHostJwtToken.hostRefs.test.ts
@@ -378,6 +378,68 @@ describe('mcpHostJwtToken — hostRefs JWT claim', () => {
const claims = await verifyMcpHostRefreshJwt(token)
expect(claims).toBeNull()
})
+
+ it.each([
+ {
+ label: 'workflow-only audience with injected HCC claims',
+ audience: MCP_HOST_WORKFLOW_AUDIENCE,
+ recipeNamespace: config.hostsNamespace,
+ recipeName: 'standalone',
+ hostRefs: ['chatllm'],
+ hostUid: 'host-uid-chatllm',
+ capabilities: [MCP_HOST_CREDENTIAL_CAPABILITY],
+ },
+ {
+ label: 'HCC audience without the bound Host UID',
+ audience: [MCP_HOST_WORKFLOW_AUDIENCE, MCP_HOST_HCC_AUDIENCE],
+ recipeNamespace: config.hostsNamespace,
+ recipeName: 'standalone',
+ hostRefs: ['chatllm'],
+ hostUid: undefined,
+ capabilities: [MCP_HOST_CREDENTIAL_CAPABILITY],
+ },
+ {
+ label: 'HCC audience with a workflow recipe binding',
+ audience: [MCP_HOST_WORKFLOW_AUDIENCE, MCP_HOST_HCC_AUDIENCE],
+ recipeNamespace: 'sandbox-recipes',
+ recipeName: 'recipe-a',
+ hostRefs: ['sandbox-recipes/recipe-a'],
+ hostUid: 'host-uid-chatllm',
+ capabilities: [MCP_HOST_CREDENTIAL_CAPABILITY],
+ },
+ ])('rejects $label', async candidate => {
+ const token = jwt.sign(
+ {
+ sub: `${candidate.recipeNamespace}/${candidate.recipeName}`,
+ recipeNamespace: candidate.recipeNamespace,
+ recipeName: candidate.recipeName,
+ hostRefs: candidate.hostRefs,
+ scope: 'workflow:approval:refresh',
+ workflowControlScopes: [],
+ ...(candidate.hostUid ? { host_uid: candidate.hostUid } : {}),
+ mcpCapabilities: candidate.capabilities,
+ },
+ config.adminJwtPrivateKey,
+ {
+ algorithm: 'RS256',
+ issuer: config.adminJwtIssuer,
+ audience: candidate.audience,
+ expiresIn: 300,
+ jwtid: `invalid-hcc-refresh-${candidate.label}`,
+ }
+ )
+
+ await expect(verifyMcpHostRefreshJwt(token)).resolves.toBeNull()
+ })
+
+ it('does not treat a control token as an access or refresh credential', async () => {
+ const { token } = issueMcpHostControlJwt(config.hostsNamespace, 'standalone', ['chatllm'], {
+ scopes: ['workflow:read'],
+ })
+
+ expect(verifyMcpHostAccessJwt(token)).toBeNull()
+ await expect(verifyMcpHostRefreshJwt(token)).resolves.toBeNull()
+ })
})
describe('verifyExpiredMcpHostRefreshJwtDetailed', () => {
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.ts
index 0ec31917d..118c5d653 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
@@ -6,7 +6,16 @@ import { config } from '../src/config.js'
import { findMembership } from '../src/services/directory/membership.js'
import * as userApprovalRequestService from '../src/services/userApprovalRequestService.js'
import { signExternalSessionToken } from '../src/utils/auth/externalSessionAuthToken.js'
-import { issueMcpHostAccessJwt, issueMcpHostRefreshJwt } from '../src/utils/auth/mcpHostJwtToken.js'
+import {
+ MCP_HOST_CREDENTIAL_CAPABILITY,
+ MCP_HOST_HCC_AUDIENCE,
+ MCP_HOST_WORKFLOW_AUDIENCE,
+ issueMcpHostAccessJwt,
+ issueMcpHostRefreshJwt,
+ verifyMcpHostAccessJwt,
+ verifyMcpHostControlJwt,
+ verifyMcpHostRefreshJwt,
+} from '../src/utils/auth/mcpHostJwtToken.js'
import { MockGateway } from './mockGateway.js'
// Mock userApprovalRequestService for all tests
@@ -549,6 +558,55 @@ describe('Security: Refresh token rotation', () => {
expect(res.status).toBe(200)
expect(res.body.accessToken).toBeDefined()
expect(res.body.refreshToken).toBeDefined()
+ for (const encoded of [res.body.accessToken, res.body.refreshToken]) {
+ const claims = jwt.decode(encoded) as Record<string, unknown>
+ expect(claims.aud).toBe(MCP_HOST_WORKFLOW_AUDIENCE)
+ expect(claims.host_uid).toBeUndefined()
+ expect(claims.mcpCapabilities).toBeUndefined()
+ }
+ })
+
+ it('preserves signed HCC lineage across ordinary rotation and keeps the control token separate', 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 res = await request(app)
+ .post('/api/v1/workflow-auth/refresh')
+ .set('Authorization', `Bearer ${refreshToken}`)
+ .send({ 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.host_uid).toBe(hostUid)
+ expect(claims.mcpCapabilities).toEqual([MCP_HOST_CREDENTIAL_CAPABILITY])
+ expect(claims.workflowControlScopes).toEqual(workflowControlScopes)
+ }
+
+ const control = jwt.decode(res.body.mcpHostControlToken) as Record<string, unknown>
+ expect(control.aud).toBe('mcp-host')
+ expect(control.hostRefs).toEqual([hostRef])
+ expect(control.scopes).toEqual(workflowControlScopes)
+ expect(control.host_uid).toBeUndefined()
+ expect(control.mcpCapabilities).toBeUndefined()
+
+ expect(verifyMcpHostAccessJwt(res.body.mcpHostControlToken)).toBeNull()
+ await expect(verifyMcpHostRefreshJwt(res.body.mcpHostControlToken)).resolves.toBeNull()
+ expect(verifyMcpHostControlJwt(res.body.accessToken)).toBeNull()
+ expect(verifyMcpHostControlJwt(res.body.refreshToken)).toBeNull()
})
it('rejects access token used as refresh token (scope mismatch)', async () => {
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 42704f637..a1cd7f004 100644
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.228",
+ "version": "0.1.229",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.228",
+ "version": "0.1.229",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index d6ee826bd..93c3c7e54 100644
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.228",
+ "version": "0.1.229",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --git a/host-context-controller/src/mcpAuthorization.test.ts b/host-context-controller/src/mcpAuthorization.test.ts
index 92ce1bb5e..a7c50f80d 100644
--- a/host-context-controller/src/mcpAuthorization.test.ts
+++ b/host-context-controller/src/mcpAuthorization.test.ts
@@ -1,10 +1,11 @@
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
import type { VerifiedMcpHostPrincipal } from './mcpApiAuthentication'
import {
type AuthorityContext,
type AuthorityHost,
type AuthorityMcpServer,
type AuthoritySecret,
+ type AuthoritySecretMetadata,
McpAuthorizationService,
type McpAuthorizationStore,
toPublicMcpTransport,
@@ -71,7 +72,7 @@ const secret: AuthoritySecret = {
class FakeStore implements McpAuthorizationStore {
secretMetadataReads = 0
secretValueReads = 0
- secretMetadataSequence: Array<AuthoritySecret | null> = [secret]
+ secretMetadataSequence: Array<AuthoritySecretMetadata | null> = [secret]
secretSequence: Array<AuthoritySecret | null> = [secret]
hostSequence: Array<AuthorityHost | null> | null = null
contextSequence: Array<AuthorityContext | null> | null = null
@@ -115,6 +116,21 @@ class FakeStore implements McpAuthorizationStore {
}
}
+async function expectCredentialFailure(
+ service: McpAuthorizationService,
+ code: string
+): Promise<void> {
+ const error = await service.getCredential(principal, 'server-a').then(
+ () => null,
+ reason => reason
+ )
+ expect(error).toMatchObject({ code })
+ expect(error).not.toHaveProperty('token')
+ expect(JSON.stringify(error)).not.toContain(
+ Buffer.from(secret.data.token, 'base64').toString('utf8')
+ )
+}
+
describe('McpAuthorizationService', () => {
it('keeps two Host/Context grant sets disjoint in both directions', async () => {
const storeA = new FakeStore()
@@ -215,6 +231,63 @@ describe('McpAuthorizationService', () => {
expect(store.secretValueReads).toBe(0)
})
+ it.each(['host', 'context', 'server', 'secret-metadata', 'secret-value'] as const)(
+ 'fails closed without disclosing a credential when the %s store read errors',
+ async read => {
+ const store = new FakeStore()
+ if (read === 'host')
+ vi.spyOn(store, 'readHost').mockRejectedValueOnce(new Error('read failed'))
+ if (read === 'context') {
+ vi.spyOn(store, 'readContext').mockRejectedValueOnce(new Error('read failed'))
+ }
+ if (read === 'server') {
+ vi.spyOn(store, 'readMcpServer').mockRejectedValueOnce(new Error('read failed'))
+ }
+ if (read === 'secret-metadata') {
+ vi.spyOn(store, 'readSecretMetadata').mockRejectedValueOnce(new Error('read failed'))
+ }
+ if (read === 'secret-value') {
+ vi.spyOn(store, 'readSecret').mockRejectedValueOnce(new Error('read failed'))
+ }
+ const service = new McpAuthorizationService(store)
+
+ await expectCredentialFailure(service, 'authorization_unavailable')
+ if (read !== 'secret-value') expect(store.secretValueReads).toBe(0)
+ if (read === 'host' || read === 'context' || read === 'server') {
+ expect(store.secretMetadataReads).toBe(0)
+ }
+ }
+ )
+
+ it.each([
+ ['missing secretRef', { auth: { type: 'bearer' as const } }, secret],
+ ['missing Secret metadata', {}, null],
+ ])('rejects %s before any Secret value read', async (_label, serverOverride, metadataValue) => {
+ const store = new FakeStore()
+ store.serverObject = { ...server, ...(serverOverride as Partial<AuthorityMcpServer>) }
+ store.secretMetadataSequence = metadataValue
+ ? [metadataValue as AuthoritySecretMetadata]
+ : [null]
+ const service = new McpAuthorizationService(store)
+
+ await expectCredentialFailure(service, 'credential_unavailable')
+ expect(store.secretValueReads).toBe(0)
+ })
+
+ it.each([
+ ['missing configured key', { other: Buffer.from('other').toString('base64') }],
+ ['empty base64', { token: '' }],
+ ['malformed base64', { token: 'invalid-test-token' }],
+ ['non-UTF8 base64', { token: Buffer.from([0xff]).toString('base64') }],
+ ])('rejects %s without returning Secret data', async (_label, data) => {
+ const store = new FakeStore()
+ store.secretSequence = [{ ...secret, data }]
+ const service = new McpAuthorizationService(store)
+
+ await expectCredentialFailure(service, 'credential_unavailable')
+ expect(store.secretValueReads).toBe(1)
+ })
+
it('uses the same opaque denial for a cross-Context and an unknown target', async () => {
const store = new FakeStore()
const service = new McpAuthorizationService(store)
@@ -373,6 +446,26 @@ describe('McpAuthorizationService', () => {
expect(store.secretValueReads).toBe(1)
})
+ it('rejects a credential when the Host is rebound during the post-read fence', async () => {
+ const store = new FakeStore()
+ store.hostSequence = [host, { ...host, metadata: meta('replacement-host-uid', '1') }]
+ const service = new McpAuthorizationService(store)
+
+ await expectCredentialFailure(service, 'unauthorized')
+ expect(store.secretMetadataReads).toBe(1)
+ expect(store.secretValueReads).toBe(1)
+ })
+
+ it('rejects a credential when the Context allowlist changes during the post-read fence', async () => {
+ const store = new FakeStore()
+ store.contextSequence = [context, { ...context, mcpServers: [] }]
+ const service = new McpAuthorizationService(store)
+
+ await expectCredentialFailure(service, 'not_found')
+ expect(store.secretMetadataReads).toBe(1)
+ expect(store.secretValueReads).toBe(1)
+ })
+
it('discards a credential when the McpServer changes during the post-read fence', async () => {
const store = new FakeStore()
store.serverSequence = [server, { ...server, metadata: meta('server-uid-a', '31') }]
diff --git a/host-context-controller/src/server.test.ts b/host-context-controller/src/server.test.ts
index 300882d6f..4202f3e30 100644
--- a/host-context-controller/src/server.test.ts
+++ b/host-context-controller/src/server.test.ts
@@ -327,6 +327,42 @@ describe('ContextMapperServer', () => {
expect(protectedRoute.store.secretValueReads).toBe(1)
})
+ it.each([
+ ['authorization_unavailable' as const, 503],
+ ['credential_unavailable' as const, 503],
+ ['not_found' as const, 404],
+ ['unauthorized' as const, 401],
+ ])('maps credential %s failures to a token-free fail-closed response', async (code, status) => {
+ const authenticator = { authenticate: () => principal } as unknown as McpApiAuthenticator
+ const authorization = {
+ getCredential: async () => {
+ throw new McpAuthorizationError(code)
+ },
+ } as unknown as McpAuthorizationService
+ server = new ContextMapperServer(
+ new FakeProvider(),
+ 0,
+ undefined,
+ undefined,
+ () => true,
+ () => true,
+ authenticator,
+ authorization
+ )
+ server.setReady(true)
+
+ const response = await invoke(server, '/api/v2/hosts/self/mcpservers/credential', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ serverName: 'server-a' }),
+ })
+
+ expect(response.statusCode).toBe(status)
+ expect(JSON.parse(response.body)).toEqual({ error: code })
+ expect(response.body).not.toContain('token')
+ expect(response.headers['Cache-Control']).toBe('no-store, private')
+ })
+
it('normalizes protected route method, media-type, and body-limit failures without a Secret read', async () => {
const protectedRoute = protectedServer()
server = protectedRoute.server
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 0d8b61fd5..56457afba 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.269",
+ "version": "0.1.270",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.269",
+ "version": "0.1.270",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index 9639271fd..f9f2c0aab 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.269",
+ "version": "0.1.270",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index 7bbc6a305..cbdb7a4d8 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -32,12 +32,7 @@ import {
projectModels,
resolveSessionModel,
} from './config/modelResolution'
-import {
- ContextMapperClient,
- ContextMapperRequestError,
- getContextMapperClient,
- isContextMapperInventoryAuthorityRevocation,
-} from './contextMapperClient'
+import { ContextMapperClient, getContextMapperClient } from './contextMapperClient'
import {
type ConversationStoreHandle,
SqliteColdStartLoader,
@@ -83,6 +78,12 @@ import {
replaceAuthoritativeMcpFleet,
runAuthoritativeMcpInitialization,
} from './mcp/authoritativeFleet'
+import {
+ createMcpAuthorityStalenessDeadline,
+ handleMcpAuthorityPollFailure,
+ isMcpAuthorityStale,
+ revokeMcpAuthorityState,
+} from './mcp/authorityLifecycle'
import { McpStatusHeartbeat } from './mcp/statusHeartbeat'
import { startMcpInitializationInBackground } from './mcpBackgroundInit'
import { IncomingMessageHandler, PendingTaskEntry } from './messageHandler'
@@ -809,67 +810,7 @@ function ensureAuthenticatedContextMapperClient(): ContextMapperClient {
return contextMapperClient
}
-export function isMcpAuthorityStale(
- lastSuccessAt: number,
- now: number,
- maxStalenessMs: number
-): boolean {
- return (
- lastSuccessAt > 0 &&
- Number.isFinite(now) &&
- Number.isFinite(maxStalenessMs) &&
- maxStalenessMs > 0 &&
- now - lastSuccessAt >= maxStalenessMs
- )
-}
-
-/**
- * Arm an absolute authority deadline from the last successful HCC snapshot.
- * The independent timeout prevents a slow or failed polling cadence from
- * extending retained authority beyond the configured staleness ceiling.
- */
-export function createMcpAuthorityStalenessDeadline(
- maxStalenessMs: number,
- onExpired: () => void,
- now: () => number = Date.now
-): { recordSuccess(successAt?: number): void; clear(): void } {
- let timer: ReturnType<typeof setTimeout> | null = null
- let deadlineAt = 0
-
- const clear = (): void => {
- if (timer !== null) clearTimeout(timer)
- timer = null
- deadlineAt = 0
- }
-
- const schedule = (): void => {
- const remaining = deadlineAt - now()
- timer = setTimeout(
- () => {
- timer = null
- if (now() < deadlineAt) {
- schedule()
- return
- }
- deadlineAt = 0
- onExpired()
- },
- Math.max(0, remaining)
- )
- }
-
- return {
- recordSuccess: (successAt = now()) => {
- clear()
- if (!Number.isFinite(successAt) || !Number.isFinite(maxStalenessMs) || maxStalenessMs <= 0) {
- return
- }
- deadlineAt = successAt + maxStalenessMs
- schedule()
- },
- clear,
- }
-}
+export { createMcpAuthorityStalenessDeadline, isMcpAuthorityStale }
const mcpAuthorityStalenessDeadline = createMcpAuthorityStalenessDeadline(
config.hccAuthorityMaxStalenessMs,
@@ -891,25 +832,31 @@ function recordMcpAuthoritySuccess(successAt: number = Date.now()): void {
* Host JWT and live Host -> Context grant snapshot.
*/
function revokeMcpAuthority(reason: string, restartPolling: boolean): void {
- mcpInitializationGeneration += 1
- stopContextMapperPolling()
- mcpAuthorityStalenessDeadline.clear()
- const closingManager = mcpManager
- mcpManager = null
- lastServerState = new Map()
- mcpAuthorityLastSuccessAt = 0
-
- if (closingManager) {
- mcpFleetCoordinator.closeManager(closingManager)
- void closingManager
- .close(cleanup => mcpFleetCoordinator.scheduleCleanup(cleanup))
- .catch(() => console.error(`[Main] MCP authority cleanup failed (reason=${reason})`))
- }
- console.warn(`[Main] MCP authority revoked (reason=${reason})`)
-
- if (restartPolling && !isShuttingDown && !config.devMode) {
- startContextMapperPolling()
- }
+ revokeMcpAuthorityState({
+ reason,
+ restartPolling,
+ invalidateInitialization: () => {
+ mcpInitializationGeneration += 1
+ },
+ stopPolling: stopContextMapperPolling,
+ clearStalenessDeadline: () => mcpAuthorityStalenessDeadline.clear(),
+ withdrawManager: () => {
+ const closingManager = mcpManager
+ mcpManager = null
+ return closingManager
+ },
+ clearServerState: () => {
+ lastServerState = new Map()
+ },
+ clearLastSuccess: () => {
+ mcpAuthorityLastSuccessAt = 0
+ },
+ coordinator: mcpFleetCoordinator,
+ onCleanupFailure: () => console.error(`[Main] MCP authority cleanup failed (reason=${reason})`),
+ onRevoked: () => console.warn(`[Main] MCP authority revoked (reason=${reason})`),
+ shouldRestartPolling: () => !isShuttingDown && !config.devMode,
+ startPolling: startContextMapperPolling,
+ })
}
async function initializeMcpServers(): Promise<void> {
@@ -1012,23 +959,18 @@ async function pollContextMapper(): Promise<void> {
recordMcpAuthoritySuccess()
}
} catch (error) {
- if (error instanceof ContextMapperRequestError && error.authorizationFailure) {
- // ContextMapperClient already revoked synchronously through its callback.
- console.warn('[Main] HCC poll rejected caller authority')
- return
- }
- if (isContextMapperInventoryAuthorityRevocation(error)) {
- revokeMcpAuthority('inventory_not_found', true)
- console.warn('[Main] HCC inventory no longer resolves live Host authority')
- return
- }
- console.error('[Main] HCC authority poll failed (reason=unavailable)')
- if (
- mcpManager &&
- isMcpAuthorityStale(mcpAuthorityLastSuccessAt, Date.now(), config.hccAuthorityMaxStalenessMs)
- ) {
- revokeMcpAuthority('authority_stale', true)
- }
+ handleMcpAuthorityPollFailure(error, {
+ hasPublishedManager: () => mcpManager !== null,
+ lastSuccessAt: () => mcpAuthorityLastSuccessAt,
+ now: Date.now,
+ maxStalenessMs: config.hccAuthorityMaxStalenessMs,
+ revoke: revokeMcpAuthority,
+ onCallerAuthorizationRejected: () =>
+ console.warn('[Main] HCC poll rejected caller authority'),
+ onInventoryAuthorityRevoked: () =>
+ console.warn('[Main] HCC inventory no longer resolves live Host authority'),
+ onUnavailable: () => console.error('[Main] HCC authority poll failed (reason=unavailable)'),
+ })
}
}
diff --git a/mcp-host/src/mcp/__tests__/authorityLifecycle.test.ts b/mcp-host/src/mcp/__tests__/authorityLifecycle.test.ts
new file mode 100644
index 000000000..3a3f0c2bf
--- /dev/null
+++ b/mcp-host/src/mcp/__tests__/authorityLifecycle.test.ts
@@ -0,0 +1,361 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { ContextMapperClient, ContextMapperRequestError } from '../../contextMapperClient'
+import type { McpServerInfo } from '../../types'
+import { AuthoritativeMcpFleetCoordinator } from '../authoritativeFleet'
+import {
+ createMcpAuthorityStalenessDeadline,
+ handleMcpAuthorityPollFailure,
+ revokeMcpAuthorityState,
+} from '../authorityLifecycle'
+import { McpClient } from '../client'
+import { McpManager } from '../manager'
+
+const securedServer: McpServerInfo = {
+ name: 'secured-server',
+ transport: { type: 'streamableHttp', url: 'http://secured-server.test/mcp' },
+ enabled: true,
+ authRequired: true,
+ credentialRevision: 'credential-revision-1',
+ status: { deployed: true, ready: true, authoritative: true },
+}
+
+function deferred(): { promise: Promise<void>; resolve(): void } {
+ let resolve!: () => void
+ const promise = new Promise<void>(resolvePromise => {
+ resolve = resolvePromise
+ })
+ return { promise, resolve }
+}
+
+function retainedClient(
+ manager: McpManager,
+ serverName = securedServer.name
+): McpClient | undefined {
+ return (
+ manager as unknown as {
+ clients: Map<string, McpClient>
+ }
+ ).clients.get(serverName)
+}
+
+function pendingClient(
+ manager: McpManager,
+ serverName = securedServer.name
+): McpClient | undefined {
+ return (
+ manager as unknown as {
+ pendingAdmissions: Map<string, { client: McpClient }>
+ }
+ ).pendingAdmissions.get(serverName)?.client
+}
+
+function createLifecycleHarness(
+ manager: McpManager,
+ coordinator = new AuthoritativeMcpFleetCoordinator(1, 1, true)
+) {
+ let currentManager: McpManager | null = manager
+ let serverState = new Map([[securedServer.name, 'credential-revision-1']])
+ let lastSuccessAt = 10_000
+ let generation = 7
+ let pollerRunning = true
+ let clearDeadline: () => void = () => undefined
+ const effects: string[] = []
+ const reasons: string[] = []
+
+ const originalCloseManager = coordinator.closeManager.bind(coordinator)
+ vi.spyOn(coordinator, 'closeManager').mockImplementation(closingManager => {
+ effects.push('coordinator-close')
+ originalCloseManager(closingManager)
+ })
+ const originalScheduleCleanup = coordinator.scheduleCleanup.bind(coordinator)
+ vi.spyOn(coordinator, 'scheduleCleanup').mockImplementation(cleanup => {
+ effects.push('cleanup-scheduled')
+ originalScheduleCleanup(cleanup)
+ })
+ const originalManagerClose = manager.close.bind(manager)
+ vi.spyOn(manager, 'close').mockImplementation(scheduleCleanup => {
+ effects.push('manager-close')
+ return originalManagerClose(scheduleCleanup)
+ })
+
+ const revoke = (reason: string, restartPolling: boolean): void => {
+ reasons.push(reason)
+ revokeMcpAuthorityState({
+ reason,
+ restartPolling,
+ invalidateInitialization: () => {
+ effects.push('generation-invalidated')
+ generation += 1
+ },
+ stopPolling: () => {
+ effects.push('polling-stopped')
+ pollerRunning = false
+ },
+ clearStalenessDeadline: () => {
+ effects.push('deadline-cleared')
+ clearDeadline()
+ },
+ withdrawManager: () => {
+ effects.push('manager-withdrawn')
+ const closingManager = currentManager
+ currentManager = null
+ return closingManager
+ },
+ clearServerState: () => {
+ effects.push('server-state-cleared')
+ serverState = new Map()
+ },
+ clearLastSuccess: () => {
+ effects.push('last-success-cleared')
+ lastSuccessAt = 0
+ },
+ coordinator,
+ onCleanupFailure: () => effects.push('cleanup-failed'),
+ onRevoked: () => effects.push('revoked'),
+ shouldRestartPolling: () => true,
+ startPolling: () => {
+ effects.push('polling-started')
+ pollerRunning = true
+ },
+ })
+ }
+
+ return {
+ coordinator,
+ effects,
+ reasons,
+ revoke,
+ setDeadlineClear: (clear: () => void) => {
+ clearDeadline = clear
+ },
+ state: () => ({
+ currentManager,
+ serverState,
+ lastSuccessAt,
+ generation,
+ pollerRunning,
+ }),
+ }
+}
+
+async function captureError(effect: () => Promise<unknown>): Promise<unknown> {
+ try {
+ await effect()
+ } catch (error) {
+ return error
+ }
+ throw new Error('Expected operation to reject')
+}
+
+describe('MCP authority lifecycle', () => {
+ afterEach(() => {
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+ })
+
+ it.each([
+ { status: 401 as const, expectedFetches: 2, expectedRefreshes: 1 },
+ { status: 403 as const, expectedFetches: 1, expectedRefreshes: 0 },
+ ])(
+ 'withdraws the live fleet synchronously and restarts polling after persistent $status',
+ async ({ status, expectedFetches, expectedRefreshes }) => {
+ vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async function (this: McpClient) {
+ ;(this as unknown as { connected: boolean }).connected = true
+ })
+ const manager = new McpManager()
+ await manager.addServer(securedServer, 'sensitive-upstream-bearer')
+ const installedClient = retainedClient(manager)
+ expect(installedClient).toBeDefined()
+
+ const harness = createLifecycleHarness(manager)
+ harness.coordinator.publishSnapshot(manager, [securedServer])
+ const refresh = vi.fn().mockResolvedValue(undefined)
+ const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status }))
+ vi.stubGlobal('fetch', fetchMock)
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: {
+ getAccessToken: () => 'host-access-token',
+ refreshOnUnauthorized: refresh,
+ onCallerAuthorizationFailure: rejectedStatus =>
+ harness.revoke(`caller_${rejectedStatus}`, true),
+ },
+ })
+
+ const error = await captureError(() => client.pollServers())
+ expect(error).toBeInstanceOf(ContextMapperRequestError)
+ const disposition = handleMcpAuthorityPollFailure(error, {
+ hasPublishedManager: () => harness.state().currentManager !== null,
+ lastSuccessAt: () => harness.state().lastSuccessAt,
+ now: () => 70_000,
+ maxStalenessMs: 60_000,
+ revoke: harness.revoke,
+ onCallerAuthorizationRejected: vi.fn(),
+ onInventoryAuthorityRevoked: vi.fn(),
+ onUnavailable: vi.fn(),
+ })
+
+ expect(disposition).toBe('caller_authorization_rejected')
+ expect(fetchMock).toHaveBeenCalledTimes(expectedFetches)
+ expect(refresh).toHaveBeenCalledTimes(expectedRefreshes)
+ expect(harness.reasons).toEqual([`caller_${status}`])
+ expect(harness.state()).toMatchObject({
+ currentManager: null,
+ lastSuccessAt: 0,
+ generation: 8,
+ pollerRunning: true,
+ })
+ expect(harness.state().serverState.size).toBe(0)
+ expect((installedClient as unknown as { authToken?: string }).authToken).toBeUndefined()
+ expect(manager.getConnectedServers()).toEqual([])
+ expect(manager.getKnownServers()).toEqual([])
+ expect(harness.effects).toEqual([
+ 'generation-invalidated',
+ 'polling-stopped',
+ 'deadline-cleared',
+ 'manager-withdrawn',
+ 'server-state-cleared',
+ 'last-success-cleared',
+ 'coordinator-close',
+ 'manager-close',
+ 'cleanup-scheduled',
+ 'revoked',
+ 'polling-started',
+ ])
+ await expect(manager.addServer(securedServer, 'new-bearer')).resolves.toBe('stale')
+ await harness.coordinator.drainCleanups()
+ }
+ )
+
+ it('classifies an actual inventory 404 as complete authority revocation', async () => {
+ const manager = new McpManager()
+ const harness = createLifecycleHarness(manager)
+ harness.coordinator.publishSnapshot(manager, [securedServer])
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 404 })))
+ const client = new ContextMapperClient('http://context-mapper.test', {
+ authentication: {
+ getAccessToken: () => 'host-access-token',
+ refreshOnUnauthorized: vi.fn(),
+ },
+ })
+ const error = await captureError(() => client.pollServers())
+ const inventoryRevoked = vi.fn()
+
+ const disposition = handleMcpAuthorityPollFailure(error, {
+ hasPublishedManager: () => harness.state().currentManager !== null,
+ lastSuccessAt: () => harness.state().lastSuccessAt,
+ now: () => 70_000,
+ maxStalenessMs: 60_000,
+ revoke: harness.revoke,
+ onCallerAuthorizationRejected: vi.fn(),
+ onInventoryAuthorityRevoked: inventoryRevoked,
+ onUnavailable: vi.fn(),
+ })
+
+ expect(disposition).toBe('inventory_not_found')
+ expect(inventoryRevoked).toHaveBeenCalledTimes(1)
+ expect(harness.reasons).toEqual(['inventory_not_found'])
+ expect(harness.state()).toMatchObject({ currentManager: null, pollerRunning: true })
+ await harness.coordinator.drainCleanups()
+ })
+
+ it('revokes the full state at the absolute staleness deadline and restarts recovery polling', () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-08-20T00:00:00.000Z'))
+ const manager = new McpManager()
+ const harness = createLifecycleHarness(manager)
+ harness.coordinator.publishSnapshot(manager, [securedServer])
+ const deadline = createMcpAuthorityStalenessDeadline(60_000, () =>
+ harness.revoke('authority_stale_deadline', true)
+ )
+ harness.setDeadlineClear(deadline.clear)
+
+ deadline.recordSuccess()
+ vi.advanceTimersByTime(60_000)
+
+ expect(harness.reasons).toEqual(['authority_stale_deadline'])
+ expect(harness.state()).toMatchObject({
+ currentManager: null,
+ lastSuccessAt: 0,
+ generation: 8,
+ pollerRunning: true,
+ })
+ expect(harness.state().serverState.size).toBe(0)
+ })
+
+ it('revokes an unavailable stale fleet through the poll-error path', async () => {
+ const manager = new McpManager()
+ const harness = createLifecycleHarness(manager)
+ harness.coordinator.publishSnapshot(manager, [securedServer])
+ const unavailable = vi.fn()
+
+ const disposition = handleMcpAuthorityPollFailure(new Error('transport unavailable'), {
+ hasPublishedManager: () => harness.state().currentManager !== null,
+ lastSuccessAt: () => harness.state().lastSuccessAt,
+ now: () => 70_000,
+ maxStalenessMs: 60_000,
+ revoke: harness.revoke,
+ onCallerAuthorizationRejected: vi.fn(),
+ onInventoryAuthorityRevoked: vi.fn(),
+ onUnavailable: unavailable,
+ })
+
+ expect(disposition).toBe('authority_stale')
+ expect(unavailable).toHaveBeenCalledTimes(1)
+ expect(harness.reasons).toEqual(['authority_stale'])
+ expect(harness.state()).toMatchObject({ currentManager: null, pollerRunning: true })
+ await harness.coordinator.drainCleanups()
+ })
+
+ it('fences a delayed admission so revocation cannot republish its bearer or tools', async () => {
+ const connectStarted = deferred()
+ const releaseConnect = deferred()
+ vi.spyOn(McpClient.prototype, 'connect').mockImplementation(async function (this: McpClient) {
+ connectStarted.resolve()
+ await releaseConnect.promise
+ if ((this as unknown as { retired: boolean }).retired) {
+ throw new Error('MCP client is closed')
+ }
+ ;(this as unknown as { connected: boolean }).connected = true
+ })
+ const manager = new McpManager()
+ const coordinator = new AuthoritativeMcpFleetCoordinator(1, 1, true)
+ const lease = coordinator.publishSnapshot(manager, [securedServer])
+ const harness = createLifecycleHarness(manager, coordinator)
+ const committed = vi.fn()
+ let outcome: string | undefined
+ const admission = coordinator.runAdmission(
+ manager,
+ securedServer.name,
+ lease,
+ async isCurrent => {
+ outcome = await manager.addServer(securedServer, 'late-sensitive-bearer', {
+ isCurrent,
+ onCommit: committed,
+ scheduleCleanup: cleanup => coordinator.scheduleCleanup(cleanup),
+ })
+ }
+ )
+
+ await connectStarted.promise
+ const candidate = pendingClient(manager)
+ expect(candidate).toBeDefined()
+ expect((candidate as unknown as { authToken?: string }).authToken).toBe('late-sensitive-bearer')
+
+ harness.revoke('caller_403', true)
+
+ expect(harness.state().currentManager).toBeNull()
+ expect((candidate as unknown as { authToken?: string }).authToken).toBeUndefined()
+ expect(manager.getConnectedServers()).toEqual([])
+ expect(manager.getKnownServers()).toEqual([])
+ releaseConnect.resolve()
+ await admission
+ await coordinator.drainCleanups()
+
+ expect(outcome).toBe('stale')
+ expect(committed).not.toHaveBeenCalled()
+ expect(manager.getAllTools()).toEqual([])
+ expect(manager.getConnectedServers()).toEqual([])
+ expect(harness.state().currentManager).toBeNull()
+ })
+})
diff --git a/mcp-host/src/mcp/authorityLifecycle.ts b/mcp-host/src/mcp/authorityLifecycle.ts
new file mode 100644
index 000000000..73f3b3103
--- /dev/null
+++ b/mcp-host/src/mcp/authorityLifecycle.ts
@@ -0,0 +1,164 @@
+import {
+ ContextMapperRequestError,
+ isContextMapperInventoryAuthorityRevocation,
+} from '../contextMapperClient'
+import type { McpDetachedServerCleanup } from './manager'
+
+interface ClosableMcpAuthorityManager {
+ close(scheduleCleanup: (cleanup: McpDetachedServerCleanup) => void): Promise<void>
+}
+
+interface McpAuthorityCoordinator<TManager extends object> {
+ closeManager(manager: TManager): void
+ scheduleCleanup(cleanup: McpDetachedServerCleanup): void
+}
+
+export interface RevokeMcpAuthorityOptions<TManager extends ClosableMcpAuthorityManager> {
+ reason: string
+ restartPolling: boolean
+ invalidateInitialization(): void
+ stopPolling(): void
+ clearStalenessDeadline(): void
+ withdrawManager(): TManager | null
+ clearServerState(): void
+ clearLastSuccess(): void
+ coordinator: McpAuthorityCoordinator<TManager>
+ onCleanupFailure(): void
+ onRevoked(): void
+ shouldRestartPolling(): boolean
+ startPolling(): void
+}
+
+/**
+ * Withdraw all locally-published MCP authority before scheduling transport
+ * cleanup. The injected state operations keep this ordering explicit and make
+ * the fail-closed lifecycle independently testable without starting main.
+ */
+export function revokeMcpAuthorityState<TManager extends ClosableMcpAuthorityManager>(
+ options: RevokeMcpAuthorityOptions<TManager>
+): void {
+ options.invalidateInitialization()
+ options.stopPolling()
+ options.clearStalenessDeadline()
+ const closingManager = options.withdrawManager()
+ options.clearServerState()
+ options.clearLastSuccess()
+
+ if (closingManager) {
+ options.coordinator.closeManager(closingManager)
+ void closingManager
+ .close(cleanup => options.coordinator.scheduleCleanup(cleanup))
+ .catch(() => options.onCleanupFailure())
+ }
+ options.onRevoked()
+
+ if (options.restartPolling && options.shouldRestartPolling()) {
+ options.startPolling()
+ }
+}
+
+export function isMcpAuthorityStale(
+ lastSuccessAt: number,
+ now: number,
+ maxStalenessMs: number
+): boolean {
+ return (
+ lastSuccessAt > 0 &&
+ Number.isFinite(now) &&
+ Number.isFinite(maxStalenessMs) &&
+ maxStalenessMs > 0 &&
+ now - lastSuccessAt >= maxStalenessMs
+ )
+}
+
+/**
+ * Arm an absolute authority deadline from the last successful HCC snapshot.
+ * The independent timeout prevents a slow or failed polling cadence from
+ * extending retained authority beyond the configured staleness ceiling.
+ */
+export function createMcpAuthorityStalenessDeadline(
+ maxStalenessMs: number,
+ onExpired: () => void,
+ now: () => number = Date.now
+): { recordSuccess(successAt?: number): void; clear(): void } {
+ let timer: ReturnType<typeof setTimeout> | null = null
+ let deadlineAt = 0
+
+ const clear = (): void => {
+ if (timer !== null) clearTimeout(timer)
+ timer = null
+ deadlineAt = 0
+ }
+
+ const schedule = (): void => {
+ const remaining = deadlineAt - now()
+ timer = setTimeout(
+ () => {
+ timer = null
+ if (now() < deadlineAt) {
+ schedule()
+ return
+ }
+ deadlineAt = 0
+ onExpired()
+ },
+ Math.max(0, remaining)
+ )
+ }
+
+ return {
+ recordSuccess: (successAt = now()) => {
+ clear()
+ if (!Number.isFinite(successAt) || !Number.isFinite(maxStalenessMs) || maxStalenessMs <= 0) {
+ return
+ }
+ deadlineAt = successAt + maxStalenessMs
+ schedule()
+ },
+ clear,
+ }
+}
+
+export type McpAuthorityPollFailureDisposition =
+ | 'caller_authorization_rejected'
+ | 'inventory_not_found'
+ | 'authority_stale'
+ | 'unavailable'
+
+export interface HandleMcpAuthorityPollFailureOptions {
+ hasPublishedManager(): boolean
+ lastSuccessAt(): number
+ now(): number
+ maxStalenessMs: number
+ revoke(reason: string, restartPolling: boolean): void
+ onCallerAuthorizationRejected(): void
+ onInventoryAuthorityRevoked(): void
+ onUnavailable(): void
+}
+
+/** Apply the main polling loop's fail-closed classification to one HCC error. */
+export function handleMcpAuthorityPollFailure(
+ error: unknown,
+ options: HandleMcpAuthorityPollFailureOptions
+): McpAuthorityPollFailureDisposition {
+ if (error instanceof ContextMapperRequestError && error.authorizationFailure) {
+ // ContextMapperClient already revoked synchronously through its callback.
+ options.onCallerAuthorizationRejected()
+ return 'caller_authorization_rejected'
+ }
+ if (isContextMapperInventoryAuthorityRevocation(error)) {
+ options.revoke('inventory_not_found', true)
+ options.onInventoryAuthorityRevoked()
+ return 'inventory_not_found'
+ }
+
+ options.onUnavailable()
+ if (
+ options.hasPublishedManager() &&
+ isMcpAuthorityStale(options.lastSuccessAt(), options.now(), options.maxStalenessMs)
+ ) {
+ options.revoke('authority_stale', true)
+ return 'authority_stale'
+ }
+ return 'unavailable'
+}
diff --git a/scripts/e2e/e2e-np08-hcc-authorization.sh b/scripts/e2e/e2e-np08-hcc-authorization.sh
index 469a2bb40..5717792fa 100755
--- a/scripts/e2e/e2e-np08-hcc-authorization.sh
+++ b/scripts/e2e/e2e-np08-hcc-authorization.sh
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
set -euo pipefail
-# Local Minikube E2E for the PR1 NP-08 caller-binding contract.
+# Local Minikube E2E for the NP-08 caller-binding contract.
#
# This is intentionally a service-to-service journey: the request originates
# inside the mcp-host pod, crosses the real HCC gateway, and is authorized by
@@ -51,12 +51,15 @@ if [[ "${profile}" != "${context}" ]]; then
fi
case "${context}" in
- clerum-codex-np-08-cross-context-mcp-token-plan-*) ;;
- *)
- echo "FAIL: refusing non branch-owned NP-08 Minikube context" >&2
+ *gke*|*prod*|*staging*|clerum-test|default|minikube)
+ echo "FAIL: refusing shared, protected, or non-local NP-08 context" >&2
exit 2
;;
esac
+if [[ ! "${context}" =~ ^[a-zA-Z0-9][a-zA-Z0-9._-]*$ ]]; then
+ echo "FAIL: NP-08 context is not a valid local Minikube identifier" >&2
+ exit 2
+fi
for command_name in kubectl jq git shasum awk python3 node; do
command -v "${command_name}" >/dev/null || {
@@ -86,11 +89,18 @@ verify_profile_ownership() {
echo "FAIL: branch profile ports.env is missing: ${PORTS_ENV}" >&2
exit 1
}
- local profile_dir profile_name profile_repo profile_dirty
+ local profile_dir profile_env profile_name profile_repo profile_branch profile_dirty current_branch
profile_dir="${PORTS_ENV%/ports.env}"
- profile_name="$(awk -F= '$1 == "PROFILE" { print substr($0, index($0, "=") + 1); exit }' "${profile_dir}/profile.env" 2>/dev/null || true)"
- profile_repo="$(awk -F= '$1 == "REPO_DIR" { print substr($0, index($0, "=") + 1); exit }' "${profile_dir}/profile.env" 2>/dev/null || true)"
- profile_dirty="$(awk -F= '$1 == "DIRTY" { print substr($0, index($0, "=") + 1); exit }' "${profile_dir}/profile.env" 2>/dev/null || true)"
+ profile_env="${profile_dir}/profile.env"
+ [[ -f "${profile_env}" ]] || {
+ echo "FAIL: branch profile metadata is missing: ${profile_env}" >&2
+ exit 1
+ }
+ profile_name="$(awk -F= '$1 == "PROFILE" { print substr($0, index($0, "=") + 1); exit }' "${profile_env}" 2>/dev/null || true)"
+ profile_repo="$(awk -F= '$1 == "REPO_DIR" { print substr($0, index($0, "=") + 1); exit }' "${profile_env}" 2>/dev/null || true)"
+ profile_branch="$(awk -F= '$1 == "BRANCH" { print substr($0, index($0, "=") + 1); exit }' "${profile_env}" 2>/dev/null || true)"
+ profile_dirty="$(awk -F= '$1 == "DIRTY" { print substr($0, index($0, "=") + 1); exit }' "${profile_env}" 2>/dev/null || true)"
+ current_branch="$(git -C "${PROJECT_DIR}" branch --show-current 2>/dev/null || true)"
[[ "${profile_name}" == "${profile}" ]] || {
echo "FAIL: profile marker belongs to '${profile_name:-unknown}', not ${profile}" >&2
exit 1
@@ -103,6 +113,10 @@ verify_profile_ownership() {
echo "FAIL: profile marker belongs to another worktree: ${profile_repo:-unknown}" >&2
exit 1
}
+ [[ -n "${current_branch}" && "${profile_branch}" == "${current_branch}" ]] || {
+ echo "FAIL: profile marker belongs to another branch" >&2
+ exit 1
+ }
}
verify_clean_and_sync_marker() {
diff --git a/scripts/minikube/t2.sh b/scripts/minikube/t2.sh
index cf29414b3..d66477f5a 100755
--- a/scripts/minikube/t2.sh
+++ b/scripts/minikube/t2.sh
@@ -22,6 +22,7 @@ T2_PLAN_TMP=""
T2_T0_STATUS=NOT_RUN
T2_T1_STATUS=NOT_RUN
T2_T2_STATUS=NOT_RUN
+T2_NP08_HCC_AUTHORIZATION_STATUS=NOT_RUN
T2_PLAYWRIGHT_STATUS=NOT_RUN
# A bootstrap or full reconcile must build the current worktree. Reusing a
# marker's ghcr coordinate would validate a release image rather than HEAD.
@@ -207,6 +208,28 @@ run_final_preflight() {
t2_evidence_write T2 PASS 'exact marker, image, PostgreSQL, namespace, Service, and deployment readiness passed'
}
+run_np08_hcc_authorization() {
+ local log_file
+ log_file="$T2_EVIDENCE_DIR/logs/np08-hcc-authorization.log"
+ printf '[minikube-t2] NP-08: deployed Host-to-HCC authorization journey\n'
+ if MINIKUBE_PROFILE="$T2_PROFILE" CLERUM_PROFILE_PORTS_ENV="$T2_PORTS_ENV" \
+ bash "$T2_PROJECT_DIR/scripts/e2e/e2e-np08-hcc-authorization.sh" \
+ --context "$T2_CONTEXT" >"$log_file" 2>&1; then
+ cat "$log_file"
+ T2_NP08_HCC_AUTHORIZATION_STATUS=PASS
+ t2_evidence_write NP08_HCC_AUTHORIZATION PASS \
+ 'deployed same-Context, cross-Context, caller-token, and credential-disclosure checks passed'
+ return 0
+ fi
+
+ cat "$log_file" >&2 || true
+ T2_NP08_HCC_AUTHORIZATION_STATUS=FAIL
+ t2_evidence_write NP08_HCC_AUTHORIZATION FAIL \
+ 'deployed Host-to-HCC authorization journey failed; see the secret-safe local log'
+ T2_NEXT_COMMAND='repair the first NP-08 authorization failure, verify cleanup, then re-run T2 on the same HEAD'
+ t2_fail NP08_HCC_AUTHORIZATION_FAILED 'deployed Host-to-HCC authorization journey failed'
+}
+
run_healthcheck_if_requested() {
if [ -z "$T2_HEALTHCHECK_COMMAND" ]; then
t2_evidence_write Health NOT_RUN 'no profile-owned user-facing health command was supplied'
@@ -263,14 +286,16 @@ main() {
t2_fail ZERO_TESTS_EXECUTED 'T1 was not executed'
fi
run_final_preflight
+ run_np08_hcc_authorization
run_healthcheck_if_requested
run_playwright_if_requested
- t2_evidence_write complete PASS "T0=$T2_T0_STATUS T1=$T2_T1_STATUS T2=$T2_T2_STATUS Playwright=$T2_PLAYWRIGHT_STATUS"
+ t2_evidence_write complete PASS "T0=$T2_T0_STATUS T1=$T2_T1_STATUS T2=$T2_T2_STATUS NP08_HCC_AUTHORIZATION=$T2_NP08_HCC_AUTHORIZATION_STATUS Playwright=$T2_PLAYWRIGHT_STATUS"
printf 'MINIKUBE_T2_PASS\n'
printf 'T0=%s\n' "$T2_T0_STATUS"
printf 'T1=%s\n' "$T2_T1_STATUS"
printf 'T2=%s\n' "$T2_T2_STATUS"
+ printf 'NP08_HCC_AUTHORIZATION=%s\n' "$T2_NP08_HCC_AUTHORIZATION_STATUS"
printf 'Playwright=%s\n' "$T2_PLAYWRIGHT_STATUS"
printf 'evidence=%s\n' "$T2_EVIDENCE_FILE"
}
diff --git a/scripts/tests/test-minikube-t2-contract.sh b/scripts/tests/test-minikube-t2-contract.sh
index 65408f82c..a7db826bd 100755
--- a/scripts/tests/test-minikube-t2-contract.sh
+++ b/scripts/tests/test-minikube-t2-contract.sh
@@ -15,12 +15,13 @@ if [ -z "$TMP_ROOT" ]; then TMP_ROOT=/tmp; fi
set -u
for file in "$COMMON" "$PREFLIGHT" "$T2" "$T1" \
+ "$ROOT/scripts/e2e/e2e-np08-hcc-authorization.sh" \
"$ROOT/scripts/tests/test-minikube-t2-public-boundary.sh" \
"$ROOT/scripts/tests/test-minikube-t2-scenarios.sh"; do
bash -n "$file"
done
-required_codes="DEVELOPMENT_SCOPE_REQUIRED PROFILE_OWNERSHIP_MISMATCH PROFILE_BUSY HEAD_MARKER_MISMATCH IMAGE_MANIFEST_MISMATCH BOOTSTRAP_REQUIRED SECRET_MISSING CONFIGMAP_MISSING POSTGRES_NOT_READY REAL_PG_REQUIRED_BUT_UNAVAILABLE REAL_PG_SUITE_FAILED ZERO_TESTS_EXECUTED PORT_FORWARD_CONFLICT"
+required_codes="DEVELOPMENT_SCOPE_REQUIRED PROFILE_OWNERSHIP_MISMATCH PROFILE_BUSY HEAD_MARKER_MISMATCH IMAGE_MANIFEST_MISMATCH BOOTSTRAP_REQUIRED SECRET_MISSING CONFIGMAP_MISSING POSTGRES_NOT_READY REAL_PG_REQUIRED_BUT_UNAVAILABLE REAL_PG_SUITE_FAILED ZERO_TESTS_EXECUTED PORT_FORWARD_CONFLICT NP08_HCC_AUTHORIZATION_FAILED"
for code in $required_codes; do
grep -Fq "$code" "$COMMON" "$PREFLIGHT" "$T2" "$T1"
done
@@ -56,9 +57,14 @@ grep -Fq 'T2_SKIP_LOCK=true T2_PLAN_MODE=true T2_PLAN_FILE' "$T2"
grep -Fq 'REUSE_DB=true' "$T2"
grep -Fq 'T2_T0_STATUS=NOT_RUN' "$T2"
grep -Fq 'T2_T1_STATUS=NOT_RUN' "$T2"
+grep -Fq 'T2_NP08_HCC_AUTHORIZATION_STATUS=NOT_RUN' "$T2"
grep -Fq "T2_T0_STATUS\" != PASS" "$T2"
grep -Fq "T2_T1_STATUS\" != PASS" "$T2"
grep -Fq 'T2_HEALTHCHECK_COMMAND' "$T2"
+grep -Fq 'run_np08_hcc_authorization' "$T2"
+grep -Fq "CLERUM_PROFILE_PORTS_ENV=\"\$T2_PORTS_ENV\"" "$T2"
+grep -Fq 'NP08_HCC_AUTHORIZATION PASS' "$T2"
+grep -Fq "NP08_HCC_AUTHORIZATION=\$T2_NP08_HCC_AUTHORIZATION_STATUS" "$T2"
grep -Fq 'trap t2_lock_release EXIT INT TERM' "$COMMON"
grep -Fq 'T2_LOCK_ROOT' "$COMMON"
diff --git a/scripts/tests/test-np08-e2e-guards.sh b/scripts/tests/test-np08-e2e-guards.sh
index af67334b9..865420795 100755
--- a/scripts/tests/test-np08-e2e-guards.sh
+++ b/scripts/tests/test-np08-e2e-guards.sh
@@ -3,12 +3,16 @@ set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)"
E2E_SCRIPT="${ROOT}/scripts/e2e/e2e-np08-hcc-authorization.sh"
+T2_SCRIPT="${ROOT}/scripts/minikube/t2.sh"
+MAKEFILE="${ROOT}/Makefile"
# shellcheck source=scripts/e2e/_lib/np08-cleanup.sh
source "${ROOT}/scripts/e2e/_lib/np08-cleanup.sh"
# shellcheck source=scripts/e2e/_lib/np08-provenance.sh
source "${ROOT}/scripts/e2e/_lib/np08-provenance.sh"
+# Consumed dynamically by the sourced cleanup helper.
+# shellcheck disable=SC2034
MCP_NS='mcp-server'
KCTL_RESULT='empty'
@@ -154,3 +158,28 @@ if ! grep -Fq 'np08_cleanup_check_residual' "${E2E_SCRIPT}" ||
fail 'the deployed E2E is not wired to every tested guard'
fi
pass 'the deployed E2E is wired to cleanup and provenance guards'
+
+if grep -Fq 'clerum-codex-np-08-cross-context-mcp-token-plan-' "${E2E_SCRIPT}"; then
+ fail 'the deployed E2E is still hard-wired to one historical branch profile'
+fi
+if ! grep -Fq '*gke*|*prod*|*staging*|clerum-test|default|minikube)' "${E2E_SCRIPT}" ||
+ ! grep -Fq 'profile_branch=' "${E2E_SCRIPT}" ||
+ ! grep -Fq 'current_branch=' "${E2E_SCRIPT}" ||
+ ! grep -Fq "git -C \"\${PROJECT_DIR}\" status --porcelain" "${E2E_SCRIPT}"; then
+ fail 'the deployed E2E does not enforce generic protected-context, branch, and clean-HEAD guards'
+fi
+pass 'the deployed E2E accepts only a clean branch-owned local profile'
+
+if ! grep -Fq 'run_np08_hcc_authorization' "${T2_SCRIPT}" ||
+ ! grep -Fq "CLERUM_PROFILE_PORTS_ENV=\"\$T2_PORTS_ENV\"" "${T2_SCRIPT}" ||
+ ! grep -Fq 'NP08_HCC_AUTHORIZATION PASS' "${T2_SCRIPT}" ||
+ ! grep -Fq "NP08_HCC_AUTHORIZATION=\$T2_NP08_HCC_AUTHORIZATION_STATUS" "${T2_SCRIPT}" ||
+ ! grep -Fq 'minikube-t2-np08-hcc-authorization: minikube-t2' "${MAKEFILE}"; then
+ fail 'the deployed E2E is not a required evidence-recorded canonical T2 phase'
+fi
+pass 'canonical local T2 records the deployed NP-08 authorization journey'
+
+if grep -R -Fq 'e2e-np08-hcc-authorization.sh' "${ROOT}/.github/workflows"; then
+ fail 'CI directly invokes the cluster-mutating NP-08 deployed journey'
+fi
+pass 'CI validates NP-08 wiring statically without cluster writes'
diff --git a/tests/e2e/helpers.test.ts b/tests/e2e/helpers.test.ts
new file mode 100644
index 000000000..3dc73fff4
--- /dev/null
+++ b/tests/e2e/helpers.test.ts
@@ -0,0 +1,52 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { sendMessage, waitForTasksProcessed } from './helpers.js'
+
+function jsonResponse(body: unknown): Response {
+ return new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+})
+
+describe('mcp-host E2E helper integrity', () => {
+ it('preserves explicit message and edge-request correlation on async admission', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValue(
+ jsonResponse({ success: true, status: 'pending', taskId: 'task-correlation' })
+ )
+ vi.stubGlobal('fetch', fetchMock)
+
+ await sendMessage('correlated payload', {
+ async: true,
+ messageId: 'message-correlation',
+ requestId: 'request-correlation',
+ })
+
+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]
+ expect(url).toMatch(/\/v1\/runtime\/messages\?async=true$/)
+ expect(JSON.parse(String(init.body))).toMatchObject({
+ content: 'correlated payload',
+ messageId: 'message-correlation',
+ })
+ expect(new Headers(init.headers).get('x-clerum-edge-request-id')).toBe('request-correlation')
+ })
+
+ it('does not treat pre-existing idle as completion without a counter advance', async () => {
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse({ agent: { state: 'idle', tasksProcessed: 7 } }))
+ .mockResolvedValueOnce(jsonResponse({ agent: { state: 'idle', tasksProcessed: 8 } }))
+ vi.stubGlobal('fetch', fetchMock)
+
+ const status = await waitForTasksProcessed(8, 1_000, 0)
+
+ expect(status.agent.tasksProcessed).toBe(8)
+ expect(fetchMock).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/tests/e2e/helpers.ts b/tests/e2e/helpers.ts
index 4d8d1cc78..07e38b123 100644
--- a/tests/e2e/helpers.ts
+++ b/tests/e2e/helpers.ts
@@ -133,14 +133,18 @@ export async function sendMessage(
channelId?: string
userId?: string
channelType?: string
+ messageId?: string
+ requestId?: string
+ async?: boolean
}
): Promise<{ status: number; data: any }> {
const sender = opts?.userId ?? 'test-user'
const hostRef = opts?.hostRef ?? DEFAULT_HOST_REF
const channelId = opts?.channelId ?? 'test-channel'
const channelType = opts?.channelType ?? 'telegram'
+ const search = opts?.async ? '?async=true' : ''
return fetchJson(
- `${MCP_HOST_URL}/v1/runtime/messages`,
+ `${MCP_HOST_URL}/v1/runtime/messages${search}`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
@@ -151,7 +155,7 @@ export async function sendMessage(
sender,
channelType,
timestamp: new Date().toISOString(),
- messageId: `e2e-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
+ messageId: opts?.messageId ?? `e2e-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
}),
},
{
@@ -160,6 +164,7 @@ export async function sendMessage(
channelType,
channelId,
sender,
+ requestId: opts?.requestId,
}
)
}
@@ -194,12 +199,16 @@ export async function waitForIdle(timeoutMs = 30_000): Promise<any> {
}
/** Wait for agent to process at least N total tasks. */
-export async function waitForTasksProcessed(minCount: number, timeoutMs = 60_000): Promise<any> {
+export async function waitForTasksProcessed(
+ minCount: number,
+ timeoutMs = 60_000,
+ pollIntervalMs = 1000
+): Promise<any> {
const start = Date.now()
while (Date.now() - start < timeoutMs) {
const status = await getStatus()
if ((status.agent?.tasksProcessed ?? 0) >= minCount) return status
- await sleep(1000)
+ await sleep(pollIntervalMs)
}
throw new Error(`Agent did not process ${minCount} tasks within ${timeoutMs}ms`)
}
diff --git a/tests/e2e/mcp-host/tool-discovery.test.ts b/tests/e2e/mcp-host/tool-discovery.test.ts
index 77fe1365a..290bbd694 100644
--- a/tests/e2e/mcp-host/tool-discovery.test.ts
+++ b/tests/e2e/mcp-host/tool-discovery.test.ts
@@ -6,7 +6,15 @@
* does not call an HCC route with a caller-selected Context.
*/
import { describe, expect, it } from 'vitest'
-import { getPodLogs, getStatus, sendMessage, waitForIdle } from '../helpers.js'
+import { randomUUID } from 'node:crypto'
+import {
+ getPodLogs,
+ getStatus,
+ getTaskResult,
+ sendMessage,
+ waitForIdle,
+ waitForTasksProcessed,
+} from '../helpers.js'
describe('Tool Discovery', () => {
it('mcp-host publishes only its effective connected mock-server fleet', async () => {
@@ -37,11 +45,35 @@ describe('Tool Discovery', () => {
})
it('mcp-host processes messages via single pipeline', async () => {
- await sendMessage('tool discovery test')
- await waitForIdle(30_000)
+ const correlationId = `tool-discovery-${randomUUID()}`
+ const before = await getStatus()
+ const tasksProcessedBefore = before.agent?.tasksProcessed
+ expect(tasksProcessedBefore).toEqual(expect.any(Number))
- const logs = getPodLogs('mcp-host', 'mcp-host', 200)
- // Single pipeline — verify the task was processed
- expect(logs).toContain('[Agent] Processing task')
+ const accepted = await sendMessage(`tool discovery test ${correlationId}`, {
+ async: true,
+ messageId: correlationId,
+ requestId: correlationId,
+ })
+ expect(accepted.status).toBe(200)
+ expect(accepted.data).toMatchObject({ success: true, status: 'pending' })
+ expect(accepted.data.taskId).toEqual(expect.any(String))
+
+ const completedCount = await waitForTasksProcessed(tasksProcessedBefore + 1, 60_000)
+ expect(completedCount.agent.tasksProcessed).toBeGreaterThanOrEqual(tasksProcessedBefore + 1)
+
+ const idle = await waitForIdle(30_000)
+ expect(idle.agent.state).toBe('idle')
+
+ const taskId = accepted.data.taskId as string
+ const result = await getTaskResult(taskId, 10_000)
+ expect(result.status).toBe(200)
+ expect(result.data.success).toBe(true)
+ expect(result.data.status).toBe('completed')
+
+ const logs = getPodLogs('mcp-host', 'mcp-host', 500)
+ expect(logs).toContain(`[Main] Message ID: ${correlationId}`)
+ expect(logs).toContain(`[Main] Message queued as async task ${taskId}`)
+ expect(logs).toContain(`[Queue] Task ${taskId} dequeued for processing`)
})
})
diff --git a/tests/e2e/package-lock.json b/tests/e2e/package-lock.json
index 5ace9758b..8b6c35470 100644
--- a/tests/e2e/package-lock.json
+++ b/tests/e2e/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-e2e-tests",
- "version": "0.1.67",
+ "version": "0.1.68",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-e2e-tests",
- "version": "0.1.67",
+ "version": "0.1.68",
"devDependencies": {
"@types/jsonwebtoken": "^9.0.10",
"@types/node": "^22.0.0",
diff --git a/tests/e2e/package.json b/tests/e2e/package.json
index 6770e4a49..b2262ef2a 100644
--- a/tests/e2e/package.json
+++ b/tests/e2e/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-e2e-tests",
- "version": "0.1.67",
+ "version": "0.1.68",
"private": true,
"type": "module",
"scripts": {