Skip to content

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

TypeScript
29.9 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
import type { K8sGateway } from '../src/k8s.js'
import { createRpcAccessUsersRouter } from '../src/routes/rpc-access/users.js'
import { DirectRunBindingConflictError } from '../src/services/tracing/directRunAttributionBindingService.js'
import { signRpcAccessToken } from '../src/utils/auth/rpcAuthToken.js'

/**
 * HTTP-level tests for the authorization gate on:
 *
 *   GET /rpc/access/users/:userId/mcp-hosts/:hostRef
 *
 * This file locks down the HANDLER contract so a future refactor cannot
 * silently re-introduce a missing-authorization 403 without us noticing.
 *
 * Scope of these tests: the HANDLER logic (control-api/src/routes/rpc-access/users.ts:95-120).
 * The handler implements THREE independent authorization checks after the
 * auth middleware has passed:
 *
 *   1. user_agents row exists  (checked via getUserAgents service)
 *   2. Host CRD exists         (checked via gateway.listResource)
 *   3. Host is enabled         (checked via host.spec.enabled !== false)
 *
 * Middleware-level tests (token validity, user match, host match) already
 * live in middleware.rpcAccessAuth.test.ts — we bypass the middleware here
 * via vi.mock so the tests stay focused and fast. Any breakage in the
 * middleware itself is caught by its own suite.
 */

const svc = vi.hoisted(() => ({
  getUserAgents: vi.fn(),
  getUserContexts: vi.fn(),
  getCurrentTeam: vi.fn(),
  getTeamAgents: vi.fn(),
}))

vi.mock('../src/services/directory/index.js', () => svc)

// Bypass the middleware chain — we are testing the handler logic specifically.
// The middleware's own tests live in middleware.rpcAccessAuth.test.ts.
//
// NOTE: because requireValidRpcAccessTokenAny is stubbed to a pass-through
// here, the route's scope ALLOW-LIST is NOT exercised by this file. The
// genuine scope-gate assertions (including that a `host:model:write`-only
// token — the R2 per-session model-selector flow — is accepted, and that a
// `mcp:servers:list`-only token is still rejected) run against the REAL
// middleware + REAL signed tokens in routes.profile.test.ts.
//
// The stub is steerable per test through `authState`, always reset in
// afterEach: `claims` overrides fields the stub would otherwise derive from the
// URL (so `sub` / `hostRefs` can be made to disagree with it), `omitClaims`
// lets the request through with no `rpcAuth` at all, and `realMiddleware`
// delegates to the REAL middleware so a genuine scope denial can be observed.
const authState = vi.hoisted(() => ({
  claims: {} as Record<string, unknown>,
  omitClaims: false,
  realMiddleware: false,
}))

vi.mock('../src/middleware/rpcAccessAuth.js', async importOriginal => {
  const actual = await importOriginal<typeof import('../src/middleware/rpcAccessAuth.js')>()
  type StubReq = { params: Record<string, string>; rpcAuth?: Record<string, unknown> }
  const stubAuth = (req: StubReq, next: () => void) => {
    if (!authState.omitClaims) {
      req.rpcAuth = {
        ...req.rpcAuth,
        sub: req.params.userId,
        hostRefs: [req.params.hostRef],
        ...authState.claims,
      }
    }
    next()
  }
  return {
    requireValidRpcAccessToken:
      (...args: Parameters<typeof actual.requireValidRpcAccessToken>) =>
      (req: StubReq, res: unknown, next: () => void) =>
        authState.realMiddleware
          ? actual.requireValidRpcAccessToken(...args)(req as never, res as never, next)
          : stubAuth(req, next),
    requireValidRpcAccessTokenAny:
      (...args: Parameters<typeof actual.requireValidRpcAccessTokenAny>) =>
      (req: StubReq, res: unknown, next: () => void) =>
        authState.realMiddleware
          ? actual.requireValidRpcAccessTokenAny(...args)(req as never, res as never, next)
          : stubAuth(req, next),
    requireRpcTokenUserMatch: () => (_req: unknown, _res: unknown, next: () => void) => next(),
    requireRpcTokenTeamMatch: () => (_req: unknown, _res: unknown, next: () => void) => next(),
    requireRpcTokenHostMatch: () => (_req: unknown, _res: unknown, next: () => void) => next(),
  }
})

