Skip to content

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

TypeScript
6.7 KB
Raw Blame
import { describe, expect, it, vi } from 'vitest'
import { PassThrough } from 'node:stream'
import {
  ClerumMcpServer,
  bindPluginSdkCredentialTarget,
  parseJsonBody,
  pluginSdkCredentialTargetEchoMatches,
  revalidatePluginSdkCredentialTicket,
} from './server'

function response(status: number, body: unknown): Response {
  return new Response(JSON.stringify(body), {
    status,
    headers: { 'Content-Type': 'application/json' },
  })
}

async function parseBody(body: string) {
  const request = new PassThrough()
  const parsed = parseJsonBody(request as never)
  request.end(body)
  return parsed
}

describe('WRC JSON body boundary', () => {
  it.each(['null', '[]', '"scalar"', '42', 'true'])(
    'rejects JSON %s because the endpoint contract requires an object',
    async body => {
      await expect(parseBody(body)).resolves.toEqual({ ok: false, reason: 'invalid_json' })
    }
  )

  it('accepts a JSON object', async () => {
    await expect(parseBody('{"messages":[]}')).resolves.toEqual({
      ok: true,
      body: { messages: [] },
    })
  })
})

describe('WRC Plugin SDK credential ticket TOCTOU revalidation', () => {
  it('denies a body target mismatch before the resolver and returns only signed claims', () => {
    const signedTarget = {
      targetRef: 'primary-openai',
      provider: 'openai',
      model: 'gpt-5.4-mini',
      credentialSlot: 'openai-api-key',
    }
    const mismatched = { ...signedTarget, provider: 'claude' }
    expect(bindPluginSdkCredentialTarget(signedTarget, mismatched)).toBeNull()
    expect(bindPluginSdkCredentialTarget(signedTarget, signedTarget)).toEqual(signedTarget)
    expect(pluginSdkCredentialTargetEchoMatches(signedTarget, mismatched)).toBe(false)
    expect(pluginSdkCredentialTargetEchoMatches(signedTarget, signedTarget)).toBe(true)
  })

  it('consumes each verified ticket jti only once within its TTL', () => {
    const server = new ClerumMcpServer({} as never, 8082, {} as never, 'sandbox-recipes')
    const consume = (
      server as unknown as { consumePluginSdkTicket: (jti: string) => boolean }
    ).consumePluginSdkTicket.bind(server)
    expect(consume('ticket-jti')).toBe(true)
    expect(consume('ticket-jti')).toBe(false)
    expect(consume('another-ticket-jti')).toBe(true)
  })

  it('calls control-api immediately with runtime auth and accepts only active=true', async () => {
    const fetchImpl = vi.fn().mockResolvedValue(response(200, { active: true }))
    await expect(
      revalidatePluginSdkCredentialTicket({
        runtimeToken: 'runtime-jwt',
        credentialTicket: 'signed-ticket',
        invocationId: 'inv-1',
        attemptGeneration: 1,
        providerAttemptId: 'provider-attempt-1',
        providerAttemptIndex: 1,
        targetRef: 'primary-zai',
        fetchImpl: fetchImpl as unknown as typeof fetch,
        controlApiBaseUrl: 'http://control-api:8090/',
      })
    ).resolves.toBe(true)
    const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]
    expect(url).toBe(
      'http://control-api:8090/api/v1/mcp-host/plugin-workload-sdk/credential-ticket/introspect'
    )
    expect((init.headers as Record<string, string>).Authorization).toBe('Bearer runtime-jwt')
    expect(JSON.parse(String(init.body))).toEqual({
      credentialTicket: 'signed-ticket',
      invocationId: 'inv-1',
      attemptGeneration: 1,
      providerAttemptId: 'provider-attempt-1',
      providerAttemptIndex: 1,
      targetRef: 'primary-zai',
    })
  })

  it('marks the post-read revalidation as the one-shot redemption boundary', async () => {
    const fetchImpl = vi.fn().mockResolvedValue(response(200, { active: true }))
    await expect(
      revalidatePluginSdkCredentialTicket({
        runtimeToken: 'runtime-jwt',
        credentialTicket: 'signed-ticket',
        invocationId: 'inv-1',
        attemptGeneration: 1,
        providerAttemptId: 'provider-attempt-2',
        providerAttemptIndex: 2,
        targetRef: 'fallback-openai',
        redeem: true,
        fetchImpl: fetchImpl as unknown as typeof fetch,
      })
    ).resolves.toBe(true)
    const [, init] = fetchImpl.mock.calls[0] as [string, RequestInit]
    expect(JSON.parse(String(init.body))).toEqual({
      credentialTicket: 'signed-ticket',
      invocationId: 'inv-1',
      attemptGeneration: 1,
      providerAttemptId: 'provider-attempt-2',
      providerAttemptIndex: 2,
      targetRef: 'fallback-openai',
      redeem: true,
    })
  })

  it.each([
    [200, { active: false }],
    [403, { error: 'provider_policy_denied' }],
    [503, { error: 'unavailable' }],
  ])('fails closed for status/body %#', async (status, body) => {
    const fetchImpl = vi.fn().mockResolvedValue(response(status as number, body))
    await expect(
      revalidatePluginSdkCredentialTicket({
        runtimeToken: 'runtime-jwt',
        credentialTicket: 'signed-ticket',
        invocationId: 'inv-1',
        attemptGeneration: 1,
        providerAttemptId: 'provider-attempt-1',
        providerAttemptIndex: 1,
        targetRef: 'primary-zai',
        fetchImpl: fetchImpl as unknown as typeof fetch,
        controlApiBaseUrl: 'http://control-api:8090',
      })
    ).resolves.toBe(false)
  })

  it('fails closed on network failure without exposing the ticket', async () => {
    const fetchImpl = vi.fn().mockRejectedValue(new Error('network detail'))
    await expect(
      revalidatePluginSdkCredentialTicket({
        runtimeToken: 'runtime-jwt',
        credentialTicket: 'signed-ticket',
        invocationId: 'inv-1',
        attemptGeneration: 1,
        providerAttemptId: 'provider-attempt-1',
        providerAttemptIndex: 1,
        targetRef: 'primary-zai',
        fetchImpl: fetchImpl as unknown as typeof fetch,
      })
    ).resolves.toBe(false)
  })
})

// C-WRC: `/configure-model` grantRedeemable for Grok must honor the same
// WRC_GROK_SUBSCRIPTION_ENABLED the recipe verdict folds in. Mutation caught:
// building the REST ModelConfigHandler without the loaded Grok flag.
describe('WRC MCP server ModelConfigHandler Grok flag wiring', () => {
  function handlerFlag(env: string | undefined): unknown {
    vi.stubEnv('WRC_GROK_SUBSCRIPTION_ENABLED', env)
    try {
      const kc = { makeApiClient: () => ({}) }
      const server = new ClerumMcpServer(
        {} as never,
        8082,
        {} as never,
        'sandbox-recipes',
        kc as never
      )
      const handler = (server as unknown as { modelConfigHandler: Record<string, unknown> | null })
        .modelConfigHandler
      return handler?.grokSubscriptionEnabled
    } finally {
      vi.unstubAllEnvs()
    }
  }

  it('reads WRC_GROK_SUBSCRIPTION_ENABLED into the configure-model broker', () => {
    expect(handlerFlag('true')).toBe(true)
    expect(handlerFlag('false')).toBe(false)
    expect(handlerFlag(undefined)).toBe(false)
  })
})