Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions packages/kilo-vscode/src/KiloProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,9 @@ import {
completeProviderOAuth as completeOAuthAction,
disconnectProvider as disconnectProviderAction,
saveCustomProvider as saveCustomProviderAction,
resolveStoredKey,
} from "./provider-actions"
import type { StoredProviderKey } from "./provider-actions"
import { fetchOpenAIModels, FetchModelsError } from "./shared/fetch-models"
import type { Agent } from "@kilocode/sdk/v2/client"
import { configFeatures } from "./features"
Expand Down Expand Up @@ -250,6 +252,13 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
private readonly extensionVersion =
vscode.extensions.getExtension("kilocode.kilo-code")?.packageJSON?.version ?? "unknown"
private cachedProvidersMessage: unknown = null
/**
* Provider API keys retained extension-side for authenticated model
* fetches (#10139). Keys are stripped before provider data reaches the
* webview, so fetch requests for an existing provider carry a providerID
* and the key is resolved here. Refreshed on every provider fetch.
*/
private storedProviderKeys: Record<string, StoredProviderKey> = {}
/** Coalesce provider refreshes — at most one follow-up rerun when a request lands mid-flight. */
private providersRefresh: Promise<void> | null = null
private providersQueued = false
Expand Down Expand Up @@ -1780,12 +1789,16 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
return
}
try {
const { response, authMethods, authStates } = await fetchProviderData(client, this.getWorkspaceDirectory())
const { response, authMethods, authStates, storedKeys } = await fetchProviderData(
client,
this.getWorkspaceDirectory(),
)
if (generation !== this.providersGeneration || client !== this.client) {
if (!this.providersQueued) return
generation = this.providersGeneration
continue
}
this.storedProviderKeys = storedKeys
const settings = vscode.workspace.getConfiguration("kilo-code.new.model")
const message = {
type: "providersLoaded",
Expand Down Expand Up @@ -1872,7 +1885,8 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
const rid = typeof msg.requestId === "string" ? msg.requestId : ""
const url = typeof msg.baseURL === "string" ? msg.baseURL : ""
if (!rid || !url) return
const key = typeof msg.apiKey === "string" ? msg.apiKey : undefined
const key =
typeof msg.apiKey === "string" ? msg.apiKey : resolveStoredKey(this.storedProviderKeys, msg.providerID, url)
const headers = msg.headers && typeof msg.headers === "object" ? (msg.headers as Record<string, string>) : undefined
try {
const models = await fetchOpenAIModels({ baseURL: url, apiKey: key, headers })
Expand Down
34 changes: 33 additions & 1 deletion packages/kilo-vscode/src/provider-actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ import { configFeatures } from "./features"
*/
type AuthState = "api" | "oauth" | "wellknown"

/** API key retained extension-side for authenticated model fetches (#10139). */
export interface StoredProviderKey {
key: string
baseURL: string
}

function disabledWithout(list: string[] | undefined, id: string) {
return (list ?? []).filter((item) => item !== id)
}
Expand Down Expand Up @@ -59,17 +65,43 @@ export async function fetchProviderData(client: KiloClient, dir: string) {
authRequest,
])
const authStates: Record<string, AuthState> = {}
const storedKeys: Record<string, StoredProviderKey> = {}
const all = response.all.map((item) => {
const raw = item as Record<string, unknown>
if (typeof raw.id === "string" && typeof raw.key === "string" && raw.key) {
authStates[raw.id] = "api"
// Retain the key on the extension side so model fetches for an existing
// provider can authenticate without the webview ever seeing the secret
// (#10139). Only providers with a configured baseURL are retained — the
// fetch handler requires a URL match before applying a stored key.
const options = record(raw.options) ? raw.options : undefined
const baseURL = options && typeof options.baseURL === "string" ? options.baseURL : undefined
if (baseURL) storedKeys[raw.id] = { key: raw.key, baseURL }
}
if (!("key" in raw)) return item
const next = { ...raw }
delete next.key
return next as (typeof response.all)[number]
})
return { response: { ...response, all }, authMethods, authStates }
return { response: { ...response, all }, authMethods, authStates, storedKeys }
}

/**
* Resolve the stored API key for a model fetch on an existing provider.
* The key is only applied when the requested URL matches the provider's
* configured baseURL, so a stored secret can never be redirected to a
* different host (e.g. after the user edits the URL field).
*/
export function resolveStoredKey(
storedKeys: Record<string, StoredProviderKey>,
providerID: unknown,
url: string,
): string | undefined {
if (typeof providerID !== "string" || !providerID) return undefined
const stored = storedKeys[providerID]
if (!stored) return undefined
const normalize = (value: string) => value.trim().replace(/\/+$/, "")
return normalize(stored.baseURL) === normalize(url) ? stored.key : undefined
}

export function buildActionContext(
Expand Down
73 changes: 72 additions & 1 deletion packages/kilo-vscode/tests/unit/provider-actions-save.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { describe, expect, it } from "bun:test"
import { connectProvider, disconnectProvider, fetchProviderData, saveCustomProvider } from "../../src/provider-actions"
import {
connectProvider,
disconnectProvider,
fetchProviderData,
resolveStoredKey,
saveCustomProvider,
} from "../../src/provider-actions"

type ExistingGlobal = { disabled_providers?: string[]; provider?: Record<string, unknown> }

Expand Down Expand Up @@ -441,4 +447,69 @@ describe("fetchProviderData", () => {
expect(result.authStates).toEqual({ "groq-test": "api" })
expect("key" in item).toBe(false)
})

it("retains stripped keys for providers with a configured baseURL", async () => {
const client = {
provider: {
list: async () => ({
data: {
all: [
{
id: "myprovider",
name: "My Provider",
source: "config",
key: "sk-stored",
env: [],
options: { baseURL: "https://example.com/v1" },
models: {},
},
{
id: "no-url",
name: "No URL",
source: "config",
key: "sk-other",
env: [],
models: {},
},
],
connected: [],
default: {},
},
}),
auth: async () => ({ data: {} }),
},
} as unknown as Parameters<typeof fetchProviderData>[0]

const result = await fetchProviderData(client, "/tmp")

expect(result.storedKeys).toEqual({
myprovider: { key: "sk-stored", baseURL: "https://example.com/v1" },
})
expect(result.response.all.every((item) => !("key" in (item as Record<string, unknown>)))).toBe(true)
})
})

