This repository has been archived by the owner on Jul 29, 2022. It is now read-only.
forked from ruimarinho/gsts
-
Notifications
You must be signed in to change notification settings - Fork 1
/
credentials-manager.js
292 lines (231 loc) · 8.86 KB
/
credentials-manager.js
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
/**
* Module dependencies.
*/
const { dirname } = require('path');
const Parser = require('./parser');
const STS = require('aws-sdk/clients/sts');
const errors = require('./errors');
const ffs = require('fs');
const ini = require('ini');
const util = require('util');
const fs = {
exists: util.promisify(ffs.exists),
mkdir: util.promisify(ffs.mkdir),
readFile: util.promisify(ffs.readFile),
stat: util.promisify(ffs.stat),
writeFile: util.promisify(ffs.writeFile),
}
// Delta (in seconds) between exact expiration date and current date to avoid requests
// on the same second to fail.
const SESSION_EXPIRATION_DELTA = 30e3; // 30 seconds
// Regex pattern for duration seconds validation error.
const REGEX_PATTERN_DURATION_SECONDS = /value less than or equal to ([0-9]+)/
/**
* Recursively create a directory based on the implementation
* from https://github.com/jprichardson/node-fs-extra.
*/
async function mkdirP(path, mode) {
try {
await fs.mkdir(path, mode);
} catch (e) {
if (e.code === 'EPERM') {
throw e;
}
if (e.code === 'ENOENT') {
if (path.dirname(path) === path) {
// This replicates the exception of `fs.mkdir` with the native
// `recusive` option when ran on an invalid drive under Windows.
// From https://github.com/jprichardson/node-fs-extra.
const error = new Error(`operation not permitted, mkdir '${path}'`);
error.code = 'EPERM';
error.errno = -4048;
error.path = path;
error.syscall = 'mkdir';
throw error;
}
if (e.message.includes('null bytes')) {
throw e;
}
await mkdirP(path.dirname(path));
}
try {
const stats = await fs.stat(path);
if (!stats.isDirectory()) {
// This error is never exposed to the user
// it is caught below, and the original error is thrown
throw new Error('The path is not a directory');
}
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
}
}
/**
* Process a SAML response and extract all relevant data to be exchanged for an
* STS token.
*/
class CredentialsManager {
constructor(logger) {
this.logger = logger;
this.sessionExpirationDelta = SESSION_EXPIRATION_DELTA;
this.parser = new Parser(logger);
}
async prepareRoleWithSAML(samlResponse, customRoleArn) {
const { roles, samlAssertion } = await this.parser.parseSamlResponse(samlResponse, customRoleArn);
if (!customRoleArn) {
this.logger.debug('A custom role ARN not been set so returning all parsed roles');
return {
roleToAssume: roles.length === 1 ? roles[0] : null,
availableRoles: roles,
samlAssertion
}
}
const customRole = roles.find(role => role.roleArn === customRoleArn);
if (!customRole) {
throw new errors.RoleNotFoundError(roles);
}
this.logger.debug('Found custom role ARN "%s" with principal ARN "%s"', customRole.roleArn, customRole.principalArn);
return {
roleToAssume: customRole,
availableRoles: roles,
samlAssertion
}
}
/**
* Parse SAML response and assume role-.
*/
async assumeRoleWithSAML(samlAssertion, awsSharedCredentialsFile, awsProfile, role, customSessionDuration) {
let sessionDuration = role.sessionDuration;
if (customSessionDuration) {
sessionDuration = customSessionDuration;
try {
await (new STS()).assumeRoleWithSAML({
DurationSeconds: sessionDuration,
PrincipalArn: role.principalArn,
RoleArn: role.roleArn,
SAMLAssertion: samlAssertion
}).promise();
} catch (e) {
if (e.code !== 'ValidationError' || !/durationSeconds/.test(e.message)) {
throw e;
}
let matches = e.message.match(REGEX_PATTERN_DURATION_SECONDS);
if (!matches) {
return;
}
let duration = matches[1];
if (duration) {
sessionDuration = Number(duration);
this.logger.warn('Custom session duration %d exceeds maximum session duration of %d allowed for role. Please set --aws-session-duration=%d or $AWS_SESSION_DURATION=%d to surpress this warning', customSessionDuration, sessionDuration, sessionDuration, sessionDuration);
}
}
}
const stsResponse = await (new STS()).assumeRoleWithSAML({
DurationSeconds: sessionDuration,
PrincipalArn: role.principalArn,
RoleArn: role.roleArn,
SAMLAssertion: samlAssertion
}).promise();
this.logger.debug('Role ARN "%s" has been assumed %O', role.roleArn, stsResponse);
await this.saveCredentials(awsSharedCredentialsFile, awsProfile, {
accessKeyId: stsResponse.Credentials.AccessKeyId,
roleArn: role.roleArn,
secretAccessKey: stsResponse.Credentials.SecretAccessKey,
sessionExpiration: stsResponse.Credentials.Expiration,
sessionToken: stsResponse.Credentials.SessionToken
});
}
/**
* Load AWS credentials from the user home preferences.
* Optionally accepts a AWS profile (usually a name representing
* a section on the .ini-like file).
*/
async loadCredentials(path, profile) {
let credentials;
try {
credentials = await fs.readFile(path, 'utf-8')
} catch (e) {
if (e.code === 'ENOENT') {
this.logger.debug('Credentials file does not exist at %s', path)
return;
}
throw e;
}
const config = ini.parse(credentials);
if (profile) {
return config[profile];
}
return config;
}
/**
* Save AWS credentials to a profile section.
*/
async saveCredentials(path, profile, { accessKeyId, roleArn, secretAccessKey, sessionExpiration, sessionToken }) {
// The config file may have other profiles configured, so parse existing data instead of writing a new file instead.
let credentials = await this.loadCredentials(path);
if (!credentials) {
credentials = {};
}
credentials[profile] = {};
credentials[profile].aws_access_key_id = accessKeyId;
credentials[profile].aws_role_arn = roleArn;
credentials[profile].aws_secret_access_key = secretAccessKey;
credentials[profile].aws_session_expiration = sessionExpiration.toISOString();
credentials[profile].aws_session_token = sessionToken;
await mkdirP(dirname(path));
await fs.writeFile(path, ini.encode(credentials));
this.logger.debug('The credentials have been stored in "%s" under AWS profile "%s" with contents %o', path, profile, credentials);
}
/**
* Export credentials as JSON output for use with AWS's `credential_process`.
* See https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sourcing-external.html
*/
async exportAsJSON(path, profile) {
this.logger.debug('Outputting data as JSON');
let credentials = await this.loadCredentials(path, profile);
if (!credentials) {
// Return a minimally-valid JSON so that the AWS SDK can return a proper error
// message instead of a failure parsing the output of this tool.
return JSON.stringify({ Version: 1 });
}
return JSON.stringify({
Version: 1,
AccessKeyId: credentials.aws_access_key_id,
SecretAccessKey: credentials.aws_secret_access_key,
SessionToken: credentials.aws_session_token,
Expiration: credentials.aws_session_expiration
});
}
/**
* Extract session expiration from AWS credentials file for a given profile.
* The property `sessionExpirationDelta` represents a safety buffer to avoid requests
* failing at the exact time of expiration.
*/
async getSessionExpirationFromCredentials(path, profile, roleArn) {
this.logger.debug('Attempting to retrieve session expiration credentials');
const credentials = await this.loadCredentials(path, profile);
if (!credentials) {
return { isValid: false, expiresAt: null };
}
if (roleArn && credentials.aws_role_arn !== roleArn) {
this.logger.warn('Found credentials for a different role ARN (found "%s" != received "%s")', credentials.aws_role_arn, roleArn);
return { isValid: false, expiresAt: null };
}
if (!credentials.aws_session_expiration) {
this.logger.debug('Session expiration date not found');
return { isValid: false, expiresAt: null };
}
if (new Date(credentials.aws_session_expiration).getTime() - this.sessionExpirationDelta > Date.now()) {
this.logger.debug('Session is expected to be valid until %s minus expiration delta of %d seconds', credentials.aws_session_expiration, this.sessionExpirationDelta / 1e3);
return { isValid: true, expiresAt: new Date(new Date(credentials.aws_session_expiration).getTime() - this.sessionExpirationDelta).toISOString() };
}
this.logger.debug('Session has expired on %s', credentials.aws_session_expiration);
return { isValid: false, expiresAt: new Date(credentials.aws_session_expiration).toISOString() };
}
}
/**
* Exports.
*/
module.exports = CredentialsManager;