/
action.ts
222 lines (189 loc) · 7.84 KB
/
action.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import { exportVariable, getInput, info, notice, setFailed, setOutput } from '@actions/core';
import { STS } from '@aws-sdk/client-sts';
import axios from 'axios';
import {
Configuration,
IDPApi,
GithubSlsRestApiSamlResponseContainer,
GithubSlsRestApiAwsAssumeSdkOptions,
} from '../api/github-sls-rest-api';
import { exec } from './exec';
const { GITHUB_TOKEN, GITHUB_REPOSITORY, GITHUB_SHA, SAML_TO_NONLIVE, SAML_TO_API_KEY } =
process.env;
export class Action {
async run(): Promise<void> {
if (!GITHUB_TOKEN) {
setFailed(`Missing GITHUB_TOKEN environment variable`);
return;
}
if (!GITHUB_REPOSITORY) {
throw new Error('Missing GITHUB_REPOSITORY environment variable');
}
const [org, repo] = GITHUB_REPOSITORY.split('/');
if (!org || !repo) {
throw new Error(
`Unable to parse owner and repo from GITHUB_REPOSITORY environment variable: ${GITHUB_REPOSITORY}`,
);
}
const role = getInput('role', { required: true });
const provider = getInput('provider', { required: false });
const region = getInput('region', { required: false }) || 'us-east-1';
const configOwner = getInput('configOwner', { required: false }) || org;
const configPath = getInput('configPath', { required: false }) || 'saml-to.yml';
const profile = getInput('profile', { required: false }) || undefined;
if (provider) {
info(`Assuming ${provider} Role: ${role} in ${region}`);
} else {
info(`Assuming Role: ${role} in ${region}`);
}
const configuration = new Configuration({
accessToken: GITHUB_TOKEN,
baseOptions: {
headers: { 'User-Agent': 'assume-aws-role-action', Origin: GITHUB_REPOSITORY },
},
});
if (SAML_TO_NONLIVE) {
configuration.basePath = 'https://sso-nonlive.saml.to/github';
configuration.apiKey = SAML_TO_API_KEY;
}
const api = new IDPApi(configuration);
let sdkOpts: GithubSlsRestApiAwsAssumeSdkOptions | undefined;
try {
const { data: response } = await api.assumeRoleForRepo(
org,
repo,
role,
provider || undefined,
GITHUB_SHA,
configOwner,
configPath,
);
info(`SAML Response generated for login to ${response.provider} via ${response.recipient}`);
sdkOpts = response.sdkOptions;
if (response.attributes && Object.keys(response.attributes).length) {
info(`
SAML Attributes:`);
Object.entries(response.attributes).forEach(([k, v]) => info(` - ${k}: ${v}`));
}
await this.assumeAws(response, region, profile);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
const providerHint = sdkOpts ? ` (${sdkOpts.PrincipalArn}) ` : ' ';
notice(`Unable to assume the role with an ARN of \`${role}\`${
provider ? ` (with explicitly specified provider: ${provider})` : ''
}.
Please ensure all of the following:
1) the SAML Provider Metadata${providerHint}in AWS IAM is correct. It can be obtained by downloading it from: https://saml.to/metadata/github/${org}
2) the SAML Provider ARN${providerHint}is correct in the \`${configPath}\` configuration file, and in the format of \`arn:aws:iam::ACCOUNT_ID:saml-provider/PROVIDER_NAME\`,
3) the Role ARN (${role}) is correct in the \`${configPath}\` configuration file, and in the format of \`arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME\`
4) the Role (${role}) has the correct Trust Relationship ${
sdkOpts ? `with ${sdkOpts.PrincipalArn}` : ``
}, which can be found by opening the Role in AWS IAM, choosing the Trust Relationship tab, editing it to ensure it's in the following format:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "${sdkOpts ? sdkOpts.PrincipalArn : 'YOUR_PROVIDER_ARN'}"
},
"Action": "sts:AssumeRoleWithSAML",
"Condition": {
"StringEquals": {
"SAML:aud": "https://signin.aws.amazon.com/saml"
}
}
}
]
}
If a provider or role hasn't been created or configured yet, please follow the configuration instructions: https://github.com/saml-to/assume-aws-role-action/blob/main/README.md#configuration`);
if (axios.isAxiosError(e)) {
let message = e.message;
if (e.response && e.response.data && e.response.data.message) {
message = e.response.data.message;
}
if (e.response && e.response.status === 403) {
const { data } = e.response;
if (data) {
const { context } = data;
if (context && context.org && context.repo && context.configFile) {
if (context.repo !== repo) {
notice(`The SAML.to configuration for \`${org}/${repo}\` is managed in a separate repository:
User/Org: ${context.org}
Repo: ${context.repo}
File: ${context.configFile}
Provider configuration and role permissions must be made there.
For more information on configuration files managed in a separate repository, visit:
https://docs.saml.to/usage/github-actions/assume-aws-role-action#centrally-managed-configuration
`);
}
}
}
}
throw new Error(`Error: ${message}`);
}
throw e;
}
}
async assumeAws(
response: GithubSlsRestApiSamlResponseContainer,
region: string,
profile?: string,
): Promise<void> {
const sts = new STS({ region });
const opts = response.sdkOptions as GithubSlsRestApiAwsAssumeSdkOptions;
if (!opts) {
throw new Error('Missing sdk options from saml response');
}
const assumeResponse = await sts.assumeRoleWithSAML({
...opts,
SAMLAssertion: response.samlResponse,
});
if (
!assumeResponse.Credentials ||
!assumeResponse.Credentials.AccessKeyId ||
!assumeResponse.Credentials.SecretAccessKey ||
!assumeResponse.Credentials.SessionToken
) {
throw new Error('Missing credentials');
}
const assumedSts = new STS({
region,
credentials: {
accessKeyId: assumeResponse.Credentials.AccessKeyId,
secretAccessKey: assumeResponse.Credentials.SecretAccessKey,
sessionToken: assumeResponse.Credentials.SessionToken,
},
});
const callerIdentity = await assumedSts.getCallerIdentity({});
info(`
Assumed ${opts.RoleArn}: ${callerIdentity.Arn} (Credential expiration at ${assumeResponse.Credentials.Expiration})`);
setOutput('region', region);
setOutput('accountId', callerIdentity.Account);
setOutput('userId', callerIdentity.UserId);
setOutput('roleArn', opts.RoleArn);
setOutput('assumedRoleArn', callerIdentity.Arn);
setOutput('accessKeyId', assumeResponse.Credentials.AccessKeyId);
setOutput('secretAccessKey', assumeResponse.Credentials.SecretAccessKey);
setOutput('sessionToken', assumeResponse.Credentials.SessionToken);
if (profile) {
exportVariable('AWS_PROFILE', profile);
const base = ['aws', 'configure'];
if (profile !== 'default') {
base.push('--profile', profile);
}
base.push('set');
await exec([...base, 'region', region]);
await exec([...base, 'aws_access_key_id', assumeResponse.Credentials.AccessKeyId]);
await exec([...base, 'aws_secret_access_key', assumeResponse.Credentials.SecretAccessKey]);
await exec([...base, 'aws_session_token', assumeResponse.Credentials.SessionToken]);
info(`AWS Profile has been set!`);
return;
}
exportVariable('AWS_DEFAULT_REGION', region);
exportVariable('AWS_ACCESS_KEY_ID', assumeResponse.Credentials.AccessKeyId);
exportVariable('AWS_SECRET_ACCESS_KEY', assumeResponse.Credentials.SecretAccessKey);
exportVariable('AWS_SESSION_TOKEN', assumeResponse.Credentials.SessionToken);
info(`Environment Variables have been set!`);
}
}