describe("resolveStoredKey", () => {
const storedKeys = {
myprovider: { key: "sk-stored", baseURL: "https://example.com/v1" },
}

it("returns the stored key when the fetch URL matches the configured baseURL", () => {
expect(resolveStoredKey(storedKeys, "myprovider", "https://example.com/v1")).toBe("sk-stored")
})

it("tolerates trailing-slash differences", () => {
expect(resolveStoredKey(storedKeys, "myprovider", "https://example.com/v1/")).toBe("sk-stored")
})

it("refuses to apply the stored key to a different host or path", () => {
expect(resolveStoredKey(storedKeys, "myprovider", "https://evil.example.net/v1")).toBeUndefined()
expect(resolveStoredKey(storedKeys, "myprovider", "https://example.com/v2")).toBeUndefined()
})

it("returns undefined for unknown or missing provider ids", () => {
expect(resolveStoredKey(storedKeys, "other", "https://example.com/v1")).toBeUndefined()
expect(resolveStoredKey(storedKeys, undefined, "https://example.com/v1")).toBeUndefined()
expect(resolveStoredKey(storedKeys, "", "https://example.com/v1")).toBeUndefined()
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,12 @@ const CustomProviderDialog = (props: CustomProviderDialogProps) => {
const raw = fetchKey().trim()
const env = raw.match(/^\{env:([^}]+)\}$/)?.[1]?.trim()
const apiKey = raw && !env ? raw : undefined
// When editing an existing provider with the key field untouched, the
// webview has no key to send — keys are stripped before provider data
// reaches it. Send the providerID so the extension can authenticate the
// fetch with the stored key (#10139). Anything typed into the field
// (a key or {env:VAR} syntax) takes precedence.
const providerID = !raw && props.existing ? props.existing.providerID : undefined
const existing = new Set(form.models.map((m) => m.id.trim()).filter(Boolean))

const hdrs = form.headers
Expand Down Expand Up @@ -253,6 +259,7 @@ const CustomProviderDialog = (props: CustomProviderDialogProps) => {
requestId: rid,
baseURL: url,
apiKey,
providerID,
headers,
})
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -953,6 +953,13 @@ export interface FetchCustomProviderModelsMessage {
requestId: string
baseURL: string
apiKey?: string
/**
* When editing an existing provider and the key field is untouched, the
* webview has no key to send (keys are stripped before they reach it).
* It sends the providerID instead so the extension can authenticate the
* fetch with the stored key — which never crosses into the webview.
*/
providerID?: string
headers?: Record<string, string>
}

Expand Down
Loading