Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(gfs): HCC host-token lifecycle telemetry and binding
Alfredo Lopezdf4f02547447
diff --git a/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts b/host-context-controller/src/__tests__/hostReconciler.mounts.test.tsindex b683de416..8200f6c2e 100644--- a/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts+++ b/host-context-controller/src/__tests__/hostReconciler.mounts.test.ts@@ -172,6 +172,7 @@ function runtimeSecretAnnotations(host = makeHost(), refreshBefore = '2999-01-01const helper = HostReconciler as unknown as {runtimeTokenHostBindingHash: (h: HostCRD) => stringruntimeTokenScopeHash: (h: HostCRD) => string+ gfsCapabilitySetHash: () => string}return {'clerum.io/runtime-token-host-binding-hash': helper.runtimeTokenHostBindingHash(host),@@ -179,6 +180,8 @@ function runtimeSecretAnnotations(host = makeHost(), refreshBefore = '2999-01-01'clerum.io/runtime-token-issuer': 'control-api','clerum.io/runtime-token-audience': 'workflow-approvals','clerum.io/runtime-token-schema-version': '2',+ 'clerum.io/gfs-token-expected-subject': `host:1st:${host.namespace}/${host.name}`,+ 'clerum.io/gfs-token-capability-set-hash': helper.gfsCapabilitySetHash(),'clerum.io/runtime-token-refresh-before': refreshBefore,'clerum.io/gfs-token-refresh-before': '2999-01-01T00:00:00.000Z',}diff --git a/host-context-controller/src/gfsConfig.test.ts b/host-context-controller/src/gfsConfig.test.tsindex 1b0e30150..b532237c3 100644--- a/host-context-controller/src/gfsConfig.test.ts+++ b/host-context-controller/src/gfsConfig.test.ts@@ -5,6 +5,9 @@ const GFS_ENV_KEYS = Object.keys(process.env).filter(k => k.startsWith('CONTEXT_afterEach(() => {for (const k of GFS_ENV_KEYS) delete process.env[k]+ delete process.env.GFS_SYNC_COPY_MAX_OBJECTS+ delete process.env.GFS_SYNC_COPY_MAX_BYTES+ delete process.env.GFS_SYNC_COPY_TIMEOUT_MSdelete process.env.CONTEXT_MAPPER_GFSC_IMAGE_PULL_POLICYdelete process.env.CONTEXT_MAPPER_NODELOCAL_DNS_CIDR})@@ -20,6 +23,22 @@ describe('gfsDefaultFactoryConfig', () => {expect(c.postgresPodLabels).toEqual({ app: 'control-postgres' })expect(c.gfscImagePullPolicy).toBe('IfNotPresent')expect(c.nodeLocalDnsCidr).toBe('')+ expect(c.pgSecretName).toBe('gfs-controller-db')+ expect(c.readerPgSecretName).toBe('gfs-controller-reader-db')+ expect(c.syncCopyMaxObjects).toBeUndefined()+ expect(c.syncCopyMaxBytes).toBeUndefined()+ expect(c.syncCopyTimeoutMs).toBeUndefined()+ })++ it('passes synchronous copy limits through verbatim, including explicit empty values', () => {+ process.env.GFS_SYNC_COPY_MAX_OBJECTS = '2500'+ process.env.GFS_SYNC_COPY_MAX_BYTES = ''+ process.env.GFS_SYNC_COPY_TIMEOUT_MS = '45000'++ const c = gfsDefaultFactoryConfig()+ expect(c.syncCopyMaxObjects).toBe('2500')+ expect(c.syncCopyMaxBytes).toBe('')+ expect(c.syncCopyTimeoutMs).toBe('45000')})it('fails loud on an invalid image pull policy (no silent default)', () => {diff --git a/host-context-controller/src/gfsConfig.ts b/host-context-controller/src/gfsConfig.tsindex f0a7b66f1..1c8760c14 100644--- a/host-context-controller/src/gfsConfig.ts+++ b/host-context-controller/src/gfsConfig.ts@@ -60,8 +60,16 @@ export function gfsDefaultFactoryConfig(): GfsFactoryConfig {jwtPublicKeyConfigMapKey: env('CONTEXT_MAPPER_GFS_JWT_CONFIGMAP_KEY', 'jwt-public-key'),pgSecretName: env('CONTEXT_MAPPER_GFS_PG_SECRET', 'gfs-controller-db'),pgSecretKey: env('CONTEXT_MAPPER_GFS_PG_SECRET_KEY', 'connection-string'),+ readerPgSecretName: env(+ 'CONTEXT_MAPPER_GFS_READER_PG_SECRET',+ 'gfs-controller-reader-db'+ ),+ readerPgSecretKey: env('CONTEXT_MAPPER_GFS_READER_PG_SECRET_KEY', 'connection-string'),driveName: env('CONTEXT_MAPPER_GFS_DRIVE_NAME', 'main'),tokenAudience: env('CONTEXT_MAPPER_GFS_TOKEN_AUDIENCE', 'gfs-controller'),+ syncCopyMaxObjects: process.env.GFS_SYNC_COPY_MAX_OBJECTS,+ syncCopyMaxBytes: process.env.GFS_SYNC_COPY_MAX_BYTES,+ syncCopyTimeoutMs: process.env.GFS_SYNC_COPY_TIMEOUT_MS,nodeLocalDnsCidr: parseNodeLocalDnsCidr(env('CONTEXT_MAPPER_NODELOCAL_DNS_CIDR', '')),}}diff --git a/host-context-controller/src/gfsHostBinding.test.ts b/host-context-controller/src/gfsHostBinding.test.tsindex 3eaf0cfa4..e76adf9e7 100644--- a/host-context-controller/src/gfsHostBinding.test.ts+++ b/host-context-controller/src/gfsHostBinding.test.ts@@ -6,7 +6,11 @@ import {mintHostGfsToken,} from './gfsHostBinding'-/** P3-S02 — first-party tokens preserve the concrete Host identity. */+/**+ * P3-S02 — HCC 1st-party host GFS token mint. Kubernetes namespace/name is the+ * trusted binding: tokens preserve the concrete Host identity and the returned+ * subject must match it exactly.+ */function okResponse(body: unknown): Response {return { ok: true, status: 200, json: async () => body } as Response@@ -49,6 +53,58 @@ describe('mintHostGfsToken', () => {})})+ it.each([+ { token: '', expiresInSeconds: 300, subject: 'host:1st:mcp-host/chatllm' },+ { token: 'tok', subject: 'host:1st:mcp-host/chatllm' },+ { token: 'tok', expiresInSeconds: 300 },+ { token: 'tok', expiresInSeconds: 0, subject: 'host:1st:mcp-host/chatllm' },+ ])('rejects a malformed successful response before returning credentials', async body => {+ const fetchFn = vi.fn(async () => okResponse(body)) as unknown as typeof fetch+ await expect(+ mintHostGfsToken(+ { name: 'chatllm', namespace: 'mcp-host' },+ { controlApiBaseUrl: 'http://x', signToken: () => 'j', fetchFn }+ )+ ).rejects.toThrow(/malformed response/)+ })++ it('rejects a subject mismatch', async () => {+ const fetchFn = vi.fn(async () =>+ okResponse({ token: 'tok', expiresInSeconds: 300, subject: 'host:1st:mcp-host/other' })+ ) as unknown as typeof fetch+ await expect(+ mintHostGfsToken(+ { name: 'chatllm', namespace: 'mcp-host' },+ { controlApiBaseUrl: 'http://x', signToken: () => 'j', fetchFn }+ )+ ).rejects.toThrow(/subject mismatch/)+ })++ it('rejects untrusted Kubernetes identity inputs before making a request', async () => {+ const fetchFn = vi.fn() as unknown as typeof fetch+ await expect(+ mintHostGfsToken(+ { name: '../chatllm', namespace: 'mcp-host' },+ { controlApiBaseUrl: 'http://x', signToken: () => 'j', fetchFn }+ )+ ).rejects.toThrow(/trusted Kubernetes namespace and name/)+ expect(fetchFn).not.toHaveBeenCalled()+ })++ it('rejects the reserved legacy standalone identity before signing or making a request', async () => {+ const signToken = vi.fn(() => 'j')+ const fetchFn = vi.fn() as unknown as typeof fetch++ await expect(+ mintHostGfsToken(+ { name: 'standalone', namespace: 'mcp-host' },+ { controlApiBaseUrl: 'http://x', signToken, fetchFn }+ )+ ).rejects.toThrow(/trusted Kubernetes namespace and name/)+ expect(signToken).not.toHaveBeenCalled()+ expect(fetchFn).not.toHaveBeenCalled()+ })+it('fails loud on a non-2xx response (never silently degrades)', async () => {const fetchFn = vi.fn(async () => ({ ok: false, status: 403 }) as Response@@ -126,7 +182,7 @@ describe('mintHostGfsToken', () => {it.each([['missing', undefined],['read-only', ['gfs.read']],- ['reordered', ['gfs.write', 'gfs.read']],+ ['duplicated', ['gfs.read', 'gfs.read']],['expanded', ['gfs.read', 'gfs.write', 'gfs.delete']],])('rejects %s JWT scopes', async (_case, scopes) => {const subject = 'host:1st:mcp-host/chatllm'@@ -142,6 +198,26 @@ describe('mintHostGfsToken', () => {).rejects.toThrow('gfs host token claim scopes mismatch: expected ["gfs.read","gfs.write"]')})+ it('accepts reordered JWT scopes with the identical ceiling', async () => {+ // The ceiling is a set: a benign ordering change in control-api's scope+ // handling must not brick every Host reconcile fleet-wide.+ const subject = 'host:1st:mcp-host/chatllm'+ const fetchFn = vi.fn(async () =>+ okResponse({+ token: jwt({ sub: subject, scopes: ['gfs.write', 'gfs.read'] }),+ expiresInSeconds: 300,+ subject,+ })+ ) as unknown as typeof fetch++ await expect(+ mintHostGfsToken(+ { name: 'chatllm', namespace: 'mcp-host' },+ { controlApiBaseUrl: 'http://x', signToken: () => 'j', fetchFn }+ )+ ).resolves.toMatchObject({ subject })+ })+it('aborts a hung request and waits for the transport to reject', async () => {vi.useFakeTimers()try {diff --git a/host-context-controller/src/gfsHostBinding.ts b/host-context-controller/src/gfsHostBinding.tsindex 798fc5360..d047f26f3 100644--- a/host-context-controller/src/gfsHostBinding.ts+++ b/host-context-controller/src/gfsHostBinding.ts@@ -1,4 +1,6 @@import { config } from './config'+import { GFS_HOST_SCOPES } from './gfsHostPolicy'+import { makeExpectedHostGfsSubject } from './gfsHostSubject'import { signInternalControlJwt } from './utils/internalControlSigner'/**@@ -6,12 +8,13 @@ import { signInternalControlJwt } from './utils/internalControlSigner'* P3-S02). HCC asks control-api (the sole gfs token minter) for a host token and* mounts it on the Host's mcp-host pod.*- * Each HCC-provisioned Host keeps its Kubernetes identity in the GFS subject.+ * The Host's trusted Kubernetes namespace/name is the durable GFS principal.* For example, the `mcp-host/chatllm` Host receives* `host:1st:mcp-host/chatllm`; another Host is never authorized through the- * same binding. The token ceiling permits the Control UI's supported Host- * operations, read and write; resource grants still decide which concrete- * resources the Host may access.+ * same binding, and HCC validates that control-api returns that exact subject+ * before exposing the credential to Kubernetes. The token ceiling permits the+ * Control UI's supported Host operations, read and write; resource grants+ * still decide which concrete resources the Host may access.*/export interface GfsHostToken {@@ -35,7 +38,9 @@ export interface GfsFirstPartyHostRef {export const GFS_HOST_TOKEN_REQUEST_TIMEOUT_MS = 10_000export const GFS_HOST_TOKEN_REQUEST_TIMEOUT_CODE = 'HCC_GFS_HOST_TOKEN_REQUEST_TIMEOUT'-const GFS_HOST_TOKEN_SCOPES = ['gfs.read', 'gfs.write'] as const+// Single source of truth: the capability ceiling shared with the reconciler's+// drift metadata. Managed agents are never granted anything beyond read+write.+const GFS_HOST_TOKEN_SCOPES = GFS_HOST_SCOPESfunction validateIssuedTokenClaims(token: unknown,@@ -68,11 +73,14 @@ function validateIssuedTokenClaims()}+ // Compare as a set: the ceiling is exactly these scopes, but a benign+ // ordering change in control-api's scope handling must not brick every+ // Host reconcile fleet-wide.const scopes = payload.scopesif (!Array.isArray(scopes) ||scopes.length !== GFS_HOST_TOKEN_SCOPES.length ||- !GFS_HOST_TOKEN_SCOPES.every((scope, index) => scopes[index] === scope)+ !GFS_HOST_TOKEN_SCOPES.every(scope => scopes.includes(scope))) {throw new Error(`gfs host token claim scopes mismatch: expected ${JSON.stringify(GFS_HOST_TOKEN_SCOPES)}`@@ -95,6 +103,13 @@ export class GfsHostTokenMintTimeoutError extends Error {}}+export class GfsHostTokenValidationError extends Error {+ constructor(message: string) {+ super(message)+ this.name = 'GfsHostTokenValidationError'+ }+}+/*** Mint a 1st-party host gfs token via control-api's provisioner route. Fails* loud on any non-2xx — a host without a working gfs token must surface, never@@ -104,11 +119,14 @@ export async function mintHostGfsToken(host: GfsFirstPartyHostRef,deps: GfsHostBindingDeps = {}): Promise<GfsHostToken> {+ const expectedSubject = makeExpectedHostGfsSubject(host.namespace, host.name)+ if (!expectedSubject) {+ throw new Error('gfs host token mint requires a trusted Kubernetes namespace and name')+ }const baseUrl = deps.controlApiBaseUrl ?? config.controlApiBaseUrlconst sign = deps.signToken ?? signInternalControlJwtconst doFetch = deps.fetchFn ?? fetchconst url = `${baseUrl}/api/v1/auth/gfs/${encodeURIComponent(host.name)}/tokens`- const expectedSubject = `host:1st:${host.namespace}/${host.name}`const timeoutError = new GfsHostTokenMintTimeoutError(GFS_HOST_TOKEN_REQUEST_TIMEOUT_MS)const controller = new AbortController()const timer = setTimeout(() => controller.abort(timeoutError), GFS_HOST_TOKEN_REQUEST_TIMEOUT_MS)@@ -123,7 +141,7 @@ export async function mintHostGfsToken(},body: JSON.stringify({namespace: host.namespace,- scopes: GFS_HOST_TOKEN_SCOPES,+ scopes: [...GFS_HOST_TOKEN_SCOPES],}),signal: controller.signal,})@@ -131,15 +149,24 @@ export async function mintHostGfsToken(if (!response.ok) {throw new Error(`gfs host token mint failed: HTTP ${response.status}`)}- const body = (await response.json()) as GfsHostToken+ const body = (await response.json()) as Partial<GfsHostToken>if (controller.signal.aborted) throw timeoutError+ if (+ typeof body.token !== 'string' ||+ body.token.length === 0 ||+ !Number.isSafeInteger(body.expiresInSeconds) ||+ (body.expiresInSeconds ?? 0) <= 0 ||+ typeof body.subject !== 'string'+ ) {+ throw new GfsHostTokenValidationError('gfs host token mint returned a malformed response')+ }if (body.subject !== expectedSubject) {- throw new Error(+ throw new GfsHostTokenValidationError(`gfs host token subject mismatch: expected ${expectedSubject}, received ${body.subject}`)}validateIssuedTokenClaims(body.token, expectedSubject)- return body+ return body as GfsHostToken} catch (error) {if (error instanceof GfsHostTokenMintTimeoutError) throw errorif (controller.signal.aborted) {diff --git a/host-context-controller/src/gfsHostPolicy.ts b/host-context-controller/src/gfsHostPolicy.tsnew file mode 100644index 000000000..d240a1def--- /dev/null+++ b/host-context-controller/src/gfsHostPolicy.ts@@ -0,0 +1,2 @@+/** Capability ceiling shared by HCC token minting and runtime drift metadata. */+export const GFS_HOST_SCOPES = ['gfs.read', 'gfs.write'] as constdiff --git a/host-context-controller/src/gfsHostSubject.test.ts b/host-context-controller/src/gfsHostSubject.test.tsnew file mode 100644index 000000000..6de4b5e9a--- /dev/null+++ b/host-context-controller/src/gfsHostSubject.test.ts@@ -0,0 +1,48 @@+import { readFileSync } from 'node:fs'+import path from 'node:path'+import { describe, expect, it } from 'vitest'+import { makeExpectedHostGfsSubject } from './gfsHostSubject'++type HostSubjectVector = {+ label: string+ namespace: string+ name: string+ displayText: string+ expectedSubjectId: string | null+ expectedSubject: string | null+}++const vectors = JSON.parse(+ readFileSync(+ path.join(__dirname, '../../tests/contracts/gfs-host-subject-vectors.json'),+ 'utf8'+ )+) as HostSubjectVector[]++describe('makeExpectedHostGfsSubject', () => {+ it.each(vectors)('matches the Control API identity contract: $label', vector => {+ const actual = makeExpectedHostGfsSubject(vector.namespace, vector.name)++ expect(actual).toBe(vector.expectedSubject)+ if (actual) {+ expect(actual).toBe(`host:${vector.expectedSubjectId}`)+ expect(actual).not.toContain(vector.displayText)+ }+ })++ it('does not accept display text in place of trusted metadata.name', () => {+ const vector = vectors.find(candidate => candidate.expectedSubject !== null)+ expect(vector).toBeDefined()+ expect(makeExpectedHostGfsSubject(vector!.namespace, vector!.displayText)).toBeNull()+ })++ it('reserves the legacy fleet-wide standalone subject without rejecting standalone elsewhere', () => {+ expect(makeExpectedHostGfsSubject('mcp-host', 'standalone')).toBeNull()+ expect(makeExpectedHostGfsSubject('sandbox-recipes', 'standalone')).toBe(+ 'host:1st:sandbox-recipes/standalone'+ )+ expect(makeExpectedHostGfsSubject('mcp-host', 'standalone-worker')).toBe(+ 'host:1st:mcp-host/standalone-worker'+ )+ })+})diff --git a/host-context-controller/src/gfsHostSubject.ts b/host-context-controller/src/gfsHostSubject.tsnew file mode 100644index 000000000..6f6ad27cc--- /dev/null+++ b/host-context-controller/src/gfsHostSubject.ts@@ -0,0 +1,21 @@+const K8S_NAME_RE = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/+const MAX_K8S_NAME_LENGTH = 63+const LEGACY_STANDALONE_NAMESPACE = 'mcp-host'+const LEGACY_STANDALONE_NAME = 'standalone'++function isK8sName(value: string): boolean {+ return value.length > 0 && value.length <= MAX_K8S_NAME_LENGTH && K8S_NAME_RE.test(value)+}++/**+ * Derive the durable first-party GFS principal for an HCC-managed Host.+ * Kubernetes namespace/name is the identity boundary. Display labels and the+ * Host UID are deliberately absent because runtime generation is separate.+ */+export function makeExpectedHostGfsSubject(namespace: string, name: string): string | null {+ if (!isK8sName(namespace) || !isK8sName(name)) return null+ // This subject belongs exclusively to the legacy fleet-wide grant migration.+ // A real Host must never acquire that historical shared principal.+ if (namespace === LEGACY_STANDALONE_NAMESPACE && name === LEGACY_STANDALONE_NAME) return null+ return `host:1st:${namespace}/${name}`+}diff --git a/host-context-controller/src/gfsReconciler.test.ts b/host-context-controller/src/gfsReconciler.test.tsindex 9950bb9bc..c9cde6bcb 100644--- a/host-context-controller/src/gfsReconciler.test.ts+++ b/host-context-controller/src/gfsReconciler.test.ts@@ -21,6 +21,8 @@ const config: GfsFactoryConfig = {jwtPublicKeyConfigMapKey: 'jwt-public-key',pgSecretName: 'gfs-controller-db',pgSecretKey: 'connection-string',+ readerPgSecretName: 'gfs-controller-reader-db',+ readerPgSecretKey: 'connection-string',driveName: 'main',tokenAudience: 'gfs-controller',}@@ -34,6 +36,7 @@ const gfs: GlobalFileSystemCRD = {class FakeApi implements GfsK8sApi {operations: string[] = []deployments: string[] = []+ deploymentManifests: k8s.V1Deployment[] = []pdbs: string[] = []services: string[] = []netpols: string[] = []@@ -59,6 +62,7 @@ class FakeApi implements GfsK8sApi {async applyDeployment(dep: k8s.V1Deployment): Promise<void> {const name = dep.metadata?.name ?? ''this.deployments.push(name)+ this.deploymentManifests.push(dep)this.operations.push(`deploy/${name}`)}async applyPodDisruptionBudget(pdb: k8s.V1PodDisruptionBudget): Promise<void> {@@ -122,6 +126,19 @@ describe('GfsReconciler.reconcile', () => {expect(api.pdbs).toEqual(['gfsc-writer-pdb'])expect(api.services).toEqual(['gfsc', 'gfsc-writer'])expect(api.netpols).toEqual(['gfsc-ingress', 'gfsc-egress'])+ const writer = api.deploymentManifests.find(d => d.metadata?.name === 'gfsc-writer')+ const reader = api.deploymentManifests.find(d => d.metadata?.name === 'gfsc-reader')+ const pgRef = (dep: k8s.V1Deployment | undefined) =>+ dep?.spec?.template.spec?.containers[0].env?.find(variable =>+ Boolean(variable.valueFrom?.secretKeyRef)+ )?.valueFrom?.secretKeyRef?.name+ expect(pgRef(writer)).toBe('gfs-controller-db')+ expect(pgRef(reader)).toBe('gfs-controller-reader-db')+ expect(writer?.spec?.strategy).toEqual({ type: 'Recreate' })+ expect(reader?.spec?.strategy).toEqual({+ type: 'RollingUpdate',+ rollingUpdate: { maxUnavailable: 0, maxSurge: 1 },+ })})it('does not scale readers down when the writer template is already current', async () => {diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex 6d5b3edf3..c9251dece 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -6,6 +6,8 @@ import type { AdministrativeOutcomeReporter } from './administrativeOutcomeReporimport { config } from './config'import { HOST_LABEL, MANAGED_BY_LABEL, MANAGED_BY_VALUE } from './constants'import { mintHostGfsToken } from './gfsHostBinding'+import { GFS_HOST_SCOPES } from './gfsHostPolicy'+import { makeExpectedHostGfsSubject } from './gfsHostSubject'import type {HccInfrastructureTelemetryPayload,InfrastructureTelemetryReporter,@@ -197,6 +199,10 @@ const RUNTIME_TOKEN_REFRESH_EXPIRES_AT_ANNOTATION = 'clerum.io/runtime-token-refconst RUNTIME_TOKEN_REFRESH_BEFORE_ANNOTATION = 'clerum.io/runtime-token-refresh-before'const GFS_TOKEN_EXPIRES_AT_ANNOTATION = 'clerum.io/gfs-token-expires-at'const GFS_TOKEN_REFRESH_BEFORE_ANNOTATION = 'clerum.io/gfs-token-refresh-before'+const GFS_TOKEN_EXPECTED_SUBJECT_ANNOTATION = 'clerum.io/gfs-token-expected-subject'+const GFS_TOKEN_CAPABILITY_SET_HASH_ANNOTATION = 'clerum.io/gfs-token-capability-set-hash'+const GFS_TOKEN_HOST_UID_ANNOTATION = 'clerum.io/gfs-token-host-uid'+const GFS_TOKEN_HOST_GENERATION_ANNOTATION = 'clerum.io/gfs-token-host-generation'const RUNTIME_TOKEN_HOST_BINDING_HASH_ANNOTATION = 'clerum.io/runtime-token-host-binding-hash'const RUNTIME_TOKEN_SCOPE_HASH_ANNOTATION = 'clerum.io/runtime-token-scope-hash'const RUNTIME_TOKEN_ISSUER_ANNOTATION = 'clerum.io/runtime-token-issuer'@@ -309,6 +315,13 @@ type RuntimeTokenProvision = {scopeHash: string}+type GfsTokenLifecycleEvidence = {+ gfs_subject: string+ gfs_outcome: 'minted' | 'rotated' | 'reused' | 'failed'+ gfs_old_host_uid?: string+ gfs_new_host_uid?: string+}+type DeploymentMutationState = {lifecycle: EffectiveHostLifecycleruntimeTokenRevision: string@@ -352,6 +365,7 @@ export class HostReconciler {) => CommunicationChannelCRD[]private readonly infrastructureTelemetryReporter?: InfrastructureTelemetryReporterprivate readonly administrativeOutcomeReporter?: AdministrativeOutcomeReporter+ private readonly gfsTokenLifecycleEvidence = new Map<string, GfsTokenLifecycleEvidence>()// B2: whether the CC cache initial-list has completed. Defaults to false// (safe: preserves existing Deployment replicas until wired by McpServerWatcher).private ccCacheSyncedFn: () => boolean = () => false@@ -792,6 +806,14 @@ export class HostReconciler {)}+ private static gfsCapabilitySetHash(): string {+ return HostReconciler.shortHash([...GFS_HOST_SCOPES].sort())+ }++ private static gfsLifecycleEvidenceKey(host: Pick<HostCRD, 'namespace' | 'name'>): string {+ return `${host.namespace}/${host.name}`+ }+private static effectiveBootstrapRefreshBeforeSec(refreshTtlSec: number): number {const configured = Math.max(0, config.mcpHostBootstrapRefreshBeforeSec ?? 0)const resyncFloor = Math.max(0, config.hostResyncIntervalSec ?? 0) * 3@@ -806,7 +828,8 @@ export class HostReconciler {secretRevision: string,nowMs: number,gfsTokenTtlSec: number,- hasChannelIngress = false+ hasChannelIngress = false,+ preservedHostUid?: string): Record<string, string> {const refreshTtlSec = Number.isFinite(tokens.refreshExpiresInSeconds)? Math.max(0, tokens.refreshExpiresInSeconds)@@ -828,6 +851,14 @@ export class HostReconciler {[RUNTIME_TOKEN_ISSUER_ANNOTATION]: RUNTIME_TOKEN_ISSUER,[RUNTIME_TOKEN_AUDIENCE_ANNOTATION]: RUNTIME_TOKEN_AUDIENCE,[RUNTIME_TOKEN_SCHEMA_VERSION_ANNOTATION]: RUNTIME_TOKEN_SCHEMA_VERSION,+ [GFS_TOKEN_EXPECTED_SUBJECT_ANNOTATION]:+ makeExpectedHostGfsSubject(host.namespace, host.name) ?? '',+ [GFS_TOKEN_CAPABILITY_SET_HASH_ANNOTATION]: HostReconciler.gfsCapabilitySetHash(),+ }+ const hostUid = host.uid ?? preservedHostUid+ if (hostUid) annotations[GFS_TOKEN_HOST_UID_ANNOTATION] = hostUid+ if (host.generation !== undefined) {+ annotations[GFS_TOKEN_HOST_GENERATION_ANNOTATION] = String(host.generation)}const gfsTtlSec = Number.isFinite(gfsTokenTtlSec) ? Math.max(0, gfsTokenTtlSec) : 0if (gfsTtlSec > 0) {@@ -880,6 +911,23 @@ export class HostReconciler {return { refresh: true, rolloutRequired: true, reason: 'contract_changed' }}+ const expectedGfsSubject = makeExpectedHostGfsSubject(host.namespace, host.name)+ if (!expectedGfsSubject) {+ return { refresh: true, rolloutRequired: true, reason: 'invalid_gfs_subject' }+ }+ if (annotations[GFS_TOKEN_EXPECTED_SUBJECT_ANNOTATION] !== expectedGfsSubject) {+ return { refresh: true, rolloutRequired: true, reason: 'gfs_subject_changed' }+ }+ if (+ annotations[GFS_TOKEN_CAPABILITY_SET_HASH_ANNOTATION] !==+ HostReconciler.gfsCapabilitySetHash()+ ) {+ return { refresh: true, rolloutRequired: true, reason: 'gfs_capability_set_changed' }+ }+ if (host.uid && annotations[GFS_TOKEN_HOST_UID_ANNOTATION] !== host.uid) {+ return { refresh: true, rolloutRequired: true, reason: 'gfs_host_uid_changed' }+ }+// Scheduling cross-check against the refresh token's REAL expiry. The// `exp` claim is decoded from the JWT payload WITHOUT signature// verification -- HCC must never verify third-party tokens (that is@@ -1052,6 +1100,10 @@ export class HostReconciler {let lastErr: unknown = nullfor (let attempt = 1; attempt <= 3; attempt++) {try {+ const expectedGfsSubject = makeExpectedHostGfsSubject(host.namespace, host.name)+ if (!expectedGfsSubject) {+ throw new Error('Host GFS token provisioning requires a trusted namespace and name')+ }const name = mcpHostRuntimeTokenSecretName(host)let existing: k8s.V1Secret | null = nulltry {@@ -1131,11 +1183,24 @@ export class HostReconciler {bootstrapIsFresh &&deploymentRevision !== '' &&deploymentRevision !== existingRevision)+ const annotationUpdates: Record<string, string> = {}+ if (+ host.generation !== undefined &&+ existing.metadata?.annotations?.[GFS_TOKEN_HOST_GENERATION_ANNOTATION] !==+ String(host.generation)+ ) {+ annotationUpdates[GFS_TOKEN_HOST_GENERATION_ANNOTATION] = String(host.generation)+ }if (bootstrapIsFresh &&HostReconciler.deploymentReady(deployment) &&deploymentRevision === existingRevision) {+ annotationUpdates[RUNTIME_TOKEN_BOOTSTRAP_STATE_ANNOTATION] =+ RUNTIME_TOKEN_BOOTSTRAP_STATE_CONSUMED+ annotationUpdates[RUNTIME_TOKEN_ROLLOUT_REQUIRED_ANNOTATION] = 'false'+ }+ if (Object.keys(annotationUpdates).length > 0) {await this.coreApi.replaceNamespacedSecret({name,namespace: host.namespace,@@ -1145,9 +1210,7 @@ export class HostReconciler {...existing.metadata,annotations: {...(existing.metadata?.annotations ?? {}),- [RUNTIME_TOKEN_BOOTSTRAP_STATE_ANNOTATION]:- RUNTIME_TOKEN_BOOTSTRAP_STATE_CONSUMED,- [RUNTIME_TOKEN_ROLLOUT_REQUIRED_ANNOTATION]: 'false',+ ...annotationUpdates,},},},@@ -1163,6 +1226,11 @@ export class HostReconciler {resourceName: name,refreshExpInHours,})+ this.gfsTokenLifecycleEvidence.set(HostReconciler.gfsLifecycleEvidenceKey(host), {+ gfs_subject: expectedGfsSubject,+ gfs_outcome: 'reused',+ ...(host.uid ? { gfs_new_host_uid: host.uid } : {}),+ })const selectedRevision =rolloutPending || HostReconciler.shouldRollForRuntimeSecret(deployment, false)? existingRevision@@ -1226,7 +1294,8 @@ export class HostReconciler {revision,nowMs,gfs.expiresInSeconds,- hasChannelIngress+ hasChannelIngress,+ existing?.metadata?.annotations?.[GFS_TOKEN_HOST_UID_ANNOTATION]),[RUNTIME_TOKEN_BOOTSTRAP_STATE_ANNOTATION]: RUNTIME_TOKEN_BOOTSTRAP_STATE_FRESH,[RUNTIME_TOKEN_ROLLOUT_REQUIRED_ANNOTATION]: rolloutRequired ? 'true' : 'false',@@ -1235,6 +1304,11 @@ export class HostReconciler {if (!existing) {await this.coreApi.createNamespacedSecret({ namespace: host.namespace, body })+ this.gfsTokenLifecycleEvidence.set(HostReconciler.gfsLifecycleEvidenceKey(host), {+ gfs_subject: expectedGfsSubject,+ gfs_outcome: 'minted',+ ...(host.uid ? { gfs_new_host_uid: host.uid } : {}),+ })log.info('created mcp-host-runtime-token Secret', {host: host.name,namespace: host.namespace,@@ -1256,6 +1330,13 @@ export class HostReconciler {namespace: host.namespace,body: replaceBody,})+ const oldHostUid = existing.metadata?.annotations?.[GFS_TOKEN_HOST_UID_ANNOTATION]+ this.gfsTokenLifecycleEvidence.set(HostReconciler.gfsLifecycleEvidenceKey(host), {+ gfs_subject: expectedGfsSubject,+ gfs_outcome: 'rotated',+ ...(oldHostUid ? { gfs_old_host_uid: oldHostUid } : {}),+ ...(host.uid ? { gfs_new_host_uid: host.uid } : {}),+ })log.info('rotated mcp-host-runtime-token Secret', {host: host.name,namespace: host.namespace,@@ -1271,6 +1352,15 @@ export class HostReconciler {}} catch (err) {lastErr = err+ const subject = makeExpectedHostGfsSubject(host.namespace, host.name)+ if (subject) {+ this.gfsTokenLifecycleEvidence.set(HostReconciler.gfsLifecycleEvidenceKey(host), {+ gfs_subject: subject,+ gfs_outcome: 'failed',+ ...(host.uid ? { gfs_new_host_uid: host.uid } : {}),+ })+ }+ if (err instanceof Error && err.name === 'GfsHostTokenValidationError') breakconst delayMs = 1000 * Math.pow(2, attempt - 1)log.error('mcp-host-runtime-token Secret attempt failed', {host: host.name,@@ -1499,7 +1589,9 @@ export class HostReconciler {status: succeeded ? 'succeeded' : 'failed',phase: status.deployed ? 'deployed' : 'not_deployed',state: status.ready ? 'ready' : 'not_ready',+ ...(this.gfsTokenLifecycleEvidence.get(HostReconciler.gfsLifecycleEvidenceKey(host)) ?? {}),})+ this.gfsTokenLifecycleEvidence.delete(HostReconciler.gfsLifecycleEvidenceKey(host))if (succeeded) this.enqueueAdministrativeOutcome(host, 'succeeded', 'reconciled')}diff --git a/host-context-controller/src/infrastructureTelemetryReporter.ts b/host-context-controller/src/infrastructureTelemetryReporter.tsindex b04014179..e7cf0441d 100644--- a/host-context-controller/src/infrastructureTelemetryReporter.ts+++ b/host-context-controller/src/infrastructureTelemetryReporter.ts@@ -35,6 +35,10 @@ export type HccInfrastructureTelemetryPayload = {detail_ref?: stringattempt?: numbercount?: number+ gfs_subject?: string+ gfs_outcome?: 'minted' | 'rotated' | 'reused' | 'failed'+ gfs_old_host_uid?: string+ gfs_new_host_uid?: string}type HccInfrastructureTelemetryProjectionBase = {@@ -74,6 +78,10 @@ export function hccReconcileOutcomeSourceId(projection: HccReconcileOutcomeProjepayload.detail_ref ?? null,payload.attempt ?? null,payload.count ?? null,+ payload.gfs_subject ?? null,+ payload.gfs_outcome ?? null,+ payload.gfs_old_host_uid ?? null,+ payload.gfs_new_host_uid ?? null,]return `hcc-reconcile-outcome-v2:${createHash('sha256').update(JSON.stringify(canonical)).digest('hex')}`}diff --git a/host-context-controller/src/k8s/gfsFactory.test.ts b/host-context-controller/src/k8s/gfsFactory.test.tsindex 2dad0c6fa..fd147ab8a 100644--- a/host-context-controller/src/k8s/gfsFactory.test.ts+++ b/host-context-controller/src/k8s/gfsFactory.test.ts@@ -35,6 +35,8 @@ const config: GfsFactoryConfig = {jwtPublicKeyConfigMapKey: 'jwt-public-key',pgSecretName: 'gfs-controller-db',pgSecretKey: 'connection-string',+ readerPgSecretName: 'gfs-controller-reader-db',+ readerPgSecretKey: 'connection-string',driveName: 'main',tokenAudience: 'gfs-controller',}@@ -145,6 +147,27 @@ describe('gfsFactory writer Deployment', () => {'gfs-controller-db')expect(byName('GFS_JWT_PUBLIC_KEY')?.valueFrom?.configMapKeyRef?.name).toBe('gfs-config')+ expect(byName('GFS_SYNC_COPY_MAX_OBJECTS')).toBeUndefined()+ expect(byName('GFS_SYNC_COPY_MAX_BYTES')).toBeUndefined()+ expect(byName('GFS_SYNC_COPY_TIMEOUT_MS')).toBeUndefined()+ })++ it('passes configured synchronous copy limits verbatim to writer and reader', () => {+ const configured = {+ ...config,+ syncCopyMaxObjects: '2500',+ syncCopyMaxBytes: '',+ syncCopyTimeoutMs: '45000',+ }++ for (const role of ['writer', 'reader'] as const) {+ const env =+ buildDeployment(gfs(), configured, role).spec?.template.spec?.containers[0].env ?? []+ const byName = (name: string) => env.find(item => item.name === name)+ expect(byName('GFS_SYNC_COPY_MAX_OBJECTS')?.value).toBe('2500')+ expect(byName('GFS_SYNC_COPY_MAX_BYTES')?.value).toBe('')+ expect(byName('GFS_SYNC_COPY_TIMEOUT_MS')?.value).toBe('45000')+ }})it('runs non-root, drops all caps, read-only rootfs (reconciler owns securityContext)', () => {@@ -199,6 +222,13 @@ describe('gfsFactory reader Deployment', () => {expect(mount?.readOnly).toBe(true)const env = dep.spec?.template.spec?.containers[0].env ?? []expect(env.find(e => e.name === 'GFS_STORAGE_ROLE')?.value).toBe('reader')+ expect(env.find(e => e.valueFrom?.secretKeyRef)?.valueFrom?.secretKeyRef?.name).toBe(+ 'gfs-controller-reader-db'+ )+ expect(dep.spec?.strategy).toEqual({+ type: 'RollingUpdate',+ rollingUpdate: { maxUnavailable: 0, maxSurge: 1 },+ })})it('requires same-node scheduling with the writer under standard-rwo', () => {diff --git a/host-context-controller/src/k8s/gfsFactory.ts b/host-context-controller/src/k8s/gfsFactory.tsindex d4d6c40da..a93a21a21 100644--- a/host-context-controller/src/k8s/gfsFactory.ts+++ b/host-context-controller/src/k8s/gfsFactory.ts@@ -12,7 +12,7 @@* - Lives in the `gfs` namespace (SFS lives in mcp-host).* - Egress = DNS + Postgres: gfsc re-checks the permission store on every op* and fails closed if it is unreachable (SFS egress is DNS-only).- * - The writer's init container only PREPARES the flat-blob storage prefix+ * - The writer's init container only PREPARES the opaque blob storage root* (ownership). rootDirectories are materialized as gfs_resources rows by* control-api (the governance plane owns the permission store), NOT here.*@@ -42,7 +42,7 @@ export const DEFAULT_GFSC_PORT = 8087export const DEFAULT_READER_REPLICAS = 2export const DEFAULT_RUN_AS_UID = 1000export const DEFAULT_RUN_AS_GID = 1000-/** Canonical mount path inside the gfsc container (the flat blob storage prefix). */+/** Canonical opaque blob-storage root inside the gfsc container. */export const GFS_MOUNT_PATH = '/data/gfs'export type GfscRole = 'writer' | 'reader'@@ -81,13 +81,20 @@ export interface GfsFactoryConfig {/** ConfigMap exposing the JWT public key gfsc verifies tokens with. */jwtPublicKeyConfigMapName: stringjwtPublicKeyConfigMapKey: string- /** Secret holding the permission-store connection string for the gfs_controller role. */+ /** Secret holding the permission-store connection string for the gfs_controller writer role. */pgSecretName: stringpgSecretKey: string+ /** Secret holding the permission-store connection string for the gfs_controller_reader role. */+ readerPgSecretName: string+ readerPgSecretKey: string/** Drive name this gfsc serves (singleton 'main' in the core). */driveName: string/** Expected audience on inbound gfs access tokens. */tokenAudience: string+ /** Optional synchronous copy limits passed through verbatim to gfsc. */+ syncCopyMaxObjects?: string+ syncCopyMaxBytes?: string+ syncCopyTimeoutMs?: string/** Optional kube-dns Service ClusterIP /32 for GKE NodeLocal DNS + Calico. */nodeLocalDnsCidr?: string}@@ -249,6 +256,18 @@ export function buildPvc(}function gfscEnv(config: GfsFactoryConfig, role: GfscRole): k8s.V1EnvVar[] {+ const pgSecretName =+ role === 'writer' ? config.pgSecretName : config.readerPgSecretName+ const pgSecretKey = role === 'writer' ? config.pgSecretKey : config.readerPgSecretKey+ const copyEnvEntries: ReadonlyArray<readonly [string, string | undefined]> = [+ ['GFS_SYNC_COPY_MAX_OBJECTS', config.syncCopyMaxObjects],+ ['GFS_SYNC_COPY_MAX_BYTES', config.syncCopyMaxBytes],+ ['GFS_SYNC_COPY_TIMEOUT_MS', config.syncCopyTimeoutMs],+ ]+ const copyEnv = copyEnvEntries.flatMap(([name, value]): k8s.V1EnvVar[] =>+ value === undefined ? [] : [{ name, value }]+ )+return [{ name: 'GFS_PORT', value: String(config.gfscPort) },{ name: 'GFS_STORAGE_PATH', value: GFS_MOUNT_PATH },@@ -265,15 +284,16 @@ function gfscEnv(config: GfsFactoryConfig, role: GfscRole): k8s.V1EnvVar[] {},},{- // gfsc connects as the least-privilege gfs_controller role (S03).+ // Keep the reader and writer on their distinct least-privilege roles.name: 'GFS_PG_CONNECTION_STRING',valueFrom: {secretKeyRef: {- name: config.pgSecretName,- key: config.pgSecretKey,+ name: pgSecretName,+ key: pgSecretKey,},},},+ ...copyEnv,]}@@ -300,7 +320,8 @@ export function buildWriterInitArgs(gfs: GlobalFileSystemCRD): string {* keeps hostpath/minikube and CSI-backed RWO volumes writable by the non-root* serving container without adding a separate pod that could race the RWO mount.* `strategy: Recreate` matches the single RW writer under RWO (two RW mounts are- * impossible); readers also use Recreate for simplicity in v1.+ * impossible). Readers use a bounded RollingUpdate so a credential/image change+ * does not deliberately remove every read endpoint at once.*/export function buildDeployment(gfs: GlobalFileSystemCRD,@@ -321,7 +342,9 @@ export function buildDeployment(metadata: { name, namespace: config.gfsNamespace, labels },spec: {replicas,- strategy: { type: 'Recreate' },+ strategy: isWriter+ ? { type: 'Recreate' }+ : { type: 'RollingUpdate', rollingUpdate: { maxUnavailable: 0, maxSurge: 1 } },selector: { matchLabels: selector },template: {metadata: { labels: selector },diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex 281d44568..c4f573f0e 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -268,6 +268,35 @@ describe('McpServerWatcher startup', () => {)})+ it('preserves Host UID from the Kubernetes inventory boundary', async () => {+ mocks.listNamespacedCustomObject.mockImplementation(async ({ plural }: { plural: string }) => {+ if (plural === 'hosts') {+ return {+ items: [+ {+ metadata: {+ name: 'uid-host',+ namespace: 'mcp-host',+ uid: '9f43826a-4031-4a31-93af-a3dd8fcfe805',+ generation: 4,+ },+ spec: { host: 'uid-host', contextRef: 'context-a', secretRef: 'host-secret' },+ },+ ],+ }+ }+ return { items: [] }+ })++ await expect(listAllHosts()).resolves.toEqual([+ expect.objectContaining({+ name: 'uid-host',+ uid: '9f43826a-4031-4a31-93af-a3dd8fcfe805',+ generation: 4,+ }),+ ])+ })+it('reconciles startup external egress before runtime full reconciliation', async () => {const eventLog: string[] = []const server = {@@ -2938,10 +2967,11 @@ describe('McpServerWatcher Host watch generation', () => {await (watcher as any).requestHostFleetReconcile('Periodic resync', undefined, 'full')await callbacks[0]('MODIFIED', {- metadata: { name: 'retry-host', namespace: 'mcp-host', generation: 1 },+ metadata: { name: 'retry-host', namespace: 'mcp-host', uid: 'retry-host-uid', generation: 1 },spec: { host: 'retry-host', lifecycle: { stateless: true } },})expect(reconcile).toHaveBeenCalledOnce()+ expect(reconcile).toHaveBeenCalledWith(expect.objectContaining({ uid: 'retry-host-uid' }), 'urgent')expect((watcher as any).hostWatchRetryTimers.size).toBe(1)expect((watcher as any).latestHostWatchEventRevisions.size).toBe(1)@@ -2956,6 +2986,7 @@ describe('McpServerWatcher Host watch generation', () => {})expect(reconcile).toHaveBeenCalledOnce()expect((watcher as any).hosts.get('retry-host')).toMatchObject({+ uid: 'retry-host-uid',generation: 1,spec: { lifecycle: { stateless: true } },})diff --git a/host-context-controller/test/hostReconciler.heartbeat.test.ts b/host-context-controller/test/hostReconciler.heartbeat.test.tsindex eb28006b4..6d9918a16 100644--- a/host-context-controller/test/hostReconciler.heartbeat.test.ts+++ b/host-context-controller/test/hostReconciler.heartbeat.test.ts@@ -82,11 +82,11 @@ vi.mock('../src/mcpHostRuntimeTokenIssuerClient', () => ({}))vi.mock('../src/gfsHostBinding', () => ({- mintHostGfsToken: vi.fn().mockResolvedValue({+ mintHostGfsToken: vi.fn(async (namespace: string, name: string) => ({['to' + 'ken']: 'gfs-runtime-value',expiresInSeconds: 600,- subject: 'host:1st:mcp-host/stateless-host',- }),+ subject: `host:1st:${namespace}/${name}`,+ })),}))function makeStatelessHost(diff --git a/host-context-controller/test/hostReconciler.lifecycle.test.ts b/host-context-controller/test/hostReconciler.lifecycle.test.tsindex c8d653513..3bd808b44 100644--- a/host-context-controller/test/hostReconciler.lifecycle.test.ts+++ b/host-context-controller/test/hostReconciler.lifecycle.test.ts@@ -90,11 +90,11 @@ vi.mock('../src/mcpHostRuntimeTokenIssuerClient', () => ({}))vi.mock('../src/gfsHostBinding', () => ({- mintHostGfsToken: vi.fn().mockResolvedValue({+ mintHostGfsToken: vi.fn(async (namespace: string, name: string) => ({['to' + 'ken']: 'gfs-runtime-value',expiresInSeconds: 600,- subject: 'host:1st:mcp-host/stateless-host',- }),+ subject: `host:1st:${namespace}/${name}`,+ })),}))function makeHost(overrides?: Partial<HostCRD>): HostCRD {diff --git a/host-context-controller/test/hostReconciler.test.ts b/host-context-controller/test/hostReconciler.test.tsindex dbe54f200..d250cf53e 100644--- a/host-context-controller/test/hostReconciler.test.ts+++ b/host-context-controller/test/hostReconciler.test.ts@@ -7,6 +7,7 @@ import {resolveWorkflowControlScopes,} from '../src/hostReconciler'import type { InfrastructureTelemetryReporter } from '../src/infrastructureTelemetryReporter'+import { mintHostGfsToken } from '../src/gfsHostBinding'import { issueMcpHostRuntimeTokens } from '../src/mcpHostRuntimeTokenIssuerClient'import { HostCRD, type HostWorkflowControlScope } from '../src/types'import {@@ -173,6 +174,106 @@ function createReconciler(}describe('HostReconciler', () => {+ it('keys GFS lifecycle evidence by canonical namespace/name', () => {+ const helper = HostReconciler as unknown as {+ gfsLifecycleEvidenceKey(host: Pick<HostCRD, 'namespace' | 'name'>): string+ }++ expect(helper.gfsLifecycleEvidenceKey({ namespace: 'tenant-a', name: 'shared-name' })).toBe(+ 'tenant-a/shared-name'+ )+ expect(helper.gfsLifecycleEvidenceKey({ namespace: 'tenant-b', name: 'shared-name' })).toBe(+ 'tenant-b/shared-name'+ )+ })++ it('binds GFS material to the exact Host and records only safe lifecycle annotations', async () => {+ const { reconciler, coreApi } = createReconciler()+ const boundHost = makeHost({ uid: 'host-uid-1', generation: 7 })++ await reconciler.reconcile(boundHost)++ expect(mintHostGfsToken).toHaveBeenCalledWith({ name: 'alpha-host', namespace: 'mcp-host' })+ const runtimeSecretWrite = coreApi.replaceNamespacedSecret.mock.calls.find(+ ([request]) => request.name === 'host-alpha-host-mcp-host-runtime-tokens'+ )?.[0].body as k8s.V1Secret+ expect(runtimeSecretWrite.metadata?.annotations).toMatchObject({+ 'clerum.io/gfs-token-expected-subject': 'host:1st:mcp-host/alpha-host',+ 'clerum.io/gfs-token-host-uid': 'host-uid-1',+ 'clerum.io/gfs-token-host-generation': '7',+ 'clerum.io/gfs-token-capability-set-hash': expect.stringMatching(/^[0-9a-f]{64}$/),+ 'clerum.io/gfs-token-expires-at': expect.any(String),+ 'clerum.io/gfs-token-refresh-before': expect.any(String),+ })+ expect(JSON.stringify(runtimeSecretWrite.metadata?.annotations)).not.toContain(+ 'gfs-runtime-value'+ )+ })++ it('leaves the per-Host Secret untouched when binding validation rejects the response', async () => {+ const { reconciler, coreApi } = createReconciler()+ const validationError = new Error('gfs host token subject mismatch')+ validationError.name = 'GfsHostTokenValidationError'+ vi.mocked(mintHostGfsToken).mockRejectedValueOnce(validationError)++ await expect(reconciler.reconcile(makeHost({ uid: 'host-uid-1' }))).rejects.toThrow(+ /subject mismatch/+ )++ expect(coreApi.createNamespacedSecret).not.toHaveBeenCalled()+ expect(coreApi.replaceNamespacedSecret).not.toHaveBeenCalled()+ })++ it('rotates for a recreated same-name Host without changing its grants identity', async () => {+ const reporter = createTelemetryReporterMock()+ const { reconciler, appsApi, coreApi } = createReconciler({+ infrastructureTelemetryReporter: reporter,+ })++ await reconciler.reconcile(makeHost({ uid: 'old-host-uid', generation: 3 }))+ const firstWrite = coreApi.replaceNamespacedSecret.mock.calls.find(+ ([request]) => request.name === 'host-alpha-host-mcp-host-runtime-tokens'+ )?.[0].body as k8s.V1Secret+ coreApi.readNamespacedSecret.mockImplementation(({ name }: { name?: string } = {}) => {+ if (name === 'host-alpha-host-mcp-host-runtime-tokens') return Promise.resolve(firstWrite)+ return Promise.resolve({ metadata: { resourceVersion: '1' }, data: {} })+ })+ coreApi.replaceNamespacedSecret.mockClear()+ appsApi.replaceNamespacedDeployment.mockClear()++ await reconciler.reconcile(makeHost({ uid: 'new-host-uid', generation: 1 }))++ expect(mintHostGfsToken).toHaveBeenLastCalledWith({+ name: 'alpha-host',+ namespace: 'mcp-host',+ })+ const recreationWrite = coreApi.replaceNamespacedSecret.mock.calls.find(+ ([request]) => request.name === 'host-alpha-host-mcp-host-runtime-tokens'+ )?.[0].body as k8s.V1Secret+ expect(recreationWrite.metadata?.annotations).toMatchObject({+ 'clerum.io/gfs-token-expected-subject': 'host:1st:mcp-host/alpha-host',+ 'clerum.io/gfs-token-host-uid': 'new-host-uid',+ 'clerum.io/gfs-token-host-generation': '1',+ 'clerum.io/runtime-token-rollout-required': 'true',+ })+ expect(reporter.enqueue).toHaveBeenCalledWith(+ expect.objectContaining({+ telemetryType: 'reconcile_outcome',+ payload: expect.objectContaining({+ gfs_subject: 'host:1st:mcp-host/alpha-host',+ gfs_old_host_uid: 'old-host-uid',+ gfs_new_host_uid: 'new-host-uid',+ gfs_outcome: 'rotated',+ }),+ })+ )+ expect(+ appsApi.replaceNamespacedDeployment.mock.calls.every(+ ([request]) => request.name === 'alpha-host'+ )+ ).toBe(true)+ })+it('creates deployment, service, and pvc for valid host', async () => {const { reconciler, appsApi, coreApi } = createReconciler()diff --git a/host-context-controller/test/hostReconciler.wake.test.ts b/host-context-controller/test/hostReconciler.wake.test.tsindex 424f9c575..91306b462 100644--- a/host-context-controller/test/hostReconciler.wake.test.ts+++ b/host-context-controller/test/hostReconciler.wake.test.ts@@ -82,11 +82,11 @@ vi.mock('../src/mcpHostRuntimeTokenIssuerClient', () => ({}))vi.mock('../src/gfsHostBinding', () => ({- mintHostGfsToken: vi.fn().mockResolvedValue({+ mintHostGfsToken: vi.fn(async (namespace: string, name: string) => ({['to' + 'ken']: 'gfs-runtime-value',expiresInSeconds: 600,- subject: 'host:1st:mcp-host/stateless-host',- }),+ subject: `host:1st:${namespace}/${name}`,+ })),}))const WAKE_ANNOTATION = 'clerum.io/wake-requested'