|
| 1 | +import { beforeEach, describe, expect, test } from '@jest/globals'; |
| 2 | +import { NextRequest, NextResponse } from 'next/server'; |
| 3 | +import type { OpenRouterModel } from '@/lib/organizations/organization-types'; |
| 4 | +import { getEnhancedOpenRouterModels } from '@/lib/ai-gateway/providers/openrouter'; |
| 5 | +import { getUserFromAuth } from '@/lib/user/server'; |
| 6 | +import { getDirectByokModelsForUser } from '@/lib/ai-gateway/providers/direct-byok'; |
| 7 | +import { listAvailableExperimentModels } from '@/lib/ai-gateway/experiments/list-available-experiment-models'; |
| 8 | +import { ORGANIZATION_ID_HEADER } from '@/lib/constants'; |
| 9 | +import { POST } from './route'; |
| 10 | + |
| 11 | +jest.mock('@sentry/nextjs', () => ({ captureException: jest.fn() })); |
| 12 | +jest.mock('@/lib/user/server', () => ({ getUserFromAuth: jest.fn() })); |
| 13 | +jest.mock('@/lib/ai-gateway/providers/openrouter', () => ({ |
| 14 | + getEnhancedOpenRouterModels: jest.fn(), |
| 15 | +})); |
| 16 | +jest.mock('@/lib/ai-gateway/providers/direct-byok', () => ({ |
| 17 | + getDirectByokModelsForUser: jest.fn(), |
| 18 | +})); |
| 19 | +jest.mock('@/lib/ai-gateway/experiments/list-available-experiment-models', () => ({ |
| 20 | + listAvailableExperimentModels: jest.fn(), |
| 21 | +})); |
| 22 | + |
| 23 | +const mockedGetUserFromAuth = jest.mocked(getUserFromAuth); |
| 24 | +const mockedGetEnhancedOpenRouterModels = jest.mocked(getEnhancedOpenRouterModels); |
| 25 | +const mockedGetDirectByokModelsForUser = jest.mocked(getDirectByokModelsForUser); |
| 26 | +const mockedListAvailableExperimentModels = jest.mocked(listAvailableExperimentModels); |
| 27 | + |
| 28 | +function makeModel(id: string): OpenRouterModel { |
| 29 | + return { |
| 30 | + id, |
| 31 | + name: id, |
| 32 | + created: 0, |
| 33 | + description: '', |
| 34 | + architecture: { |
| 35 | + input_modalities: ['text'], |
| 36 | + output_modalities: ['text'], |
| 37 | + tokenizer: 'test', |
| 38 | + }, |
| 39 | + top_provider: { is_moderated: false }, |
| 40 | + pricing: { prompt: '0', completion: '0' }, |
| 41 | + context_length: 0, |
| 42 | + supported_parameters: ['tools'], |
| 43 | + }; |
| 44 | +} |
| 45 | + |
| 46 | +function request(modelId: string, headers?: HeadersInit) { |
| 47 | + return new NextRequest('http://localhost:3000/api/openrouter/models/validate', { |
| 48 | + method: 'POST', |
| 49 | + headers, |
| 50 | + body: JSON.stringify({ modelId }), |
| 51 | + }); |
| 52 | +} |
| 53 | + |
| 54 | +describe('POST /api/openrouter/models/validate', () => { |
| 55 | + beforeEach(() => { |
| 56 | + jest.resetAllMocks(); |
| 57 | + mockedGetUserFromAuth.mockResolvedValue({ |
| 58 | + user: null, |
| 59 | + organizationId: null, |
| 60 | + authFailedResponse: null, |
| 61 | + } as never); |
| 62 | + mockedGetEnhancedOpenRouterModels.mockResolvedValue({ data: [makeModel('available/model')] }); |
| 63 | + mockedGetDirectByokModelsForUser.mockResolvedValue([]); |
| 64 | + mockedListAvailableExperimentModels.mockResolvedValue([]); |
| 65 | + }); |
| 66 | + |
| 67 | + test('confirms a Kilo-eligible catalog model', async () => { |
| 68 | + const response = await POST(request('available/model')); |
| 69 | + |
| 70 | + expect(response.status).toBe(200); |
| 71 | + await expect(response.json()).resolves.toEqual({ valid: true }); |
| 72 | + }); |
| 73 | + |
| 74 | + test('does not expose details for an unavailable model', async () => { |
| 75 | + const response = await POST(request('missing/model')); |
| 76 | + |
| 77 | + expect(response.status).toBe(200); |
| 78 | + await expect(response.json()).resolves.toEqual({ valid: false, reason: 'unavailable' }); |
| 79 | + }); |
| 80 | + |
| 81 | + test('uses the public catalog after failed optional authentication', async () => { |
| 82 | + mockedGetUserFromAuth.mockResolvedValue({ |
| 83 | + user: null, |
| 84 | + organizationId: null, |
| 85 | + authFailedResponse: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }), |
| 86 | + } as never); |
| 87 | + |
| 88 | + const response = await POST(request('available/model')); |
| 89 | + |
| 90 | + expect(response.status).toBe(200); |
| 91 | + await expect(response.json()).resolves.toEqual({ valid: true }); |
| 92 | + }); |
| 93 | + |
| 94 | + test('rejects organization-scoped validation through the personal endpoint', async () => { |
| 95 | + const response = await POST( |
| 96 | + request('available/model', { [ORGANIZATION_ID_HEADER]: 'organization-id' }) |
| 97 | + ); |
| 98 | + |
| 99 | + expect(response.status).toBe(400); |
| 100 | + await expect(response.json()).resolves.toEqual({ |
| 101 | + error: 'Organization-scoped validation must use /api/organizations/[id]/models/validate', |
| 102 | + }); |
| 103 | + expect(mockedGetUserFromAuth).not.toHaveBeenCalled(); |
| 104 | + expect(mockedGetEnhancedOpenRouterModels).not.toHaveBeenCalled(); |
| 105 | + }); |
| 106 | + |
| 107 | + test('returns a service failure when catalog construction fails', async () => { |
| 108 | + mockedGetEnhancedOpenRouterModels.mockRejectedValue(new Error('catalog unavailable')); |
| 109 | + |
| 110 | + const response = await POST(request('available/model')); |
| 111 | + |
| 112 | + expect(response.status).toBe(500); |
| 113 | + await expect(response.json()).resolves.toEqual({ |
| 114 | + error: 'Failed to validate model', |
| 115 | + message: 'Error from model catalog', |
| 116 | + }); |
| 117 | + }); |
| 118 | + |
| 119 | + test('loads authenticated auxiliary catalogs concurrently', async () => { |
| 120 | + mockedGetUserFromAuth.mockResolvedValue({ |
| 121 | + user: { id: 'user-id' }, |
| 122 | + organizationId: null, |
| 123 | + authFailedResponse: null, |
| 124 | + } as never); |
| 125 | + mockedGetEnhancedOpenRouterModels.mockResolvedValue({ data: [] }); |
| 126 | + let markByokStarted: (() => void) | undefined; |
| 127 | + const byokStarted = new Promise<void>(resolve => { |
| 128 | + markByokStarted = resolve; |
| 129 | + }); |
| 130 | + type DirectByokModels = Awaited<ReturnType<typeof getDirectByokModelsForUser>>; |
| 131 | + let resolveByok: ((models: DirectByokModels) => void) | undefined; |
| 132 | + const byokPending = new Promise<DirectByokModels>(resolve => { |
| 133 | + resolveByok = resolve; |
| 134 | + }); |
| 135 | + mockedGetDirectByokModelsForUser.mockImplementation(() => { |
| 136 | + if (!markByokStarted) throw new Error('BYOK start signal was not initialized'); |
| 137 | + markByokStarted(); |
| 138 | + return byokPending; |
| 139 | + }); |
| 140 | + mockedListAvailableExperimentModels.mockResolvedValue([makeModel('experiment/model')]); |
| 141 | + |
| 142 | + const responsePromise = POST(request('experiment/model')); |
| 143 | + await byokStarted; |
| 144 | + const finishByok = resolveByok; |
| 145 | + if (!finishByok) throw new Error('BYOK lookup did not start'); |
| 146 | + try { |
| 147 | + expect(mockedListAvailableExperimentModels).toHaveBeenCalledTimes(1); |
| 148 | + } finally { |
| 149 | + finishByok([]); |
| 150 | + await responsePromise; |
| 151 | + } |
| 152 | + }); |
| 153 | + |
| 154 | + test('rejects an invalid body without reading a catalog', async () => { |
| 155 | + const response = await POST( |
| 156 | + new NextRequest('http://localhost:3000/api/openrouter/models/validate', { |
| 157 | + method: 'POST', |
| 158 | + body: JSON.stringify({ modelId: '' }), |
| 159 | + }) |
| 160 | + ); |
| 161 | + |
| 162 | + expect(response.status).toBe(400); |
| 163 | + expect(mockedGetEnhancedOpenRouterModels).not.toHaveBeenCalled(); |
| 164 | + }); |
| 165 | +}); |
0 commit comments