Last active
June 26, 2024 16:09
-
-
Save emeraldsanto/76c371e2a10d663baf92f82f9590bb1e to your computer and use it in GitHub Desktop.
Presign an AWS STS GetCallerIdentity request for later use, adapted to JavaScript from https://donchev.is/post/aws-lambda-invoker-identification
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { defaultProvider } from "@aws-sdk/credential-provider-node"; | |
import { HttpRequest } from "@aws-sdk/protocol-http"; | |
import { Sha256 } from '@aws-crypto/sha256-js'; | |
import { SignatureV4 } from "@aws-sdk/signature-v4"; | |
import { stringify } from "qs"; | |
async function main(): Promise<string> { | |
const signer = new SignatureV4({ | |
credentials: defaultProvider(), | |
region: process.env.AWS_REGION, | |
service: "sts", | |
sha256: Sha256, | |
}); | |
const host = `sts.${process.env.AWS_REGION}.amazonaws.com`; | |
const req = new HttpRequest({ | |
headers: { | |
'Content-Type': 'application/json', | |
host | |
}, | |
hostname: host, | |
method: "GET", | |
path: '/', | |
query: { | |
Action: 'GetCallerIdentity', | |
Version: '2011-06-15', | |
}, | |
}); | |
const signed = await signer.presign(req, { expiresIn: 60 * 10 }); | |
return `https://${signed.hostname}${signed.path}?${stringify(signed.query)}`; | |
} | |
main() | |
.then((output) => console.log(output)) | |
.catch((e) => console.log(e)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this, it saved me some time! I made a few tweaks for my use case:
fromNodeProviderChain
for credentials to support all the same mechanisms as the AWS CLI@smithy/...
packagesquerystring
library built into nodepresign-sts-get-caller-identity.mjs
Usage example with curl: