Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(llm): add Application Default Credentials support for Vertex AI (#11039)

Hassieb Pakzad4b0b898d785b
diff --git a/packages/shared/src/interfaces/customLLMProviderConfigSchemas.ts b/packages/shared/src/interfaces/customLLMProviderConfigSchemas.ts
index cf360bd874..df20c5072f 100644
--- a/packages/shared/src/interfaces/customLLMProviderConfigSchemas.ts
+++ b/packages/shared/src/interfaces/customLLMProviderConfigSchemas.ts
@@ -4,6 +4,10 @@ import { z } from "zod/v4";
export const BEDROCK_USE_DEFAULT_CREDENTIALS =
"__BEDROCK_DEFAULT_CREDENTIALS__";
+// Sentinel value for Vertex AI default credential provider chain (ADC)
+export const VERTEXAI_USE_DEFAULT_CREDENTIALS =
+ "__VERTEXAI_DEFAULT_CREDENTIALS__";
+
export const BedrockConfigSchema = z.object({ region: z.string() });
export type BedrockConfig = z.infer<typeof BedrockConfigSchema>;
@@ -15,7 +19,12 @@ export const BedrockCredentialSchema = z
.optional();
export type BedrockCredential = z.infer<typeof BedrockCredentialSchema>;
-export const VertexAIConfigSchema = z.object({ location: z.string() });
+export const VertexAIConfigSchema = z
+ .object({
+ location: z.string().optional(),
+ })
+ .strict();
+
export type VertexAIConfig = z.infer<typeof VertexAIConfigSchema>;
export const GCPServiceAccountKeySchema = z.object({
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index 9bc75e6ca8..670b24029c 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -25,6 +25,7 @@ import GCPServiceAccountKeySchema, {
BedrockCredentialSchema,
VertexAIConfigSchema,
BEDROCK_USE_DEFAULT_CREDENTIALS,
+ VERTEXAI_USE_DEFAULT_CREDENTIALS,
} from "../../interfaces/customLLMProviderConfigSchemas";
import {
ChatMessage,
@@ -352,11 +353,27 @@ export async function fetchLLMCompletion(
additionalModelRequestFields: modelParams.providerOptions as any,
});
} else if (modelParams.adapter === LLMAdapter.VertexAI) {
- const credentials = GCPServiceAccountKeySchema.parse(JSON.parse(apiKey));
const { location } = config
? VertexAIConfigSchema.parse(config)
: { location: undefined };
+ // Handle both explicit credentials and default provider chain (ADC)
+ // Only allow default provider chain in self-hosted or internal AI features
+ const shouldUseDefaultCredentials =
+ apiKey === VERTEXAI_USE_DEFAULT_CREDENTIALS && !isLangfuseCloud;
+
+ // When using ADC, authOptions must be undefined to use google-auth-library's default credential chain
+ // This supports: GKE Workload Identity, Cloud Run service accounts, GCE metadata service, gcloud auth
+ // Security: We intentionally ignore user-provided projectId when using ADC to prevent
+ // privilege escalation attacks where users could access other GCP projects via the server's credentials
+ const authOptions = shouldUseDefaultCredentials
+ ? undefined // Always use ADC auto-detection, never allow user-specified projectId
+ : {
+ credentials: GCPServiceAccountKeySchema.parse(JSON.parse(apiKey)),
+ projectId: GCPServiceAccountKeySchema.parse(JSON.parse(apiKey))
+ .project_id,
+ };
+
// Requests time out after 60 seconds for both public and private endpoints by default
// Reference: https://cloud.google.com/vertex-ai/docs/predictions/get-online-predictions#send-request
chatModel = new ChatVertexAI({
@@ -367,10 +384,7 @@ export async function fetchLLMCompletion(
callbacks: finalCallbacks,
maxRetries,
location,
- authOptions: {
- projectId: credentials.project_id,
- credentials,
- },
+ authOptions,
...(modelParams.providerOptions && {
additionalModelRequestFields: modelParams.providerOptions,
}),
diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.ts
index df63d29a17..5082990f37 100644
--- a/web/src/features/llm-api-key/server/router.ts
+++ b/web/src/features/llm-api-key/server/router.ts
@@ -19,6 +19,7 @@ import {
BedrockConfigSchema,
VertexAIConfigSchema,
BEDROCK_USE_DEFAULT_CREDENTIALS,
+ VERTEXAI_USE_DEFAULT_CREDENTIALS,
} from "@langfuse/shared";
import { encrypt, decrypt } from "@langfuse/shared/encryption";
import {
@@ -35,6 +36,9 @@ export function getDisplaySecretKey(secretKey: string) {
if (secretKey === BEDROCK_USE_DEFAULT_CREDENTIALS) {
return "Default AWS credentials";
}
+ if (secretKey === VERTEXAI_USE_DEFAULT_CREDENTIALS) {
+ return "Default GCP credentials (ADC)";
+ }
return secretKey.endsWith('"}')
? "..." + secretKey.slice(-6, -2)
: "..." + secretKey.slice(-4);
@@ -61,10 +65,14 @@ async function testLLMConnection(
if (!model) throw Error("No model found");
if (params.adapter === LLMAdapter.VertexAI) {
- const parsed = GCPServiceAccountKeySchema.safeParse(
- JSON.parse(params.secretKey),
- );
- if (!parsed.success) throw Error("Invalid GCP service account JSON key");
+ // Skip validation if using ADC (Application Default Credentials)
+ if (params.secretKey !== VERTEXAI_USE_DEFAULT_CREDENTIALS) {
+ const parsed = GCPServiceAccountKeySchema.safeParse(
+ JSON.parse(params.secretKey),
+ );
+ if (!parsed.success)
+ throw Error("Invalid GCP service account JSON key");
+ }
}
const testMessages: ChatMessage[] = [
@@ -79,6 +87,7 @@ async function testLLMConnection(
let parsedConfig: Record<string, string> | null = null;
if (params.config && params.adapter === LLMAdapter.Bedrock) {
const bedrockConfig = BedrockConfigSchema.parse(params.config);
+
parsedConfig = { region: bedrockConfig.region };
} else if (params.config && params.adapter === LLMAdapter.VertexAI) {
const vertexAIConfig = VertexAIConfigSchema.parse(params.config);
@@ -127,17 +136,25 @@ export const llmApiKeyRouter = createTRPCRouter({
scope: "llmApiKeys:create",
});
- // Validate that default credentials sentinel is only allowed for Bedrock in self-hosted deployments
- if (input.secretKey === BEDROCK_USE_DEFAULT_CREDENTIALS) {
- const isLangfuseCloud = Boolean(
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
- );
+ // Validate that default credentials sentinel is only allowed for Bedrock/VertexAI in self-hosted deployments
+ const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
+ if (input.secretKey === BEDROCK_USE_DEFAULT_CREDENTIALS) {
if (isLangfuseCloud || input.adapter !== LLMAdapter.Bedrock) {
throw new TRPCError({
code: "BAD_REQUEST",
message:
- "Default credentials are only allowed for Bedrock in self-hosted deployments.",
+ "Default AWS credentials are only allowed for Bedrock in self-hosted deployments.",
+ });
+ }
+ }
+
+ if (input.secretKey === VERTEXAI_USE_DEFAULT_CREDENTIALS) {
+ if (isLangfuseCloud || input.adapter !== LLMAdapter.VertexAI) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "Default GCP credentials (ADC) are only allowed for Vertex AI in self-hosted deployments.",
});
}
}
@@ -426,17 +443,25 @@ export const llmApiKeyRouter = createTRPCRouter({
});
}
- // Validate that default credentials sentinel is only allowed for Bedrock in self-hosted deployments
- if (input.secretKey === BEDROCK_USE_DEFAULT_CREDENTIALS) {
- const isLangfuseCloud = Boolean(
- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
- );
+ // Validate that default credentials sentinel is only allowed for Bedrock/VertexAI in self-hosted deployments
+ const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
+ if (input.secretKey === BEDROCK_USE_DEFAULT_CREDENTIALS) {
if (isLangfuseCloud || input.adapter !== LLMAdapter.Bedrock) {
throw new TRPCError({
code: "BAD_REQUEST",
message:
- "Default credentials are only allowed for Bedrock in self-hosted deployments.",
+ "Default AWS credentials are only allowed for Bedrock in self-hosted deployments.",
+ });
+ }
+ }
+
+ if (input.secretKey === VERTEXAI_USE_DEFAULT_CREDENTIALS) {
+ if (isLangfuseCloud || input.adapter !== LLMAdapter.VertexAI) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "Default GCP credentials (ADC) are only allowed for Vertex AI in self-hosted deployments.",
});
}
}
diff --git a/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx b/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx
index 20de26ab71..e4de2a804a 100644
--- a/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx
+++ b/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx
@@ -8,6 +8,7 @@ import {
LLMAdapter,
type LlmApiKeys,
BEDROCK_USE_DEFAULT_CREDENTIALS,
+ VERTEXAI_USE_DEFAULT_CREDENTIALS,
} from "@langfuse/shared";
import { ChevronDown, PlusIcon, TrashIcon } from "lucide-react";
import { z } from "zod/v4";
@@ -127,9 +128,28 @@ const createFormSchema = (mode: "create" | "update") =>
path: ["withDefaultModels"],
},
)
+ // Vertex AI validation - service account key or ADC sentinel value required
+ .refine(
+ (data) => {
+ if (data.adapter !== LLMAdapter.VertexAI) return true;
+
+ // In update mode, credentials are optional (existing ones are preserved)
+ if (mode === "update") return true;
+
+ // secretKey is required (either JSON key or VERTEXAI_USE_DEFAULT_CREDENTIALS sentinel)
+ return !!data.secretKey;
+ },
+ {
+ message: isLangfuseCloud
+ ? "GCP service account JSON key is required for Vertex AI"
+ : "GCP service account JSON key or Application Default Credentials is required.",
+ path: ["secretKey"],
+ },
+ )
.refine(
(data) =>
data.adapter === LLMAdapter.Bedrock ||
+ data.adapter === LLMAdapter.VertexAI ||
mode === "update" ||
data.secretKey,
{
@@ -211,7 +231,11 @@ export function CreateLLMApiKeyForm({
? {
adapter: existingKey.adapter as LLMAdapter,
provider: existingKey.provider,
- secretKey: "",
+ secretKey:
+ existingKey.adapter === LLMAdapter.VertexAI &&
+ existingKey.displaySecretKey === "Default GCP credentials (ADC)"
+ ? VERTEXAI_USE_DEFAULT_CREDENTIALS
+ : "",
baseURL:
existingKey.baseURL ??
getCustomizedBaseURL(existingKey.adapter as LLMAdapter),
@@ -442,13 +466,29 @@ export function CreateLLMApiKeyForm({
config = {
region: values.awsRegion ?? "",
};
- } else if (
- currentAdapter === LLMAdapter.VertexAI &&
- values.vertexAILocation
- ) {
- config = {
- location: values.vertexAILocation.trim(),
- };
+ } else if (currentAdapter === LLMAdapter.VertexAI) {
+ // Handle Vertex AI credentials
+ // secretKey already contains either JSON key or VERTEXAI_USE_DEFAULT_CREDENTIALS sentinel
+ if (mode === "update") {
+ // In update mode, only update secretKey if a new one is provided
+ if (values.secretKey) {
+ secretKey = values.secretKey;
+ } else {
+ // Keep existing credentials by not setting secretKey
+ secretKey = undefined;
+ }
+ }
+ // In create mode, secretKey is already set from values.secretKey
+
+ // Build config with location only (projectId removed for security - ADC auto-detects)
+ config = {};
+ if (values.vertexAILocation?.trim()) {
+ config.location = values.vertexAILocation.trim();
+ }
+ // If config is empty, set to undefined
+ if (Object.keys(config).length === 0) {
+ config = undefined;
+ }
}
const extraHeaders =
@@ -580,7 +620,7 @@ export function CreateLLMApiKeyForm({
)}
/>
- {/* API Key or AWS Credentials */}
+ {/* API Key or AWS Credentials or Vertex AI Credentials */}
{currentAdapter === LLMAdapter.Bedrock ? (
<>
<FormField
@@ -722,25 +762,65 @@ export function CreateLLMApiKeyForm({
</div>
)}
</>
- ) : (
- <FormField
- control={form.control}
- name="secretKey"
- render={({ field }) => (
+ ) : currentAdapter === LLMAdapter.VertexAI ? (
+ <>
+ {/* Vertex AI ADC option for self-hosted only, create mode only */}
+ {!isLangfuseCloud && mode === "create" && (
<FormItem>
- <FormLabel>API Key</FormLabel>
- <FormDescription>
- {isLangfuseCloud
- ? "Your API keys are stored encrypted on our servers."
- : "Your API keys are stored encrypted in your database."}
- </FormDescription>
- {currentAdapter === LLMAdapter.VertexAI && (
- <FormDescription className="text-dark-yellow">
- Paste your GCP service account JSON key here. The service
- account must have `Vertex AI User` role permissions.
- Example JSON:
- <pre className="text-xs">
- {`{
+ <span className="row flex">
+ <span className="flex-1">
+ <FormLabel>
+ Use Application Default Credentials (ADC)
+ </FormLabel>
+ <FormDescription>
+ When enabled, authentication uses the GCP
+ environment&apos;s default credentials instead of a
+ service account key.
+ </FormDescription>
+ </span>
+ <FormControl>
+ <Switch
+ checked={
+ form.watch("secretKey") ===
+ VERTEXAI_USE_DEFAULT_CREDENTIALS
+ }
+ onCheckedChange={(checked) => {
+ if (checked) {
+ form.setValue(
+ "secretKey",
+ VERTEXAI_USE_DEFAULT_CREDENTIALS,
+ );
+ } else {
+ form.setValue("secretKey", "");
+ }
+ }}
+ />
+ </FormControl>
+ </span>
+ </FormItem>
+ )}
+
+ {/* Service Account Key - hidden when ADC is enabled */}
+ {(isLangfuseCloud ||
+ form.watch("secretKey") !==
+ VERTEXAI_USE_DEFAULT_CREDENTIALS) && (
+ <FormField
+ control={form.control}
+ name="secretKey"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>GCP Service Account Key (JSON)</FormLabel>
+ <FormDescription>
+ {isLangfuseCloud
+ ? "Your API keys are stored encrypted on our servers."
+ : "Your API keys are stored encrypted in your database."}
+ </FormDescription>
+ <FormDescription className="text-dark-yellow">
+ Paste your GCP service account JSON key here. The
+ service account must have `Vertex AI User` role
+ permissions. Example JSON:
+ <pre className="text-xs">
+ {`{
"type": "service_account",
"project_id": "<project_id>",
"private_key_id": "<private_key_id>",
@@ -752,9 +832,74 @@ export function CreateLLMApiKeyForm({
"auth_provider_x509_cert_url": "<auth_provider_x509_cert_url>",
"client_x509_cert_url": "<client_x509_cert_url>",
}`}
- </pre>
- </FormDescription>
+ </pre>
+ </FormDescription>
+ <FormControl>
+ <Input
+ {...field}
+ placeholder={
+ mode === "update"
+ ? existingKey?.displaySecretKey
+ : '{"type": "service_account", ...}'
+ }
+ autoComplete="off"
+ spellCheck="false"
+ autoCapitalize="off"
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
)}
+ />
+ )}
+
+ {/* ADC info box for self-hosted */}
+ {!isLangfuseCloud &&
+ form.watch("secretKey") ===
+ VERTEXAI_USE_DEFAULT_CREDENTIALS && (
+ <div className="space-y-2 border-l-2 border-blue-200 pl-4 text-sm text-muted-foreground">
+ <p>
+ <strong>Application Default Credentials (ADC):</strong>{" "}
+ When enabled, the system will automatically check for
+ credentials in this order:
+ </p>
+ <ul className="ml-2 list-inside list-disc space-y-1">
+ <li>
+ Environment variable (GOOGLE_APPLICATION_CREDENTIALS)
+ </li>
+ <li>
+ gcloud CLI credentials (gcloud auth application-default
+ login)
+ </li>
+ <li>GKE Workload Identity</li>
+ <li>Cloud Run service account</li>
+ <li>GCE instance service account (metadata service)</li>
+ </ul>
+ <p>
+ <a
+ href="https://cloud.google.com/docs/authentication/application-default-credentials"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-blue-600 underline hover:text-blue-800"
+ >
+ Learn more about GCP Application Default Credentials →
+ </a>
+ </p>
+ </div>
+ )}
+ </>
+ ) : (
+ <FormField
+ control={form.control}
+ name="secretKey"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>API Key</FormLabel>
+ <FormDescription>
+ {isLangfuseCloud
+ ? "Your API keys are stored encrypted on our servers."
+ : "Your API keys are stored encrypted in your database."}
+ </FormDescription>
<FormControl>
<Input
{...field}