afterEach(() => {
  authState.claims = {}
  authState.omitClaims = false
  authState.realMiddleware = false
})

type HostCRD = { metadata: { name: string }; spec?: { enabled?: boolean } }

function buildApp(hosts: HostCRD[], rpcAuth?: { teamId?: string }, bindingBudgetMs?: number) {
  const gatewayStub = {
    listResource: vi.fn(async () => hosts),
    getResource: vi.fn(async () => ({}) as never),
    createResource: vi.fn(async () => ({})),
    updateResource: vi.fn(async () => ({})),
    deleteResource: vi.fn(async () => ({ ok: true })),
  }
  const bindingService = { bind: vi.fn() }
  const app = express()
  if (rpcAuth) {
    // Simulate what the auth middleware does: attach rpcAuth to req
    app.use((req: express.Request & { rpcAuth?: unknown }, _res, next) => {
      req.rpcAuth = rpcAuth
      next()
    })
  }
  app.use(
    createRpcAccessUsersRouter(gatewayStub as unknown as K8sGateway, {
      bindingService,
      bindingBudgetMs,
    })
  )
  return { app, gatewayStub, bindingService }
}

// Pinned literally on purpose: rpc-proxy reads this exact header name, so the
// test must fail if the exported constant is ever renamed.
const DENIAL_HEADER = 'x-host-access-denial-reason'

const DIRECT_BINDING_BODY = {
  runId: '00000000-0000-4000-8000-000000000123',
  sessionId: 'session-a',
  origin: 'direct_chat',
}

