Skip to content

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

TypeScript

feat(host-context-controller): provision oauth:user-token for oauth-fronting hosts

Diego Zacarias464e3cc10a82
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index e9b28c157..6b6a904d8 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.170",
+ "version": "0.1.171",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.170",
+ "version": "0.1.171",
"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 17c98b81a..bf06f1a88 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.170",
+ "version": "0.1.171",
"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/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index 5730e5553..d891b7abf 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -48,6 +48,7 @@ import {
CommunicationChannelCRD,
HostCRD,
HostChannelReaderStatus,
+ HostRuntimeControlScope,
HostRuntimeStatus,
HostWorkflowControlScope,
HostWorkflowControlSpec,
@@ -172,6 +173,40 @@ export function resolveWorkflowControlScopes(
return []
}
+/**
+ * The scope HCC appends for a Host runtime that fronts an enabled
+ * `auth.type: oauth` mcp-server. control-api's OAuth user-token broker
+ * (`POST /api/v1/mcp-oauth/user-token`) requires the caller's mcp-host control
+ * JWT to carry this scope; it is derive-only (never user-declarable) — see
+ * {@link HostRuntimeControlScope}.
+ */
+export const OAUTH_USER_TOKEN_SCOPE = 'oauth:user-token' as const
+
+/**
+ * Resolve the EFFECTIVE runtime control scopes minted into the mcp-host control
+ * JWT: the declarable workflow-control scopes plus the derive-only
+ * `oauth:user-token` when the Host fronts an enabled oauth mcp-server.
+ *
+ * This is the SINGLE source of truth shared by BOTH the mint path
+ * (`resolveWorkflowControlScopesForHost`) and the drift hash
+ * (`runtimeTokenScopeHash`), so the scopes carried by the token and the scopes
+ * hashed for change-detection can never diverge.
+ */
+export function resolveRuntimeControlScopes(
+ workflowControl: HostWorkflowControlSpec | undefined,
+ options: { hasChannelIngress?: boolean; frontsOAuthServer?: boolean } = {}
+): HostRuntimeControlScope[] {
+ const scopes: HostRuntimeControlScope[] = [
+ ...resolveWorkflowControlScopes(workflowControl, {
+ hasChannelIngress: options.hasChannelIngress,
+ }),
+ ]
+ if (options.frontsOAuthServer === true) {
+ scopes.push(OAUTH_USER_TOKEN_SCOPE)
+ }
+ return scopes
+}
+
/**
* One SharedFileSystem mount injected into a Host's mcp-host Deployment.
* The PVC is mounted RO at the requested path; mcp-host's built-in
@@ -191,6 +226,15 @@ export interface ResolvedSfsMount {
export type ResolveContextMountsFn = (host: HostCRD) => Promise<ResolvedSfsMount[]>
+/**
+ * Resolve whether a Host's referenced Context fronts at least one ENABLED
+ * `auth.type: oauth` mcp-server. Wired in production from the McpServerWatcher
+ * (which owns the Context + McpServer caches) so HCC can decide whether to
+ * request the derive-only `oauth:user-token` scope without HostReconciler
+ * needing direct K8s access to non-Host CRDs. Default (unwired) returns false.
+ */
+export type HostFrontsOAuthServerFn = (host: HostCRD) => Promise<boolean>
+
const CONTEXT_LABEL = 'clerum.io/context'
const CONTEXT_MOUNT_PATH_PATTERN = /^\/[a-zA-Z0-9_.][a-zA-Z0-9_.\/-]*$/
const RUNTIME_TOKEN_REVISION_ANNOTATION = 'clerum.io/runtime-token-revision'
@@ -268,6 +312,13 @@ type HostReconcilerDeps = {
* to non-Host CRDs.
*/
resolveContextMounts?: ResolveContextMountsFn
+ /**
+ * Resolve whether the Host fronts an enabled `auth.type: oauth` mcp-server,
+ * gating the derive-only `oauth:user-token` runtime scope. Wired in
+ * production by `McpServerWatcher` over `getServerInfosByContext`. Default
+ * (no override) returns false — fail closed: no oauth scope until wired.
+ */
+ hostFrontsOAuthServer?: HostFrontsOAuthServerFn
/**
* Count CommunicationChannels referencing this Host. Used by
* `buildChannelReaderDeployment` to compute `spec.replicas`
@@ -359,6 +410,7 @@ export class HostReconciler {
*/
private readonly lifecycle: StatelessLifecycleExecutor
private resolveContextMounts: ResolveContextMountsFn
+ private hostFrontsOAuthServerFn: HostFrontsOAuthServerFn
private countCommunicationChannels: (hostName: string) => number
private findCommunicationChannelsByHostRef: (host: string) => CommunicationChannelCRD[]
private findCommunicationChannelsByCredentialsSecretName: (
@@ -404,6 +456,7 @@ export class HostReconciler {
this.now = deps?.now ?? (() => new Date())
this.newTelemetryOccurrenceId = deps?.newTelemetryOccurrenceId ?? randomUUID
this.resolveContextMounts = deps?.resolveContextMounts ?? (async () => [])
+ this.hostFrontsOAuthServerFn = deps?.hostFrontsOAuthServer ?? (async () => false)
this.countCommunicationChannels = deps?.countCommunicationChannels ?? (() => 0)
this.findCommunicationChannelsByHostRef = deps?.findCommunicationChannelsByHostRef ?? (() => [])
this.findCommunicationChannelsByCredentialsSecretName =
@@ -458,6 +511,39 @@ export class HostReconciler {
this.resolveContextMounts = fn
}
+ /**
+ * Late-bound setter so the McpServerWatcher (which owns the Context and
+ * McpServer caches) can wire up the oauth-server resolver after this
+ * reconciler is constructed. Pattern mirrors setResolveContextMounts.
+ */
+ setHostFrontsOAuthServer(fn: HostFrontsOAuthServerFn): void {
+ this.hostFrontsOAuthServerFn = fn
+ }
+
+ /**
+ * Whether this Host fronts an enabled `auth.type: oauth` mcp-server, gating
+ * the derive-only `oauth:user-token` runtime scope. Fails CLOSED (false) when
+ * the cross-CRD read throws: an uncertain read must never grant the scope.
+ * Computed ONCE per reconcile and threaded into BOTH the mint-scope derive
+ * and the drift hash so the two never diverge.
+ */
+ private async frontsOAuthServer(host: HostCRD): Promise<boolean> {
+ try {
+ return await this.hostFrontsOAuthServerFn(host)
+ } catch (err) {
+ log.warn(
+ 'failed to resolve whether Host fronts an oauth mcp-server; failing closed (no oauth:user-token scope)',
+ {
+ host: host.name,
+ namespace: host.namespace,
+ contextRef: host.spec.contextRef,
+ err: err instanceof Error ? err.message : String(err),
+ }
+ )
+ return false
+ }
+ }
+
/**
* Late-bound setter so the McpServerWatcher (which owns the
* communicationChannels cache) can wire up the counter after this
@@ -797,13 +883,25 @@ export class HostReconciler {
return HostReconciler.shortHash({ namespace: host.namespace, host: host.name })
}
- private static runtimeTokenScopeHash(host: HostCRD, hasChannelIngress = false): string {
+ private static runtimeTokenScopeHash(
+ host: HostCRD,
+ hasChannelIngress = false,
+ frontsOAuthServer = false
+ ): string {
// Hash the EFFECTIVE (resolved) scopes — what actually gets minted into the
// control token — so change-detection matches the default-fallback applied
// at issuance (otherwise a null workflowControl hashes as [] while the token
- // carries the first-party defaults, and the two drift).
+ // carries the first-party defaults, and the two drift). Uses the SAME
+ // `resolveRuntimeControlScopes` as the mint path (see
+ // `resolveWorkflowControlScopesForHost`) so the hashed set and the minted
+ // set — including the derive-only `oauth:user-token` — can never diverge.
return HostReconciler.shortHash(
- [...resolveWorkflowControlScopes(host.spec.workflowControl, { hasChannelIngress })].sort()
+ [
+ ...resolveRuntimeControlScopes(host.spec.workflowControl, {
+ hasChannelIngress,
+ frontsOAuthServer,
+ }),
+ ].sort()
)
}
@@ -830,6 +928,7 @@ export class HostReconciler {
nowMs: number,
gfsTokenTtlSec: number,
hasChannelIngress = false,
+ frontsOAuthServer = false,
preservedHostUid?: string
): Record<string, string> {
const refreshTtlSec = Number.isFinite(tokens.refreshExpiresInSeconds)
@@ -847,7 +946,8 @@ export class HostReconciler {
HostReconciler.runtimeTokenHostBindingHash(host),
[RUNTIME_TOKEN_SCOPE_HASH_ANNOTATION]: HostReconciler.runtimeTokenScopeHash(
host,
- hasChannelIngress
+ hasChannelIngress,
+ frontsOAuthServer
),
[RUNTIME_TOKEN_ISSUER_ANNOTATION]: RUNTIME_TOKEN_ISSUER,
[RUNTIME_TOKEN_AUDIENCE_ANNOTATION]: RUNTIME_TOKEN_AUDIENCE,
@@ -877,7 +977,8 @@ export class HostReconciler {
host: HostCRD,
secret: k8s.V1Secret,
nowMs: number,
- hasChannelIngress = false
+ hasChannelIngress = false,
+ frontsOAuthServer = false
): { refresh: boolean; rolloutRequired: boolean; reason: string; refreshTokenExpMs?: number } {
const labels = secret.metadata?.labels ?? {}
if (labels[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE || labels[HOST_LABEL] !== host.name) {
@@ -892,7 +993,11 @@ export class HostReconciler {
const annotations = secret.metadata?.annotations ?? {}
const expectedHostBindingHash = HostReconciler.runtimeTokenHostBindingHash(host)
- const expectedScopeHash = HostReconciler.runtimeTokenScopeHash(host, hasChannelIngress)
+ const expectedScopeHash = HostReconciler.runtimeTokenScopeHash(
+ host,
+ hasChannelIngress,
+ frontsOAuthServer
+ )
const hasContractMetadata =
RUNTIME_TOKEN_HOST_BINDING_HASH_ANNOTATION in annotations ||
RUNTIME_TOKEN_SCOPE_HASH_ANNOTATION in annotations ||
@@ -1082,10 +1187,18 @@ export class HostReconciler {
private resolveWorkflowControlScopesForHost(
host: HostCRD,
- hasChannelIngress = this.hasChannelIngress(host)
- ): HostWorkflowControlScope[] {
- const scopes = resolveWorkflowControlScopes(host.spec.workflowControl, { hasChannelIngress })
- if (hasChannelIngress && scopes.length === 0) {
+ hasChannelIngress = this.hasChannelIngress(host),
+ frontsOAuthServer = false
+ ): HostRuntimeControlScope[] {
+ // Delegate to the SAME resolver the drift hash uses so the minted scope set
+ // and the hashed scope set can never diverge (a divergence re-issues the
+ // token every reconcile).
+ const scopes = resolveRuntimeControlScopes(host.spec.workflowControl, {
+ hasChannelIngress,
+ frontsOAuthServer,
+ })
+ const hasWorkflowScope = scopes.some(scope => scope !== OAUTH_USER_TOKEN_SCOPE)
+ if (hasChannelIngress && !hasWorkflowScope) {
log.warn('channel-bearing Host resolved with no workflow-control scopes', {
host: host.name,
namespace: host.namespace,
@@ -1121,14 +1234,28 @@ export class HostReconciler {
RUNTIME_TOKEN_BOOTSTRAP_STATE_FRESH
const nowMs = Date.now()
const hasChannelIngress = this.hasChannelIngress(host)
- const scopeHash = HostReconciler.runtimeTokenScopeHash(host, hasChannelIngress)
+ // Resolve ONCE per issuance and thread the SAME bool into the mint-scope
+ // derive, the refresh decision, the scope hash and the stored
+ // annotation, so the minted token and the drift hash never diverge.
+ const frontsOAuthServer = await this.frontsOAuthServer(host)
+ const scopeHash = HostReconciler.runtimeTokenScopeHash(
+ host,
+ hasChannelIngress,
+ frontsOAuthServer
+ )
let decision: {
refresh: boolean
rolloutRequired: boolean
reason: string
refreshTokenExpMs?: number
} = existing
- ? HostReconciler.runtimeTokenRefreshDecision(host, existing, nowMs, hasChannelIngress)
+ ? HostReconciler.runtimeTokenRefreshDecision(
+ host,
+ existing,
+ nowMs,
+ hasChannelIngress,
+ frontsOAuthServer
+ )
: { refresh: true, rolloutRequired: false, reason: 'missing_secret' }
if (
existing &&
@@ -1268,7 +1395,7 @@ export class HostReconciler {
const tokens = await issueMcpHostRuntimeTokens(
host.name,
- this.resolveWorkflowControlScopesForHost(host, hasChannelIngress)
+ this.resolveWorkflowControlScopesForHost(host, hasChannelIngress, frontsOAuthServer)
)
const gfs = await mintHostGfsToken({ name: host.name, namespace: host.namespace })
const body = buildMcpHostRuntimeTokenSecret(
@@ -1296,6 +1423,7 @@ export class HostReconciler {
nowMs,
gfs.expiresInSeconds,
hasChannelIngress,
+ frontsOAuthServer,
existing?.metadata?.annotations?.[GFS_TOKEN_HOST_UID_ANNOTATION]
),
[RUNTIME_TOKEN_BOOTSTRAP_STATE_ANNOTATION]: RUNTIME_TOKEN_BOOTSTRAP_STATE_FRESH,
@@ -3746,7 +3874,8 @@ export class HostReconciler {
for (let attempt = 1; attempt <= 3; attempt++) {
const currentScopeHash = HostReconciler.runtimeTokenScopeHash(
host,
- this.hasChannelIngress(host)
+ this.hasChannelIngress(host),
+ await this.frontsOAuthServer(host)
)
if (runtimeTokenProvision.scopeHash === currentScopeHash) return
@@ -3757,7 +3886,8 @@ export class HostReconciler {
})
const postProvisionScopeHash = HostReconciler.runtimeTokenScopeHash(
host,
- this.hasChannelIngress(host)
+ this.hasChannelIngress(host),
+ await this.frontsOAuthServer(host)
)
if (runtimeTokenProvision.scopeHash === postProvisionScopeHash) return
@@ -3779,7 +3909,8 @@ export class HostReconciler {
const effective = await resolveDeploymentLifecycle()
const currentScopeHash = HostReconciler.runtimeTokenScopeHash(
host,
- this.hasChannelIngress(host)
+ this.hasChannelIngress(host),
+ await this.frontsOAuthServer(host)
)
if (runtimeTokenProvision.scopeHash === currentScopeHash) {
return {
diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.ts
index 2aa0ccea4..50b15a673 100644
--- a/host-context-controller/src/k8sClient.test.ts
+++ b/host-context-controller/src/k8sClient.test.ts
@@ -149,6 +149,7 @@ vi.mock('./hostReconciler', () => ({
reconcile = vi.fn()
reconcileDelete = vi.fn()
setResolveContextMounts = vi.fn()
+ setHostFrontsOAuthServer = vi.fn()
// §10.4/§10.5 wiring: McpServerWatcher injects the live Host-cache resolver
// and the watch-authority snapshot into HostReconciler at construction.
setResolveCurrentHost = vi.fn()
@@ -3920,3 +3921,67 @@ describe('externalEgressResyncDelayMs (issue #299 H2)', () => {
expect(externalEgressResyncDelayMs(3, 5)).toBe(5_000)
})
})
+
+describe('McpServerWatcher.hostFrontsOAuthServer (oauth:user-token scope probe)', () => {
+ const hostFor = (contextRef: string): HostCRD =>
+ ({
+ name: 'h',
+ namespace: 'mcp-host',
+ spec: { host: 'h', contextRef, secretRef: 's' },
+ }) as HostCRD
+
+ it('returns true when the Context fronts an enabled auth.type=oauth mcp-server', async () => {
+ const watcher = new McpServerWatcher()
+ vi.spyOn(watcher, 'getServerInfosByContext').mockResolvedValue([
+ {
+ name: 'notion',
+ contextRef: 'ctx',
+ transport: { type: 'streamableHttp' },
+ enabled: true,
+ auth: { type: 'oauth' },
+ status: {},
+ },
+ ] as any)
+ await expect((watcher as any).hostFrontsOAuthServer(hostFor('ctx'))).resolves.toBe(true)
+ watcher.stop()
+ })
+
+ it('returns false for a non-oauth mcp-server', async () => {
+ const watcher = new McpServerWatcher()
+ vi.spyOn(watcher, 'getServerInfosByContext').mockResolvedValue([
+ {
+ name: 'redis',
+ contextRef: 'ctx',
+ transport: { type: 'streamableHttp' },
+ enabled: true,
+ auth: { type: 'bearer' },
+ status: {},
+ },
+ ] as any)
+ await expect((watcher as any).hostFrontsOAuthServer(hostFor('ctx'))).resolves.toBe(false)
+ watcher.stop()
+ })
+
+ it('returns false for a disabled oauth mcp-server', async () => {
+ const watcher = new McpServerWatcher()
+ vi.spyOn(watcher, 'getServerInfosByContext').mockResolvedValue([
+ {
+ name: 'notion',
+ contextRef: 'ctx',
+ transport: { type: 'streamableHttp' },
+ enabled: false,
+ auth: { type: 'oauth' },
+ status: {},
+ },
+ ] as any)
+ await expect((watcher as any).hostFrontsOAuthServer(hostFor('ctx'))).resolves.toBe(false)
+ watcher.stop()
+ })
+
+ it('returns false when the Context fronts no servers', async () => {
+ const watcher = new McpServerWatcher()
+ vi.spyOn(watcher, 'getServerInfosByContext').mockResolvedValue([] as any)
+ await expect((watcher as any).hostFrontsOAuthServer(hostFor('ctx'))).resolves.toBe(false)
+ watcher.stop()
+ })
+})
diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.ts
index 7965c6044..46b588de9 100644
--- a/host-context-controller/src/k8sClient.ts
+++ b/host-context-controller/src/k8sClient.ts
@@ -680,6 +680,11 @@ export class McpServerWatcher implements McpServerProvider {
// Wire the cross-CRD lookup the HostReconciler needs to mount each
// referenced SharedFileSystem RO into the per-Host mcp-host pod.
this.hostReconciler.setResolveContextMounts(host => this.resolveContextMounts(host))
+ // Wire the oauth-server probe the HostReconciler uses to gate the
+ // derive-only `oauth:user-token` runtime scope: true iff the Host's Context
+ // fronts an enabled `auth.type: oauth` mcp-server. Reuses the same
+ // Context-scoped allow-list projection as mcp-host discovery.
+ this.hostReconciler.setHostFrontsOAuthServer(host => this.hostFrontsOAuthServer(host))
// #281: HostReconciler drives channel-reader Deployment replicas from
// the CC count below, populated by the CommunicationChannel watch
// (see startCommunicationChannelWatch).
@@ -1481,6 +1486,20 @@ export class McpServerWatcher implements McpServerProvider {
* no matching SharedFileSystem CRD are skipped (and logged) so the pod
* can still come up while the operator catches up.
*/
+ /**
+ * True iff the Host's referenced Context fronts at least one ENABLED
+ * `auth.type: oauth` mcp-server. HostReconciler uses this to gate the
+ * derive-only `oauth:user-token` runtime scope. Reads the same
+ * Context-scoped allow-list projection (`getServerInfosByContext`, which
+ * already filters to enabled + allowed servers) that mcp-host discovery uses,
+ * so HCC does not need a second cross-CRD read path. HostReconciler wraps this
+ * call in a fail-closed guard, so a thrown read there yields no oauth scope.
+ */
+ private async hostFrontsOAuthServer(host: HostCRD): Promise<boolean> {
+ const servers = await this.getServerInfosByContext(host.spec.contextRef)
+ return servers.some(server => server.enabled && server.auth?.type === 'oauth')
+ }
+
private async resolveContextMounts(host: HostCRD): Promise<ResolvedSfsMount[]> {
const context = this.contexts.get(host.spec.contextRef)
const refs = context?.spec.sharedFileSystems ?? []
diff --git a/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts b/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts
index 219d928db..a12dda49e 100644
--- a/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts
+++ b/host-context-controller/src/mcpHostRuntimeTokenIssuerClient.ts
@@ -5,7 +5,7 @@
*/
import { config } from './config'
import { hccLogger } from './logger'
-import type { HostWorkflowControlScope } from './types'
+import type { HostRuntimeControlScope } from './types'
import { signInternalControlJwt } from './utils/internalControlSigner'
export interface McpHostRuntimeTokenResponse {
@@ -40,7 +40,7 @@ type CanonicalMcpHostTokenResponse = {
*/
export async function issueMcpHostRuntimeTokens(
hostName: string,
- workflowControlScopes: HostWorkflowControlScope[] = []
+ workflowControlScopes: HostRuntimeControlScope[] = []
): Promise<McpHostRuntimeTokenResponse> {
const recipeNamespace = config.hccTargetNamespace
const url = `${config.controlApiBaseUrl}/api/v1/auth/mcp-host/${encodeURIComponent(recipeNamespace)}/${encodeURIComponent(SENTINEL_RECIPE_NAME)}/tokens`
diff --git a/host-context-controller/src/types.ts b/host-context-controller/src/types.ts
index c1a6496ed..45066e58c 100644
--- a/host-context-controller/src/types.ts
+++ b/host-context-controller/src/types.ts
@@ -415,6 +415,21 @@ export interface HostWorkflowControlSpec {
scopes?: HostWorkflowControlScope[]
}
+/**
+ * Runtime control scopes minted into an mcp-host's control JWT. This is the
+ * DERIVED superset of the user-declarable {@link HostWorkflowControlScope}:
+ * HCC appends `oauth:user-token` for a Host runtime that fronts an enabled
+ * `auth.type: oauth` mcp-server, so the mcp-host can call control-api's OAuth
+ * user-token broker on that connection's behalf.
+ *
+ * `oauth:user-token` is HCC-derived and MUST NEVER be user-declarable: it is
+ * deliberately absent from {@link HostWorkflowControlScope} and from the Host
+ * CRD `spec.workflowControl.scopes` enum. HCC computes it per reconcile from
+ * the referenced Context's McpServer allow-list; nothing writes it back to the
+ * Host CR.
+ */
+export type HostRuntimeControlScope = HostWorkflowControlScope | 'oauth:user-token'
+
export interface HostSpec {
host: string
contextRef: string
diff --git a/host-context-controller/test/hostReconciler.test.ts b/host-context-controller/test/hostReconciler.test.ts
index ccb55d3a8..cf71f679d 100644
--- a/host-context-controller/test/hostReconciler.test.ts
+++ b/host-context-controller/test/hostReconciler.test.ts
@@ -5,6 +5,8 @@ import { mintHostGfsToken } from '../src/gfsHostBinding'
import {
DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES,
HostReconciler,
+ OAUTH_USER_TOKEN_SCOPE,
+ resolveRuntimeControlScopes,
resolveWorkflowControlScopes,
} from '../src/hostReconciler'
import type { InfrastructureTelemetryReporter } from '../src/infrastructureTelemetryReporter'
@@ -1939,3 +1941,106 @@ describe('reconcileChannelReaderDeployment — B2: preserve replicas on unsynced
expect(replaceBody.spec?.replicas).toBe(1)
})
})
+
+describe('HostReconciler oauth:user-token runtime scope provisioning', () => {
+ // Extract the runtime-token scope arg from the LAST issuer call, sorted for
+ // stable comparison. This is the REAL derive → issuance payload: the mock
+ // captures whatever `resolveWorkflowControlScopesForHost` (the production
+ // derive) actually produced — no hand-minted JWT.
+ function lastIssuedScopes(): string[] {
+ const calls = vi.mocked(issueMcpHostRuntimeTokens).mock.calls
+ const last = calls[calls.length - 1]
+ return [...(last?.[1] ?? [])].sort()
+ }
+
+ // Access the private static scope-hash used for drift detection.
+ const scopeHashOf = (
+ HostReconciler as unknown as {
+ runtimeTokenScopeHash(
+ host: HostCRD,
+ hasChannelIngress?: boolean,
+ frontsOAuthServer?: boolean
+ ): string
+ }
+ ).runtimeTokenScopeHash
+
+ it('requests oauth:user-token through the real issuance payload when the Host fronts an enabled oauth mcp-server', async () => {
+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()
+ const { reconciler } = createReconciler()
+ // Host CRD carries NO oauth scope — the value is derive-only. HCC learns
+ // the Host fronts an oauth server exclusively from this injected probe.
+ reconciler.setHostFrontsOAuthServer(async () => true)
+
+ await reconciler.reconcile(makeHost())
+
+ // Goes through the REAL derive (resolveWorkflowControlScopesForHost →
+ // resolveRuntimeControlScopes). Without the derive change this scope is
+ // absent and the assertion fails.
+ expect(lastIssuedScopes()).toEqual(
+ [...DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES, OAUTH_USER_TOKEN_SCOPE].sort()
+ )
+ expect(lastIssuedScopes()).toContain('oauth:user-token')
+ })
+
+ it('does NOT request oauth:user-token when the Host fronts no oauth mcp-server', async () => {
+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()
+ const { reconciler } = createReconciler()
+ reconciler.setHostFrontsOAuthServer(async () => false)
+
+ await reconciler.reconcile(makeHost())
+
+ expect(lastIssuedScopes()).toEqual([...DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES].sort())
+ expect(lastIssuedScopes()).not.toContain('oauth:user-token')
+ })
+
+ it('defaults to NO oauth:user-token when the probe is unwired', async () => {
+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()
+ const { reconciler } = createReconciler()
+ // No setHostFrontsOAuthServer — production default is fail-closed false.
+
+ await reconciler.reconcile(makeHost())
+
+ expect(lastIssuedScopes()).not.toContain('oauth:user-token')
+ })
+
+ it('fails closed (no oauth:user-token) when the oauth-server probe throws', async () => {
+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()
+ const { reconciler } = createReconciler()
+ reconciler.setHostFrontsOAuthServer(async () => {
+ throw new Error('context read failed')
+ })
+
+ await reconciler.reconcile(makeHost())
+
+ expect(lastIssuedScopes()).toEqual([...DEFAULT_FIRST_PARTY_WORKFLOW_CONTROL_SCOPES].sort())
+ expect(lastIssuedScopes()).not.toContain('oauth:user-token')
+ })
+
+ it('toggling oauth-server presence changes the runtime-token scope hash (drift re-issues)', () => {
+ const host = makeHost()
+ const withoutOAuth = scopeHashOf(host, true, false)
+ const withOAuth = scopeHashOf(host, true, true)
+ expect(withOAuth).not.toBe(withoutOAuth)
+ })
+
+ it('mint scope set matches the scope-hash input (no mint/hash divergence)', async () => {
+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()
+ const { reconciler } = createReconciler()
+ reconciler.setHostFrontsOAuthServer(async () => true)
+ const host = makeHost()
+
+ await reconciler.reconcile(host)
+
+ // The scopes minted into the token (issuer payload) must equal the exact
+ // set the drift hash is computed over — both flow through
+ // resolveRuntimeControlScopes, so a hash miss would re-issue forever.
+ const hashInput = [
+ ...resolveRuntimeControlScopes(host.spec.workflowControl, {
+ hasChannelIngress: true,
+ frontsOAuthServer: true,
+ }),
+ ].sort()
+ expect(lastIssuedScopes()).toEqual(hashInput)
+ expect(hashInput).toContain('oauth:user-token')
+ })
+})
diff --git a/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts b/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts
index 33e81b51f..28b4e3acb 100644
--- a/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts
+++ b/host-context-controller/test/mcpHostRuntimeTokenIssuerClient.test.ts
@@ -116,6 +116,24 @@ describe('mcpHostRuntimeTokenIssuerClient (HCC)', () => {
expect(claims.jti).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)
})
+ it('serializes the derive-only oauth:user-token scope into the request body', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => canonicalIssueResponse(),
+ } as Response)
+ globalThis.fetch = fetchMock as unknown as typeof globalThis.fetch
+
+ const issueMcpHostRuntimeTokens = await loadIssuer()
+ await issueMcpHostRuntimeTokens('chatllm', ['workflow:read', 'oauth:user-token'])
+
+ const [, init] = fetchMock.mock.calls[0]
+ // The scope must survive verbatim into the wire body control-api reads —
+ // proving the broker actually receives `oauth:user-token`.
+ expect((init as RequestInit).body).toBe(
+ '{"includeMcpHostControlToken":true,"host":"chatllm","workflowControlScopes":["workflow:read","oauth:user-token"]}'
+ )
+ })
+
it('uses HCC_TARGET_NAMESPACE when building the issuance URL', async () => {
vi.resetModules()
process.env.HCC_TARGET_NAMESPACE = 'first-party-hosts'