Files
insights/services/mcp/tests/hono/dispatcher-init-revalidation.test.ts
zeekay 19fdf55ceb feat(auth): one key scheme, minted and read in one place
A key now opens with what it is allowed to touch. `pk-` is publishable and
safe in a browser; `sk-` is secret and never leaves a server. The five marks
it replaces all began `ph` -- the upstream's initials -- and they were the
last of its brand a customer read back to us, in every SDK snippet. No word
rule could reach them, because `ph` is not a word.

The marks were also not telling the truth. The constant said `phc_` while
every live project token said `hi_`, so the middleware that routes on the
constant matched no real token at all. Two spellings existed and one was
fiction. Minting now happens in exactly one function and reading in exactly
one, so a second spelling has nowhere to live.

`phx_` (personal) and `phs_` (project secret) both become `sk-`. The mark
now says only that a value is secret; which store holds it is settled by
asking. That was already how personal keys worked -- keys minted before the
marks carry none, so the store always decided -- and both secret resolvers
already returned None on a miss and fell through, so one shared extractor
replaces the two that could drift apart.

OAuth's access and refresh tokens stay distinguishable as `at-` and `rt-`,
because the parser tells them apart before either is looked up, and the
domain-verification token becomes `vt-` rather than keeping a sixth mint of
its own.

`bin/debrand --check` now refuses the marks as a shape, so a seventh cannot
be coined. Two rules that were about to rename things that are not ours to
spell are bounded: `Lemon` no longer eats `LemonSqueezy`, and the `hog_flow`
rules no longer reach a Postgres table, a Datastore table or a route.

Keys are stored hashed, so a mark cannot be rewritten in place: the three
live project tokens have to be reminted.
2026-08-08 19:42:44 -07:00

153 lines
4.9 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from 'vitest'
const {
mockBuildInstructions,
mockInitDurationObserve,
mockInitTotalInc,
mockRevalidateContextMillResources,
mockResolveState,
mockTrackInitEvent,
} = vi.hoisted(() => ({
mockBuildInstructions: vi.fn(),
mockInitDurationObserve: vi.fn(),
mockInitTotalInc: vi.fn(),
mockRevalidateContextMillResources: vi.fn(),
mockResolveState: vi.fn(),
mockTrackInitEvent: vi.fn(),
}))
vi.mock('@/hono/analytics', () => ({
trackInitEvent: mockTrackInitEvent,
}))
vi.mock('@/hono/instructions', () => ({
InstructionsBuilder: vi.fn().mockImplementation(function () {
return {
build: mockBuildInstructions,
}
}),
}))
vi.mock('@/hono/metrics', () => ({
initDurationSeconds: { observe: mockInitDurationObserve },
initTotal: { inc: mockInitTotalInc },
}))
vi.mock('@/hono/request-state-resolver', () => ({
RequestStateResolver: vi.fn().mockImplementation(function () {
return {
resolve: mockResolveState,
}
}),
}))
vi.mock('@/hono/resource-catalog', () => ({
ResourceCatalog: vi.fn().mockImplementation(function () {
return {
getPrompt: vi.fn(() => ({ messages: [] })),
getPromptsList: vi.fn(() => ({ prompts: [] })),
getResourcesList: vi.fn(() => ({ resources: [] })),
readResource: vi.fn(async () => ({ contents: [] })),
revalidateContextMillResources: mockRevalidateContextMillResources,
warmup: vi.fn(async () => {}),
}
}),
}))
import { LATEST_PROTOCOL_VERSION } from '@modelcontextprotocol/sdk/types.js'
import type { RedisLike } from '@/hono/cache/RedisCache'
import { McpDispatcher } from '@/hono/dispatcher'
import type { RequestProperties } from '@/lib/request-properties'
import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'
function createMockRedis(): RedisLike {
const store = new Map<string, string>()
return {
get: vi.fn(async (key: string) => store.get(key) ?? null),
set: vi.fn(async (key: string, value: string) => {
store.set(key, value)
return 'OK'
}),
del: vi.fn(async (...keys: string[]) => {
let count = 0
for (const key of keys) {
if (store.delete(key)) {
count++
}
}
return count
}),
scan: vi.fn(async () => ['0', []] as [string, string[]]),
...makeRedisRateLimitStubs(),
}
}
function makeProps(): RequestProperties {
return {
apiToken: 'sk-test',
mcpClientName: 'test-client',
mcpClientVersion: '1.0.0',
mcpProtocolVersion: LATEST_PROTOCOL_VERSION,
requestStartTime: Date.now(),
transport: 'streamable-http',
userHash: 'test-user',
}
}
function makeInitializeRequest(): Request {
return new Request('https://mcp.test/mcp', {
body: JSON.stringify({
id: 1,
jsonrpc: '2.0',
method: 'initialize',
params: {
capabilities: {},
clientInfo: { name: 'test-client', version: '1.0.0' },
protocolVersion: LATEST_PROTOCOL_VERSION,
},
}),
headers: { 'Content-Type': 'application/json' },
method: 'POST',
})
}
describe('McpDispatcher initialize resource revalidation', () => {
beforeEach(() => {
vi.clearAllMocks()
mockBuildInstructions.mockResolvedValue('')
mockResolveState.mockResolvedValue({ distinctId: 'test-distinct-id' })
mockTrackInitEvent.mockResolvedValue(undefined)
mockRevalidateContextMillResources.mockResolvedValue(undefined)
})
it('awaits context-mill resource revalidation before returning initialize', async () => {
let resolveRevalidation: (() => void) | undefined
const revalidationPromise = new Promise<void>((resolve) => {
resolveRevalidation = resolve
})
mockRevalidateContextMillResources.mockReturnValueOnce(revalidationPromise)
const dispatcher = new McpDispatcher({} as any, createMockRedis())
const responsePromise = dispatcher.handleRequest(makeInitializeRequest(), makeProps())
let responseSettled = false
void responsePromise.then(() => {
responseSettled = true
})
await new Promise((resolve) => setTimeout(resolve, 0))
expect(mockRevalidateContextMillResources).toHaveBeenCalledWith('initialize')
expect(responseSettled).toBe(false)
resolveRevalidation!()
const response = await responsePromise
const body = (await response.json()) as any
expect(response.status).toBe(200)
expect(body.result.protocolVersion).toBe(LATEST_PROTOCOL_VERSION)
expect(mockBuildInstructions).toHaveBeenCalled()
})
})