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
fix(gateway): tell gcp token failures apart
bernie-g0a311c7434d5
diff --git a/backend/src/ee/services/resource-auth-method/gcp-auth-fns.test.ts b/backend/src/ee/services/resource-auth-method/gcp-auth-fns.test.tsindex 1aae50bdeb..03a8dea9ec 100644--- a/backend/src/ee/services/resource-auth-method/gcp-auth-fns.test.ts+++ b/backend/src/ee/services/resource-auth-method/gcp-auth-fns.test.ts@@ -155,11 +155,17 @@ vi.mock("@app/services/identity-gcp-auth/identity-gcp-auth-fns", () => ({// Neither the logger nor the crypto layer is initialised in the unit environment.vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));+// jsonwebtoken returns null for anything it cannot decode rather than throwing.vi.mock("@app/lib/crypto", () => ({crypto: {jwt: () => ({- decode: (token: string) =>- JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString()) as Record<string, unknown>+ decode: (token: string) => {+ try {+ return JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString()) as Record<string, unknown>;+ } catch {+ return null;+ }+ }})}}));@@ -176,8 +182,9 @@ describe("verifyGcpTokenAndExtractCaller", () => {test("dispatches the gce type to the ID token validator", async () => {vi.mocked(validateIdTokenIdentity).mockResolvedValue({ email: SERVICE_ACCOUNT, computeEngineDetails: undefined });- await verifyGcpTokenAndExtractCaller({ type: "gce", jwt: "t", audience: "gw-1", errorContext });- expect(validateIdTokenIdentity).toHaveBeenCalledWith({ audience: "gw-1", jwt: "t" });+ const jwt = jwtWith({ aud: "gw-1" });+ await verifyGcpTokenAndExtractCaller({ type: "gce", jwt, audience: "gw-1", errorContext });+ expect(validateIdTokenIdentity).toHaveBeenCalledWith({ audience: "gw-1", jwt });expect(validateIamIdentity).not.toHaveBeenCalled();});@@ -189,16 +196,23 @@ describe("verifyGcpTokenAndExtractCaller", () => {expect(validateIdTokenIdentity).not.toHaveBeenCalled();});- test("wraps a verification failure as an unauthorized error carrying the resource id", async () => {+ test("refuses a token that does not parse before calling a validator", async () => {+ await expect(+ verifyGcpTokenAndExtractCaller({ type: "gce", jwt: "not-a-jwt", audience: "gw-1", errorContext })+ ).rejects.toMatchObject({ detail: { reasonCode: "gcp_malformed_token", resourceId: "gw-1" } });+ expect(validateIdTokenIdentity).not.toHaveBeenCalled();+ });++ test("reports a signature or upstream failure separately from a rejected claim", async () => {vi.mocked(validateIdTokenIdentity).mockRejectedValue(new Error("bad signature"));await expect(- verifyGcpTokenAndExtractCaller({ type: "gce", jwt: "t", audience: "gw-1", errorContext })+ verifyGcpTokenAndExtractCaller({ type: "gce", jwt: jwtWith({ aud: "gw-1" }), audience: "gw-1", errorContext })).rejects.toMatchObject({detail: { reasonCode: "gcp_token_verification_failed", resourceId: "gw-1" }});});- test("wraps an unauthorized error raised by the validator itself", async () => {+ test("reports a claim the validator rejected as such", async () => {vi.mocked(validateIamIdentity).mockRejectedValue(new UnauthorizedError({ message: "Invalid audience" }));await expect(verifyGcpTokenAndExtractCaller({@@ -208,7 +222,7 @@ describe("verifyGcpTokenAndExtractCaller", () => {errorContext})).rejects.toMatchObject({- detail: { reasonCode: "gcp_token_verification_failed", resourceId: "gw-1" }+ detail: { reasonCode: "gcp_token_rejected", resourceId: "gw-1" }});});diff --git a/backend/src/ee/services/resource-auth-method/gcp-auth-fns.ts b/backend/src/ee/services/resource-auth-method/gcp-auth-fns.tsindex f859447a52..32478efc38 100644--- a/backend/src/ee/services/resource-auth-method/gcp-auth-fns.ts+++ b/backend/src/ee/services/resource-auth-method/gcp-auth-fns.ts@@ -46,6 +46,14 @@ export const verifyGcpTokenAndExtractCaller = async ({audience,errorContext}: TVerifyGcpTokenInput): Promise<TGcpIdentityDetails> => {+ // A token that does not even parse is the caller's mistake, not a verification outcome.+ if (!crypto.jwt().decode(jwt)) {+ throw new UnauthorizedError({+ message: "Access denied: the GCP token could not be parsed as a JWT.",+ detail: { reasonCode: ResourceAuthLoginFailureReason.GcpMalformedToken, ...errorContext }+ });+ }+let identityDetails: TGcpIdentityDetails;try {identityDetails =@@ -57,12 +65,20 @@ export const verifyGcpTokenAndExtractCaller = async ({err,`Resource GCP Auth Login: token verification failed [resourceId=${String(errorContext.resourceId)}]`);++ // The validators raise UnauthorizedError when a claim is wrong and anything else when the+ // signature check or the call to Google fails, so the two are worth telling apart.+ const claimRejected = err instanceof UnauthorizedError;throw new UnauthorizedError({- message:- type === GcpAuthType.Gce- ? "Could not verify the GCP identity token. Check that it was issued for this gateway's ID as the audience."- : "Could not verify the signed GCP service account token. Check that it was signed for this gateway's ID as the audience.",- detail: { reasonCode: ResourceAuthLoginFailureReason.GcpTokenVerificationFailed, ...errorContext }+ message: claimRejected+ ? "Access denied: the GCP token's claims were rejected. Check that it was issued for this gateway's ID as the audience, and that it carries a service account identity."+ : "Access denied: the GCP token could not be verified against Google's signing keys. This is a bad signature, an expired token, or Google being unreachable.",+ detail: {+ reasonCode: claimRejected+ ? ResourceAuthLoginFailureReason.GcpTokenRejected+ : ResourceAuthLoginFailureReason.GcpTokenVerificationFailed,+ ...errorContext+ }});}diff --git a/backend/src/ee/services/resource-auth-method/resource-auth-method-fns.ts b/backend/src/ee/services/resource-auth-method/resource-auth-method-fns.tsindex a7699650f1..825ee24d3c 100644--- a/backend/src/ee/services/resource-auth-method/resource-auth-method-fns.ts+++ b/backend/src/ee/services/resource-auth-method/resource-auth-method-fns.ts@@ -172,6 +172,8 @@ export const ResourceAuthLoginFailureReason = {NameNotAllowed: "name_not_allowed",AudienceNotAllowed: "audience_not_allowed",GatewayProxyUnavailable: "gateway_proxy_unavailable",+ GcpMalformedToken: "gcp_malformed_token",+ GcpTokenRejected: "gcp_token_rejected",GcpTokenVerificationFailed: "gcp_token_verification_failed",GcpTokenLifetimeRejected: "gcp_token_lifetime_rejected",ServiceAccountNotAllowed: "service_account_not_allowed",