describe('POST /rpc/access/users/:userId/mcp-hosts/:hostRef — atomic access and binding', () => {
  beforeEach(() => {
    svc.getUserAgents.mockReset()
    svc.getCurrentTeam.mockReset()
    svc.getCurrentTeam.mockImplementation(async (userId: string, teamId: string) => ({
      id: teamId,
      name: 'Team',
      role: 'member',
      userId,
    }))
    svc.getTeamAgents.mockReset()
  })

  it('authorizes once, derives identity from verified claims, and records the binding', async () => {
    const userId = '00000000-0000-4000-8000-000000000001'
    const teamId = '00000000-0000-4000-8000-000000000002'
    svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
    const { app, bindingService } = buildApp(
      [{ metadata: { name: 'host-a' }, spec: { enabled: true } }],
      { teamId }
    )
    bindingService.bind.mockResolvedValue({
      runId: DIRECT_BINDING_BODY.runId,
      status: 'created',
      createdAt: '2026-07-16T10:00:00.000Z',
    })

    await request(app)
      .post(`/rpc/access/users/${userId}/mcp-hosts/host-a`)
      .send(DIRECT_BINDING_BODY)
      .expect(200)
      .expect({
        userId,
        hostRef: 'host-a',
        url: 'http://host-a.mcp-host.svc.cluster.local:8080',
        bindingStatus: 'recorded',
      })

    expect(bindingService.bind).toHaveBeenCalledWith({
      ...DIRECT_BINDING_BODY,
      hostRef: 'host-a',
      identityIssuer: expect.any(String),
      actorHumanSub: userId,
      userId,
      teamId,
    })
  })

  it('rejects body-supplied identity and never records a binding', async () => {
    const userId = '00000000-0000-4000-8000-000000000001'
    svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
    const { app, bindingService } = buildApp([
      { metadata: { name: 'host-a' }, spec: { enabled: true } },
    ])

    await request(app)
      .post(`/rpc/access/users/${userId}/mcp-hosts/host-a`)
      .send({ ...DIRECT_BINDING_BODY, userId })
      .expect(400)

    expect(bindingService.bind).not.toHaveBeenCalled()
  })

  it('fails closed before binding when the directory grant is absent', async () => {
    const userId = '00000000-0000-4000-8000-000000000001'
    svc.getUserAgents.mockResolvedValue({ userId, agentNames: [] })
    const { app, bindingService, gatewayStub } = buildApp([
      { metadata: { name: 'host-a' }, spec: { enabled: true } },
    ])

    await request(app)
      .post(`/rpc/access/users/${userId}/mcp-hosts/host-a`)
      .send(DIRECT_BINDING_BODY)
      .expect(403)
      .expect(DENIAL_HEADER, 'directory_grant_missing')

    expect(gatewayStub.listResource).not.toHaveBeenCalled()
    expect(bindingService.bind).not.toHaveBeenCalled()
  })

  it('uses the route-local 2 KiB body ceiling', async () => {
    const userId = '00000000-0000-4000-8000-000000000001'
    svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
    const { app, bindingService } = buildApp([
      { metadata: { name: 'host-a' }, spec: { enabled: true } },
    ])

    await request(app)
      .post(`/rpc/access/users/${userId}/mcp-hosts/host-a`)
      .send({ ...DIRECT_BINDING_BODY, sessionId: 'x'.repeat(3_000) })
      .expect(413)

    expect(bindingService.bind).not.toHaveBeenCalled()
  })

  it('returns an available Host connection when binding storage is transiently unavailable', async () => {
    const userId = '00000000-0000-4000-8000-000000000001'
    svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
    const { app, bindingService } = buildApp([
      { metadata: { name: 'host-a' }, spec: { enabled: true } },
    ])
    bindingService.bind.mockRejectedValue(new Error('storage unavailable'))

    await request(app)
      .post(`/rpc/access/users/${userId}/mcp-hosts/host-a`)
      .send(DIRECT_BINDING_BODY)
      .expect(200)
      .expect(({ body }) => {
        expect(body).toMatchObject({
          userId,
          hostRef: 'host-a',
          bindingStatus: 'unavailable',
        })
      })
  })

  it('returns 409 when immutable attribution already exists for the run ID', async () => {
    const userId = '00000000-0000-4000-8000-000000000001'
    svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
    const { app, bindingService } = buildApp([
      { metadata: { name: 'host-a' }, spec: { enabled: true } },
    ])
    bindingService.bind.mockRejectedValue(new DirectRunBindingConflictError())

    await request(app)
      .post(`/rpc/access/users/${userId}/mcp-hosts/host-a`)
      .send(DIRECT_BINDING_BODY)
      .expect(409)
      .expect({ error: 'direct_run_binding_conflict' })
  })

  it('does not wait for the tracing statement timeout when a binding stalls', async () => {
    const userId = '00000000-0000-4000-8000-000000000001'
    svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
    const { app, bindingService } = buildApp(
      [{ metadata: { name: 'host-a' }, spec: { enabled: true } }],
      undefined,
      5
    )
    bindingService.bind.mockImplementation(() => new Promise(() => undefined))

    await request(app)
      .post(`/rpc/access/users/${userId}/mcp-hosts/host-a`)
      .send(DIRECT_BINDING_BODY)
      .expect(200)
      .expect(({ body }) => {
        expect(body.bindingStatus).toBe('unavailable')
      })
  })
})

