-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.js
503 lines (445 loc) · 18.8 KB
/
setup.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
const inquirer = require('inquirer');
const { execSync } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { S3Client, PutObjectCommand } = require('@aws-sdk/client-s3');
const { CloudFormationClient, DescribeStacksCommand } = require('@aws-sdk/client-cloudformation');
const awsCredentials = require('./utils/awsCredentials');
const { EventEmitter } = require('events');
const { IAMClient, DetachUserPolicyCommand, AttachUserPolicyCommand, ListAttachedUserPoliciesCommand, CreatePolicyCommand } = require('@aws-sdk/client-iam');
const { STSClient, GetCallerIdentityCommand } = require('@aws-sdk/client-sts');
// Set max listeners to 15 to prevent warnings
EventEmitter.defaultMaxListeners = 15;
const isCommandAvailable = (command) => {
try {
execSync(`command -v ${command}`, { stdio: 'ignore' });
return true;
} catch {
return false;
}
};
const checkWorkingDirectory = () => {
// Get the directory name of the current working directory
const currentDir = path.basename(process.cwd());
if (currentDir !== 'MMM-S3Photos') {
console.error('\x1b[31mError: This script must be run from the MMM-S3Photos module directory\x1b[0m');
console.log('\nPlease use cd to change to the MMM-S3Photos module directory and then run this script again');
process.exit(1);
}
};
const questions = [
{
type: 'confirm',
name: 'hasAwsAccount',
message: 'Have you set up an AWS account and IAM User?',
default: true
},
{
type: 'input',
name: 'awsAccountInstructions',
message: 'Please follow the instructions in the README to create an AWS account. Press Enter to continue...',
when: (answers) => !answers.hasAwsAccount
},
{
type: 'confirm',
name: 'useExistingCreds',
message: 'An existing AWS credentials file was found. Do you want to use the existing credentials?',
when: () => fs.existsSync('./local_aws-credentials'),
default: true
},
{
type: 'input',
name: 'accountId',
message: 'Enter your AWS Account ID:',
when: (answers) => answers.hasAwsAccount && (!answers.useExistingCreds || !fs.existsSync('./local_aws-credentials'))
},
{
type: 'input',
name: 'accessKeyId',
message: 'Enter your AWS Access Key ID:',
when: (answers) => answers.hasAwsAccount && (!answers.useExistingCreds || !fs.existsSync('./local_aws-credentials'))
},
{
type: 'input',
name: 'secretAccessKey',
message: 'Enter your AWS Secret Access Key:',
when: (answers) => answers.hasAwsAccount && (!answers.useExistingCreds || !fs.existsSync('./local_aws-credentials'))
},
{
type: 'input',
name: 'region',
message: 'Enter your AWS Region example: us-east-1:',
when: (answers) => answers.hasAwsAccount && (!answers.useExistingCreds || !fs.existsSync('./local_aws-credentials'))
},
{
type: 'confirm',
name: 'lockDownUser',
message: 'Would you like to apply security restrictions to your IAM user? (Highly Recommended)\n' +
' • Will removes admin access from this IAM-user\n' +
' • Limits IAM user access to only the S3 bucket and required Lambda functions\n' +
' • Reduces risk if credentials are exposed\n' +
'\n WARNING: This can only be reversed through the AWS Console',
default: false,
when: (answers) => answers.hasAwsAccount
}
];
const getBucketName = async (region) => {
if (!region) {
console.error('Region not provided to getBucketName');
return null;
}
try {
const cloudFormationClient = new CloudFormationClient({ region });
const command = new DescribeStacksCommand({ StackName: 'S3PhotosStack' });
const data = await cloudFormationClient.send(command);
const outputs = data.Stacks[0].Outputs;
const output = outputs.find(output => output.OutputKey === 'S3PhotosBucketName');
return output ? output.OutputValue : null;
} catch (err) {
console.error('Error retrieving stack outputs:', err);
return null;
}
};
const installAwsCli = () => {
console.log('Installing AWS CLI...');
if (os.platform() === 'linux') {
execSync('curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"', { stdio: 'inherit' });
execSync('unzip awscliv2.zip', { stdio: 'inherit' });
execSync('sudo ./aws/install', { stdio: 'inherit' });
} else if (os.platform() === 'darwin') {
execSync('curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"', { stdio: 'inherit' });
execSync('sudo installer -pkg AWSCLIV2.pkg -target /', { stdio: 'inherit' });
}
};
const installAwsCdk = () => {
console.log('Installing AWS CDK...');
execSync('npm install -g aws-cdk', { stdio: 'inherit' });
};
const uploadSampleFile = async (bucketName) => {
console.log('Uploading sample file to S3 bucket...');
await awsCredentials.withCredentials(async () => {
const s3Client = new S3Client({ region: process.env.AWS_REGION });
const filePath1 = path.join(__dirname, 'cache', 'samples', 'pexels-dan-mooham.jpg');
const fileContent1 = fs.readFileSync(filePath1);
const filePath2 = path.join(__dirname, 'cache', 'samples', 'pexels-matreding.jpg');
const fileContent2 = fs.readFileSync(filePath2);
const filePath3 = path.join(__dirname, 'cache', 'samples', 'pexels-pixabay.jpg');
const fileContent3 = fs.readFileSync(filePath3);
const params1 = {
Bucket: bucketName,
Key: 'samples/pexels-dan-mooham.jpg',
Body: fileContent1,
ContentType: 'image/jpeg'
};
const params2 = {
Bucket: bucketName,
Key: 'samples/pexels-matreding.jpg',
Body: fileContent2,
ContentType: 'image/jpeg'
};
const params3 = {
Bucket: bucketName,
Key: 'samples/pexels-pixabay.jpg',
Body: fileContent3,
ContentType: 'image/jpeg'
};
try {
await s3Client.send(new PutObjectCommand(params1));
console.log('First Sample file uploaded successfully.');
} catch (err) {
console.error('Error uploading sample file:', err);
throw err;
}
try {
await s3Client.send(new PutObjectCommand(params2));
console.log('Second Sample file uploaded successfully.');
} catch (err) {
console.error('Error uploading sample file:', err);
throw err;
}
try {
await s3Client.send(new PutObjectCommand(params3));
console.log('Second Sample file uploaded successfully.');
} catch (err) {
console.error('Error uploading sample file:', err);
throw err;
}
});
};
const setupModulePermissions = async () => {
console.log('Setting up module permissions...');
const modulePath = path.join(__dirname, '..');
const cachePath = path.join(modulePath, 'cache');
try {
// Create cache directory if it doesn't exist
if (!fs.existsSync(cachePath)) {
fs.mkdirSync(cachePath, { recursive: true });
}
// Set directory permissions (755 = rwxr-xr-x)
fs.chmodSync(cachePath, '755');
// Create an empty photos.json file with proper permissions
const photosJsonPath = path.join(cachePath, 'photos.json');
if (!fs.existsSync(photosJsonPath)) {
fs.writeFileSync(photosJsonPath, '[]');
fs.chmodSync(photosJsonPath, '644'); // 644 = rw-r--r--
}
console.log('Module permissions set successfully.');
} catch (error) {
console.error('Error setting module permissions:', error);
throw error;
}
};
// Add after other requires
const isRoot = () => process.getuid && process.getuid() === 0;
const checkSudoPrivileges = () => {
// Only check for sudo on Linux/Mac systems
if (os.platform() !== 'linux' && os.platform() !== 'darwin') {
return;
}
// Check if AWS CLI is already installed
const awsInstalled = isCommandAvailable('aws');
if (!awsInstalled && !isRoot()) {
console.error('\x1b[31mError: AWS CLI installation requires sudo privileges\x1b[0m');
console.log('\nPlease run the setup script with sudo:');
console.log('\x1b[33msudo node setup.js\x1b[0m\n');
process.exit(1);
}
};
const main = async () => {
try {
checkWorkingDirectory();
checkSudoPrivileges();
const answers = await inquirer.prompt(questions);
// Early exit if no AWS account
if (!answers.hasAwsAccount) {
console.log('Please create an AWS account and then run this script again.');
return;
}
// Handle credentials
let credentials;
if (answers.useExistingCreds && fs.existsSync('./local_aws-credentials')) {
credentials = parseCredentialsFile('./local_aws-credentials');
} else {
credentials = {
accessKeyId: answers.accessKeyId,
secretAccessKey: answers.secretAccessKey,
region: answers.region,
accountId: answers.accountId
};
// Save new credentials
saveCredentialsFile('./local_aws-credentials', credentials);
}
// Set environment variables
setAwsEnvironmentVariables(credentials);
// Deploy infrastructure
await deployInfrastructure(credentials);
// Generate configuration files
await generateConfigFiles(credentials);
// After infrastructure deployment and before final config generation
if (answers.lockDownUser) {
const username = await getCurrentUser(credentials);
console.log(`Detected IAM user: ${username}`);
await updateUserPermissions(credentials, username);
console.log('.');
console.log('.');
console.log('.');
console.log('Setup complete! AWS Cloud Formation has been deployed log and outputs here:');
console.log('- local_aws-credentials (AWS credentials DO NOT DELETE)');
console.log('- aws-resources.json (AWS resource configuration DO NOT DELETE)');
console.log('.');
console.log('.');
console.log('Sample files have been uploaded to the S3 bucket. To delete them run the below command after uploading your own photos:');
console.log(' node delete_samples.js');
} else {
console.log('.');
console.log('.');
console.log('.');
console.log('Setup complete! AWS Cloud Formation has been deployed log and outputs here:');
console.log('- local_aws-credentials (AWS credentials DO NOT DELETE)');
console.log('- aws-resources.json (AWS resource configuration DO NOT DELETE)');
console.log('.');
console.log('.');
console.log('Sample files have been uploaded to the S3 bucket. To delete them run the below command after uploading your own photos:');
console.log(' node delete_samples.js');
console.log('You chose not to restrict the IAM user. It is highly recommended to limit this user\'s permissions to reduce risk. Please refer to the README for guidance.');
}
} catch (error) {
console.error('Setup failed:', error);
process.exit(1);
}
};
// Helper functions
const parseCredentialsFile = (filePath) => {
const content = fs.readFileSync(filePath, 'utf8');
return content.split('\n').reduce((acc, line) => {
const [key, value] = line.split('=').map(s => s.trim());
if (key && value) {
acc[key.replace('aws_', '')] = value;
}
return acc;
}, {});
};
const saveCredentialsFile = (filePath, credentials) => {
const content = `[default]
aws_access_key_id = ${credentials.accessKeyId}
aws_secret_access_key = ${credentials.secretAccessKey}
region = ${credentials.region}
account_id = ${credentials.accountId}
`;
fs.writeFileSync(filePath, content);
};
const setAwsEnvironmentVariables = (credentials) => {
process.env.AWS_ACCESS_KEY_ID = credentials.accessKeyId;
process.env.AWS_SECRET_ACCESS_KEY = credentials.secretAccessKey;
process.env.AWS_REGION = credentials.region;
process.env.AWS_ACCOUNT_ID = credentials.accountId;
};
const deployInfrastructure = async (credentials) => {
// Install dependencies if needed
if (!isCommandAvailable('aws')) installAwsCli();
if (!isCommandAvailable('cdk')) installAwsCdk();
console.log('Installing project dependencies...');
execSync('npm install', { stdio: 'inherit' });
const bootstrapStackName = 'mmm-s3photos-bootstrap';
console.log('Bootstrapping environment...');
// Load environment variables in setup mode
const loadEnv = require('./utils/loadEnv');
if (!loadEnv(true)) { // Pass true for setup mode
throw new Error('Failed to load environment variables');
}
try {
execSync(
`cdk bootstrap aws://${process.env.AWS_ACCOUNT_ID}/${process.env.AWS_REGION} --toolkit-stack-name ${bootstrapStackName} --qualifier mmm`,
{
stdio: 'inherit',
env: process.env
}
);
} catch (error) {
if (!error.message.includes('already bootstrapped')) {
throw error;
}
console.log('Environment already bootstrapped. Proceeding...');
}
console.log('Deploying CDK stack...');
execSync(
`cdk deploy S3PhotosStack --toolkit-stack-name ${bootstrapStackName} --require-approval never`,
{
stdio: 'inherit',
env: process.env
}
);
};
const generateConfigFiles = async (credentials) => {
await awsCredentials.withCredentials(async () => {
// Get stack outputs for resources
const cloudFormationClient = new CloudFormationClient({ region: credentials.region });
const command = new DescribeStacksCommand({ StackName: 'S3PhotosStack' });
const data = await cloudFormationClient.send(command);
const outputs = data.Stacks[0].Outputs;
// Extract values from stack outputs
const config = {
s3Bucket: outputs.find(o => o.OutputKey === 'S3PhotosBucketName').OutputValue,
lambdaFunction: outputs.find(o => o.OutputKey === 'S3PhotosHandlerName').OutputValue
};
// Save aws-resources.json
const resourcesPath = path.join(__dirname, 'aws-resources.json');
fs.writeFileSync(resourcesPath, JSON.stringify(config, null, 2));
// Upload sample files using the bucket name from config
await uploadSampleFile(config.s3Bucket);
// Generate minimal IAM policy using values from config
const minimalPolicy = {
Version: "2012-10-17",
Statement: [
{
Effect: "Allow",
Action: [
"s3:GetObject",
"s3:PutObject",
"s3:ListBucket",
"s3:DeleteObject"
],
Resource: [
`arn:aws:s3:::${config.s3Bucket}`,
`arn:aws:s3:::${config.s3Bucket}/*`
]
},
{
Effect: "Allow",
Action: ["lambda:InvokeFunction"],
Resource: `arn:aws:lambda:${process.env.AWS_REGION}:${process.env.AWS_ACCOUNT_ID}:function:${config.lambdaFunction}`
}
]
};
fs.writeFileSync(
path.join(__dirname, 'minimal-policy.json'),
JSON.stringify(minimalPolicy, null, 2)
);
});
};
async function updateUserPermissions(credentials, username) {
await awsCredentials.withCredentials(async () => {
const iamClient = new IAMClient({ region: process.env.AWS_REGION });
try {
// List current policies
const listPoliciesCommand = new ListAttachedUserPoliciesCommand({
UserName: username
});
const { AttachedPolicies } = await iamClient.send(listPoliciesCommand);
// Find and detach admin policy
const adminPolicy = AttachedPolicies.find(policy =>
policy.PolicyArn.includes('AdministratorAccess')
);
if (adminPolicy) {
console.log('Removing administrator access...');
await iamClient.send(new DetachUserPolicyCommand({
UserName: username,
PolicyArn: adminPolicy.PolicyArn
}));
}
// Create and attach minimal policy
console.log('Applying minimal access policy...');
const minimalPolicyDocument = fs.readFileSync(
path.join(__dirname, 'minimal-policy.json'),
'utf8'
);
// Create new policy and attach it
const policyName = 'MMMS3PhotosMinimalAccess';
const createPolicyCommand = new CreatePolicyCommand({
PolicyName: policyName,
PolicyDocument: minimalPolicyDocument
});
const { Policy } = await iamClient.send(createPolicyCommand);
await iamClient.send(new AttachUserPolicyCommand({
UserName: username,
PolicyArn: Policy.Arn
}));
console.log('*');
console.log('*');
console.log('Successfully updated user permissions to minimal access.');
console.log('Note: This change can only be undone through the AWS Console.');
console.log('*');
console.log('*');
} catch (error) {
console.error('Error updating user permissions:', error);
throw error;
}
});
}
// Add this function to get the current IAM user
async function getCurrentUser() {
return awsCredentials.withCredentials(async () => {
const stsClient = new STSClient({ region: process.env.AWS_REGION });
try {
const response = await stsClient.send(new GetCallerIdentityCommand({}));
// The ARN format is: arn:aws:iam::ACCOUNT-ID:user/USERNAME
const arnParts = response.Arn.split('/');
return arnParts[arnParts.length - 1]; // Gets the username
} catch (error) {
console.error('Error getting current user:', error);
throw error;
}
});
}
main();