Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(gcp): enhance GCP IAM integration with AWS support and improved error logging
Victor Hugo dos Santos1bb35aa6db2a
diff --git a/backend/src/ee/services/dynamic-secret/providers/gcp-iam.ts b/backend/src/ee/services/dynamic-secret/providers/gcp-iam.tsindex d560b3d94f..d87e9f6c26 100644--- a/backend/src/ee/services/dynamic-secret/providers/gcp-iam.ts+++ b/backend/src/ee/services/dynamic-secret/providers/gcp-iam.ts@@ -4,6 +4,7 @@ import { GetAccessTokenResponse } from "google-auth-library/build/src/auth/oauthimport { getConfig } from "@app/lib/config/env";import { BadRequestError, InternalServerError } from "@app/lib/errors";import { sanitizeString } from "@app/lib/fn";+import { logger } from "@app/lib/logger";import { alphaNumericNanoId } from "@app/lib/nanoid";import { buildGcpSourceCredential } from "@app/services/app-connection/gcp/gcp-connection-fns";@@ -37,13 +38,13 @@ export const GcpIamProvider = (): TDynamicProviderFns => {try {tokenResponse = await impersonatedCredentials.getAccessToken();} catch (error) {- let message = "Unable to validate connection";- if (error instanceof gaxios.GaxiosError) {- message = error.message;- }+ logger.error(+ { err: error },+ `Failed to obtain GCP impersonated access token [serviceAccountEmail=${serviceAccountEmail}]`+ );throw new BadRequestError({- message+ message: error instanceof gaxios.GaxiosError ? error.message : "Unable to validate connection"});}diff --git a/backend/src/services/app-connection/gcp/gcp-connection-fns.test.ts b/backend/src/services/app-connection/gcp/gcp-connection-fns.test.tsnew file mode 100644index 0000000000..1c42341150--- /dev/null+++ b/backend/src/services/app-connection/gcp/gcp-connection-fns.test.ts@@ -0,0 +1,73 @@+import { AwsClient, JWT } from "google-auth-library";++import { buildGcpSourceCredential } from "./gcp-connection-fns";++// A workload-identity-federation config as downloaded from GCP for an AWS provider. Note the+// `credential_source` pointing at the EC2 metadata endpoint (169.254.169.254) - the address that is+// unreachable on ECS Fargate / Lambda / EKS and produced the original "unable to impersonate" error.+const awsExternalAccountJson = JSON.stringify({+ type: "external_account",+ audience:+ "//iam.googleapis.com/projects/123456789/locations/global/workloadIdentityPools/test-pool/providers/aws-provider",+ subject_token_type: "urn:ietf:params:aws:token-type:aws4_request",+ token_url: "https://sts.googleapis.com/v1/token",+ service_account_impersonation_url:+ "https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/[email protected]:generateAccessToken",+ credential_source: {+ environment_id: "aws1",+ region_url: "http://169.254.169.254/latest/meta-data/placement/availability-zone",+ url: "http://169.254.169.254/latest/meta-data/iam/security-credentials",+ regional_cred_verification_url: "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15",+ imdsv2_session_token_url: "http://169.254.169.254/latest/api/token"+ }+});++const serviceAccountKeyJson = JSON.stringify({+ type: "service_account",+ client_email: "[email protected]",+ // Test-only RSA key (not a real credential).+ private_key:+ "-----BEGIN PRIVATE KEY-----\nMIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAuKKMfyqM\n-----END PRIVATE KEY-----\n"+});++describe("buildGcpSourceCredential", () => {+ const AWS_ENV_KEYS = ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_REGION"];+ const savedEnv: Record<string, string | undefined> = {};++ beforeEach(() => {+ AWS_ENV_KEYS.forEach((key) => {+ savedEnv[key] = process.env[key];+ });+ });++ afterEach(() => {+ AWS_ENV_KEYS.forEach((key) => {+ if (savedEnv[key] === undefined) delete process.env[key];+ else process.env[key] = savedEnv[key];+ });+ });++ it("sources AWS credentials via the AWS SDK chain (never the EC2 metadata endpoint) for AWS external_account configs", async () => {+ // Simulate the instance's AWS identity being resolvable without metadata (as on Fargate, where the+ // container provider resolves credentials). If the client fell back to the EC2 metadata default, this+ // call would instead try to connect to 169.254.169.254 and fail.+ process.env.AWS_ACCESS_KEY_ID = "AKIATESTEXAMPLE";+ process.env.AWS_SECRET_ACCESS_KEY = "secretexample";+ process.env.AWS_SESSION_TOKEN = "sessiontoken";+ process.env.AWS_REGION = "us-east-1";++ const client = buildGcpSourceCredential(awsExternalAccountJson);+ expect(client).toBeInstanceOf(AwsClient);++ // retrieveSubjectToken() resolves credentials through the supplier and signs the STS request locally.+ // It completes offline here precisely because credentials come from the SDK chain, not metadata.+ const subjectToken = await (client as AwsClient).retrieveSubjectToken();+ expect(typeof subjectToken).toBe("string");+ expect(subjectToken.length).toBeGreaterThan(0);+ });++ it("builds a JWT client for service-account-key credentials", () => {+ const client = buildGcpSourceCredential(serviceAccountKeyJson);+ expect(client).toBeInstanceOf(JWT);+ });+});diff --git a/backend/src/services/app-connection/gcp/gcp-connection-fns.ts b/backend/src/services/app-connection/gcp/gcp-connection-fns.tsindex 3fc0ec133c..b6b81d2862 100644--- a/backend/src/services/app-connection/gcp/gcp-connection-fns.ts+++ b/backend/src/services/app-connection/gcp/gcp-connection-fns.ts@@ -1,9 +1,12 @@-import { ExternalAccountClient, gaxios, Impersonated, JWT } from "google-auth-library";+import { STSClient } from "@aws-sdk/client-sts";+import { AwsClient, ExternalAccountClient, gaxios, Impersonated, JWT } from "google-auth-library";import { GetAccessTokenResponse } from "google-auth-library/build/src/auth/oauth2client";+import RE2 from "re2";import { getConfig } from "@app/lib/config/env";import { request } from "@app/lib/config/request";import { BadRequestError, InternalServerError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";import { getAppConnectionMethodName } from "@app/services/app-connection/app-connection-fns";import { IntegrationUrls } from "@app/services/integration-auth/integration-list";@@ -27,16 +30,61 @@ export const getGcpConnectionListItem = () => {};};+type TGcpCredentialJson = {+ type?: string;+ client_email?: string;+ private_key?: string;+ subject_token_type?: string;+ credential_source?: { environment_id?: string };+};++const AWS_ENV_ID_REGEX = new RE2(/^aws\d+$/i);++// AWS federation configs default `credential_source` to the EC2 metadata endpoint, which+// is absent on Fargate/Lambda/EKS. Detect them so we can source creds via the AWS SDK chain instead.+const isAwsExternalAccount = (credJson: TGcpCredentialJson) =>+ credJson.subject_token_type === "urn:ietf:params:aws:token-type:aws4_request" ||+ AWS_ENV_ID_REGEX.test(credJson.credential_source?.environment_id ?? "");++const buildGcpAwsExternalAccountClient = (credJson: TGcpCredentialJson, scopes: string[]) => {+ // Resolve AWS creds via the SDK default chain.+ const stsClient = new STSClient({});++ const awsSecurityCredentialsSupplier = {+ getAwsRegion: async () => {+ try {+ return await stsClient.config.region();+ } catch {+ return "us-east-1";+ }+ },+ getAwsSecurityCredentials: async () => {+ const credentials = await stsClient.config.credentials();+ return {+ accessKeyId: credentials.accessKeyId,+ secretAccessKey: credentials.secretAccessKey,+ token: credentials.sessionToken+ };+ }+ };++ // credential_source and aws_security_credentials_supplier are mutually exclusive; drop the metadata source.+ const awsClientOptions = { ...credJson, scopes, aws_security_credentials_supplier: awsSecurityCredentialsSupplier };+ delete awsClientOptions.credential_source;++ return new AwsClient(awsClientOptions as unknown as ConstructorParameters<typeof AwsClient>[0]);+};+export const buildGcpSourceCredential = (credentialJson: string) => {const scopes = ["https://www.googleapis.com/auth/cloud-platform"];- const credJson = JSON.parse(credentialJson) as {- type?: string;- client_email?: string;- private_key?: string;- };+ const credJson = JSON.parse(credentialJson) as TGcpCredentialJson;if (credJson.type === "external_account") {+ if (isAwsExternalAccount(credJson)) {+ return buildGcpAwsExternalAccountClient(credJson, scopes);+ }+const externalClient = ExternalAccountClient.fromJSON({...credJson,scopes@@ -83,13 +131,13 @@ export const getGcpConnectionAuthToken = async (appConnection: TGcpConnectionContry {tokenResponse = await impersonatedCredentials.getAccessToken();} catch (error) {- let message = "Unable to validate connection";- if (error instanceof gaxios.GaxiosError) {- message = error.message;- }+ logger.error(+ { err: error },+ `Failed to obtain GCP impersonated access token [serviceAccountEmail=${appConnection.credentials.serviceAccountEmail}]`+ );throw new BadRequestError({- message+ message: error instanceof gaxios.GaxiosError ? error.message : "Unable to validate connection"});}diff --git a/docs/documentation/platform/dynamic-secrets/gcp-iam.mdx b/docs/documentation/platform/dynamic-secrets/gcp-iam.mdxindex 95e3cf2593..a76b7b2305 100644--- a/docs/documentation/platform/dynamic-secrets/gcp-iam.mdx+++ b/docs/documentation/platform/dynamic-secrets/gcp-iam.mdx@@ -50,12 +50,16 @@ The Infisical GCP IAM dynamic secret allows you to generate GCP service accountWorkload identity federation is also supported. Instead of a service account key, you mayset `INF_APP_CONNECTION_GCP_SERVICE_ACCOUNT_CREDENTIAL` to an `external_account` credentialconfiguration JSON (the file produced by `gcloud iam workload-identity-pools create-cred-config`).- Infisical detects the credential type from the `type` field automatically.+ Infisical detects the credential type from the `type` field automatically. The federated identity+ needs the `roles/iam.serviceAccountTokenCreator` role on the service accounts it impersonates.- Because an `external_account` config does not contain a secret but instead references a- credential source (a mounted file, a URL, or a metadata endpoint), that source must be- reachable from the Infisical instance at runtime. The federated identity also needs the- `roles/iam.serviceAccountTokenCreator` role on the service accounts it impersonates.+ For **AWS** providers, Infisical resolves the instance's AWS credentials through the standard AWS+ SDK credential chain, so federation works on EC2, ECS/Fargate, EKS (IRSA), and Lambda, or from+ `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` environment variables. The region defaults to+ `us-east-1`; set `AWS_REGION` (or `AWS_DEFAULT_REGION`) to use a specific regional STS endpoint.++ For other providers, the referenced credential source (a mounted file or URL) must be reachable+ from the Infisical instance at runtime.</Note></Step></Steps>diff --git a/docs/integrations/app-connections/gcp.mdx b/docs/integrations/app-connections/gcp.mdxindex bc31838611..45aba6d487 100644--- a/docs/integrations/app-connections/gcp.mdx+++ b/docs/integrations/app-connections/gcp.mdx@@ -48,12 +48,16 @@ Infisical supports [service account impersonation](https://cloud.google.com/iam/Workload identity federation is also supported. Instead of a service account key, you mayset `INF_APP_CONNECTION_GCP_SERVICE_ACCOUNT_CREDENTIAL` to an `external_account` credentialconfiguration JSON (the file produced by `gcloud iam workload-identity-pools create-cred-config`).- Infisical detects the credential type from the `type` field automatically.+ Infisical detects the credential type from the `type` field automatically. The federated identity+ needs the `roles/iam.serviceAccountTokenCreator` role on the service accounts it impersonates.- Because an `external_account` config does not contain a secret but instead references a- credential source (a mounted file, a URL, or a metadata endpoint), that source must be- reachable from the Infisical instance at runtime. The federated identity also needs the- `roles/iam.serviceAccountTokenCreator` role on the service accounts it impersonates.+ For **AWS** providers, Infisical resolves the instance's AWS credentials through the standard AWS+ SDK credential chain, so federation works on EC2, ECS/Fargate, EKS (IRSA), and Lambda, or from+ `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` environment variables. The region defaults to+ `us-east-1`; set `AWS_REGION` (or `AWS_DEFAULT_REGION`) to use a specific regional STS endpoint.++ For other providers, the referenced credential source (a mounted file or URL) must be reachable+ from the Infisical instance at runtime.</Note></Step></Steps>