@@ -12,7 +12,7 @@ import {
1212 mayUseHostedKey ,
1313} from '@/lib/billing/core/hosted-key-access'
1414import type { UsageUpgradePayer } from '@/lib/billing/usage-upgrade'
15- import { getRotatingApiKey } from '@/lib/core/config/api-keys'
15+ import { getRotatingApiKey , hasRotatingApiKey } from '@/lib/core/config/api-keys'
1616import { env } from '@/lib/core/config/env'
1717import { isHosted } from '@/lib/core/config/env-flags'
1818import { redactDatabaseQueryError } from '@/lib/core/errors/database-query-error'
@@ -76,11 +76,8 @@ function nextRotationIndex(poolKey: string, poolSize: number): number {
7676 * pool can never fall through to an organization pool.
7777 */
7878async function decryptBYOKPool (
79- keys : readonly EncryptedBYOKKey [ ] ,
80- rotationPoolKey : string ,
81- providerId : BYOKProviderId ,
82- scope : BYOKKeyScope ,
83- scopeName : BYOKKeyScopeName
79+ { keys, rotationPoolKey, scope, scopeName } : BYOKKeyPool ,
80+ providerId : BYOKProviderId
8481) : Promise < BYOKKeyResult > {
8582 const startIndex = nextRotationIndex ( rotationPoolKey , keys . length )
8683 for ( let offset = 0 ; offset < keys . length ; offset ++ ) {
@@ -122,13 +119,43 @@ export async function getBYOKKey(
122119 options : { signal ?: AbortSignal } = { }
123120) : Promise < BYOKKeyResult | null > {
124121 if ( ! workspaceId ) return null
122+ return withBYOKLookup ( workspaceId , providerId , options . signal , async ( signal ) => {
123+ const pool = await findBYOKKeyPool ( workspaceId , providerId , signal )
124+ return pool ? decryptBYOKPool ( pool , providerId ) : null
125+ } )
126+ }
125127
128+ /**
129+ * Whether the workspace holds an eligible BYOK key for the provider, by the same rules as
130+ * {@link getBYOKKey}, without decrypting a key or advancing its pool's rotation.
131+ */
132+ async function hasBYOKKey (
133+ workspaceId : string | undefined | null ,
134+ providerId : BYOKProviderId ,
135+ options : { signal ?: AbortSignal } = { }
136+ ) : Promise < boolean > {
137+ if ( ! workspaceId ) return false
138+ return withBYOKLookup (
139+ workspaceId ,
140+ providerId ,
141+ options . signal ,
142+ async ( signal ) => ( await findBYOKKeyPool ( workspaceId , providerId , signal ) ) !== null
143+ )
144+ }
145+
146+ /** Runs one BYOK lookup under the shared deadline, retrying transient database reads. */
147+ function withBYOKLookup < T > (
148+ workspaceId : string ,
149+ providerId : BYOKProviderId ,
150+ parentSignal : AbortSignal | undefined ,
151+ lookup : ( signal : AbortSignal ) => Promise < T >
152+ ) : Promise < T > {
126153 return withinDeadline (
127154 async ( signal ) => {
128155 for ( let attempt = 1 ; ; attempt ++ ) {
129156 signal . throwIfAborted ( )
130157 try {
131- const result = await resolveBYOKKey ( workspaceId , providerId , signal )
158+ const result = await lookup ( signal )
132159 signal . throwIfAborted ( )
133160 return result
134161 } catch ( error ) {
@@ -150,15 +177,23 @@ export async function getBYOKKey(
150177 }
151178 } ,
152179 Date . now ( ) + BYOK_LOOKUP_TIMEOUT_MS ,
153- options . signal
180+ parentSignal
154181 )
155182}
156183
157- async function resolveBYOKKey (
184+ interface BYOKKeyPool {
185+ keys : EncryptedBYOKKey [ ]
186+ rotationPoolKey : string
187+ scope : BYOKKeyScope
188+ scopeName : BYOKKeyScopeName
189+ }
190+
191+ /** Selects the one key pool a workspace's BYOK lookup may use, or null when none is eligible. */
192+ async function findBYOKKeyPool (
158193 workspaceId : string ,
159194 providerId : BYOKProviderId ,
160195 signal : AbortSignal
161- ) : Promise < BYOKKeyResult | null > {
196+ ) : Promise < BYOKKeyPool | null > {
162197 const workspaceKeys = await db
163198 . select ( { id : workspaceBYOKKeys . id , encryptedApiKey : workspaceBYOKKeys . encryptedApiKey } )
164199 . from ( workspaceBYOKKeys )
@@ -172,13 +207,12 @@ async function resolveBYOKKey(
172207
173208 signal . throwIfAborted ( )
174209 if ( workspaceKeys . length ) {
175- return decryptBYOKPool (
176- workspaceKeys ,
177- `${ workspaceId } :${ providerId } ` ,
178- providerId ,
179- { workspaceId } ,
180- 'workspace'
181- )
210+ return {
211+ keys : workspaceKeys ,
212+ rotationPoolKey : `${ workspaceId } :${ providerId } ` ,
213+ scope : { workspaceId } ,
214+ scopeName : 'workspace' ,
215+ }
182216 }
183217
184218 const organizationKeys = await db
@@ -223,13 +257,12 @@ async function resolveBYOKKey(
223257 return null
224258 }
225259
226- return decryptBYOKPool (
227- organizationKeys ,
228- `organization:${ organizationId } :${ providerId } ` ,
229- providerId ,
230- { workspaceId, organizationId } ,
231- 'organization'
232- )
260+ return {
261+ keys : organizationKeys ,
262+ rotationPoolKey : `organization:${ organizationId } :${ providerId } ` ,
263+ scope : { workspaceId, organizationId } ,
264+ scopeName : 'organization' ,
265+ }
233266}
234267
235268/**
@@ -277,6 +310,37 @@ async function resolveHostedModelKey(
277310 }
278311}
279312
313+ /** The platform key pool that serves a provider's hosted models (Google's is `gemini`). */
314+ function hostedKeyPool ( provider : string ) : string {
315+ return provider === 'google' ? 'gemini' : provider
316+ }
317+
318+ /**
319+ * Whether {@link getApiKeyWithBYOK} would find a key for a catalogued hosted model on hosted Sim,
320+ * with no caller key: Sim's key when the platform holds one for the provider and the payer may
321+ * use it, else the workspace's BYOK key for the provider. Answers without resolving the key, so
322+ * nothing is decrypted and no pool's rotation advances. Any other model, or a self-hosted
323+ * deployment, answers false.
324+ */
325+ export async function hasHostedModelKey (
326+ provider : string ,
327+ model : string ,
328+ workspaceId : string ,
329+ options : { billingAttribution ?: UsageUpgradePayer ; signal ?: AbortSignal } = { }
330+ ) : Promise < boolean > {
331+ if ( ! isHosted ) return false
332+ if ( ! getHostedModels ( ) . some ( ( hosted ) => hosted . toLowerCase ( ) === model . toLowerCase ( ) ) ) {
333+ return false
334+ }
335+ if (
336+ hasRotatingApiKey ( hostedKeyPool ( provider ) ) &&
337+ ( await mayUseHostedKey ( workspaceId , options . billingAttribution ) )
338+ ) {
339+ return true
340+ }
341+ return hasBYOKKey ( workspaceId , provider as BYOKProviderId , { signal : options . signal } )
342+ }
343+
280344/**
281345 * Resolves credentials for the provider already selected by model routing.
282346 * Discovery lists must not override that provider and select a different key pool.
@@ -453,7 +517,7 @@ export async function getApiKeyWithBYOK(
453517
454518 if ( isModelHosted ) {
455519 return resolveHostedModelKey (
456- isGeminiModel ? 'gemini' : provider ,
520+ hostedKeyPool ( provider ) ,
457521 model ,
458522 workspaceId ,
459523 userProvidedKey ,
0 commit comments