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
chore: improved aws auth checks
=9a8bd5fa412a
diff --git a/backend/src/ee/services/resource-auth-method/aws-auth-fns.ts b/backend/src/ee/services/resource-auth-method/aws-auth-fns.tsindex 432925eced..7f6e087f7e 100644--- a/backend/src/ee/services/resource-auth-method/aws-auth-fns.ts+++ b/backend/src/ee/services/resource-auth-method/aws-auth-fns.ts@@ -1,32 +1,14 @@import RE2 from "re2";-import { isValidAwsRegion } from "@app/lib/aws/region";import { request } from "@app/lib/config/request";-import { UnauthorizedError } from "@app/lib/errors";+import { BadRequestError, UnauthorizedError } from "@app/lib/errors";import { logger } from "@app/lib/logger";-import { extractPrincipalArn } from "@app/services/identity-aws-auth/identity-aws-auth-fns";+import {+ extractPrincipalArn,+ parseSignedGetCallerIdentityRequest+} from "@app/services/identity-aws-auth/identity-aws-auth-fns";-import { TAwsGetCallerIdentityHeaders, TGetCallerIdentityResponse } from "./aws-auth-types";--// Parses the AWS region from the SigV4 Authorization header's Credential=… segment.-// Same approach as identity-aws-auth (services/identity-aws-auth/identity-aws-auth-service.ts).-// We trust the caller-provided region because the signature itself is bound to it; if the-// region is wrong, AWS STS will reject the proxied request.-const awsRegionFromHeader = (authorizationHeader: string): string | null => {- // Authorization: AWS4-HMAC-SHA256 Credential=AKIA.../<date>/<region>/sts/aws4_request, ...- try {- const fields = authorizationHeader.split(" ");- for (const field of fields) {- if (field.startsWith("Credential=")) {- const parts = field.split("/");- if (parts.length >= 3) return parts[2];- }- }- } catch {- return null;- }- return null;-};+import { TGetCallerIdentityResponse } from "./aws-auth-types";type TVerifyStsCallerInput = {iamHttpRequestMethod: string;@@ -45,34 +27,21 @@ export const verifyStsAndExtractCaller = async ({iamRequestHeaders,errorContext}: TVerifyStsCallerInput) => {- let headers: TAwsGetCallerIdentityHeaders;- let body: string;+ let signedRequest: ReturnType<typeof parseSignedGetCallerIdentityRequest>;try {- headers = JSON.parse(Buffer.from(iamRequestHeaders, "base64").toString()) as TAwsGetCallerIdentityHeaders;- body = Buffer.from(iamRequestBody, "base64").toString();- } catch {+ signedRequest = parseSignedGetCallerIdentityRequest({ iamHttpRequestMethod, iamRequestBody, iamRequestHeaders });+ } catch (err) {throw new UnauthorizedError({- message: "Malformed signed STS request",+ message: err instanceof BadRequestError ? err.message : "Malformed signed STS request",detail: { reasonCode: "malformed_request", ...errorContext }});}-- const authHeader = headers.Authorization || headers.authorization;- const region = authHeader ? awsRegionFromHeader(authHeader) : null;-- if (!isValidAwsRegion(region)) {- throw new UnauthorizedError({- message: "Invalid AWS region",- detail: { reasonCode: "invalid_region", ...errorContext }- });- }-- const url = `https://sts.${region}.amazonaws.com`;+ const { url, headers, body } = signedRequest;let stsResponse: { data: TGetCallerIdentityResponse };try {stsResponse = await request({- method: iamHttpRequestMethod,+ method: "POST",url,headers,data: bodydiff --git a/backend/src/ee/services/resource-auth-method/aws-auth-types.ts b/backend/src/ee/services/resource-auth-method/aws-auth-types.tsindex ab591ea22b..40bb0b7053 100644--- a/backend/src/ee/services/resource-auth-method/aws-auth-types.ts+++ b/backend/src/ee/services/resource-auth-method/aws-auth-types.ts@@ -1,13 +1,3 @@-export type TAwsGetCallerIdentityHeaders = {- "Content-Type": string;- Host: string;- "X-Amz-Date": string;- "Content-Length": number;- "x-amz-security-token": string;- Authorization: string;- authorization?: string;-};-export type TGetCallerIdentityResponse = {GetCallerIdentityResponse: {GetCallerIdentityResult: {diff --git a/backend/src/lib/aws/region.ts b/backend/src/lib/aws/region.tsindex f9db2167ee..2e75abf4bf 100644--- a/backend/src/lib/aws/region.ts+++ b/backend/src/lib/aws/region.ts@@ -1,6 +1,7 @@import RE2 from "re2";-const validRegionPattern = new RE2("^[a-z0-9-]+$");+// Shaped like a real region so sts.<region>.amazonaws.com can only be an STS endpoint, never e.g. sts.s3.amazonaws.com+const validRegionPattern = new RE2("^[a-z]+(-[a-z]+)+-[0-9]+$");export const isValidAwsRegion = (region: string | null): boolean => {if (typeof region !== "string" || region.length === 0 || region.length > 20) return false;diff --git a/backend/src/services/identity-aws-auth/identity-aws-auth-fns.test.ts b/backend/src/services/identity-aws-auth/identity-aws-auth-fns.test.tsindex 3dc5ac61b9..92c3d0494d 100644--- a/backend/src/services/identity-aws-auth/identity-aws-auth-fns.test.ts+++ b/backend/src/services/identity-aws-auth/identity-aws-auth-fns.test.ts@@ -1,6 +1,6 @@import { describe, expect, test } from "vitest";-import { hasAwsTrustBinding } from "./identity-aws-auth-fns";+import { hasAwsTrustBinding, parseSignedGetCallerIdentityRequest } from "./identity-aws-auth-fns";describe("hasAwsTrustBinding", () => {test.each([@@ -22,3 +22,120 @@ describe("hasAwsTrustBinding", () => {).toBe(true);});});++describe("parseSignedGetCallerIdentityRequest", () => {+ const authorizationFor = (region: string) =>+ `AWS4-HMAC-SHA256 Credential=AKIA/20260101/${region}/sts/aws4_request, SignedHeaders=host;x-amz-date, Signature=abc`;++ const signedHeaders = {+ Authorization: authorizationFor("us-east-1"),+ "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",+ "X-Amz-Date": "20260101T000000Z",+ "x-amz-security-token": "session-token",+ Host: "sts.us-east-1.amazonaws.com",+ "Content-Length": "43"+ };++ const parse = ({+ method = "POST",+ body = "Action=GetCallerIdentity&Version=2011-06-15",+ headers = signedHeaders as unknown+ }: { method?: string; body?: string; headers?: unknown } = {}) =>+ parseSignedGetCallerIdentityRequest({+ iamHttpRequestMethod: method,+ iamRequestBody: Buffer.from(body).toString("base64"),+ iamRequestHeaders: Buffer.from(JSON.stringify(headers)).toString("base64")+ });++ test("targets the regional STS endpoint and forwards every header except routing and framing ones", () => {+ expect(+ parse({+ headers: {+ ...signedHeaders,+ Accept: "application/json",+ "Transfer-Encoding": "chunked",+ Connection: "keep-alive",+ "Keep-Alive": "timeout=5",+ Upgrade: "h2c",+ Expect: "100-continue"+ }+ })+ ).toEqual({+ url: "https://sts.us-east-1.amazonaws.com",+ body: "Action=GetCallerIdentity&Version=2011-06-15",+ headers: {+ authorization: signedHeaders.Authorization,+ "content-type": signedHeaders["Content-Type"],+ "x-amz-date": signedHeaders["X-Amz-Date"],+ "x-amz-security-token": signedHeaders["x-amz-security-token"],+ accept: "application/json"+ }+ });+ });++ test("drops a numeric Content-Length instead of rejecting it", () => {+ expect(parse({ headers: { ...signedHeaders, "Content-Length": 43 } }).headers).not.toHaveProperty("content-length");+ });++ test.each(["us-east-1", "us-gov-west-1", "eu-central-2", "ap-southeast-4"])("accepts region %s", (region) => {+ expect(parse({ headers: { Authorization: authorizationFor(region) } }).url).toBe(+ `https://sts.${region}.amazonaws.com`+ );+ });++ test.each(["s3", "s3-us-west-2", "compute-1", "s3-website-us-east-1", "us-east", ""])(+ "rejects region %j",+ (region) => {+ expect(() => parse({ headers: { Authorization: authorizationFor(region) } })).toThrow("Invalid AWS region");+ }+ );++ test("rejects a request without an authorization header", () => {+ expect(() => parse({ headers: { "X-Amz-Date": "20260101T000000Z" } })).toThrow("Invalid AWS region");+ });++ test.each(["GET", "PUT"])("rejects method %s", (method) => {+ expect(() => parse({ method })).toThrow("must be a POST of Action=GetCallerIdentity");+ });++ test.each([+ "",+ "Action=AssumeRole",+ "Action=GetCallerIdentity&Action=GetCallerIdentity",+ "GET /caller.json HTTP/1.1\r\nX-Swallow: "+ ])("rejects body %j", (body) => {+ expect(() => parse({ body })).toThrow("must be a POST of Action=GetCallerIdentity");+ });++ test("rejects a second spelling of the authorization header", () => {+ expect(() => parse({ headers: { ...signedHeaders, authorization: null } })).toThrow("invalid authorization header");+ expect(() => parse({ headers: { ...signedHeaders, authorization: authorizationFor("us-west-2") } })).toThrow(+ "invalid authorization header"+ );+ });++ test("rejects a non-string value for a forwarded header", () => {+ expect(() => parse({ headers: { ...signedHeaders, "X-Amz-Date": 1 } })).toThrow("invalid x-amz-date header");+ expect(() => parse({ headers: { ...signedHeaders, Accept: null } })).toThrow("invalid accept header");+ });++ test("rejects a second spelling of any forwarded header", () => {+ expect(() => parse({ headers: { ...signedHeaders, "x-amz-date": "20260102T000000Z" } })).toThrow(+ "invalid x-amz-date header"+ );+ });++ test.each([null, [], "headers"])("rejects a header document of %j", (headers) => {+ expect(() => parse({ headers })).toThrow("must be a JSON object");+ });++ test("rejects headers that are not JSON", () => {+ expect(() =>+ parseSignedGetCallerIdentityRequest({+ iamHttpRequestMethod: "POST",+ iamRequestBody: Buffer.from("Action=GetCallerIdentity").toString("base64"),+ iamRequestHeaders: Buffer.from("not json").toString("base64")+ })+ ).toThrow("must be base64-encoded JSON");+ });+});diff --git a/backend/src/services/identity-aws-auth/identity-aws-auth-fns.ts b/backend/src/services/identity-aws-auth/identity-aws-auth-fns.tsindex 345058a3c1..bdad01e74e 100644--- a/backend/src/services/identity-aws-auth/identity-aws-auth-fns.ts+++ b/backend/src/services/identity-aws-auth/identity-aws-auth-fns.ts@@ -1,3 +1,6 @@+import { isValidAwsRegion } from "@app/lib/aws/region";+import { BadRequestError } from "@app/lib/errors";+interface PrincipalArnEntity {Partition: string;Service: "iam" | "sts";@@ -102,3 +105,70 @@ export const hasAwsTrustBinding = ({}) => Boolean(allowedAccountIds?.trim()) || Boolean(allowedPrincipalArns?.trim());export const AWS_TRUST_BINDING_REQUIRED_MESSAGE = "Configure at least one allowed AWS account ID or principal ARN.";++// Credential=<access-key-id>/<date>/<region>/<service>/aws4_request+const awsRegionFromAuthorizationHeader = (authorizationHeader: string): string | null => {+ const credentialField = authorizationHeader.split(" ").find((field) => field.startsWith("Credential="));+ const credentialParts = credentialField?.split("/");+ return credentialParts && credentialParts.length >= 3 ? credentialParts[2] : null;+};++// Left to the HTTP client, which derives them from the STS URL and the body it sends; forwarding them lets the+// caller pick the server (Host) or leave bytes on a pooled connection for the next request (framing headers)+const STRIPPED_STS_HEADERS = new Set([+ "host",+ "content-length",+ "transfer-encoding",+ "connection",+ "keep-alive",+ "proxy-connection",+ "te",+ "trailer",+ "upgrade",+ "expect"+]);++// The caller's input is replayed to STS and the answer is trusted, so it is narrowed to the one request STS must answer+export const parseSignedGetCallerIdentityRequest = ({+ iamHttpRequestMethod,+ iamRequestBody,+ iamRequestHeaders+}: {+ iamHttpRequestMethod: string;+ iamRequestBody: string;+ iamRequestHeaders: string;+}) => {+ let rawHeaders: unknown;+ try {+ rawHeaders = JSON.parse(Buffer.from(iamRequestHeaders, "base64").toString());+ } catch {+ throw new BadRequestError({ message: "Signed STS request headers must be base64-encoded JSON" });+ }+ if (!rawHeaders || typeof rawHeaders !== "object" || Array.isArray(rawHeaders)) {+ throw new BadRequestError({ message: "Signed STS request headers must be a JSON object" });+ }++ const body = Buffer.from(iamRequestBody, "base64").toString();+ const actions = new URLSearchParams(body).getAll("Action");+ if (iamHttpRequestMethod.toUpperCase() !== "POST" || actions.length !== 1 || actions[0] !== "GetCallerIdentity") {+ throw new BadRequestError({ message: "Signed STS request must be a POST of Action=GetCallerIdentity" });+ }++ const headers: Record<string, string> = {};+ Object.entries(rawHeaders).forEach(([name, value]) => {+ const headerName = name.toLowerCase();+ if (STRIPPED_STS_HEADERS.has(headerName)) return;+ // A second spelling of a name would let the value that is validated differ from the one that is sent+ if (headerName in headers || typeof value !== "string") {+ throw new BadRequestError({ message: `Signed STS request has an invalid ${headerName} header` });+ }+ headers[headerName] = value;+ });++ const region = headers.authorization ? awsRegionFromAuthorizationHeader(headers.authorization) : null;+ if (!isValidAwsRegion(region)) {+ throw new BadRequestError({ message: "Invalid AWS region" });+ }++ return { url: `https://sts.${region}.amazonaws.com`, headers, body };+};diff --git a/backend/src/services/identity-aws-auth/identity-aws-auth-service.test.ts b/backend/src/services/identity-aws-auth/identity-aws-auth-service.test.tsindex 02387f7221..ea8bf738b0 100644--- a/backend/src/services/identity-aws-auth/identity-aws-auth-service.test.ts+++ b/backend/src/services/identity-aws-auth/identity-aws-auth-service.test.ts@@ -149,6 +149,40 @@ describe("awsAuthService.login without a trust binding", () => {await expect(result).rejects.toMatchObject({ detail: { reasonCode: "account_id_not_allowed" } });});++ test("replays only a POST to the regional STS endpoint with the signature headers", async () => {+ const { result } = login({ allowedAccountIds: ACCOUNT_ID });++ await expect(result).resolves.toMatchObject({ accessToken: ACCESS_TOKEN });+ expect(request).toHaveBeenCalledWith({+ method: "POST",+ url: "https://sts.us-east-1.amazonaws.com",+ headers: {+ authorization: "AWS4-HMAC-SHA256 Credential=AKIA/20260101/us-east-1/sts/aws4_request, SignedHeaders=host"+ },+ data: "Action=GetCallerIdentity&Version=2011-06-15"+ });+ });++ test("refuses a crafted request before contacting AWS", async () => {+ const { service } = makeService({ allowedAccountIds: ACCOUNT_ID });+ const headers = {+ Authorization: "AWS4-HMAC-SHA256 Credential=x/x/s3/x/aws4_request",+ authorization: null,+ Host: "attacker-bucket.s3.amazonaws.com",+ "Content-Length": "0"+ };++ await expect(+ service.login({+ identityId: IDENTITY_ID,+ iamHttpRequestMethod: "GET",+ iamRequestBody: Buffer.from("GET /caller.json HTTP/1.1\r\nX-Swallow: ").toString("base64"),+ iamRequestHeaders: Buffer.from(JSON.stringify(headers)).toString("base64")+ } as never)+ ).rejects.toThrow("Signed STS request must be a POST of Action=GetCallerIdentity");+ expect(request).not.toHaveBeenCalled();+ });});// Attach and update are the only places a binding can be saved. The permission service is an empty object, so adiff --git a/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts b/backend/src/services/identity-aws-auth/identity-aws-auth-service.tsindex 302ce45a7b..7cea4e857f 100644--- a/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts+++ b/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts@@ -44,11 +44,11 @@ import {AWS_TRUST_BINDING_REQUIRED_MESSAGE,extractPrincipalArn,extractPrincipalArnEntity,- hasAwsTrustBinding+ hasAwsTrustBinding,+ parseSignedGetCallerIdentityRequest} from "./identity-aws-auth-fns";import {TAttachAwsAuthDTO,- TAwsGetCallerIdentityHeaders,TGetAwsAuthDTO,TGetCallerIdentityResponse,TLoginAwsAuthDTO,@@ -77,40 +77,6 @@ type TIdentityAwsAuthServiceFactoryDep = {export type TIdentityAwsAuthServiceFactory = ReturnType<typeof identityAwsAuthServiceFactory>;-const awsRegionFromHeader = (authorizationHeader: string): string | null => {- // https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-auth-using-authorization-header.html- // The Authorization header takes the following form.- // Authorization: AWS4-HMAC-SHA256- // Credential=AKIAIOSFODNN7EXAMPLE/20230719/us-east-1/sts/aws4_request,- // SignedHeaders=content-length;content-type;host;x-amz-date,- // Signature=fe5f80f77d5fa3beca038a248ff027d0445342fe2855ddc963176630326f1024- //- // The credential is in the form of "<your-access-key-id>/<date>/<aws-region>/<aws-service>/aws4_request"xi- try {- const fields = authorizationHeader.split(" ");- for (const field of fields) {- if (field.startsWith("Credential=")) {- const parts = field.split("/");- if (parts.length >= 3) {- return parts[2];- }- }- }- } catch {- return null;- }- return null;-};--function isValidAwsRegion(region: string | null): boolean {- const validRegionPattern = new RE2("^[a-z0-9-]+$");- if (typeof region !== "string" || region.length === 0 || region.length > 20) {- return false;- }-- return validRegionPattern.test(region);-}-export const identityAwsAuthServiceFactory = ({identityDAL,identityAccessTokenDAL,@@ -158,17 +124,11 @@ export const identityAwsAuthServiceFactory = ({logger.warn(`AWS Auth Login: identity has no trust binding, allowing [identity-id=${identity.id}]`);}- const headers: TAwsGetCallerIdentityHeaders = JSON.parse(Buffer.from(iamRequestHeaders, "base64").toString());- const body: string = Buffer.from(iamRequestBody, "base64").toString();-- const authHeader = headers.Authorization || headers.authorization;- const region = authHeader ? awsRegionFromHeader(authHeader) : null;-- if (!isValidAwsRegion(region)) {- throw new BadRequestError({ message: "Invalid AWS region" });- }-- const url = region ? `https://sts.${region}.amazonaws.com` : identityAwsAuth.stsEndpoint;+ const { url, headers, body } = parseSignedGetCallerIdentityRequest({+ iamHttpRequestMethod,+ iamRequestBody,+ iamRequestHeaders+ });const {data: {@@ -177,7 +137,7 @@ export const identityAwsAuthServiceFactory = ({}}}: { data: TGetCallerIdentityResponse } = await request({- method: iamHttpRequestMethod,+ method: "POST",url,headers,data: bodydiff --git a/backend/src/services/identity-aws-auth/identity-aws-auth-types.ts b/backend/src/services/identity-aws-auth/identity-aws-auth-types.tsindex 563b834bd7..a480cd779d 100644--- a/backend/src/services/identity-aws-auth/identity-aws-auth-types.ts+++ b/backend/src/services/identity-aws-auth/identity-aws-auth-types.ts@@ -36,16 +36,6 @@ export type TGetAwsAuthDTO = {identityId: string;} & Omit<TProjectPermission, "projectId">;-export type TAwsGetCallerIdentityHeaders = {- "Content-Type": string;- Host: string;- "X-Amz-Date": string;- "Content-Length": number;- "x-amz-security-token": string;- Authorization?: string;- authorization?: string;-};-export type TGetCallerIdentityResponse = {GetCallerIdentityResponse: {GetCallerIdentityResult: {