// Copyright Abridged, Inc. 2021,2024. All Rights Reserved. // Node module: @collabland/aws // This file is licensed under the MIT License. // License text available at https://opensource.org/licenses/MIT import { AssumeRoleCommand, AssumeRoleCommandInput, GetCallerIdentityCommand, GetCallerIdentityCommandInput, STSClient, STSClientConfig, } from '@aws-sdk/client-sts'; import {loggers} from '@collabland/common'; import {getAWSAccountId, getDefaultConfig} from '../common/types.js'; const {trace} = loggers('collabland:aws:sts'); export class STSServiceClient { readonly sts: STSClient; constructor(options?: STSClientConfig) { trace('STS options: %O', options); this.sts = new STSClient({...getDefaultConfig(), ...options}); } async getCallerIdentity() { const params: GetCallerIdentityCommandInput = {}; trace('Getting caller id: %O', params); const command = new GetCallerIdentityCommand(params); const result = await this.sts.send(command); trace('Caller identity: %O', result); return result; } async assumeRole( roleArn: string, sessionName?: string, durationSeconds = 900, ) { if (sessionName == null) { const caller = await this.getCallerIdentity(); sessionName = caller.Arn?.replace(/^arn:aws:iam::/, '').replace( /[^\w+=,.@-]/g, '_', ); } const params: AssumeRoleCommandInput = { RoleArn: roleArn, DurationSeconds: durationSeconds, RoleSessionName: sessionName, }; trace('Assuming role: %O', params); const command = new AssumeRoleCommand(params); const result = await this.sts.send(command); return result; } } /** * Get IAM role arn * @param roleName - Role name * @param accountId - AWS account id * @returns */ export function getIAMRoleArn(roleName: string, accountId = getAWSAccountId()) { const arn = `arn:aws:iam::${accountId}:role/${roleName}`; return arn; }