From 0a28ac4a7d4f38ddeea4bd7221250810b0aacc3a Mon Sep 17 00:00:00 2001 From: Maidul Islam Date: Sun, 30 Mar 2025 16:13:41 -0400 Subject: [PATCH] extract region only --- .../identity-aws-auth-service.ts | 32 +++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts b/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts index 4622bc509..f430b4149 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 @@ -42,6 +42,31 @@ type TIdentityAwsAuthServiceFactoryDep = { export type TIdentityAwsAuthServiceFactory = ReturnType; +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 "////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; +}; + export const identityAwsAuthServiceFactory = ({ identityAccessTokenDAL, identityAwsAuthDAL, @@ -58,7 +83,10 @@ export const identityAwsAuthServiceFactory = ({ const identityMembershipOrg = await identityOrgMembershipDAL.findOne({ identityId: identityAwsAuth.identityId }); const headers: TAwsGetCallerIdentityHeaders = JSON.parse(Buffer.from(iamRequestHeaders, "base64").toString()); - const body: string = Buffer.from(iamRequestBody, "base64").toString(); + const body: string = Buffer.from(iamRequestBody, "base64").toString(); + + const region = headers.Authorization ? awsRegionFromHeader(headers.Authorization) : null; + const url = region ? `https://sts.${region}.amazonaws.com` : identityAwsAuth.stsEndpoint; const { data: { @@ -68,7 +96,7 @@ export const identityAwsAuthServiceFactory = ({ } }: { data: TGetCallerIdentityResponse } = await axios({ method: iamHttpRequestMethod, - url: headers?.Host ? `https://${headers.Host}` : identityAwsAuth.stsEndpoint, + url, headers, data: body });