@fishawack/lab-env 5.6.1 → 5.7.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/_Test/boilerplate-adonis.js +1 -1
  3. package/_Test/boilerplate-craftcms.js +1 -1
  4. package/_Test/boilerplate-drupal.js +1 -1
  5. package/_Test/boilerplate-laravel.js +1 -1
  6. package/_Test/boilerplate-python.js +1 -1
  7. package/_Test/boilerplate-wordpress.js +1 -1
  8. package/_Test/boilerplate.js +1 -1
  9. package/_Test/provision.js +4 -9
  10. package/_Test/prune.js +8 -5
  11. package/bitbucket-pipelines.yml +2 -2
  12. package/cli.js +2 -0
  13. package/commands/create/cmds/dekey.js +13 -9
  14. package/commands/create/cmds/deprovision.js +66 -6
  15. package/commands/create/cmds/diagnose.js +10 -0
  16. package/commands/create/cmds/key.js +74 -41
  17. package/commands/create/cmds/provision.js +641 -22
  18. package/commands/create/cmds/rekey.js +283 -0
  19. package/commands/create/cmds/sync-secrets.js +198 -0
  20. package/commands/create/libs/output-credentials.js +59 -0
  21. package/commands/create/libs/parallel-runner.js +296 -0
  22. package/commands/create/libs/resolve-operator.js +59 -0
  23. package/commands/create/libs/utilities.js +75 -8
  24. package/commands/create/libs/vars.js +273 -377
  25. package/commands/create/services/aws/acm.js +61 -0
  26. package/commands/create/services/aws/cloudfront.js +51 -45
  27. package/commands/create/services/aws/ec2.js +781 -5
  28. package/commands/create/services/aws/elasticache.js +159 -0
  29. package/commands/create/services/aws/elasticbeanstalk.js +200 -48
  30. package/commands/create/services/aws/iam.js +430 -82
  31. package/commands/create/services/aws/index.js +1598 -100
  32. package/commands/create/services/aws/opensearch.js +155 -0
  33. package/commands/create/services/aws/rds.js +272 -0
  34. package/commands/create/services/aws/s3.js +52 -31
  35. package/commands/create/services/aws/secretsmanager.js +82 -0
  36. package/commands/create/services/aws/ses.js +203 -0
  37. package/commands/create/templates/elasticbeanstalk/.ebextensions/laravel/cron.config +45 -0
  38. package/commands/create/templates/elasticbeanstalk/.ebextensions/laravel/queue-worker.config +29 -0
  39. package/commands/create/templates/elasticbeanstalk/.ebextensions/laravel/rds-ssl.config +5 -0
  40. package/commands/create/templates/elasticbeanstalk/.ebextensions/laravel/software.config +12 -0
  41. package/commands/create/templates/elasticbeanstalk/.ebextensions/misc/setvars.config +1 -0
  42. package/commands/create/templates/elasticbeanstalk/.platform/confighooks/postdeploy/restart_queue.sh +4 -0
  43. package/commands/create/templates/elasticbeanstalk/.platform/confighooks/postdeploy/rewrite-flush.sh +1 -1
  44. package/commands/create/templates/elasticbeanstalk/.platform/confighooks/prebuild/setvars.sh +19 -0
  45. package/commands/create/templates/elasticbeanstalk/.platform/hooks/postdeploy/restart_queue.sh +4 -0
  46. package/commands/create/templates/elasticbeanstalk/.platform/hooks/prebuild/setvars.sh +19 -0
  47. package/commands/scan.js +1 -1
  48. package/core/1/CHANGELOG.md +41 -0
  49. package/core/1/Dockerfile +3 -3
  50. package/core/1/bitbucket-pipelines.yml +5 -5
  51. package/core/1/package.json +1 -1
  52. package/globals.js +4 -0
  53. package/package.json +9 -2
@@ -1,18 +1,203 @@
1
- const md5 = require("apache-md5");
2
- const fs = require("fs-extra");
1
+ const generator = require("generate-password");
2
+ const { S3Client, ListBucketsCommand } = require("@aws-sdk/client-s3");
3
+ const {
4
+ RDSClient,
5
+ DescribeDBInstancesCommand,
6
+ } = require("@aws-sdk/client-rds");
7
+ const {
8
+ SecretsManagerClient,
9
+ DescribeSecretCommand,
10
+ } = require("@aws-sdk/client-secrets-manager");
11
+ const {
12
+ OpenSearchClient,
13
+ DescribeDomainCommand,
14
+ } = require("@aws-sdk/client-opensearch");
15
+ const {
16
+ ElastiCacheClient,
17
+ DescribeReplicationGroupsCommand,
18
+ } = require("@aws-sdk/client-elasticache");
3
19
 
4
- const { nameSafe } = require("../../libs/utilities.js");
5
- const { eb } = require("../../libs/vars.js");
20
+ const { nameSafe, Spinner, pollAll } = require("../../libs/utilities.js");
21
+ const { eb, secretGroups } = require("../../libs/vars.js");
6
22
 
7
23
  module.exports.s3 = require("./s3.js");
8
24
  module.exports.cloudfront = require("./cloudfront.js");
9
25
  module.exports.iam = require("./iam.js");
10
26
  module.exports.elasticbeanstalk = require("./elasticbeanstalk.js");
11
27
  module.exports.ec2 = require("./ec2.js");
28
+ module.exports.rds = require("./rds.js");
29
+ module.exports.opensearch = require("./opensearch.js");
30
+ module.exports.elasticache = require("./elasticache.js");
31
+ module.exports.secretsmanager = require("./secretsmanager.js");
32
+ module.exports.acm = require("./acm.js");
33
+ module.exports.ses = require("./ses.js");
12
34
 
13
35
  module.exports.slug = (repo, client, branch, service = "s3") =>
14
36
  nameSafe(`${branch}-${repo}-${client}`, service);
15
37
 
38
+ module.exports.fullstackPreflight = async (
39
+ name,
40
+ repo,
41
+ branch,
42
+ {
43
+ storage = false,
44
+ database = false,
45
+ opensearch = false,
46
+ cache = false,
47
+ } = {},
48
+ ) => {
49
+ const existing = {
50
+ environment: false,
51
+ storage: false,
52
+ database: false,
53
+ opensearch: false,
54
+ cache: false,
55
+ secrets: {
56
+ app: null,
57
+ storage: null,
58
+ database: null,
59
+ opensearch: null,
60
+ cache: null,
61
+ mail: null,
62
+ },
63
+ };
64
+
65
+ const spinner = new Spinner("Running pre-flight checks", true);
66
+
67
+ try {
68
+ // Check EB environment
69
+ spinner.ora.text = "Checking for existing EB environment";
70
+ try {
71
+ const { Environments } =
72
+ await module.exports.elasticbeanstalk.describeEnvironment(name);
73
+ const active = Environments.filter(
74
+ (e) => e.Status !== "Terminated",
75
+ );
76
+ if (active.length) {
77
+ existing.environment = active[0];
78
+ }
79
+ } catch {
80
+ /* does not exist */
81
+ }
82
+
83
+ // Check S3
84
+ if (storage) {
85
+ const s3Slug = module.exports.slug(
86
+ repo,
87
+ process.env.AWS_PROFILE,
88
+ branch,
89
+ "s3",
90
+ );
91
+
92
+ spinner.ora.text = "Checking for existing S3 bucket";
93
+ try {
94
+ const { Buckets } = await new S3Client({}).send(
95
+ new ListBucketsCommand({}),
96
+ );
97
+ if (Buckets.some((b) => b.Name === s3Slug)) {
98
+ existing.storage = true;
99
+ }
100
+ } catch {
101
+ /* empty */
102
+ }
103
+ }
104
+
105
+ // Check RDS
106
+ if (database) {
107
+ const rdsSlug = module.exports.slug(
108
+ repo,
109
+ process.env.AWS_PROFILE,
110
+ branch,
111
+ "rds",
112
+ );
113
+
114
+ spinner.ora.text = "Checking for existing RDS instance";
115
+ try {
116
+ const res = await new RDSClient({}).send(
117
+ new DescribeDBInstancesCommand({
118
+ DBInstanceIdentifier: rdsSlug,
119
+ }),
120
+ );
121
+ const instance = res.DBInstances[0];
122
+ if (instance && instance.DBInstanceStatus !== "deleting") {
123
+ existing.database = true;
124
+ }
125
+ } catch {
126
+ /* does not exist */
127
+ }
128
+ }
129
+
130
+ // Check OpenSearch
131
+ if (opensearch) {
132
+ const osSlug = module.exports.slug(
133
+ repo,
134
+ process.env.AWS_PROFILE,
135
+ branch,
136
+ "os",
137
+ );
138
+
139
+ spinner.ora.text = "Checking for existing OpenSearch domain";
140
+ try {
141
+ const { DomainStatus } = await new OpenSearchClient({}).send(
142
+ new DescribeDomainCommand({ DomainName: osSlug }),
143
+ );
144
+ if (DomainStatus && !DomainStatus.Deleted) {
145
+ existing.opensearch = true;
146
+ }
147
+ } catch {
148
+ /* does not exist */
149
+ }
150
+ }
151
+
152
+ // Check ElastiCache
153
+ if (cache) {
154
+ const cacheSlug = module.exports.slug(
155
+ repo,
156
+ process.env.AWS_PROFILE,
157
+ branch,
158
+ "cache",
159
+ );
160
+
161
+ spinner.ora.text = "Checking for existing ElastiCache cluster";
162
+ try {
163
+ const { ReplicationGroups } = await new ElastiCacheClient(
164
+ {},
165
+ ).send(
166
+ new DescribeReplicationGroupsCommand({
167
+ ReplicationGroupId: cacheSlug,
168
+ }),
169
+ );
170
+ const group = ReplicationGroups[0];
171
+ if (group && group.Status !== "deleting") {
172
+ existing.cache = true;
173
+ }
174
+ } catch {
175
+ /* does not exist */
176
+ }
177
+ }
178
+
179
+ // Check for existing secrets
180
+ for (const group of secretGroups) {
181
+ spinner.ora.text = `Checking for existing ${group} secret`;
182
+ try {
183
+ const secret = await new SecretsManagerClient({}).send(
184
+ new DescribeSecretCommand({ SecretId: `${name}-${group}` }),
185
+ );
186
+ existing.secrets[group] = secret.ARN;
187
+ } catch {
188
+ /* does not exist */
189
+ }
190
+ }
191
+
192
+ spinner.ora.succeed("Pre-flight checks complete");
193
+ } catch (e) {
194
+ spinner.ora.fail("Pre-flight checks failed");
195
+ throw e;
196
+ }
197
+
198
+ return { existing };
199
+ };
200
+
16
201
  module.exports.clients = [
17
202
  "fishawack",
18
203
  "abbvie",
@@ -58,6 +243,7 @@ module.exports.clients = [
58
243
  "dompe",
59
244
  "test",
60
245
  "bristolmyers",
246
+ "argenx",
61
247
  ];
62
248
 
63
249
  module.exports.static = async (
@@ -157,175 +343,1487 @@ module.exports.staticTerminate = async (name, repo, branch, id) => {
157
343
  }
158
344
  };
159
345
 
346
+ // Private provisioner functions for parallel execution
347
+
348
+ const provisionStorage = async (
349
+ aws,
350
+ s3Slug,
351
+ tags,
352
+ isLaravel,
353
+ existingResources,
354
+ ) => {
355
+ let s3Data = {};
356
+
357
+ if (!existingResources.storage) {
358
+ if (isLaravel) {
359
+ await aws.s3.createS3Bucket(s3Slug, tags, {
360
+ BlockPublicAcls: true,
361
+ IgnorePublicAcls: true,
362
+ BlockPublicPolicy: false,
363
+ RestrictPublicBuckets: false,
364
+ });
365
+
366
+ await aws.s3.setPublicReadPolicy(s3Slug, "public/*");
367
+ } else {
368
+ await aws.iam.createIAMUser(s3Slug, tags);
369
+ await aws.iam.attachIAMPolicy(
370
+ s3Slug,
371
+ "arn:aws:iam::aws:policy/AmazonS3FullAccess",
372
+ );
373
+ const {
374
+ AccessKey: { AccessKeyId },
375
+ AccessKey: { SecretAccessKey },
376
+ } = await aws.iam.createAccessKey(s3Slug);
377
+
378
+ await aws.s3.createS3Bucket(
379
+ s3Slug,
380
+ tags,
381
+ false,
382
+ "BucketOwnerPreferred",
383
+ );
384
+
385
+ s3Data = { s3Slug, AccessKeyId, SecretAccessKey };
386
+ }
387
+ }
388
+
389
+ if (!s3Data.s3Slug) {
390
+ s3Data = { s3Slug };
391
+ }
392
+
393
+ return s3Data;
394
+ };
395
+
396
+ const provisionRDS = async (
397
+ aws,
398
+ name,
399
+ repo,
400
+ branch,
401
+ tags,
402
+ vpcData,
403
+ existingResources,
404
+ existingSecrets,
405
+ snapshot,
406
+ ) => {
407
+ const rdsSlug = aws.slug(repo, process.env.AWS_PROFILE, branch, "rds");
408
+ const rdsClient = new RDSClient({});
409
+
410
+ if (!existingResources.database) {
411
+ const dbPassword = generator.generate({
412
+ length: 10,
413
+ numbers: true,
414
+ });
415
+
416
+ await aws.rds.ensureSSLParameterGroup();
417
+
418
+ const rdsSecurityGroupId = await aws.ec2.createRDSSecurityGroup(
419
+ rdsSlug,
420
+ tags,
421
+ );
422
+
423
+ const dbSubnetGroupName = await aws.rds.ensureDBSubnetGroup(
424
+ vpcData.privateSubnetIds,
425
+ );
426
+
427
+ if (snapshot) {
428
+ await aws.rds.restoreRDSInstanceFromSnapshot(
429
+ rdsSlug,
430
+ snapshot,
431
+ rdsSecurityGroupId,
432
+ tags,
433
+ dbSubnetGroupName,
434
+ );
435
+
436
+ await aws.rds.waitForRDSInstance(rdsSlug);
437
+ await aws.rds.modifyRDSPassword(rdsSlug, dbPassword);
438
+ } else {
439
+ await aws.rds.createRDSInstance(
440
+ rdsSlug,
441
+ tags,
442
+ dbPassword,
443
+ rdsSecurityGroupId,
444
+ dbSubnetGroupName,
445
+ );
446
+ }
447
+
448
+ return {
449
+ rdsData: { RDS_PASSWORD: dbPassword },
450
+ rdsSlug,
451
+ poll: {
452
+ name: "RDS",
453
+ cb: async () =>
454
+ (
455
+ await rdsClient.send(
456
+ new DescribeDBInstancesCommand({
457
+ DBInstanceIdentifier: rdsSlug,
458
+ }),
459
+ )
460
+ ).DBInstances[0],
461
+ shouldContinue: ({ DBInstanceStatus }) =>
462
+ DBInstanceStatus !== "available",
463
+ },
464
+ };
465
+ } else if (existingResources.database && !existingSecrets.database) {
466
+ const dbPassword = generator.generate({
467
+ length: 10,
468
+ numbers: true,
469
+ });
470
+
471
+ await aws.rds.modifyRDSPassword(rdsSlug, dbPassword);
472
+
473
+ return {
474
+ rdsData: { RDS_PASSWORD: dbPassword },
475
+ rdsSlug,
476
+ poll: {
477
+ name: "RDS",
478
+ cb: async () =>
479
+ (
480
+ await rdsClient.send(
481
+ new DescribeDBInstancesCommand({
482
+ DBInstanceIdentifier: rdsSlug,
483
+ }),
484
+ )
485
+ ).DBInstances[0],
486
+ shouldContinue: ({ DBInstanceStatus }) =>
487
+ DBInstanceStatus !== "available",
488
+ },
489
+ };
490
+ } else {
491
+ const secretValue = await aws.secretsmanager.getSecretValue(
492
+ `${name}-database`,
493
+ );
494
+ return {
495
+ rdsData: {
496
+ RDS_HOSTNAME: secretValue.RDS_HOSTNAME,
497
+ RDS_PORT: secretValue.RDS_PORT,
498
+ RDS_PASSWORD: secretValue.RDS_PASSWORD,
499
+ },
500
+ rdsSlug,
501
+ };
502
+ }
503
+ };
504
+
505
+ const provisionOpenSearch = async (
506
+ aws,
507
+ osSlug,
508
+ tags,
509
+ vpcData,
510
+ instanceProfileName,
511
+ existingResources,
512
+ ) => {
513
+ const osClient = new OpenSearchClient({});
514
+
515
+ if (!existingResources.opensearch) {
516
+ await aws.iam.ensureOpenSearchServiceRole();
517
+
518
+ const roleArn = instanceProfileName
519
+ ? (await aws.iam.getRole(instanceProfileName)).Role.Arn
520
+ : undefined;
521
+
522
+ const osSecurityGroupId = await aws.ec2.createOpenSearchSecurityGroup(
523
+ osSlug,
524
+ tags,
525
+ );
526
+
527
+ await aws.opensearch.createOpenSearchDomain(
528
+ osSlug,
529
+ osSecurityGroupId,
530
+ vpcData.privateSubnetIds,
531
+ roleArn,
532
+ tags,
533
+ );
534
+
535
+ return {
536
+ osData: {},
537
+ poll: {
538
+ name: "OpenSearch",
539
+ cb: async () => {
540
+ const { DomainStatus } = await osClient.send(
541
+ new DescribeDomainCommand({ DomainName: osSlug }),
542
+ );
543
+ return DomainStatus;
544
+ },
545
+ shouldContinue: (status) =>
546
+ status.Processing ||
547
+ (!status.Endpoint && !status.Endpoints),
548
+ },
549
+ };
550
+ } else {
551
+ const osDomain = await aws.opensearch.describeOpenSearchDomain(osSlug);
552
+
553
+ const osEndpoint =
554
+ osDomain.Endpoint || (osDomain.Endpoints && osDomain.Endpoints.vpc);
555
+
556
+ return { osData: { SEARCH_HOST: `https://${osEndpoint}` } };
557
+ }
558
+ };
559
+
560
+ const provisionCache = async (
561
+ aws,
562
+ name,
563
+ cacheSlug,
564
+ tags,
565
+ vpcData,
566
+ existingResources,
567
+ existingSecrets,
568
+ ) => {
569
+ const cacheClient = new ElastiCacheClient({});
570
+
571
+ if (!existingResources.cache) {
572
+ const cachePassword = generator.generate({
573
+ length: 16,
574
+ numbers: true,
575
+ symbols: false,
576
+ strict: true,
577
+ });
578
+
579
+ const cacheSubnetGroupName =
580
+ await aws.elasticache.ensureCacheSubnetGroup(
581
+ vpcData.privateSubnetIds,
582
+ );
583
+
584
+ const cacheSecurityGroupId = await aws.ec2.createCacheSecurityGroup(
585
+ cacheSlug,
586
+ tags,
587
+ );
588
+
589
+ await aws.elasticache.createCacheCluster(
590
+ cacheSlug,
591
+ cacheSecurityGroupId,
592
+ cacheSubnetGroupName,
593
+ cachePassword,
594
+ tags,
595
+ );
596
+
597
+ return {
598
+ cacheData: { REDIS_PASSWORD: cachePassword },
599
+ poll: {
600
+ name: "ElastiCache",
601
+ cb: async () => {
602
+ const { ReplicationGroups } = await cacheClient.send(
603
+ new DescribeReplicationGroupsCommand({
604
+ ReplicationGroupId: cacheSlug,
605
+ }),
606
+ );
607
+ return ReplicationGroups[0];
608
+ },
609
+ shouldContinue: (group) => group.Status !== "available",
610
+ },
611
+ };
612
+ } else if (existingResources.cache && !existingSecrets.cache) {
613
+ const cluster = await aws.elasticache.describeCacheCluster(cacheSlug);
614
+
615
+ const cacheEndpoint = cluster.NodeGroups[0].PrimaryEndpoint;
616
+
617
+ return {
618
+ cacheData: {
619
+ REDIS_HOST: cacheEndpoint.Address,
620
+ REDIS_PORT: String(cacheEndpoint.Port),
621
+ REDIS_PASSWORD: "",
622
+ },
623
+ };
624
+ } else {
625
+ const secretValue = await aws.secretsmanager.getSecretValue(
626
+ `${name}-cache`,
627
+ );
628
+ return {
629
+ cacheData: {
630
+ REDIS_HOST: secretValue.REDIS_HOST,
631
+ REDIS_PORT: secretValue.REDIS_PORT,
632
+ REDIS_PASSWORD: secretValue.REDIS_PASSWORD,
633
+ },
634
+ };
635
+ }
636
+ };
637
+
638
+ const provisionMail = async (aws, name, tags, mailData) => {
639
+ const {
640
+ IAMClient,
641
+ CreateUserCommand,
642
+ GetUserCommand,
643
+ CreateAccessKeyCommand,
644
+ ListAccessKeysCommand,
645
+ } = require("@aws-sdk/client-iam");
646
+ const { fromIni } = require("@aws-sdk/credential-providers");
647
+
648
+ const sesProfile = "fishawack";
649
+ const sesRegion = "us-east-1";
650
+ const groupName = "AWSSESSendingGroupDoNotRename";
651
+
652
+ const iamClient = new IAMClient({
653
+ region: sesRegion,
654
+ credentials: fromIni({ profile: sesProfile }),
655
+ });
656
+
657
+ const userName = `${name}-ses`;
658
+
659
+ // Create user in the fishawack account
660
+ try {
661
+ await Spinner.prototype.simple(
662
+ `Creating SES IAM user ${userName}`,
663
+ () => {
664
+ return iamClient.send(
665
+ new CreateUserCommand({
666
+ UserName: userName,
667
+ Tags: [
668
+ { Key: "client", Value: process.env.AWS_PROFILE },
669
+ ].concat(
670
+ tags.map((t) => ({
671
+ Key: t.Key,
672
+ Value: String(t.Value),
673
+ })),
674
+ ),
675
+ }),
676
+ );
677
+ },
678
+ );
679
+ } catch {
680
+ await Spinner.prototype.simple(
681
+ `Retrieving existing SES IAM user ${userName}`,
682
+ () => {
683
+ return iamClient.send(
684
+ new GetUserCommand({ UserName: userName }),
685
+ );
686
+ },
687
+ );
688
+ }
689
+
690
+ // Add user to SES sending group
691
+ await aws.iam.addUserToGroup(userName, groupName, iamClient);
692
+
693
+ // Create access key
694
+ const existingKeys = await iamClient.send(
695
+ new ListAccessKeysCommand({ UserName: userName }),
696
+ );
697
+
698
+ if (existingKeys.AccessKeyMetadata.length) {
699
+ // Keys already exist — we can't retrieve the secret again so return what we have in secrets
700
+ return {
701
+ MAIL_USERNAME: existingKeys.AccessKeyMetadata[0].AccessKeyId,
702
+ MAIL_PASSWORD: "",
703
+ MAIL_FROM_ADDRESS: mailData.fromAddress,
704
+ MAIL_FROM_NAME: mailData.fromName,
705
+ };
706
+ }
707
+
708
+ const keyRes = await Spinner.prototype.simple(
709
+ `Creating access key for SES user`,
710
+ () => {
711
+ return iamClient.send(
712
+ new CreateAccessKeyCommand({ UserName: userName }),
713
+ );
714
+ },
715
+ );
716
+
717
+ // Derive SMTP credentials
718
+ const smtpPassword = aws.ses.deriveSmtpPassword(
719
+ keyRes.AccessKey.SecretAccessKey,
720
+ sesRegion,
721
+ );
722
+
723
+ return {
724
+ MAIL_USERNAME: keyRes.AccessKey.AccessKeyId,
725
+ MAIL_PASSWORD: smtpPassword,
726
+ MAIL_FROM_ADDRESS: mailData.fromAddress,
727
+ MAIL_FROM_NAME: mailData.fromName,
728
+ };
729
+ };
730
+
731
+ const authorizeIngress = async (aws, name, slug, service, authorizer) => {
732
+ try {
733
+ const sg = await aws.ec2.findSecurityGroupByName(`${slug}-${service}`);
734
+ const ebSg = await aws.ec2.findSecurityGroupByTag([
735
+ {
736
+ Name: "tag:elasticbeanstalk:environment-name",
737
+ Values: [name],
738
+ },
739
+ {
740
+ Name: "tag:aws:cloudformation:logical-id",
741
+ Values: ["AWSEBSecurityGroup"],
742
+ },
743
+ ]);
744
+ if (sg && ebSg) {
745
+ await authorizer(sg.GroupId, ebSg.GroupId);
746
+ }
747
+ } catch {
748
+ /* empty */
749
+ }
750
+ };
751
+
160
752
  module.exports.fullstack = async (
161
753
  name,
162
754
  tags = [],
163
- credentials = [],
164
755
  repo,
165
756
  branch,
166
757
  framework,
167
- availability,
168
758
  database = false,
759
+ storage = false,
760
+ opensearch = false,
761
+ cache = false,
762
+ mail = false,
763
+ existingSecrets = {
764
+ app: null,
765
+ storage: null,
766
+ database: null,
767
+ opensearch: null,
768
+ cache: null,
769
+ mail: null,
770
+ },
771
+ snapshot = null,
772
+ elbScheme = "public",
773
+ existingEnvironment = false,
774
+ existingResources = {
775
+ storage: false,
776
+ database: false,
777
+ opensearch: false,
778
+ cache: false,
779
+ },
780
+ appName,
781
+ appDomain,
782
+ certArn,
783
+ instanceType = "t3.micro",
784
+ mailData = {},
169
785
  ) => {
170
786
  const { platform, language } = eb.configurations[framework];
787
+ const isLaravel = framework === "laravel";
788
+ const aws = module.exports;
171
789
 
172
- const s3Slug = module.exports.slug(
173
- repo,
174
- process.env.AWS_PROFILE,
175
- branch,
176
- "s3",
177
- );
790
+ // Compute slugs
791
+ const s3Slug =
792
+ storage || existingSecrets.storage
793
+ ? aws.slug(repo, process.env.AWS_PROFILE, branch, "s3")
794
+ : undefined;
178
795
 
179
- await module.exports.iam.createIAMUser(s3Slug, tags);
180
- await module.exports.iam.attachIAMPolicy(
181
- s3Slug,
182
- "arn:aws:iam::aws:policy/AmazonS3FullAccess",
183
- );
184
- const {
185
- AccessKey: { AccessKeyId },
186
- AccessKey: { SecretAccessKey },
187
- } = await module.exports.iam.createAccessKey(s3Slug);
188
-
189
- await module.exports.s3.createS3Bucket(
190
- s3Slug,
191
- tags,
192
- false,
193
- "BucketOwnerPreferred",
194
- );
796
+ const osSlug =
797
+ opensearch || existingSecrets.opensearch
798
+ ? aws.slug(repo, process.env.AWS_PROFILE, branch, "os")
799
+ : undefined;
800
+
801
+ const cacheSlug =
802
+ cache || existingSecrets.cache
803
+ ? aws.slug(repo, process.env.AWS_PROFILE, branch, "cache")
804
+ : undefined;
195
805
 
196
- await module.exports.iam.ensureEBInstanceProfileExists();
197
- await module.exports.iam.ensureEBManagedUpdateProfileExists();
806
+ const opensearchDomainArn = osSlug
807
+ ? `arn:aws:es:${process.env.AWS_REGION}:*:domain/${osSlug}`
808
+ : undefined;
809
+
810
+ // Phase 1: IAM prerequisites (needed before OpenSearch and EB env)
811
+ let instanceProfileName;
812
+
813
+ if (isLaravel) {
814
+ instanceProfileName = await aws.iam.ensureEnvironmentInstanceProfile(
815
+ name,
816
+ s3Slug,
817
+ opensearchDomainArn,
818
+ tags,
819
+ );
820
+ } else {
821
+ await aws.iam.ensureEBInstanceProfileExists();
822
+ }
823
+
824
+ // Phase 2: VPC + EB app in parallel
825
+ const [vpcData] = await Promise.all([
826
+ aws.ec2.ensurePrivateSubnets(),
827
+ aws.iam.ensureEBManagedUpdateProfileExists(),
828
+ ]);
198
829
 
199
830
  try {
200
- await module.exports.elasticbeanstalk.createElasticBeanstalkApplication(
831
+ await aws.elasticbeanstalk.createElasticBeanstalkApplication(
201
832
  repo,
833
+ tags,
202
834
  );
203
835
  } catch {
204
836
  /* empty */
205
837
  }
206
838
 
207
- let hasKeyPair = false;
839
+ // Phase 3: Provision services in parallel
840
+ const servicePromises = [];
208
841
 
209
- try {
210
- await module.exports.ec2.getKeyPair("id_rsa_prev");
211
- hasKeyPair = true;
212
- } catch {
213
- /* empty */
842
+ if (storage) {
843
+ servicePromises.push(
844
+ provisionStorage(aws, s3Slug, tags, isLaravel, existingResources),
845
+ );
846
+ } else {
847
+ servicePromises.push(Promise.resolve(s3Slug ? { s3Slug } : {}));
848
+ }
849
+
850
+ if (database) {
851
+ servicePromises.push(
852
+ provisionRDS(
853
+ aws,
854
+ name,
855
+ repo,
856
+ branch,
857
+ tags,
858
+ vpcData,
859
+ existingResources,
860
+ existingSecrets,
861
+ snapshot,
862
+ ),
863
+ );
864
+ } else {
865
+ servicePromises.push(Promise.resolve({ rdsData: {}, rdsSlug: null }));
866
+ }
867
+
868
+ if (opensearch) {
869
+ servicePromises.push(
870
+ provisionOpenSearch(
871
+ aws,
872
+ osSlug,
873
+ tags,
874
+ vpcData,
875
+ instanceProfileName,
876
+ existingResources,
877
+ ),
878
+ );
879
+ } else {
880
+ servicePromises.push(Promise.resolve({ osData: {} }));
881
+ }
882
+
883
+ if (cache) {
884
+ servicePromises.push(
885
+ provisionCache(
886
+ aws,
887
+ name,
888
+ cacheSlug,
889
+ tags,
890
+ vpcData,
891
+ existingResources,
892
+ existingSecrets,
893
+ ),
894
+ );
895
+ } else {
896
+ servicePromises.push(Promise.resolve({ cacheData: {} }));
897
+ }
898
+
899
+ const [s3Data, rdsResult, osResult, cacheResult] =
900
+ await Promise.all(servicePromises);
901
+
902
+ // Phase 3b: Wait for all pending services with single spinner
903
+ const pendingPolls = [rdsResult, osResult, cacheResult]
904
+ .filter((r) => r && r.poll)
905
+ .map((r) => r.poll);
906
+
907
+ const pollResults = pendingPolls.length ? await pollAll(pendingPolls) : [];
908
+
909
+ // Extract endpoint data from poll results
910
+ let rdsData = rdsResult.rdsData || {};
911
+
912
+ if (rdsResult.poll) {
913
+ const rdsInstance = pollResults[pendingPolls.indexOf(rdsResult.poll)];
914
+ rdsData.RDS_HOSTNAME = rdsInstance.Endpoint.Address;
915
+ rdsData.RDS_PORT = String(rdsInstance.Endpoint.Port);
916
+ }
917
+
918
+ let osData = osResult.osData || {};
919
+
920
+ if (osResult.poll) {
921
+ const osDomain = pollResults[pendingPolls.indexOf(osResult.poll)];
922
+ const osEndpoint =
923
+ osDomain.Endpoint || (osDomain.Endpoints && osDomain.Endpoints.vpc);
924
+ osData.SEARCH_HOST = `https://${osEndpoint}`;
925
+ }
926
+
927
+ let cacheData = cacheResult.cacheData || {};
928
+
929
+ if (cacheResult.poll) {
930
+ const cluster = pollResults[pendingPolls.indexOf(cacheResult.poll)];
931
+ const cacheEndpoint = cluster.NodeGroups[0].PrimaryEndpoint;
932
+ cacheData.REDIS_HOST = cacheEndpoint.Address;
933
+ cacheData.REDIS_PORT = String(cacheEndpoint.Port);
214
934
  }
215
935
 
216
- // LetsEncrypt CN records are limited to 64 chars so use only the hash from the generated name
936
+ // Phase 4: Build secrets and EB environment (sequential)
217
937
  const CNAMEPrefix = `fw-auto-${name.split("-")[name.split("-").length - 1]}`;
218
938
  process.env.DOMAIN_LINK = `${CNAMEPrefix}.${process.env.AWS_REGION}.elasticbeanstalk.com`;
219
939
 
220
- const OptionSettings = eb.merge(
221
- "environments",
222
- { framework, availability, platform, language, database },
223
- { s3Slug, AccessKeyId, SecretAccessKey },
940
+ // Provision mail credentials if needed
941
+ let mailCreds = {};
942
+ if (mail && !existingSecrets.mail) {
943
+ mailCreds = await provisionMail(aws, name, tags, mailData);
944
+ }
945
+
946
+ const payloads = eb.buildSecretPayloads(
947
+ {
948
+ framework,
949
+ platform,
950
+ language,
951
+ database,
952
+ storage,
953
+ opensearch,
954
+ cache,
955
+ mail: mail && !existingSecrets.mail,
956
+ },
957
+ {
958
+ ...s3Data,
959
+ ...rdsData,
960
+ ...osData,
961
+ ...cacheData,
962
+ ...mailCreds,
963
+ APP_NAME: appName,
964
+ APP_DOMAIN: appDomain,
965
+ SESSION_DOMAIN: appDomain || undefined,
966
+ },
224
967
  );
225
968
 
226
- if (hasKeyPair) {
227
- OptionSettings.push({
228
- OptionName: "EC2KeyName",
229
- Value: "id_rsa_prev",
230
- Namespace: "aws:autoscaling:launchconfiguration",
969
+ const secretArns = {};
970
+
971
+ for (const group of secretGroups) {
972
+ if (existingSecrets[group]) {
973
+ secretArns[`${group}SecretArn`] = existingSecrets[group];
974
+
975
+ if (Object.keys(payloads[group]).length) {
976
+ const currentValue = await aws.secretsmanager.getSecretValue(
977
+ `${name}-${group}`,
978
+ );
979
+ const newKeys = Object.keys(payloads[group]).filter(
980
+ (k) => !(k in currentValue),
981
+ );
982
+
983
+ if (newKeys.length) {
984
+ const merged = { ...currentValue };
985
+ for (const k of newKeys) {
986
+ merged[k] = payloads[group][k];
987
+ }
988
+ await aws.secretsmanager.updateSecretValue(
989
+ `${name}-${group}`,
990
+ merged,
991
+ );
992
+ }
993
+ }
994
+ } else if (Object.keys(payloads[group]).length) {
995
+ const res = await aws.secretsmanager.createSecret(
996
+ `${name}-${group}`,
997
+ payloads[group],
998
+ tags,
999
+ );
1000
+ secretArns[`${group}SecretArn`] = res.ARN;
1001
+ }
1002
+ }
1003
+
1004
+ const secretSettings = [];
1005
+
1006
+ for (const group of secretGroups) {
1007
+ const arn = secretArns[`${group}SecretArn`];
1008
+ if (!arn) continue;
1009
+
1010
+ let keys;
1011
+
1012
+ if (existingSecrets[group]) {
1013
+ const secretValue = await aws.secretsmanager.getSecretValue(
1014
+ `${name}-${group}`,
1015
+ );
1016
+ keys = Object.keys(secretValue);
1017
+ } else {
1018
+ keys = Object.keys(payloads[group]);
1019
+ }
1020
+
1021
+ for (const key of keys) {
1022
+ secretSettings.push({
1023
+ OptionName: key,
1024
+ Value: `${arn}:${key}`,
1025
+ Namespace:
1026
+ "aws:elasticbeanstalk:application:environmentsecrets",
1027
+ });
1028
+ }
1029
+ }
1030
+
1031
+ // Phase 5: Create or update EB environment
1032
+ let environment;
1033
+
1034
+ if (existingEnvironment) {
1035
+ const SECRETS_NAMESPACE =
1036
+ "aws:elasticbeanstalk:application:environmentsecrets";
1037
+ const currentSettings =
1038
+ await aws.elasticbeanstalk.describeConfigurationSettings(
1039
+ repo,
1040
+ name,
1041
+ );
1042
+ const currentSecrets = currentSettings.filter(
1043
+ (s) => s.Namespace === SECRETS_NAMESPACE,
1044
+ );
1045
+
1046
+ const currentKeys = new Set(currentSecrets.map((s) => s.OptionName));
1047
+ const expectedKeys = new Set(secretSettings.map((s) => s.OptionName));
1048
+
1049
+ const toAdd = secretSettings.filter(
1050
+ (s) => !currentKeys.has(s.OptionName),
1051
+ );
1052
+ const toUpdate = secretSettings.filter((s) => {
1053
+ const current = currentSecrets.find(
1054
+ (c) => c.OptionName === s.OptionName,
1055
+ );
1056
+ return current && current.Value !== s.Value;
231
1057
  });
1058
+ const toRemove = currentSecrets
1059
+ .filter((s) => !expectedKeys.has(s.OptionName))
1060
+ .map((s) => ({
1061
+ OptionName: s.OptionName,
1062
+ Namespace: SECRETS_NAMESPACE,
1063
+ }));
1064
+
1065
+ const optionSettings = [...toAdd, ...toUpdate];
1066
+
1067
+ if (optionSettings.length || toRemove.length) {
1068
+ await aws.elasticbeanstalk.updateEnvironmentSettings(
1069
+ name,
1070
+ optionSettings,
1071
+ toRemove,
1072
+ );
1073
+ }
1074
+
1075
+ environment = existingEnvironment;
1076
+ } else {
1077
+ const OptionSettings = eb.merge(
1078
+ "environments",
1079
+ {
1080
+ framework,
1081
+ platform,
1082
+ language,
1083
+ database,
1084
+ storage,
1085
+ opensearch,
1086
+ vpcId: vpcData.vpcId,
1087
+ privateSubnetIds: vpcData.privateSubnetIds.join(","),
1088
+ publicSubnetIds: vpcData.publicSubnetIds.join(","),
1089
+ elbScheme,
1090
+ instanceProfileName,
1091
+ instanceType,
1092
+ },
1093
+ {
1094
+ ...s3Data,
1095
+ ...rdsData,
1096
+ ...osData,
1097
+ ...cacheData,
1098
+ APP_NAME: appName,
1099
+ APP_DOMAIN: appDomain,
1100
+ SESSION_DOMAIN: appDomain || undefined,
1101
+ },
1102
+ );
1103
+
1104
+ if (certArn) {
1105
+ OptionSettings.push(
1106
+ {
1107
+ OptionName: "ListenerEnabled",
1108
+ Value: "true",
1109
+ Namespace: "aws:elbv2:listener:443",
1110
+ },
1111
+ {
1112
+ OptionName: "Protocol",
1113
+ Value: "HTTPS",
1114
+ Namespace: "aws:elbv2:listener:443",
1115
+ },
1116
+ {
1117
+ OptionName: "SSLCertificateArns",
1118
+ Value: certArn,
1119
+ Namespace: "aws:elbv2:listener:443",
1120
+ },
1121
+ {
1122
+ OptionName: "SSLPolicy",
1123
+ Value: "ELBSecurityPolicy-FS-1-2-Res-2020-10",
1124
+ Namespace: "aws:elbv2:listener:443",
1125
+ },
1126
+ {
1127
+ OptionName: "DefaultProcess",
1128
+ Value: "default",
1129
+ Namespace: "aws:elbv2:listener:443",
1130
+ },
1131
+ );
1132
+ }
1133
+
1134
+ OptionSettings.push(...secretSettings);
1135
+
1136
+ environment =
1137
+ await aws.elasticbeanstalk.createElasticBeanstalkEnvironment(
1138
+ name,
1139
+ { framework, platform, language },
1140
+ repo,
1141
+ OptionSettings,
1142
+ CNAMEPrefix,
1143
+ tags,
1144
+ );
232
1145
  }
233
1146
 
234
- const environment =
235
- await module.exports.elasticbeanstalk.createElasticBeanstalkEnvironment(
1147
+ // Phase 6: SG ingress rules in parallel
1148
+ const rdsSlugForIngress = aws.slug(
1149
+ repo,
1150
+ process.env.AWS_PROFILE,
1151
+ branch,
1152
+ "rds",
1153
+ );
1154
+
1155
+ const ingressPromises = [
1156
+ authorizeIngress(
1157
+ aws,
236
1158
  name,
237
- { framework, availability, platform, language },
238
- repo,
239
- OptionSettings,
240
- CNAMEPrefix,
241
- tags,
1159
+ rdsSlugForIngress,
1160
+ "rds",
1161
+ aws.ec2.authorizeRDSIngress,
1162
+ ),
1163
+ ];
1164
+
1165
+ if (osSlug) {
1166
+ ingressPromises.push(
1167
+ authorizeIngress(
1168
+ aws,
1169
+ name,
1170
+ osSlug,
1171
+ "os",
1172
+ aws.ec2.authorizeOpenSearchIngress,
1173
+ ),
242
1174
  );
1175
+ }
243
1176
 
1177
+ if (cacheSlug) {
1178
+ ingressPromises.push(
1179
+ authorizeIngress(
1180
+ aws,
1181
+ name,
1182
+ cacheSlug,
1183
+ "cache",
1184
+ aws.ec2.authorizeCacheIngress,
1185
+ ),
1186
+ );
1187
+ }
1188
+
1189
+ await Promise.all(ingressPromises);
1190
+
1191
+ // Phase 7: Copy configs and return
244
1192
  const configurations = eb.merge("configurations", {
245
1193
  framework,
246
- availability,
247
1194
  platform,
248
1195
  language,
249
1196
  });
250
1197
 
251
- if (credentials.length) {
252
- configurations.push(
253
- `.platform/${platform}/conf.d/elasticbeanstalk/${platform === "httpd" ? `z-${framework}-` : ""}htpasswd.conf`,
254
- );
255
- fs.outputFileSync(
256
- `.platform/${platform}/conf.d/elasticbeanstalk/.htpasswd-${branch}`,
257
- credentials
258
- .map((d) => `${d.username}:${md5(d.password)}`)
259
- .join("\n"),
1198
+ await aws.elasticbeanstalk.copyElasticBeanstalkConfigs(
1199
+ configurations,
1200
+ branch,
1201
+ );
1202
+
1203
+ let config = {
1204
+ url: `https://${environment.CNAME}`,
1205
+ environment: environment.EnvironmentName,
1206
+ paths: [`_IaC/${branch}/*`],
1207
+ copy: [
1208
+ {
1209
+ src: `_IaC/${branch}/.elasticbeanstalk/config.yml`,
1210
+ dest: `.elasticbeanstalk/config.yml`,
1211
+ },
1212
+ ],
1213
+ };
1214
+
1215
+ return config;
1216
+ };
1217
+
1218
+ module.exports.fullstackClone = async (
1219
+ name,
1220
+ tags,
1221
+ repo,
1222
+ branch,
1223
+ applicationName,
1224
+ sourceEnvironmentName,
1225
+ sourceVersionLabel,
1226
+ sourceBranch,
1227
+ ) => {
1228
+ const aws = module.exports;
1229
+
1230
+ // Phase 1: Read source configuration
1231
+ const sourceSettings =
1232
+ await aws.elasticbeanstalk.describeConfigurationSettings(
1233
+ applicationName,
1234
+ sourceEnvironmentName,
260
1235
  );
1236
+
1237
+ // Phase 2: Filter settings — keep relevant namespaces, exclude immutable/auto-managed
1238
+ const excludedOptions = new Set([
1239
+ "aws:elasticbeanstalk:environment::EnvironmentName",
1240
+ ]);
1241
+
1242
+ const includedNamespaces = new Set([
1243
+ "aws:elasticbeanstalk:application:environment",
1244
+ "aws:elasticbeanstalk:application:environmentsecrets",
1245
+ "aws:autoscaling:launchconfiguration",
1246
+ "aws:autoscaling:asg",
1247
+ "aws:ec2:vpc",
1248
+ "aws:elbv2:listener:443",
1249
+ "aws:elbv2:listener:default",
1250
+ "aws:elasticbeanstalk:environment",
1251
+ "aws:elasticbeanstalk:environment:process:default",
1252
+ "aws:elasticbeanstalk:healthreporting:system",
1253
+ "aws:elasticbeanstalk:managedactions",
1254
+ "aws:elasticbeanstalk:managedactions:platformupdate",
1255
+ "aws:elasticbeanstalk:cloudwatch:logs",
1256
+ "aws:elasticbeanstalk:cloudwatch:logs:health",
1257
+ ]);
1258
+
1259
+ const OptionSettings = sourceSettings
1260
+ .filter((s) => {
1261
+ if (!includedNamespaces.has(s.Namespace)) return false;
1262
+ const key = `${s.Namespace}::${s.OptionName}`;
1263
+ if (excludedOptions.has(key)) return false;
1264
+ // Exclude empty values
1265
+ if (s.Value === undefined || s.Value === null || s.Value === "")
1266
+ return false;
1267
+ return true;
1268
+ })
1269
+ .map((s) => ({
1270
+ Namespace: s.Namespace,
1271
+ OptionName: s.OptionName,
1272
+ Value: s.Value,
1273
+ }));
1274
+
1275
+ // Detect which services exist from source secrets
1276
+ const sourceSecrets = sourceSettings.filter(
1277
+ (s) =>
1278
+ s.Namespace ===
1279
+ "aws:elasticbeanstalk:application:environmentsecrets",
1280
+ );
1281
+
1282
+ const hasOpenSearch = sourceSecrets.some(
1283
+ (s) => s.OptionName === "SEARCH_HOST",
1284
+ );
1285
+
1286
+ // Set SECRET_MIRROR_ENV so setvars.sh reads secrets from the source env
1287
+ OptionSettings.push({
1288
+ Namespace: "aws:elasticbeanstalk:application:environment",
1289
+ OptionName: "SECRET_MIRROR_ENV",
1290
+ Value: sourceEnvironmentName,
1291
+ });
1292
+
1293
+ // Override HealthCheckGracePeriod for initial deploy window
1294
+ const healthGraceIdx = OptionSettings.findIndex(
1295
+ (s) =>
1296
+ s.Namespace ===
1297
+ "aws:elasticbeanstalk:environment:process:default" &&
1298
+ s.OptionName === "HealthCheckGracePeriod",
1299
+ );
1300
+ if (healthGraceIdx !== -1) {
1301
+ OptionSettings[healthGraceIdx].Value = "600";
261
1302
  }
262
1303
 
263
- await module.exports.elasticbeanstalk.copyElasticBeanstalkConfigs(
264
- configurations,
1304
+ // Phase 4: Create the environment
1305
+ const CNAMEPrefix = `fw-auto-${name.split("-")[name.split("-").length - 1]}`;
1306
+
1307
+ const environment =
1308
+ await aws.elasticbeanstalk.createElasticBeanstalkEnvironment(
1309
+ name,
1310
+ { language: detectLanguageFromSettings(sourceSettings) },
1311
+ applicationName,
1312
+ OptionSettings,
1313
+ CNAMEPrefix,
1314
+ tags,
1315
+ sourceVersionLabel,
1316
+ );
1317
+
1318
+ // Phase 5: Authorize SG ingress on source service security groups
1319
+ const rdsSlug = aws.slug(
1320
+ repo,
1321
+ process.env.AWS_PROFILE,
1322
+ sourceBranch,
1323
+ "rds",
1324
+ );
1325
+ const cacheSlug = aws.slug(
1326
+ repo,
1327
+ process.env.AWS_PROFILE,
1328
+ sourceBranch,
1329
+ "cache",
265
1330
  );
266
1331
 
267
- if (credentials.length) {
268
- configurations.push(
269
- `.platform/${platform}/conf.d/elasticbeanstalk/.htpasswd-${branch}`,
1332
+ const ingressPromises = [
1333
+ authorizeIngress(
1334
+ aws,
1335
+ name,
1336
+ rdsSlug,
1337
+ "rds",
1338
+ aws.ec2.authorizeRDSIngress,
1339
+ ),
1340
+ ];
1341
+
1342
+ if (hasOpenSearch) {
1343
+ const sourceOsSlug = aws.slug(
1344
+ repo,
1345
+ process.env.AWS_PROFILE,
1346
+ sourceBranch,
1347
+ "os",
1348
+ );
1349
+ ingressPromises.push(
1350
+ authorizeIngress(
1351
+ aws,
1352
+ name,
1353
+ sourceOsSlug,
1354
+ "os",
1355
+ aws.ec2.authorizeOpenSearchIngress,
1356
+ ),
1357
+ );
1358
+ }
1359
+
1360
+ if (sourceSecrets.some((s) => s.OptionName === "REDIS_HOST")) {
1361
+ ingressPromises.push(
1362
+ authorizeIngress(
1363
+ aws,
1364
+ name,
1365
+ cacheSlug,
1366
+ "cache",
1367
+ aws.ec2.authorizeCacheIngress,
1368
+ ),
270
1369
  );
271
1370
  }
272
1371
 
273
- let config = {
1372
+ await Promise.all(ingressPromises);
1373
+
1374
+ // Phase 6: Copy configs
1375
+ const framework = detectFrameworkFromSettings(sourceSettings);
1376
+ const { platform, language } = eb.configurations[framework];
1377
+ const configurations = eb.merge("configurations", {
1378
+ framework,
1379
+ platform,
1380
+ language,
1381
+ });
1382
+
1383
+ await aws.elasticbeanstalk.copyElasticBeanstalkConfigs(
1384
+ configurations,
1385
+ branch,
1386
+ );
1387
+
1388
+ return {
274
1389
  url: `https://${environment.CNAME}`,
275
1390
  environment: environment.EnvironmentName,
276
- paths: configurations.map((d) => {
277
- const obj = { src: d, dest: d };
278
- // Fix for core mistakenly mapping .htpasswd to directory
279
- if (d.includes(`.htpasswd-${branch}`)) {
280
- obj.file = true;
281
- obj.dest = d.split(`-${branch}`)[0];
282
- }
283
- return obj;
284
- }),
1391
+ paths: [`_IaC/${branch}/*`],
1392
+ copy: [
1393
+ {
1394
+ src: `_IaC/${branch}/.elasticbeanstalk/config.yml`,
1395
+ dest: `.elasticbeanstalk/config.yml`,
1396
+ },
1397
+ ],
285
1398
  };
1399
+ };
286
1400
 
287
- return config;
1401
+ const detectLanguageFromSettings = (settings) => {
1402
+ const envVars = settings.filter(
1403
+ (s) =>
1404
+ s.Namespace === "aws:elasticbeanstalk:application:environment" ||
1405
+ s.Namespace ===
1406
+ "aws:elasticbeanstalk:application:environmentsecrets",
1407
+ );
1408
+ const keys = envVars.map((s) => s.OptionName);
1409
+ if (keys.includes("DJANGO_SETTINGS_MODULE")) return "python";
1410
+ if (keys.includes("NODE_ENV")) return "node";
1411
+ return "php";
288
1412
  };
289
1413
 
290
- module.exports.fullstackTerminate = async (name, repo, branch) => {
291
- const s3Slug = module.exports.slug(
1414
+ const detectFrameworkFromSettings = (settings) => {
1415
+ const envVars = settings.filter(
1416
+ (s) =>
1417
+ s.Namespace === "aws:elasticbeanstalk:application:environment" ||
1418
+ s.Namespace ===
1419
+ "aws:elasticbeanstalk:application:environmentsecrets",
1420
+ );
1421
+ const keys = envVars.map((s) => s.OptionName);
1422
+ if (keys.includes("DJANGO_SETTINGS_MODULE")) return "python";
1423
+ if (keys.includes("ADONIS_ACE_CWD")) return "adonis";
1424
+ if (keys.includes("APP_KEY")) return "laravel";
1425
+ return "laravel";
1426
+ };
1427
+
1428
+ module.exports.fullstackCloneTerminate = async (
1429
+ name,
1430
+ repo,
1431
+ branch,
1432
+ sourceBranch,
1433
+ ) => {
1434
+ const aws = module.exports;
1435
+
1436
+ const rdsSlug = aws.slug(
292
1437
  repo,
293
1438
  process.env.AWS_PROFILE,
294
- branch,
295
- "s3",
1439
+ sourceBranch,
1440
+ "rds",
296
1441
  );
1442
+ const osSlug = aws.slug(repo, process.env.AWS_PROFILE, sourceBranch, "os");
1443
+ const cacheSlug = aws.slug(
1444
+ repo,
1445
+ process.env.AWS_PROFILE,
1446
+ sourceBranch,
1447
+ "cache",
1448
+ );
1449
+
1450
+ // Phase 1: Revoke SG ingress rules
1451
+ await Promise.all([
1452
+ authorizeIngress(aws, name, rdsSlug, "rds", aws.ec2.revokeRDSIngress),
1453
+ authorizeIngress(
1454
+ aws,
1455
+ name,
1456
+ osSlug,
1457
+ "os",
1458
+ aws.ec2.revokeOpenSearchIngress,
1459
+ ),
1460
+ authorizeIngress(
1461
+ aws,
1462
+ name,
1463
+ cacheSlug,
1464
+ "cache",
1465
+ aws.ec2.revokeCacheIngress,
1466
+ ),
1467
+ ]);
297
1468
 
1469
+ // Phase 2: Terminate EB environment
298
1470
  try {
299
- await module.exports.iam.removeIAMUser(s3Slug);
1471
+ await aws.elasticbeanstalk.removeElasticBeanstalkEnvironment(name);
300
1472
  } catch {
301
1473
  /* empty */
302
1474
  }
303
1475
 
304
- try {
305
- await module.exports.s3.emptyS3Bucket(s3Slug);
306
- } catch {
307
- /* empty */
1476
+ // Phase 3: Terminate EB environment + try removing app if empty
1477
+ await Promise.all([
1478
+ (async () => {
1479
+ try {
1480
+ const envs = await aws.elasticbeanstalk.listEnvironments(repo);
1481
+ if (!envs.length) {
1482
+ await aws.elasticbeanstalk.removeElasticBeanstalkApplication(
1483
+ repo,
1484
+ );
1485
+ }
1486
+ } catch {
1487
+ /* empty */
1488
+ }
1489
+ })(),
1490
+ ]);
1491
+ };
1492
+
1493
+ module.exports.fullstackTerminate = async (
1494
+ name,
1495
+ repo,
1496
+ branch,
1497
+ {
1498
+ deleteStorage = false,
1499
+ deleteDatabase = false,
1500
+ deleteOpenSearch = false,
1501
+ deleteCache = false,
1502
+ deleteMail = false,
1503
+ deleteAppSecret = false,
1504
+ } = {},
1505
+ ) => {
1506
+ const aws = module.exports;
1507
+
1508
+ const rdsSlug = aws.slug(repo, process.env.AWS_PROFILE, branch, "rds");
1509
+ const osSlug = aws.slug(repo, process.env.AWS_PROFILE, branch, "os");
1510
+ const cacheSlug = aws.slug(repo, process.env.AWS_PROFILE, branch, "cache");
1511
+
1512
+ // Phase 1: Storage cleanup + revoke all SG ingress rules in parallel
1513
+ const phase1 = [];
1514
+
1515
+ if (deleteStorage) {
1516
+ const s3Slug = aws.slug(repo, process.env.AWS_PROFILE, branch, "s3");
1517
+
1518
+ phase1.push(
1519
+ (async () => {
1520
+ try {
1521
+ await aws.iam.removeIAMUser(s3Slug);
1522
+ } catch {
1523
+ /* empty */
1524
+ }
1525
+ try {
1526
+ await aws.s3.emptyS3Bucket(s3Slug);
1527
+ } catch {
1528
+ /* empty */
1529
+ }
1530
+ try {
1531
+ await aws.s3.removeS3Bucket(s3Slug);
1532
+ } catch {
1533
+ /* empty */
1534
+ }
1535
+ })(),
1536
+ );
308
1537
  }
309
1538
 
1539
+ phase1.push(
1540
+ authorizeIngress(aws, name, rdsSlug, "rds", aws.ec2.revokeRDSIngress),
1541
+ authorizeIngress(
1542
+ aws,
1543
+ name,
1544
+ osSlug,
1545
+ "os",
1546
+ aws.ec2.revokeOpenSearchIngress,
1547
+ ),
1548
+ authorizeIngress(
1549
+ aws,
1550
+ name,
1551
+ cacheSlug,
1552
+ "cache",
1553
+ aws.ec2.revokeCacheIngress,
1554
+ ),
1555
+ );
1556
+
1557
+ await Promise.all(phase1);
1558
+
1559
+ // Phase 2: Terminate EB environment (must complete before SG deletion)
310
1560
  try {
311
- await module.exports.s3.removeS3Bucket(s3Slug);
1561
+ await aws.elasticbeanstalk.removeElasticBeanstalkEnvironment(name);
312
1562
  } catch {
313
1563
  /* empty */
314
1564
  }
315
1565
 
316
- try {
317
- await module.exports.elasticbeanstalk.removeElasticBeanstalkEnvironment(
318
- name,
1566
+ // Phase 3: EB app + instance profile + initiate service deletions in parallel
1567
+ const phase3 = [
1568
+ (async () => {
1569
+ try {
1570
+ await aws.elasticbeanstalk.removeElasticBeanstalkApplication(
1571
+ repo,
1572
+ );
1573
+ } catch {
1574
+ /* empty */
1575
+ }
1576
+ })(),
1577
+ (async () => {
1578
+ try {
1579
+ await aws.iam.removeEnvironmentInstanceProfile(name);
1580
+ } catch {
1581
+ /* empty */
1582
+ }
1583
+ })(),
1584
+ ];
1585
+
1586
+ if (deleteDatabase) {
1587
+ phase3.push(aws.rds.deleteRDSInstance(rdsSlug).catch(() => {}));
1588
+ }
1589
+
1590
+ if (deleteOpenSearch) {
1591
+ phase3.push(
1592
+ aws.opensearch.deleteOpenSearchDomain(osSlug).catch(() => {}),
319
1593
  );
320
- } catch {
321
- /* empty */
322
1594
  }
323
1595
 
324
- try {
325
- await module.exports.elasticbeanstalk.removeElasticBeanstalkApplication(
326
- repo,
1596
+ if (deleteCache) {
1597
+ phase3.push(
1598
+ aws.elasticache.deleteCacheCluster(cacheSlug).catch(() => {}),
1599
+ );
1600
+ }
1601
+
1602
+ await Promise.all(phase3);
1603
+
1604
+ // Phase 4: Wait for service deletions with round-robin polling
1605
+ const deletionPolls = [];
1606
+
1607
+ if (deleteDatabase) {
1608
+ const rdsClient = new RDSClient({});
1609
+
1610
+ deletionPolls.push({
1611
+ name: "RDS",
1612
+ cb: async () => {
1613
+ try {
1614
+ const res = await rdsClient.send(
1615
+ new DescribeDBInstancesCommand({
1616
+ DBInstanceIdentifier: rdsSlug,
1617
+ }),
1618
+ );
1619
+ return res.DBInstances[0];
1620
+ } catch (e) {
1621
+ if (
1622
+ e.name === "DBInstanceNotFoundFault" ||
1623
+ e.name === "InvalidParameterValue"
1624
+ ) {
1625
+ return { DBInstanceStatus: "deleted" };
1626
+ }
1627
+ throw e;
1628
+ }
1629
+ },
1630
+ shouldContinue: ({ DBInstanceStatus }) =>
1631
+ DBInstanceStatus !== "deleted",
1632
+ });
1633
+ }
1634
+
1635
+ if (deleteOpenSearch) {
1636
+ const osClient = new OpenSearchClient({});
1637
+
1638
+ deletionPolls.push({
1639
+ name: "OpenSearch",
1640
+ cb: async () => {
1641
+ try {
1642
+ const { DomainStatus } = await osClient.send(
1643
+ new DescribeDomainCommand({ DomainName: osSlug }),
1644
+ );
1645
+ return DomainStatus;
1646
+ } catch (e) {
1647
+ if (
1648
+ e.name === "ResourceNotFoundException" ||
1649
+ e.name === "ValidationException"
1650
+ ) {
1651
+ return { deleted: true };
1652
+ }
1653
+ throw e;
1654
+ }
1655
+ },
1656
+ shouldContinue: (status) => !status.deleted,
1657
+ });
1658
+ }
1659
+
1660
+ if (deleteCache) {
1661
+ const cacheClient = new ElastiCacheClient({});
1662
+
1663
+ deletionPolls.push({
1664
+ name: "ElastiCache",
1665
+ cb: async () => {
1666
+ try {
1667
+ const { ReplicationGroups } = await cacheClient.send(
1668
+ new DescribeReplicationGroupsCommand({
1669
+ ReplicationGroupId: cacheSlug,
1670
+ }),
1671
+ );
1672
+ return ReplicationGroups[0];
1673
+ } catch (e) {
1674
+ if (
1675
+ e.name === "ReplicationGroupNotFoundFault" ||
1676
+ e.name === "InvalidParameterValue"
1677
+ ) {
1678
+ return { deleted: true };
1679
+ }
1680
+ throw e;
1681
+ }
1682
+ },
1683
+ shouldContinue: (group) => !group.deleted,
1684
+ });
1685
+ }
1686
+
1687
+ if (deletionPolls.length) {
1688
+ await pollAll(deletionPolls, "Waiting for services to terminate");
1689
+ }
1690
+
1691
+ // Phase 5: Delete security groups after services are gone
1692
+ const sgDeletions = [];
1693
+
1694
+ if (deleteDatabase) {
1695
+ sgDeletions.push(
1696
+ (async () => {
1697
+ try {
1698
+ const sg = await aws.ec2.findSecurityGroupByName(
1699
+ `${rdsSlug}-rds`,
1700
+ );
1701
+ if (sg) {
1702
+ await aws.ec2.deleteSecurityGroup(sg.GroupId);
1703
+ }
1704
+ } catch {
1705
+ /* empty */
1706
+ }
1707
+ })(),
1708
+ );
1709
+ }
1710
+
1711
+ if (deleteOpenSearch) {
1712
+ sgDeletions.push(
1713
+ (async () => {
1714
+ try {
1715
+ const sg = await aws.ec2.findSecurityGroupByName(
1716
+ `${osSlug}-os`,
1717
+ );
1718
+ if (sg) {
1719
+ await aws.ec2.deleteSecurityGroup(sg.GroupId);
1720
+ }
1721
+ } catch {
1722
+ /* empty */
1723
+ }
1724
+ })(),
1725
+ );
1726
+ }
1727
+
1728
+ if (deleteCache) {
1729
+ sgDeletions.push(
1730
+ (async () => {
1731
+ try {
1732
+ const sg = await aws.ec2.findSecurityGroupByName(
1733
+ `${cacheSlug}-cache`,
1734
+ );
1735
+ if (sg) {
1736
+ await aws.ec2.deleteSecurityGroup(sg.GroupId);
1737
+ }
1738
+ } catch {
1739
+ /* empty */
1740
+ }
1741
+ })(),
1742
+ );
1743
+ }
1744
+
1745
+ if (sgDeletions.length) {
1746
+ await Promise.all(sgDeletions);
1747
+ }
1748
+
1749
+ // Phase 6: Delete secrets in parallel
1750
+ const secretDeletions = [];
1751
+
1752
+ if (deleteStorage) {
1753
+ secretDeletions.push(
1754
+ aws.secretsmanager.deleteSecret(`${name}-storage`).catch(() => {}),
1755
+ );
1756
+ }
1757
+ if (deleteDatabase) {
1758
+ secretDeletions.push(
1759
+ aws.secretsmanager.deleteSecret(`${name}-database`).catch(() => {}),
327
1760
  );
328
- } catch {
329
- /* empty */
330
1761
  }
1762
+ if (deleteOpenSearch) {
1763
+ secretDeletions.push(
1764
+ aws.secretsmanager
1765
+ .deleteSecret(`${name}-opensearch`)
1766
+ .catch(() => {}),
1767
+ );
1768
+ }
1769
+ if (deleteCache) {
1770
+ secretDeletions.push(
1771
+ aws.secretsmanager.deleteSecret(`${name}-cache`).catch(() => {}),
1772
+ );
1773
+ }
1774
+ if (deleteAppSecret) {
1775
+ secretDeletions.push(
1776
+ aws.secretsmanager.deleteSecret(`${name}-app`).catch(() => {}),
1777
+ );
1778
+ }
1779
+ if (deleteMail) {
1780
+ secretDeletions.push(
1781
+ aws.secretsmanager.deleteSecret(`${name}-mail`).catch(() => {}),
1782
+ );
1783
+ secretDeletions.push(
1784
+ (async () => {
1785
+ const {
1786
+ IAMClient,
1787
+ DeleteAccessKeyCommand,
1788
+ ListAccessKeysCommand,
1789
+ RemoveUserFromGroupCommand,
1790
+ DeleteUserCommand,
1791
+ } = require("@aws-sdk/client-iam");
1792
+ const { fromIni } = require("@aws-sdk/credential-providers");
1793
+
1794
+ const iamClient = new IAMClient({
1795
+ region: "us-east-1",
1796
+ credentials: fromIni({ profile: "fishawack" }),
1797
+ });
1798
+ const userName = `${name}-ses`;
1799
+
1800
+ try {
1801
+ const keys = await iamClient.send(
1802
+ new ListAccessKeysCommand({ UserName: userName }),
1803
+ );
1804
+ for (const key of keys.AccessKeyMetadata || []) {
1805
+ await iamClient.send(
1806
+ new DeleteAccessKeyCommand({
1807
+ UserName: userName,
1808
+ AccessKeyId: key.AccessKeyId,
1809
+ }),
1810
+ );
1811
+ }
1812
+ await iamClient.send(
1813
+ new RemoveUserFromGroupCommand({
1814
+ UserName: userName,
1815
+ GroupName: "AWSSESSendingGroupDoNotRename",
1816
+ }),
1817
+ );
1818
+ await iamClient.send(
1819
+ new DeleteUserCommand({ UserName: userName }),
1820
+ );
1821
+ } catch {
1822
+ /* user may not exist */
1823
+ }
1824
+ })(),
1825
+ );
1826
+ }
1827
+
1828
+ await Promise.all(secretDeletions);
331
1829
  };