describe('GET /rpc/access/users/:userId/mcp-hosts/:hostRef — happy path', () => {
  beforeEach(() => {
    svc.getUserAgents.mockReset()
    svc.getTeamAgents.mockReset()
  })

  it('returns 200 with connection URL when user has row AND host exists AND host is not disabled', async () => {
    const userId = 'user-golden-1'
    const hostRef = 'product'

    svc.getUserAgents.mockResolvedValue({
      userId,
      agentNames: ['product', 'chatllm'],
    })

    const { app, gatewayStub } = buildApp([
      { metadata: { name: 'product' }, spec: {} },
      { metadata: { name: 'chatllm' }, spec: {} },
    ])

    const res = await request(app)
      .get(`/rpc/access/users/${userId}/mcp-hosts/${hostRef}`)
      .expect(200)

    expect(res.body).toMatchObject({
      userId,
      hostRef,
      url: expect.stringContaining(hostRef),
    })
    expect(svc.getUserAgents).toHaveBeenCalledWith(userId)
    expect(gatewayStub.listResource).toHaveBeenCalledWith('hosts', expect.any(String))
  })

  it('returns 200 when host has spec.enabled=true explicitly', async () => {
    svc.getUserAgents.mockResolvedValue({ userId: 'user-a', agentNames: ['chatllm'] })
    const { app } = buildApp([{ metadata: { name: 'chatllm' }, spec: { enabled: true } }])
    await request(app).get(`/rpc/access/users/user-a/mcp-hosts/chatllm`).expect(200)
  })

  it('returns 200 when user has MULTIPLE agents and the target is one of them', async () => {
    svc.getUserAgents.mockResolvedValue({
      userId: 'user-multi',
      agentNames: ['allinone', 'chatllm', 'product', 'researcher'],
    })
    const { app } = buildApp([
      { metadata: { name: 'allinone' }, spec: {} },
      { metadata: { name: 'chatllm' }, spec: {} },
      { metadata: { name: 'product' }, spec: {} },
    ])
    await request(app).get(`/rpc/access/users/user-multi/mcp-hosts/allinone`).expect(200)
  })

  it('returns 200 for hostRef with hyphens (kebab-case agent names)', async () => {
    svc.getUserAgents.mockResolvedValue({
      userId: 'user-a',
      agentNames: ['multi-word-agent'],
    })
    const { app } = buildApp([{ metadata: { name: 'multi-word-agent' }, spec: {} }])
    await request(app).get(`/rpc/access/users/user-a/mcp-hosts/multi-word-agent`).expect(200)
  })
})

describe('GET /rpc/access/users/:userId/mcp-hosts/:hostRef — CHECK #1 (user_agents row, the incident bug)', () => {
  beforeEach(() => {
    svc.getUserAgents.mockReset()
    svc.getTeamAgents.mockReset()
  })

  it("returns 403 'Forbidden' when user has ZERO rows in user_agents (the exact state of [email protected] pre-mitigation)", async () => {
    const userId = 'f8b160d5-dcfc-43cf-a8c8-f18c37f4b39d' // real UUID from the incident
    const hostRef = 'product'

    svc.getUserAgents.mockResolvedValue({ userId, agentNames: [] })

    // Even though the host exists, the user_agents check fires first and blocks
    const { app } = buildApp([{ metadata: { name: 'product' }, spec: {} }])

    const res = await request(app)
      .get(`/rpc/access/users/${userId}/mcp-hosts/${hostRef}`)
      .expect(403)

    // The reason travels out of band so the body below can stay byte-identical.
    expect(res.headers[DENIAL_HEADER]).toBe('directory_grant_missing')

    // CRITICAL contract: the response body MUST be exactly {"error":"Forbidden"}.
    // The Desktop App error "No permitted scopes/hostRefs for requested RPC token"
    // is a CLIENT-SIDE translation of this 21-byte backend response. If you
    // change this shape, update the client translation too, or users will see
    // misleading errors like in this incident.
    expect(res.body).toEqual({ error: 'Forbidden' })
    // 21 bytes is the nginx gateway log signature of this specific error path.
    // The body is {"error":"Forbidden"} = 21 bytes exactly. This is the literal
    // "21" column we saw in the production nginx logs during incident triage.
    expect(Buffer.byteLength(JSON.stringify(res.body), 'utf-8')).toBe(21)
  })

  it('returns 403 when user has OTHER agents but not the requested one', async () => {
    svc.getUserAgents.mockResolvedValue({
      userId: 'user-has-chatllm-only',
      agentNames: ['chatllm'],
    })
    const { app } = buildApp([{ metadata: { name: 'product' }, spec: {} }])
    const res = await request(app)
      .get(`/rpc/access/users/user-has-chatllm-only/mcp-hosts/product`)
      .expect(403)
    expect(res.body).toEqual({ error: 'Forbidden' })
    expect(res.headers[DENIAL_HEADER]).toBe('directory_grant_missing')
  })

  it("is an exact-string match (no substring bypass) — user with 'allinone' cannot access 'allinone2'", async () => {
    svc.getUserAgents.mockResolvedValue({ userId: 'u', agentNames: ['allinone'] })
    const { app } = buildApp([{ metadata: { name: 'allinone2' }, spec: {} }])
    await request(app).get(`/rpc/access/users/u/mcp-hosts/allinone2`).expect(403)
  })

  it('fires the user_agents check BEFORE the host CRD check (short-circuit order)', async () => {
    // Empty user_agents list + existing host → should fail at check #1, not #2
    svc.getUserAgents.mockResolvedValue({ userId: 'u', agentNames: [] })
    const gatewayListResource = vi.fn(async () => [{ metadata: { name: 'product' }, spec: {} }])
    const gatewayStub = {
      listResource: gatewayListResource,
      getResource: vi.fn(),
      createResource: vi.fn(),
      updateResource: vi.fn(),
      deleteResource: vi.fn(),
    }
    const app = express()
    app.use(express.json())
    app.use(
      createRpcAccessUsersRouter(gatewayStub as unknown as K8sGateway, {
        bindingService: { bind: vi.fn() },
      })
    )

    await request(app).get(`/rpc/access/users/u/mcp-hosts/product`).expect(403)

    // Critical: the handler short-circuits on check #1, so listResource is NEVER called.
    // This is a performance guarantee (skip the K8s roundtrip when DB already rejected).
    expect(gatewayListResource).not.toHaveBeenCalled()
  })
})

