-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathbasic.js
More file actions
272 lines (241 loc) · 7.25 KB
/
basic.js
File metadata and controls
272 lines (241 loc) · 7.25 KB
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
import { fileURLToPath } from "node:url";
// snippet-start:[javascript.iam_scenarios.iam_basics]
import {
CreateUserCommand,
GetUserCommand,
CreateAccessKeyCommand,
CreatePolicyCommand,
CreateRoleCommand,
AttachRolePolicyCommand,
DeleteAccessKeyCommand,
DeleteUserCommand,
DeleteRoleCommand,
DeletePolicyCommand,
DetachRolePolicyCommand,
IAMClient,
} from "@aws-sdk/client-iam";
import { ListBucketsCommand, S3Client } from "@aws-sdk/client-s3";
import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts";
import { retry } from "@aws-doc-sdk-examples/lib/utils/util-timers.js";
import { ScenarioInput } from "@aws-doc-sdk-examples/lib/scenario/index.js";
// Set the parameters.
const iamClient = new IAMClient({});
const userName = "iam_basic_test_username";
const policyName = "iam_basic_test_policy";
const roleName = "iam_basic_test_role";
/**
* Create a new IAM user. If the user already exists, give
* the option to delete and re-create it.
* @param {string} name
*/
export const createUser = async (name, confirmAll = false) => {
try {
const { User } = await iamClient.send(
new GetUserCommand({ UserName: name }),
);
const input = new ScenarioInput(
"deleteUser",
"Do you want to delete and remake this user?",
{ type: "confirm" },
);
const deleteUser = await input.handle({}, { confirmAll });
// If the user exists, and you want to delete it, delete the user
// and then create it again.
if (deleteUser) {
await iamClient.send(new DeleteUserCommand({ UserName: User.UserName }));
await iamClient.send(new CreateUserCommand({ UserName: name }));
} else {
console.warn(
`${name} already exists. The scenario may not work as expected.`,
);
return User;
}
} catch (caught) {
// If there is no user by that name, create one.
if (caught instanceof Error && caught.name === "NoSuchEntityException") {
const { User } = await iamClient.send(
new CreateUserCommand({ UserName: name }),
);
return User;
}
throw caught;
}
};
export const main = async (confirmAll = false) => {
// Create a user. The user has no permissions by default.
const User = await createUser(userName, confirmAll);
if (!User) {
throw new Error("User not created");
}
// Create an access key. This key is used to authenticate the new user to
// Amazon Simple Storage Service (Amazon S3) and AWS Security Token Service (AWS STS).
// It's not best practice to use access keys. For more information, see https://aws.amazon.com/iam/resources/best-practices/.
const createAccessKeyResponse = await iamClient.send(
new CreateAccessKeyCommand({ UserName: userName }),
);
if (
!createAccessKeyResponse.AccessKey?.AccessKeyId ||
!createAccessKeyResponse.AccessKey?.SecretAccessKey
) {
throw new Error("Access key not created");
}
const {
AccessKey: { AccessKeyId, SecretAccessKey },
} = createAccessKeyResponse;
let s3Client = new S3Client({
credentials: {
accessKeyId: AccessKeyId,
secretAccessKey: SecretAccessKey,
},
});
// Retry the list buckets operation until it succeeds. InvalidAccessKeyId is
// thrown while the user and access keys are still stabilizing.
await retry({ intervalInMs: 1000, maxRetries: 300 }, async () => {
try {
return await listBuckets(s3Client);
} catch (err) {
if (err instanceof Error && err.name === "InvalidAccessKeyId") {
throw err;
}
}
});
// Retry the create role operation until it succeeds. A MalformedPolicyDocument error
// is thrown while the user and access keys are still stabilizing.
const { Role } = await retry(
{
intervalInMs: 2000,
maxRetries: 60,
},
() =>
iamClient.send(
new CreateRoleCommand({
AssumeRolePolicyDocument: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Principal: {
// Allow the previously created user to assume this role.
AWS: User.Arn,
},
Action: "sts:AssumeRole",
},
],
}),
RoleName: roleName,
}),
),
);
if (!Role) {
throw new Error("Role not created");
}
// Create a policy that allows the user to list S3 buckets.
const { Policy: listBucketPolicy } = await iamClient.send(
new CreatePolicyCommand({
PolicyDocument: JSON.stringify({
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Action: ["s3:ListAllMyBuckets"],
Resource: "*",
},
],
}),
PolicyName: policyName,
}),
);
if (!listBucketPolicy) {
throw new Error("Policy not created");
}
// Attach the policy granting the 's3:ListAllMyBuckets' action to the role.
await iamClient.send(
new AttachRolePolicyCommand({
PolicyArn: listBucketPolicy.Arn,
RoleName: Role.RoleName,
}),
);
// Assume the role.
const stsClient = new STSClient({
credentials: {
accessKeyId: AccessKeyId,
secretAccessKey: SecretAccessKey,
},
});
// Retry the assume role operation until it succeeds.
const { Credentials } = await retry(
{ intervalInMs: 2000, maxRetries: 60 },
() =>
stsClient.send(
new AssumeRoleCommand({
RoleArn: Role.Arn,
RoleSessionName: `iamBasicScenarioSession-${Math.floor(
Math.random() * 1000000,
)}`,
DurationSeconds: 900,
}),
),
);
if (!Credentials?.AccessKeyId || !Credentials?.SecretAccessKey) {
throw new Error("Credentials not created");
}
s3Client = new S3Client({
credentials: {
accessKeyId: Credentials.AccessKeyId,
secretAccessKey: Credentials.SecretAccessKey,
sessionToken: Credentials.SessionToken,
},
});
// List the S3 buckets again.
// Retry the list buckets operation until it succeeds. AccessDenied might
// be thrown while the role policy is still stabilizing.
await retry({ intervalInMs: 2000, maxRetries: 120 }, () =>
listBuckets(s3Client),
);
// Clean up.
await iamClient.send(
new DetachRolePolicyCommand({
PolicyArn: listBucketPolicy.Arn,
RoleName: Role.RoleName,
}),
);
await iamClient.send(
new DeletePolicyCommand({
PolicyArn: listBucketPolicy.Arn,
}),
);
await iamClient.send(
new DeleteRoleCommand({
RoleName: Role.RoleName,
}),
);
await iamClient.send(
new DeleteAccessKeyCommand({
UserName: userName,
AccessKeyId,
}),
);
await iamClient.send(
new DeleteUserCommand({
UserName: userName,
}),
);
};
/**
*
* @param {S3Client} s3Client
*/
const listBuckets = async (s3Client) => {
const { Buckets } = await s3Client.send(new ListBucketsCommand({}));
if (!Buckets) {
throw new Error("Buckets not listed");
}
console.log(Buckets.map((bucket) => bucket.Name).join("\n"));
};
// snippet-end:[javascript.iam_scenarios.iam_basics]
// Invoke main function if this file was run directly.
if (process.argv[1] === fileURLToPath(import.meta.url)) {
main();
}