refactor, add new major version features and proxy

This commit is contained in:
peterwoodworth committed 2023-03-10 14:35:59 -08:00
1 parent 0037a686cc
commit f9f25e69f5
9 files changed
+333 -212

No files matched your search

+93 -58
View File
@@ -2,14 +2,69 @@ import assert from 'assert';
import fs from 'fs';
import path from 'path';
import * as core from '@actions/core';
import type { AssumeRoleCommandInput, Tag } from '@aws-sdk/client-sts';
import type { AssumeRoleCommandInput, STSClient, Tag } from '@aws-sdk/client-sts';
import { AssumeRoleCommand, AssumeRoleWithWebIdentityCommand } from '@aws-sdk/client-sts';
import { errorMessage, getStsClient, isDefined, sanitizeGithubActor, sanitizeGithubWorkflowName } from './helpers';
import type { CredentialsClient } from './CredentialsClient';
import { errorMessage, isDefined, sanitizeGithubActor, sanitizeGithubWorkflowName } from './helpers';
async function assumeRoleWithOIDC(params: AssumeRoleCommandInput, client: STSClient, webIdentityToken: string) {
delete params.Tags;
core.info('Assuming role with OIDC');
try {
return await client.send(
new AssumeRoleWithWebIdentityCommand({
...params,
WebIdentityToken: webIdentityToken,
})
);
} catch (error) {
throw new Error(`Could not assume role with OIDC: ${errorMessage(error)}`);
}
}
async function assumeRoleWithWebIdentityTokenFile(
params: AssumeRoleCommandInput,
client: STSClient,
webIdentityTokenFile: string,
workspace: string
) {
core.debug(
'webIdentityTokenFile provided. Will call sts:AssumeRoleWithWebIdentity and take session tags from token contents.'
);
const webIdentityTokenFilePath = path.isAbsolute(webIdentityTokenFile)
? webIdentityTokenFile
: path.join(workspace, webIdentityTokenFile);
if (!fs.existsSync(webIdentityTokenFilePath)) {
throw new Error(`Web identity token file does not exist: ${webIdentityTokenFilePath}`);
}
core.info('Assuming role with web identity token file');
try {
const webIdentityToken = fs.readFileSync(webIdentityTokenFilePath, 'utf8');
delete params.Tags;
return await client.send(
new AssumeRoleWithWebIdentityCommand({
...params,
WebIdentityToken: webIdentityToken,
})
);
} catch (error) {
throw new Error(`Could not assume role with web identity token file: ${errorMessage(error)}`);
}
}
async function assumeRoleWithCredentials(params: AssumeRoleCommandInput, client: STSClient) {
core.info('Assuming role with user credentials');
try {
return await client.send(new AssumeRoleCommand({ ...params }));
} catch (error) {
throw new Error(`Could not assume role with user credentials: ${errorMessage(error)}`);
}
}
export interface assumeRoleParams {
region: string;
credentialsClient: CredentialsClient;
roleToAssume: string;
roleDurationSeconds: number;
roleDuration: number;
roleSessionName: string;
roleSkipSessionTagging?: boolean;
sourceAccountId?: string;
@@ -19,34 +74,25 @@ export interface assumeRoleParams {
}
export async function assumeRole(params: assumeRoleParams) {
// Assume a role to get short-lived credentials using longer-lived credentials.
const {
credentialsClient,
sourceAccountId,
roleToAssume,
roleExternalId,
roleDurationSeconds,
roleDuration,
roleSessionName,
region,
roleSkipSessionTagging,
webIdentityTokenFile,
webIdentityToken,
} = { ...params };
// Load GitHub environment variables
const { GITHUB_REPOSITORY, GITHUB_WORKFLOW, GITHUB_ACTION, GITHUB_ACTOR, GITHUB_SHA, GITHUB_WORKSPACE } = process.env;
if (!GITHUB_REPOSITORY || !GITHUB_WORKFLOW || !GITHUB_ACTION || !GITHUB_ACTOR || !GITHUB_SHA || !GITHUB_WORKSPACE) {
throw new Error('Missing required environment variables. Are you running in GitHub Actions?');
}
let RoleArn = roleToAssume;
if (!RoleArn.startsWith('arn:aws')) {
// Supports only 'aws' partition. Customers in other partitions ('aws-cn') will need to provide full ARN
assert(
isDefined(sourceAccountId),
'Source Account ID is needed if the Role Name is provided and not the Role Arn.'
);
RoleArn = `arn:aws:iam::${sourceAccountId}:role/${RoleArn}`;
}
// Load role session tags
const tagArray: Tag[] = [
{ Key: 'GitHub', Value: 'Actions' },
{ Key: 'Repository', Value: GITHUB_REPOSITORY },
@@ -55,68 +101,57 @@ export async function assumeRole(params: assumeRoleParams) {
{ Key: 'Actor', Value: sanitizeGithubActor(GITHUB_ACTOR) },
{ Key: 'Commit', Value: GITHUB_SHA },
];
if (process.env['GITHUB_REF']) {
tagArray.push({ Key: 'Branch', Value: process.env['GITHUB_REF'] });
}
const Tags = roleSkipSessionTagging ? undefined : tagArray;
if (!Tags) {
const tags = roleSkipSessionTagging ? undefined : tagArray;
if (!tags) {
core.debug('Role session tagging has been skipped.');
} else {
core.debug(`${Tags.length} role session tags are being used.`);
core.debug(`${tags.length} role session tags are being used.`);
}
const ExternalId = roleExternalId;
// Calculate role ARN from name and account ID (currently only supports `aws` partition)
let roleArn = roleToAssume;
if (!roleArn.startsWith('arn:aws')) {
assert(
isDefined(sourceAccountId),
'Source Account ID is needed if the Role Name is provided and not the Role Arn.'
);
roleArn = `arn:aws:iam::${sourceAccountId}:role/${roleArn}`;
}
// Ready common parameters to assume role
const commonAssumeRoleParams: AssumeRoleCommandInput = {
RoleArn,
RoleArn: roleArn,
RoleSessionName: roleSessionName,
DurationSeconds: roleDurationSeconds,
...(Tags ? { Tags } : {}),
...(ExternalId ? { ExternalId } : {}),
DurationSeconds: roleDuration,
Tags: tags ? tags : undefined,
ExternalId: roleExternalId ? roleExternalId : undefined,
};
const keys = Object.keys(commonAssumeRoleParams) as Array<keyof typeof commonAssumeRoleParams>;
keys.forEach((k) => commonAssumeRoleParams[k] === undefined && delete commonAssumeRoleParams[k]);
const sts = getStsClient(region);
// Instantiate STS client
const stsClient = credentialsClient.getStsClient();
// Assume role using one of three methods
switch (true) {
case !!webIdentityToken: {
delete commonAssumeRoleParams.Tags;
return sts.send(
new AssumeRoleWithWebIdentityCommand({
...commonAssumeRoleParams,
WebIdentityToken: webIdentityToken,
})
);
return assumeRoleWithOIDC(commonAssumeRoleParams, stsClient, webIdentityToken!);
}
case !!webIdentityTokenFile: {
core.debug(
'webIdentityTokenFile provided. Will call sts:AssumeRoleWithWebIdentity and take session tags from token contents.'
return assumeRoleWithWebIdentityTokenFile(
commonAssumeRoleParams,
stsClient,
webIdentityTokenFile!,
GITHUB_WORKSPACE
);
const webIdentityTokenFilePath = path.isAbsolute(webIdentityTokenFile!)
? webIdentityTokenFile!
: path.join(GITHUB_WORKSPACE, webIdentityTokenFile!);
if (!fs.existsSync(webIdentityTokenFilePath)) {
throw new Error(`Web identity token file does not exist: ${webIdentityTokenFilePath}`);
}
try {
const widt = fs.readFileSync(webIdentityTokenFilePath, 'utf8');
delete commonAssumeRoleParams.Tags;
return await sts.send(
new AssumeRoleWithWebIdentityCommand({
...commonAssumeRoleParams,
WebIdentityToken: widt,
})
);
} catch (error) {
throw new Error(`Web identity token file could not be read: ${errorMessage(error)}`);
}
}
default: {
return sts.send(new AssumeRoleCommand({ ...commonAssumeRoleParams }));
return assumeRoleWithCredentials(commonAssumeRoleParams, stsClient);
}
}
}