describe('GET /rpc/access/users/:userId/mcp-hosts/:hostRef — CHECK #2 (Host CRD must exist)', () => {
  beforeEach(() => {
    svc.getUserAgents.mockReset()
    svc.getTeamAgents.mockReset()
  })

  it('returns 403 when the Host CRD does not exist, even if user_agents has the row (orphan protection)', async () => {
    // This is exactly the orphan 'researcher' case we found in prod — the DB
    // has a user_agents row but no corresponding Host CRD exists.
    svc.getUserAgents.mockResolvedValue({
      userId: 'user-orphan',
      agentNames: ['researcher'],
    })
    const { app } = buildApp([
      { metadata: { name: 'chatllm' }, spec: {} },
      { metadata: { name: 'product' }, spec: {} },
    ])

    const res = await request(app)
      .get(`/rpc/access/users/user-orphan/mcp-hosts/researcher`)
      .expect(403)
    expect(res.body).toEqual({ error: 'Forbidden' })
    expect(res.headers[DENIAL_HEADER]).toBe('host_missing')
  })

  it('returns 403 when the gateway returns an empty list of hosts', async () => {
    svc.getUserAgents.mockResolvedValue({ userId: 'u', agentNames: ['product'] })
    const { app } = buildApp([]) // no hosts at all
    await request(app).get(`/rpc/access/users/u/mcp-hosts/product`).expect(403)
  })
})

describe('GET /rpc/access/users/:userId/mcp-hosts/:hostRef — CHECK #3 (host must not be disabled)', () => {
  beforeEach(() => {
    svc.getUserAgents.mockReset()
    svc.getTeamAgents.mockReset()
  })

  it('returns 403 when host.spec.enabled === false (kill switch)', async () => {
    svc.getUserAgents.mockResolvedValue({ userId: 'u', agentNames: ['product'] })
    const { app } = buildApp([
      { metadata: { name: 'product' }, spec: { enabled: false } }, // DISABLED
    ])
    const res = await request(app).get(`/rpc/access/users/u/mcp-hosts/product`).expect(403)
    expect(res.body).toEqual({ error: 'Forbidden' })
    expect(res.headers[DENIAL_HEADER]).toBe('host_disabled')
  })

  it('returns 200 when spec.enabled is undefined (default permissive, the common case)', async () => {
    // This is exactly how 'product' and 'allinone' are configured in prod —
    // no explicit enabled field, which must behave as enabled=true.
    svc.getUserAgents.mockResolvedValue({ userId: 'u', agentNames: ['product'] })
    const { app } = buildApp([{ metadata: { name: 'product' }, spec: {} }])
    await request(app).get(`/rpc/access/users/u/mcp-hosts/product`).expect(200)
  })

  it('returns 200 when spec itself is undefined', async () => {
    svc.getUserAgents.mockResolvedValue({ userId: 'u', agentNames: ['product'] })
    const { app } = buildApp([
      { metadata: { name: 'product' } }, // no spec at all
    ])
    await request(app).get(`/rpc/access/users/u/mcp-hosts/product`).expect(200)
  })
})

