-
-
Notifications
You must be signed in to change notification settings - Fork 26
/
cli.js
executable file
·316 lines (261 loc) · 8.87 KB
/
cli.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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#!/usr/bin/env node
import { promisify } from 'util';
import meow from 'meow';
import fs from 'fs';
import { readFile } from 'fs/promises';
import path from 'path';
import sanitizeFilename from 'sanitize-filename';
import JSONStream from 'JSONStream';
import Debug from 'debug';
import mkdirp from 'mkdirp';
import assert from 'assert';
import { pipeline as pipelineCb } from 'stream';
import pMap from 'p-map';
import {
CognitoIdentityProviderClient, ListUserPoolsCommand, AdminListGroupsForUserCommand, ListUsersCommand, ListGroupsCommand, AdminCreateUserCommand, CreateGroupCommand, AdminAddUserToGroupCommand, GroupExistsException, UsernameExistsException,
} from '@aws-sdk/client-cognito-identity-provider';
import { fromIni } from '@aws-sdk/credential-providers';
const debug = Debug('cognito-backup');
const pipeline = promisify(pipelineCb);
const cli = meow(
`
Usage
$ cognito-backup backup-users <user-pool-id> <options> Backup/export all users in a single user pool
$ cognito-backup backup-groups <user-pool-id> <options> Backup/export all groups in a single user pool
$ cognito-backup backup-all-users <options> Backup all users in all user pools for this account
$ cognito-backup restore-users <user-pool-id> <temp-password> Restore/import users to a single user pool
$ cognito-backup restore-groups <user-pool-id> Restore/import groups to a single user pool
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_REGION
can be specified in env variables or ~/.aws/credentials
Options
--region AWS region
--file File name to export/import single pool users to (defaults to user-pool-id.json)
--dir Path to export all pools, all users to (defaults to current dir)
--profile utilize named profile from .aws/credentials file
--stack-trace Log stack trace upon error
--max-attempts The maximum number of times requests that encounter retryable failures should be attempted
--concurrency More will be faster, too many may cause throttling error`,
{
importMeta: import.meta,
flags: {
stackTrace: {
type: 'boolean',
},
maxAttempts: {
type: 'number',
},
concurrency: {
type: 'number',
},
verbose: {
type: 'boolean',
},
},
},
);
const {
region,
concurrency = 1,
verbose = false,
maxAttempts = 5,
} = cli.flags;
const config = {
region,
retryMode: 'standard',
maxAttempts,
};
if (cli.flags.profile) {
config.credentials = fromIni({
profile: cli.flags.profile,
});
}
const cognitoIsp = new CognitoIdentityProviderClient(config);
function getFilename(userPoolId) {
return `${userPoolId}.json`;
}
async function listUserPools() {
const data = await cognitoIsp.send(new ListUserPoolsCommand({ MaxResults: 60 }));
assert(!data.NextToken, 'More than 60 user pools is not yet supported');
const userPools = data.UserPools;
debug({ userPools });
return userPools.map((p) => p.Id);
}
async function backupUsers(userPoolId, file) {
const writeStream = fs.createWriteStream(file);
const stringify = JSONStream.stringify();
const params = { UserPoolId: userPoolId };
async function getUserGroupNames(user) {
const data = await cognitoIsp.send(new AdminListGroupsForUserCommand({
UserPoolId: userPoolId,
Username: user.Username,
}));
return data.Groups.map((group) => group.GroupName);
}
async function page() {
debug(`Fetching users - page: ${params.PaginationToken || 'first'}`);
const data = await cognitoIsp.send(new ListUsersCommand(params));
const users = await pMap(data.Users, async (user) => {
const groupNames = await getUserGroupNames(user);
return { ...user, Groups: groupNames };
}, { concurrency });
users.forEach((item) => stringify.write(item));
if (data.PaginationToken !== undefined) {
params.PaginationToken = data.PaginationToken;
await page();
return;
}
stringify.end();
}
page();
await pipeline(stringify, writeStream);
}
async function backupGroups(userPoolId, file) {
const writeStream = fs.createWriteStream(file);
const stringify = JSONStream.stringify();
const params = { UserPoolId: userPoolId, Limit: 1 };
async function page() {
debug(`Fetching groups - page: ${params.PaginationToken || 'first'}`);
const data = await cognitoIsp.send(new ListGroupsCommand(params));
data.Groups.forEach((item) => stringify.write(item));
if (data.NextToken !== undefined) {
params.NextToken = data.NextToken;
await page();
return;
}
stringify.end();
}
page();
await pipeline(stringify, writeStream);
}
const getUserPoolFileName = (userPoolId) => cli.flags.file || sanitizeFilename(getFilename(userPoolId));
const getUserPoolGroupFileName = (userPoolId) => cli.flags.file || sanitizeFilename(getFilename(`${userPoolId}_groups`));
async function backupUsersCli() {
const userPoolId = cli.input[1];
const file = getUserPoolFileName(userPoolId);
if (!userPoolId) {
console.error('user-pool-id is required');
cli.showHelp();
}
return backupUsers(userPoolId, file);
}
function backupGroupsCli() {
const userPoolId = cli.input[1];
const file = getUserPoolGroupFileName(userPoolId);
if (!userPoolId) {
console.error('user-pool-id is required');
cli.showHelp();
}
return backupGroups(userPoolId, file);
}
async function backupAllUsersCli() {
const dir = cli.flags.dir || '.';
await mkdirp(dir);
await pMap(await listUserPools(), (userPoolId) => {
const file = path.join(dir, getFilename(userPoolId));
console.error(`Exporting ${userPoolId} to ${file}`);
return backupUsers(userPoolId, file);
}, { concurrency: 1 });
}
async function restoreUsers() {
const userPoolId = cli.input[1];
const tempPassword = cli.input[2];
const file = getUserPoolFileName(userPoolId);
if (!userPoolId) {
console.error('user-pool-id is required');
cli.showHelp();
}
if (!tempPassword) {
console.error('temp-password is required');
cli.showHelp();
}
// TODO make streamable
const data = await readFile(file, 'utf8');
const users = JSON.parse(data);
return pMap(users, async (user) => {
// sub is non-writable attribute
const attributes = user.Attributes.filter((attribute) => attribute.Name !== 'sub');
const params = {
UserPoolId: userPoolId,
Username: user.Username,
DesiredDeliveryMediums: [],
MessageAction: 'SUPPRESS',
ForceAliasCreation: false,
TemporaryPassword: tempPassword.toString(),
UserAttributes: attributes,
};
try {
const response = await cognitoIsp.send(new AdminCreateUserCommand(params));
debug('Restored user', response?.User?.Username);
if (verbose) {
const oldSub = user.Attributes.find((attribute) => attribute.Name === 'sub');
const newSub = response.User.Attributes.find((attribute) => attribute.Name === 'sub');
console.log(`Restored user - oldSub: "${oldSub?.Value}" newSub: "${newSub?.Value}"`);
}
} catch (e) {
if (e instanceof UsernameExistsException) {
console.error(`Warning: UserName=${user.Username} exists and is skipped.`);
} else {
throw e;
}
}
if (user.Groups) {
await pMap(user.Groups, async (group) => {
const groupParams = {
UserPoolId: userPoolId,
Username: user.Username,
GroupName: group,
};
await cognitoIsp.send(new AdminAddUserToGroupCommand(groupParams));
debug('Added user', user.Username, 'to group', group);
}, { concurrency: 1 });
}
}, { concurrency });
}
async function restoreGroups() {
const userPoolId = cli.input[1];
const file = getUserPoolGroupFileName(userPoolId);
if (!userPoolId) {
console.error('user-pool-id is required');
cli.showHelp();
}
// TODO make streamable
const data = await readFile(file, 'utf8');
const groups = JSON.parse(data);
return pMap(groups, async (group) => {
const params = {
UserPoolId: userPoolId,
GroupName: group.GroupName,
Description: group.Description,
Precedence: group.Precedence,
RoleArn: group.RoleArn,
};
try {
const response = await cognitoIsp.send(new CreateGroupCommand(params));
debug('Restored group', response?.Group.GroupName);
} catch (e) {
if (e instanceof GroupExistsException) {
console.error(`Warning: GroupName=${group.GroupName} exists and is skipped.`);
} else {
throw e;
}
}
}, { concurrency });
}
const methods = {
'backup-users': backupUsersCli,
'backup-groups': backupGroupsCli,
'backup-all-users': backupAllUsersCli,
'restore-users': restoreUsers,
'restore-groups': restoreGroups,
};
const method = methods[cli.input[0]] || cli.showHelp();
try {
await method();
} catch (err) {
if (cli.flags.stackTrace) {
console.error('Error:', err);
} else {
console.error('Error:', err.message);
}
process.exitCode = 1;
}