-
-
Notifications
You must be signed in to change notification settings - Fork 38
/
credentials-manager.js
189 lines (147 loc) · 5.59 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
/**
* Module dependencies.
*/
import { Parser } from './parser.js';
import { STSClient, AssumeRoleWithSAMLCommand } from '@aws-sdk/client-sts';
import { ProfileNotFoundError, RoleNotFoundError, RoleMismatchError } from './errors.js';
import { Session } from './session.js';
import { dirname, join } from 'node:path';
import { chmod, mkdir, readFile, writeFile, constants } from 'node:fs/promises';
import ini from 'ini';
// Regex pattern for duration seconds validation error.
const REGEX_PATTERN_DURATION_SECONDS = /value less than or equal to ([0-9]+)/
/**
* Process a SAML response and extract all relevant data to be exchanged for an
* STS token.
*/
export class CredentialsManager {
constructor(logger, region, cacheDir) {
this.logger = logger;
this.parser = new Parser(logger);
this.credentialsFile = cacheDir ? join(cacheDir, 'credentials') : null;
this.stsClient = new STSClient({ region })
}
async prepareRoleWithSAML(samlResponse, customRoleArn) {
const { roles, samlAssertion } = await this.parser.parseSamlResponse(samlResponse, customRoleArn);
if (roles && roles.length) {
roles.sort((a, b) => {
if (a.roleArn < b.roleArn) {
return -1;
} else if (a.roleArn > b.roleArn) {
return 1;
}
return 0;
});
}
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 RoleNotFoundError(roles);
}
this.logger.debug('Found requested 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, role, profile, customSessionDuration) {
let sessionDuration = customSessionDuration || role.sessionDuration;
let stsResponse;
try {
const assumeRoleCommand = {
PrincipalArn: role.principalArn,
RoleArn: role.roleArn,
SAMLAssertion: samlAssertion
};
if (sessionDuration) {
assumeRoleCommand.DurationSeconds = sessionDuration;
}
stsResponse = await this.stsClient.send(new AssumeRoleWithSAMLCommand(assumeRoleCommand));
} catch (e) {
if (REGEX_PATTERN_DURATION_SECONDS.test(e.message)) {
let matches = e.message.match(REGEX_PATTERN_DURATION_SECONDS);
let maxDuration = matches[1];
if (maxDuration) {
this.logger.warn(`Custom session duration ${customSessionDuration} exceeds maximum session duration of ${maxDuration} allowed for role. Please set --aws-session-duration=%d or $GSTS_AWS_SESSION_DURATION=%d to surpress this warning`);
}
}
throw e;
}
this.logger.info('Role ARN "%s" has been assumed via SAML', role.roleArn);
this.logger.debug('Role ARN "%s" AssumeRoleWithSAMLCommand response was %o', role.roleArn, stsResponse);
const session = new Session({
accessKeyId: stsResponse.Credentials.AccessKeyId,
secretAccessKey: stsResponse.Credentials.SecretAccessKey,
sessionToken: stsResponse.Credentials.SessionToken,
expiresAt: new Date(stsResponse.Credentials.Expiration),
role,
samlAssertion,
profile
});
if (this.credentialsFile) {
await this.saveCredentials(profile, session);
}
return session;
}
/**
* Save AWS credentials to a profile section.
*/
async saveCredentials(profile, session) {
let contents = {};
try {
contents = await this.loadCredentialsFile();
} catch (e) {
if (e.code !== 'ENOENT') {
throw e;
}
this.logger.debug(`Credentials file not found at "${this.credentialsFile}", creating it...`)
}
contents[profile] = session.toIni();
await mkdir(dirname(this.credentialsFile), { recursive: true });
await writeFile(this.credentialsFile, ini.encode(contents));
await chmod(this.credentialsFile, constants.S_IRUSR | constants.S_IWUSR);
this.logger.info('The credentials have been stored in "%s" under AWS profile "%s"', this.credentialsFile, profile);
this.logger.debug('Contents for credentials file "%s" is: \n %o', this.credentialsFile, contents);
}
/**
* Load AWS credentials for a specific profile.
* Optionally accepts a AWS profile (usually a name representing
* a section on the .ini-like file).
*/
async loadCredentials(profile, roleArn) {
const credentials = await this.loadCredentialsFile();
if (!credentials[profile]) {
throw new ProfileNotFoundError(profile);
}
const session = Session.fromIni(credentials[profile]);
if (roleArn && (roleArn !== session.role.roleArn)) {
this.logger.warn(`Found profile "${profile}" credentials for a different role ARN (found "${session.role.roleArn}" != received "${roleArn}").`);
throw new RoleMismatchError(roleArn, session.role.roleArn);
}
return session;
}
/**
* Load AWS credentials from the user home preferences.
*/
async loadCredentialsFile() {
if (!this.credentialsFile) {
const error = new Error('ENOENT: no such file or directory');
error.code = 'ENOENT';
throw error;
}
let credentials = ini.parse(await readFile(this.credentialsFile, 'utf-8'));
this.logger.info(`Loaded credentials from "${this.credentialsFile}".`);
return credentials;
}
}