describe('GET /rpc/access/users/:userId/mcp-hosts/:hostRef — error propagation', () => {
  beforeEach(() => {
    svc.getUserAgents.mockReset()
    svc.getTeamAgents.mockReset()
  })

  it('returns 500 when getUserAgents throws (e.g. DB connection lost)', async () => {
    svc.getUserAgents.mockRejectedValue(new Error('postgres down'))
    const { app } = buildApp([{ metadata: { name: 'product' }, spec: {} }])
    await request(app).get(`/rpc/access/users/u/mcp-hosts/product`).expect(500)
  })

  it('returns 500 when gateway.listResource throws', async () => {
    svc.getUserAgents.mockResolvedValue({ userId: 'u', agentNames: ['product'] })
    const gatewayStub = {
      listResource: vi.fn(async () => {
        throw new Error('k8s api unreachable')
      }),
      getResource: vi.fn(),
      createResource: vi.fn(),
      updateResource: vi.fn(),
      deleteResource: vi.fn(),
    }
    const app = express()
    app.use(express.json())
    app.use(
      createRpcAccessUsersRouter(gatewayStub as unknown as K8sGateway, {
        bindingService: { bind: vi.fn() },
      })
    )

    await request(app).get(`/rpc/access/users/u/mcp-hosts/product`).expect(500)
  })
})

describe('GET /rpc/access/users/:userId/mcp-hosts/:hostRef — team-level access (issue #141)', () => {
  beforeEach(() => {
    svc.getUserAgents.mockReset()
    svc.getTeamAgents.mockReset()
  })

  it('returns 200 when user has no user_agents row but team has the agent (the core bug)', async () => {
    const userId = 'josue-user-id'
    const hostRef = 'development'
    const teamId = 'a9ad4638-efe0-4f03-9bba-dd1f3f9a13ca'

    svc.getUserAgents.mockResolvedValue({ userId, agentNames: [] })
    svc.getTeamAgents.mockResolvedValue({ teamId, agentNames: ['development', 'other-agent'] })

    const { app } = buildApp([{ metadata: { name: 'development' }, spec: {} }], { teamId })

    const res = await request(app)
      .get(`/rpc/access/users/${userId}/mcp-hosts/${hostRef}`)
      .expect(200)

    expect(res.body).toMatchObject({ userId, hostRef, url: expect.stringContaining(hostRef) })
    expect(svc.getTeamAgents).toHaveBeenCalledWith(teamId)
  })

  it('returns 403 when user_agents is empty AND team does not have the agent', async () => {
    const userId = 'u'
    const hostRef = 'development'
    const teamId = 'team-123'

    svc.getUserAgents.mockResolvedValue({ userId, agentNames: [] })
    svc.getTeamAgents.mockResolvedValue({ teamId, agentNames: ['other-agent'] })

    const { app } = buildApp([{ metadata: { name: 'development' }, spec: {} }], { teamId })

    const res = await request(app)
      .get(`/rpc/access/users/${userId}/mcp-hosts/${hostRef}`)
      .expect(403)
    expect(res.body).toEqual({ error: 'Forbidden' })
    expect(res.headers[DENIAL_HEADER]).toBe('directory_grant_missing')
  })

  it('returns 403 when user_agents is empty AND no teamId is in the token', async () => {
    svc.getUserAgents.mockResolvedValue({ userId: 'u', agentNames: [] })

    // No rpcAuth injected → teamId is undefined
    const { app } = buildApp([{ metadata: { name: 'development' }, spec: {} }])

    const res = await request(app).get(`/rpc/access/users/u/mcp-hosts/development`).expect(403)
    expect(res.body).toEqual({ error: 'Forbidden' })
    expect(res.headers[DENIAL_HEADER]).toBe('directory_grant_missing')
    // getTeamAgents must NOT be called when there is no teamId to look up
    expect(svc.getTeamAgents).not.toHaveBeenCalled()
  })

  it('skips team lookup entirely when user already has direct access (performance: no extra DB call)', async () => {
    const userId = 'u'
    const hostRef = 'development'
    const teamId = 'team-123'

    svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['development'] })

    const { app } = buildApp([{ metadata: { name: 'development' }, spec: {} }], { teamId })

    await request(app).get(`/rpc/access/users/${userId}/mcp-hosts/${hostRef}`).expect(200)
    expect(svc.getTeamAgents).not.toHaveBeenCalled()
  })
})

