-
Notifications
You must be signed in to change notification settings - Fork 41
feat(gateway): add custom BYOK upstream routing primitives #3544
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| import { and, eq } from 'drizzle-orm'; | ||
| import { gateway_custom_upstreams } from '@kilocode/db/schema'; | ||
| import { decryptApiKey } from '@/lib/ai-gateway/byok/encryption'; | ||
| import { BYOK_ENCRYPTION_KEY } from '@/lib/config.server'; | ||
| import type { db as drizzleDb } from '@/lib/drizzle'; | ||
|
|
||
| export type CustomUpstreamResolved = { | ||
| providerId: string; | ||
| upstreamModelId: string; | ||
| apiKey: string; | ||
| baseUrl: string; | ||
| extraHeaders: Record<string, string>; | ||
| }; | ||
|
|
||
| export async function getCustomUpstreamForModel( | ||
| db: typeof drizzleDb, | ||
| owner: { organizationId?: string; userId: string }, | ||
| requestedModel: string | ||
| ): Promise<CustomUpstreamResolved | null> { | ||
| const [providerId, ...rest] = requestedModel.split('/'); | ||
| const upstreamModelId = rest.join('/'); | ||
| if (!providerId || !upstreamModelId) return null; | ||
|
|
||
| const [row] = await db | ||
| .select() | ||
| .from(gateway_custom_upstreams) | ||
| .where( | ||
| and( | ||
| eq(gateway_custom_upstreams.provider_id, providerId), | ||
| eq(gateway_custom_upstreams.is_enabled, true), | ||
| owner.organizationId | ||
| ? eq(gateway_custom_upstreams.organization_id, owner.organizationId) | ||
| : eq(gateway_custom_upstreams.kilo_user_id, owner.userId) | ||
| ) | ||
| ); | ||
| if (!row) return null; | ||
| try { | ||
| const apiKey = decryptApiKey(row.encrypted_api_key, BYOK_ENCRYPTION_KEY); | ||
| const extraHeaders = row.encrypted_extra_headers | ||
| ? (JSON.parse(decryptApiKey(row.encrypted_extra_headers, BYOK_ENCRYPTION_KEY)) as Record< | ||
| string, | ||
| string | ||
| >) | ||
| : {}; | ||
| return { providerId, upstreamModelId, apiKey, baseUrl: row.base_url, extraHeaders }; | ||
| } catch (error) { | ||
| console.error('[getCustomUpstreamForModel] failed to decrypt custom upstream', { | ||
| providerId, | ||
| upstreamModelId, | ||
| error, | ||
| }); | ||
| return null; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,18 +1,63 @@ | ||
| import { baseProcedure, createTRPCRouter } from '@/lib/trpc/init'; | ||
| import { preferredModels } from '@/lib/ai-gateway/models'; | ||
| import { getEnhancedOpenRouterModels } from '@/lib/ai-gateway/providers/openrouter'; | ||
| import { db } from '@/lib/drizzle'; | ||
| import { gateway_custom_upstreams, organization_memberships } from '@kilocode/db/schema'; | ||
| import { and, eq, inArray } from 'drizzle-orm'; | ||
| import { ensureOrganizationAccess } from '@/routers/organizations/utils'; | ||
| import * as z from 'zod'; | ||
|
|
||
| const preferredSet = new Set(preferredModels); | ||
|
|
||
| export const modelsRouter = createTRPCRouter({ | ||
| list: baseProcedure.query(async () => { | ||
| const response = await getEnhancedOpenRouterModels(); | ||
|
|
||
| return (response.data ?? []).map(model => ({ | ||
| id: model.id, | ||
| name: model.name, | ||
| supportsVision: model.architecture.input_modalities.includes('image'), | ||
| isPreferred: preferredSet.has(model.id), | ||
| })); | ||
| }), | ||
| list: baseProcedure | ||
| .input(z.object({ organizationId: z.string().uuid().optional() }).optional()) | ||
| .query(async ({ ctx, input }) => { | ||
| const response = await getEnhancedOpenRouterModels(); | ||
|
|
||
| const gatewayModels = (response.data ?? []).map(model => ({ | ||
| id: model.id, | ||
| name: model.name, | ||
| supportsVision: model.architecture.input_modalities.includes('image'), | ||
| isPreferred: preferredSet.has(model.id), | ||
| })); | ||
|
|
||
| if (input?.organizationId) { | ||
| await ensureOrganizationAccess(ctx, input.organizationId); | ||
| } | ||
|
|
||
| const orgMemberships = await db | ||
| .select({ organization_id: organization_memberships.organization_id }) | ||
| .from(organization_memberships) | ||
| .where(eq(organization_memberships.kilo_user_id, ctx.user.id)); | ||
| const orgIds = orgMemberships.map(m => m.organization_id); | ||
|
|
||
| const upstreams = await db | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. SUGGESTION: Over-fetching sensitive fields — the full |
||
| .select() | ||
| .from(gateway_custom_upstreams) | ||
| .where( | ||
| and( | ||
| eq(gateway_custom_upstreams.is_enabled, true), | ||
| input?.organizationId | ||
| ? eq(gateway_custom_upstreams.organization_id, input.organizationId) | ||
| : orgIds.length > 0 | ||
| ? inArray(gateway_custom_upstreams.organization_id, orgIds) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. WARNING: Logic bug — user-owned upstreams are silently dropped when the user belongs to any organization. When The intent is likely to include both org-owned upstreams and user-owned upstreams when no |
||
| : eq(gateway_custom_upstreams.kilo_user_id, ctx.user.id) | ||
| ) | ||
| ); | ||
|
|
||
| const customModels = upstreams.flatMap(upstream => { | ||
| const mm = upstream.model_metadata as { | ||
| models?: Array<{ id: string; name?: string; supportsVision?: boolean }>; | ||
| }; | ||
| return (mm.models ?? []).map(model => ({ | ||
| id: `${upstream.provider_id}/${model.id}`, | ||
| name: model.name ?? model.id, | ||
| supportsVision: !!model.supportsVision, | ||
| isPreferred: false, | ||
| })); | ||
| }); | ||
|
|
||
| return [...gatewayModels, ...customModels]; | ||
| }), | ||
| }); | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| CREATE TABLE "gateway_custom_upstreams" ( | ||
| "id" uuid PRIMARY KEY DEFAULT pg_catalog.gen_random_uuid() NOT NULL, | ||
| "organization_id" uuid, | ||
| "kilo_user_id" text, | ||
| "provider_id" text NOT NULL, | ||
| "display_name" text NOT NULL, | ||
| "base_url" text NOT NULL, | ||
| "encrypted_api_key" jsonb NOT NULL, | ||
| "encrypted_extra_headers" jsonb, | ||
| "model_metadata" jsonb DEFAULT '{}'::jsonb NOT NULL, | ||
| "is_enabled" boolean DEFAULT true NOT NULL, | ||
| "created_at" timestamp with time zone DEFAULT now() NOT NULL, | ||
| "updated_at" timestamp with time zone DEFAULT now() NOT NULL, | ||
| "created_by" text NOT NULL, | ||
| CONSTRAINT "UQ_gateway_custom_upstreams_org_provider" UNIQUE("organization_id","provider_id"), | ||
| CONSTRAINT "UQ_gateway_custom_upstreams_user_provider" UNIQUE("kilo_user_id","provider_id"), | ||
| CONSTRAINT "gateway_custom_upstreams_owner_check" CHECK ((( "gateway_custom_upstreams"."kilo_user_id" IS NOT NULL AND "gateway_custom_upstreams"."organization_id" IS NULL) OR ( "gateway_custom_upstreams"."kilo_user_id" IS NULL AND "gateway_custom_upstreams"."organization_id" IS NOT NULL))) | ||
| ); | ||
| --> statement-breakpoint | ||
| ALTER TABLE "gateway_custom_upstreams" ADD CONSTRAINT "gateway_custom_upstreams_organization_id_organizations_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organizations"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint | ||
| ALTER TABLE "gateway_custom_upstreams" ADD CONSTRAINT "gateway_custom_upstreams_kilo_user_id_kilocode_users_id_fk" FOREIGN KEY ("kilo_user_id") REFERENCES "public"."kilocode_users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint | ||
| CREATE INDEX "IDX_gateway_custom_upstreams_organization_id" ON "gateway_custom_upstreams" USING btree ("organization_id");--> statement-breakpoint | ||
| CREATE INDEX "IDX_gateway_custom_upstreams_kilo_user_id" ON "gateway_custom_upstreams" USING btree ("kilo_user_id");--> statement-breakpoint | ||
| CREATE INDEX "IDX_gateway_custom_upstreams_provider_id" ON "gateway_custom_upstreams" USING btree ("provider_id"); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
WARNING: Unsafe
ascast on decrypted JSON —JSON.parse(...)is cast directly toRecord<string, string>without validation. If the storedencrypted_extra_headerspayload was not a flat string-to-string object (e.g. nested values, numbers, or null), header injection could silently pass malformed data to the upstream. Consider adding a runtime shape check or using a Zod schema here.