mirror of
https://github.com/hanzoai/insights.git
synced 2026-11-02 14:32:45 +00:00
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.
94 lines
3.8 KiB
TypeScript
94 lines
3.8 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
|
|
|
import { rateLimitBlockedByTeam } from '@/hono/metrics'
|
|
import { __resetTrackedTeamIds, recordRateLimitBlock } from '@/hono/rate-limit-telemetry'
|
|
import type { RateLimitResult } from '@/hono/rate-limiter'
|
|
import type { RequestProperties } from '@/lib/request-properties'
|
|
|
|
function blocked(scope = 'mcp_sustained'): RateLimitResult {
|
|
return { allowed: false, scope, limit: 4800, remaining: 0, resetSeconds: 60 }
|
|
}
|
|
|
|
function makeProps(overrides: Partial<RequestProperties> = {}): RequestProperties {
|
|
return { apiToken: 'token', userHash: 'hash-a', ...overrides } as RequestProperties
|
|
}
|
|
|
|
async function teamValue(teamId: string, scope = 'mcp_sustained'): Promise<number> {
|
|
const data = await rateLimitBlockedByTeam.get()
|
|
const match = data.values.find((v) => v.labels.team_id === teamId && v.labels.scope === scope)
|
|
return match?.value ?? 0
|
|
}
|
|
|
|
describe('recordRateLimitBlock', () => {
|
|
beforeEach(() => {
|
|
rateLimitBlockedByTeam.reset()
|
|
__resetTrackedTeamIds()
|
|
})
|
|
|
|
async function totalSeries(): Promise<number> {
|
|
return (await rateLimitBlockedByTeam.get()).values.length
|
|
}
|
|
|
|
it('labels by the client-supplied project id without touching redis', async () => {
|
|
const get = vi.fn()
|
|
await recordRateLimitBlock({ get } as never, makeProps({ projectId: '123' }), blocked())
|
|
expect(await teamValue('123')).toBe(1)
|
|
expect(get).not.toHaveBeenCalled()
|
|
})
|
|
|
|
it('falls back to the cached team id when no header is present', async () => {
|
|
const get = vi.fn(async (key: string) => (key === 'mcp:token:hash-a:projectId' ? JSON.stringify('456') : null))
|
|
await recordRateLimitBlock({ get } as never, makeProps(), blocked())
|
|
expect(await teamValue('456')).toBe(1)
|
|
})
|
|
|
|
it('uses the unresolved bucket when the team is unknown', async () => {
|
|
const get = vi.fn(async () => null)
|
|
await recordRateLimitBlock({ get } as never, makeProps(), blocked())
|
|
expect(await teamValue('unresolved')).toBe(1)
|
|
})
|
|
|
|
it('never throws and still records when the cache read fails', async () => {
|
|
const get = vi.fn(async () => {
|
|
throw new Error('redis down')
|
|
})
|
|
await expect(recordRateLimitBlock({ get } as never, makeProps(), blocked())).resolves.toBeUndefined()
|
|
expect(await teamValue('unresolved')).toBe(1)
|
|
})
|
|
|
|
it('logs the block with the project id and a token redacted to its last 4 chars', async () => {
|
|
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
|
const get = vi.fn()
|
|
await recordRateLimitBlock(
|
|
{ get } as never,
|
|
makeProps({ projectId: '123', apiToken: 'sk-secrettoken9876' }),
|
|
blocked('mcp_burst')
|
|
)
|
|
expect(warn).toHaveBeenCalledWith(
|
|
'[RateLimiter] rate limited',
|
|
JSON.stringify({ scope: 'mcp_burst', projectId: '123', token: '****9876' })
|
|
)
|
|
warn.mockRestore()
|
|
})
|
|
|
|
it.each([['not-a-number'], ['12345678901234567890'], ['1; DROP']])(
|
|
'buckets a non-numeric or oversized project id %j as unresolved',
|
|
async (projectId) => {
|
|
const get = vi.fn()
|
|
await recordRateLimitBlock({ get } as never, makeProps({ projectId }), blocked())
|
|
expect(await teamValue('unresolved')).toBe(1)
|
|
expect(get).not.toHaveBeenCalled()
|
|
}
|
|
)
|
|
|
|
it('caps distinct team series and routes the overflow to other', async () => {
|
|
const get = vi.fn()
|
|
for (let i = 0; i < 1500; i += 1) {
|
|
await recordRateLimitBlock({ get } as never, makeProps({ projectId: String(i) }), blocked())
|
|
}
|
|
// 1000 real teams + the "other" overflow bucket = 1001 series, never 1500
|
|
expect(await totalSeries()).toBe(1001)
|
|
expect(await teamValue('other')).toBe(500)
|
|
})
|
|
})
|