( credentialId: string, actingUserId: string | undefined, callerLabel = 'vertex' )
| 14 | * members and by derived workspace admins, matching `authorizeCredentialUse`. |
| 15 | */ |
| 16 | export async function resolveVertexCredential( |
| 17 | credentialId: string, |
| 18 | actingUserId: string | undefined, |
| 19 | callerLabel = 'vertex' |
| 20 | ): Promise<string> { |
| 21 | const requestId = `${callerLabel}-${Date.now()}` |
| 22 | |
| 23 | logger.info(`[${requestId}] Resolving Vertex AI credential: ${credentialId}`) |
| 24 | |
| 25 | if (!actingUserId) { |
| 26 | throw new Error('Vertex AI credential use requires an authenticated user') |
| 27 | } |
| 28 | |
| 29 | const access = await getCredentialActorContext(credentialId, actingUserId) |
| 30 | const cred = access.credential |
| 31 | if (!cred) { |
| 32 | throw new Error(`Vertex AI credential not found: ${credentialId}`) |
| 33 | } |
| 34 | if (!access.hasWorkspaceAccess || (!access.member && !access.isAdmin)) { |
| 35 | throw new Error('Not authorized to use this Vertex AI credential') |
| 36 | } |
| 37 | |
| 38 | if (cred.type === 'service_account') { |
| 39 | const accessToken = await getServiceAccountToken(cred.id, [ |
| 40 | 'https://www.googleapis.com/auth/cloud-platform', |
| 41 | ]) |
| 42 | logger.info(`[${requestId}] Successfully resolved Vertex AI service account credential`) |
| 43 | return accessToken |
| 44 | } |
| 45 | |
| 46 | if (cred.type !== 'oauth' || !cred.accountId) { |
| 47 | throw new Error(`Vertex AI credential is not a valid OAuth credential: ${credentialId}`) |
| 48 | } |
| 49 | |
| 50 | const accountRow = await db.query.account.findFirst({ |
| 51 | where: eq(account.id, cred.accountId), |
| 52 | }) |
| 53 | |
| 54 | if (!accountRow) { |
| 55 | throw new Error(`Vertex AI credential not found: ${credentialId}`) |
| 56 | } |
| 57 | |
| 58 | const { accessToken } = await refreshTokenIfNeeded(requestId, accountRow, cred.accountId) |
| 59 | |
| 60 | if (!accessToken) { |
| 61 | throw new Error('Failed to get Vertex AI access token') |
| 62 | } |
| 63 | |
| 64 | logger.info(`[${requestId}] Successfully resolved Vertex AI credential`) |
| 65 | return accessToken |
| 66 | } |
no test coverage detected