describe('Sibling endpoint sanity: GET /rpc/access/users/:userId/agents', () => {
  beforeEach(() => {
    svc.getUserAgents.mockReset()
    svc.getTeamAgents.mockReset()
  })

  it('returns the full user_agents list for the user', async () => {
    svc.getUserAgents.mockResolvedValue({
      userId: 'u',
      agentNames: ['chatllm', 'product'],
    })
    const { app } = buildApp([])
    const res = await request(app).get(`/rpc/access/users/u/agents`).expect(200)
    expect(res.body).toEqual({ userId: 'u', agentNames: ['chatllm', 'product'] })
  })
})

describe('host access denial reason header (rpc-proxy contract)', () => {
  beforeEach(() => {
    svc.getUserAgents.mockReset()
    svc.getCurrentTeam.mockReset()
    svc.getTeamAgents.mockReset()
  })

  const HOST_URL = (userId: string, hostRef: string) =>
    `/rpc/access/users/${userId}/mcp-hosts/${hostRef}`
  const KNOWN_HOSTS: HostCRD[] = [{ metadata: { name: 'host-a' }, spec: { enabled: true } }]

  type DenialCase = {
    reason: string
    arrange: (userId: string) => { hosts: HostCRD[]; rpcAuth?: { teamId?: string } }
  }

  // One case per control-api denial reason that reaches the handler. `arrange`
  // wires the directory / claims / Host CRs so exactly that reason fires.
  const DENIAL_CASES: DenialCase[] = [
    {
      reason: 'directory_grant_missing',
      arrange: userId => {
        svc.getUserAgents.mockResolvedValue({ userId, agentNames: [] })
        return { hosts: KNOWN_HOSTS }
      },
    },
    {
      reason: 'team_membership_missing',
      arrange: userId => {
        svc.getUserAgents.mockResolvedValue({ userId, agentNames: [] })
        svc.getCurrentTeam.mockResolvedValue(null)
        return { hosts: KNOWN_HOSTS, rpcAuth: { teamId: 'team-gone' } }
      },
    },
    {
      reason: 'subject_mismatch',
      arrange: userId => {
        svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
        authState.claims = { sub: 'someone-else' }
        return { hosts: KNOWN_HOSTS }
      },
    },
    {
      reason: 'host_claim_missing',
      arrange: userId => {
        svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
        authState.claims = { hostRefs: ['other-host'] }
        return { hosts: KNOWN_HOSTS }
      },
    },
    {
      reason: 'host_missing',
      arrange: userId => {
        svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
        return { hosts: [] }
      },
    },
    {
      reason: 'host_disabled',
      arrange: userId => {
        svc.getUserAgents.mockResolvedValue({ userId, agentNames: ['host-a'] })
        return { hosts: [{ metadata: { name: 'host-a' }, spec: { enabled: false } }] }
      },
    },
  ]

  it.each(DENIAL_CASES)(
    'GET 403 carries the reason $reason in the header and keeps the 21-byte body',
    async ({ reason, arrange }) => {
      const userId = 'user-1'
      const { hosts, rpcAuth } = arrange(userId)
      const { app } = buildApp(hosts, rpcAuth)

      const res = await request(app).get(HOST_URL(userId, 'host-a')).expect(403)

      expect(res.headers[DENIAL_HEADER]).toBe(reason)
      expect(res.body).toEqual({ error: 'Forbidden' })
      expect(Buffer.byteLength(res.text, 'utf-8')).toBe(21)
    }
  )

  it.each(DENIAL_CASES)(
    'POST 403 carries the reason $reason in the header, keeps the 21-byte body and records no binding',
    async ({ reason, arrange }) => {
      const userId = 'user-1'
      const { hosts, rpcAuth } = arrange(userId)
      const { app, bindingService } = buildApp(hosts, rpcAuth)

      const res = await request(app)
        .post(HOST_URL(userId, 'host-a'))
        .send(DIRECT_BINDING_BODY)
        .expect(403)

      expect(res.headers[DENIAL_HEADER]).toBe(reason)
      expect(res.body).toEqual({ error: 'Forbidden' })
      expect(Buffer.byteLength(res.text, 'utf-8')).toBe(21)
      // Witness for the negative: the route was entered and denied by the
      // handler (header present above), and it never reached the binding step.
      expect(bindingService.bind).not.toHaveBeenCalled()
    }
  )

  it('GET without verified claims is denied with claims_missing', async () => {
    authState.omitClaims = true
    const { app } = buildApp(KNOWN_HOSTS)

    const res = await request(app).get(HOST_URL('user-1', 'host-a')).expect(403)

    expect(res.headers[DENIAL_HEADER]).toBe('claims_missing')
    expect(Buffer.byteLength(res.text, 'utf-8')).toBe(21)
    expect(svc.getUserAgents).not.toHaveBeenCalled()
  })

  it('POST without verified claims is denied with claims_missing', async () => {
    authState.omitClaims = true
    const { app, bindingService } = buildApp(KNOWN_HOSTS)

    const res = await request(app)
      .post(HOST_URL('user-1', 'host-a'))
      .send(DIRECT_BINDING_BODY)
      .expect(403)

    expect(res.headers[DENIAL_HEADER]).toBe('claims_missing')
    expect(Buffer.byteLength(res.text, 'utf-8')).toBe(21)
    expect(bindingService.bind).not.toHaveBeenCalled()
  })

  it('a successful authorization carries no denial header', async () => {
    svc.getUserAgents.mockResolvedValue({ userId: 'user-1', agentNames: ['host-a'] })
    const { app } = buildApp(KNOWN_HOSTS)

    const res = await request(app).get(HOST_URL('user-1', 'host-a')).expect(200)

    expect(res.body.hostRef).toBe('host-a')
    expect(res.headers[DENIAL_HEADER]).toBeUndefined()
  })

  it('a middleware scope denial carries no denial header (only handler denials do)', async () => {
    authState.realMiddleware = true
    svc.getUserAgents.mockResolvedValue({ userId: 'user-1', agentNames: [] })
    const { app } = buildApp(KNOWN_HOSTS)
    const tokenWith = (scopes: Array<'mcp:servers:list' | 'host:status:read'>, jti: string) =>
      signRpcAccessToken({
        sub: 'user-1',
        typ: 'user',
        teamId: 'team-1',
        role: 'member',
        scopes,
        hostRefs: ['host-a'],
        jti,
      })

    // Scope not in the route's allow-list: the REAL middleware answers 403.
    const scopeDenied = await request(app)
      .get(HOST_URL('user-1', 'host-a'))
      .set('x-rpc-access-token', tokenWith(['mcp:servers:list'], 'rpc-jti-scope-denied'))
      .expect(403)
    expect(scopeDenied.body).toEqual({ error: 'Forbidden' })
    expect(scopeDenied.headers[DENIAL_HEADER]).toBeUndefined()
    // Witness: the handler never ran for the scope denial.
    expect(svc.getUserAgents).not.toHaveBeenCalled()

    // Same real middleware, allowed scope: the handler runs and its denial DOES
    // carry the header, proving the absence above is the middleware's doing.
    const handlerDenied = await request(app)
      .get(HOST_URL('user-1', 'host-a'))
      .set('x-rpc-access-token', tokenWith(['host:status:read'], 'rpc-jti-handler-denied'))
      .expect(403)
    // The token carries a teamId and the directory stub knows no such team.
    expect(handlerDenied.headers[DENIAL_HEADER]).toBe('team_membership_missing')
    expect(svc.getUserAgents).toHaveBeenCalledTimes(1)
  })
})