@friggframework/devtools 2.0.0-next.11 → 2.0.0-next.110

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 (247) hide show
  1. package/frigg-cli/README.md +1289 -0
  2. package/frigg-cli/__tests__/unit/commands/build.test.js +279 -0
  3. package/frigg-cli/__tests__/unit/commands/db-setup.test.js +649 -0
  4. package/frigg-cli/__tests__/unit/commands/deploy.test.js +320 -0
  5. package/frigg-cli/__tests__/unit/commands/doctor.test.js +309 -0
  6. package/frigg-cli/__tests__/unit/commands/generate-iam.test.js +97 -0
  7. package/frigg-cli/__tests__/unit/commands/install.test.js +400 -0
  8. package/frigg-cli/__tests__/unit/commands/ui.test.js +346 -0
  9. package/frigg-cli/__tests__/unit/dependencies.test.js +74 -0
  10. package/frigg-cli/__tests__/unit/utils/database-validator.test.js +397 -0
  11. package/frigg-cli/__tests__/unit/utils/error-messages.test.js +345 -0
  12. package/frigg-cli/__tests__/unit/version-detection.test.js +171 -0
  13. package/frigg-cli/__tests__/utils/mock-factory.js +270 -0
  14. package/frigg-cli/__tests__/utils/prisma-mock.js +194 -0
  15. package/frigg-cli/__tests__/utils/test-fixtures.js +463 -0
  16. package/frigg-cli/__tests__/utils/test-setup.js +287 -0
  17. package/frigg-cli/auth-command/CLAUDE.md +293 -0
  18. package/frigg-cli/auth-command/README.md +450 -0
  19. package/frigg-cli/auth-command/api-key-flow.js +153 -0
  20. package/frigg-cli/auth-command/auth-tester.js +344 -0
  21. package/frigg-cli/auth-command/credential-storage.js +182 -0
  22. package/frigg-cli/auth-command/index.js +256 -0
  23. package/frigg-cli/auth-command/json-schema-form.js +67 -0
  24. package/frigg-cli/auth-command/module-loader.js +172 -0
  25. package/frigg-cli/auth-command/oauth-callback-server.js +431 -0
  26. package/frigg-cli/auth-command/oauth-flow.js +195 -0
  27. package/frigg-cli/auth-command/utils/browser.js +30 -0
  28. package/frigg-cli/build-command/index.js +45 -12
  29. package/frigg-cli/db-setup-command/index.js +246 -0
  30. package/frigg-cli/deploy-command/SPEC-DEPLOY-DRY-RUN.md +981 -0
  31. package/frigg-cli/deploy-command/index.js +339 -23
  32. package/frigg-cli/doctor-command/index.js +335 -0
  33. package/frigg-cli/generate-command/__tests__/generate-command.test.js +301 -0
  34. package/frigg-cli/generate-command/azure-generator.js +43 -0
  35. package/frigg-cli/generate-command/gcp-generator.js +47 -0
  36. package/frigg-cli/generate-command/index.js +333 -0
  37. package/frigg-cli/generate-command/terraform-generator.js +555 -0
  38. package/frigg-cli/generate-iam-command.js +119 -0
  39. package/frigg-cli/index.js +189 -1
  40. package/frigg-cli/index.test.js +1 -4
  41. package/frigg-cli/init-command/backend-first-handler.js +756 -0
  42. package/frigg-cli/init-command/index.js +93 -0
  43. package/frigg-cli/init-command/template-handler.js +143 -0
  44. package/frigg-cli/install-command/index.js +1 -4
  45. package/frigg-cli/jest.config.js +124 -0
  46. package/frigg-cli/package.json +63 -0
  47. package/frigg-cli/repair-command/index.js +564 -0
  48. package/frigg-cli/ssm-command/index.js +308 -0
  49. package/frigg-cli/ssm-command/index.test.js +318 -0
  50. package/frigg-cli/start-command/index.js +118 -5
  51. package/frigg-cli/start-command/start-command.test.js +297 -0
  52. package/frigg-cli/test/init-command.test.js +180 -0
  53. package/frigg-cli/test/npm-registry.test.js +319 -0
  54. package/frigg-cli/ui-command/index.js +154 -0
  55. package/frigg-cli/utils/app-resolver.js +319 -0
  56. package/frigg-cli/utils/backend-path.js +16 -17
  57. package/frigg-cli/utils/database-validator.js +167 -0
  58. package/frigg-cli/utils/error-messages.js +329 -0
  59. package/frigg-cli/utils/npm-registry.js +167 -0
  60. package/frigg-cli/utils/process-manager.js +199 -0
  61. package/frigg-cli/utils/repo-detection.js +405 -0
  62. package/infrastructure/ARCHITECTURE.md +487 -0
  63. package/infrastructure/CLAUDE.md +481 -0
  64. package/infrastructure/HEALTH.md +468 -0
  65. package/infrastructure/README.md +540 -0
  66. package/infrastructure/__tests__/fixtures/mock-aws-resources.js +391 -0
  67. package/infrastructure/__tests__/helpers/test-utils.js +275 -0
  68. package/infrastructure/__tests__/postgres-config.test.js +914 -0
  69. package/infrastructure/__tests__/scoped-environment.test.js +126 -0
  70. package/infrastructure/__tests__/ssm-preload-node-options.test.js +79 -0
  71. package/infrastructure/__tests__/template-generation.test.js +687 -0
  72. package/infrastructure/create-frigg-infrastructure.js +129 -20
  73. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +630 -0
  74. package/infrastructure/docs/PRE-DEPLOYMENT-HEALTH-CHECK-SPEC.md +1317 -0
  75. package/infrastructure/docs/WEBSOCKET-CONFIGURATION.md +105 -0
  76. package/infrastructure/docs/deployment-instructions.md +268 -0
  77. package/infrastructure/docs/generate-iam-command.md +278 -0
  78. package/infrastructure/docs/iam-policy-templates.md +193 -0
  79. package/infrastructure/domains/admin-scripts/admin-script-builder.js +567 -0
  80. package/infrastructure/domains/admin-scripts/admin-script-builder.test.js +1017 -0
  81. package/infrastructure/domains/admin-scripts/index.js +5 -0
  82. package/infrastructure/domains/database/aurora-builder.js +857 -0
  83. package/infrastructure/domains/database/aurora-builder.test.js +960 -0
  84. package/infrastructure/domains/database/aurora-discovery.js +87 -0
  85. package/infrastructure/domains/database/aurora-discovery.test.js +188 -0
  86. package/infrastructure/domains/database/aurora-resolver.js +210 -0
  87. package/infrastructure/domains/database/aurora-resolver.test.js +347 -0
  88. package/infrastructure/domains/database/migration-builder.js +757 -0
  89. package/infrastructure/domains/database/migration-builder.test.js +454 -0
  90. package/infrastructure/domains/database/migration-resolver.js +163 -0
  91. package/infrastructure/domains/database/migration-resolver.test.js +337 -0
  92. package/infrastructure/domains/health/application/ports/IPropertyReconciler.js +164 -0
  93. package/infrastructure/domains/health/application/ports/IResourceDetector.js +129 -0
  94. package/infrastructure/domains/health/application/ports/IResourceImporter.js +142 -0
  95. package/infrastructure/domains/health/application/ports/IStackRepository.js +131 -0
  96. package/infrastructure/domains/health/application/ports/index.js +26 -0
  97. package/infrastructure/domains/health/application/use-cases/__tests__/execute-resource-import-use-case.test.js +679 -0
  98. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +167 -0
  99. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +1130 -0
  100. package/infrastructure/domains/health/application/use-cases/execute-resource-import-use-case.js +221 -0
  101. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.js +152 -0
  102. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.test.js +343 -0
  103. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.js +535 -0
  104. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.test.js +376 -0
  105. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.js +213 -0
  106. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +441 -0
  107. package/infrastructure/domains/health/docs/ACME-DEV-DRIFT-ANALYSIS.md +267 -0
  108. package/infrastructure/domains/health/docs/BUILD-VS-DEPLOYED-TEMPLATE-ANALYSIS.md +324 -0
  109. package/infrastructure/domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md +386 -0
  110. package/infrastructure/domains/health/docs/SPEC-CLEANUP-COMMAND.md +1419 -0
  111. package/infrastructure/domains/health/docs/TDD-IMPLEMENTATION-SUMMARY.md +391 -0
  112. package/infrastructure/domains/health/docs/TEMPLATE-COMPARISON-IMPLEMENTATION.md +551 -0
  113. package/infrastructure/domains/health/domain/entities/issue.js +299 -0
  114. package/infrastructure/domains/health/domain/entities/issue.test.js +528 -0
  115. package/infrastructure/domains/health/domain/entities/property-mismatch.js +108 -0
  116. package/infrastructure/domains/health/domain/entities/property-mismatch.test.js +275 -0
  117. package/infrastructure/domains/health/domain/entities/resource.js +159 -0
  118. package/infrastructure/domains/health/domain/entities/resource.test.js +432 -0
  119. package/infrastructure/domains/health/domain/entities/stack-health-report.js +306 -0
  120. package/infrastructure/domains/health/domain/entities/stack-health-report.test.js +601 -0
  121. package/infrastructure/domains/health/domain/services/__tests__/health-score-percentage-based.test.js +380 -0
  122. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +971 -0
  123. package/infrastructure/domains/health/domain/services/__tests__/import-template-generator.test.js +1150 -0
  124. package/infrastructure/domains/health/domain/services/__tests__/logical-id-mapper.test.js +672 -0
  125. package/infrastructure/domains/health/domain/services/__tests__/template-parser.test.js +496 -0
  126. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +419 -0
  127. package/infrastructure/domains/health/domain/services/health-score-calculator.js +248 -0
  128. package/infrastructure/domains/health/domain/services/health-score-calculator.test.js +504 -0
  129. package/infrastructure/domains/health/domain/services/import-progress-monitor.js +195 -0
  130. package/infrastructure/domains/health/domain/services/import-template-generator.js +435 -0
  131. package/infrastructure/domains/health/domain/services/logical-id-mapper.js +345 -0
  132. package/infrastructure/domains/health/domain/services/mismatch-analyzer.js +234 -0
  133. package/infrastructure/domains/health/domain/services/mismatch-analyzer.test.js +431 -0
  134. package/infrastructure/domains/health/domain/services/property-mutability-config.js +382 -0
  135. package/infrastructure/domains/health/domain/services/template-parser.js +245 -0
  136. package/infrastructure/domains/health/domain/services/update-progress-monitor.js +192 -0
  137. package/infrastructure/domains/health/domain/value-objects/health-score.js +138 -0
  138. package/infrastructure/domains/health/domain/value-objects/health-score.test.js +267 -0
  139. package/infrastructure/domains/health/domain/value-objects/property-mutability.js +161 -0
  140. package/infrastructure/domains/health/domain/value-objects/property-mutability.test.js +198 -0
  141. package/infrastructure/domains/health/domain/value-objects/resource-state.js +167 -0
  142. package/infrastructure/domains/health/domain/value-objects/resource-state.test.js +196 -0
  143. package/infrastructure/domains/health/domain/value-objects/stack-identifier.js +192 -0
  144. package/infrastructure/domains/health/domain/value-objects/stack-identifier.test.js +262 -0
  145. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-cfn-tagged.test.js +312 -0
  146. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-multi-stack.test.js +367 -0
  147. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +432 -0
  148. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.js +784 -0
  149. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +1133 -0
  150. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.js +565 -0
  151. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +554 -0
  152. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.js +318 -0
  153. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.test.js +398 -0
  154. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.js +777 -0
  155. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.test.js +580 -0
  156. package/infrastructure/domains/integration/integration-builder.js +656 -0
  157. package/infrastructure/domains/integration/integration-builder.test.js +1064 -0
  158. package/infrastructure/domains/integration/integration-resolver.js +170 -0
  159. package/infrastructure/domains/integration/integration-resolver.test.js +369 -0
  160. package/infrastructure/domains/integration/websocket-builder.js +69 -0
  161. package/infrastructure/domains/integration/websocket-builder.test.js +195 -0
  162. package/infrastructure/domains/networking/vpc-builder.js +2101 -0
  163. package/infrastructure/domains/networking/vpc-builder.test.js +2001 -0
  164. package/infrastructure/domains/networking/vpc-discovery.js +184 -0
  165. package/infrastructure/domains/networking/vpc-discovery.test.js +368 -0
  166. package/infrastructure/domains/networking/vpc-resolver.js +514 -0
  167. package/infrastructure/domains/networking/vpc-resolver.test.js +841 -0
  168. package/infrastructure/domains/parameters/offload-utils.js +190 -0
  169. package/infrastructure/domains/parameters/offload-utils.test.js +193 -0
  170. package/infrastructure/domains/parameters/ssm-builder.js +132 -0
  171. package/infrastructure/domains/parameters/ssm-builder.test.js +346 -0
  172. package/infrastructure/domains/parameters/ssm-discovery.js +84 -0
  173. package/infrastructure/domains/parameters/ssm-discovery.test.js +210 -0
  174. package/infrastructure/domains/scheduler/scheduler-builder.js +247 -0
  175. package/infrastructure/domains/scheduler/scheduler-builder.test.js +118 -0
  176. package/infrastructure/domains/security/iam-generator.js +851 -0
  177. package/infrastructure/domains/security/iam-generator.test.js +287 -0
  178. package/infrastructure/domains/security/kms-builder.js +415 -0
  179. package/infrastructure/domains/security/kms-builder.test.js +392 -0
  180. package/infrastructure/domains/security/kms-discovery.js +80 -0
  181. package/infrastructure/domains/security/kms-discovery.test.js +177 -0
  182. package/infrastructure/domains/security/kms-resolver.js +96 -0
  183. package/infrastructure/domains/security/kms-resolver.test.js +216 -0
  184. package/infrastructure/domains/security/templates/frigg-deployment-iam-stack.yaml +418 -0
  185. package/infrastructure/domains/security/templates/iam-policy-basic.json +218 -0
  186. package/infrastructure/domains/security/templates/iam-policy-full.json +293 -0
  187. package/infrastructure/domains/shared/base-builder.js +112 -0
  188. package/infrastructure/domains/shared/base-resolver.js +186 -0
  189. package/infrastructure/domains/shared/base-resolver.test.js +305 -0
  190. package/infrastructure/domains/shared/builder-orchestrator.js +226 -0
  191. package/infrastructure/domains/shared/builder-orchestrator.test.js +258 -0
  192. package/infrastructure/domains/shared/cloudformation-discovery-v2.js +334 -0
  193. package/infrastructure/domains/shared/cloudformation-discovery.js +681 -0
  194. package/infrastructure/domains/shared/cloudformation-discovery.test.js +1320 -0
  195. package/infrastructure/domains/shared/environment-builder.js +192 -0
  196. package/infrastructure/domains/shared/environment-builder.test.js +529 -0
  197. package/infrastructure/domains/shared/function-environments.js +97 -0
  198. package/infrastructure/domains/shared/function-environments.test.js +146 -0
  199. package/infrastructure/domains/shared/providers/aws-provider-adapter.js +579 -0
  200. package/infrastructure/domains/shared/providers/aws-provider-adapter.test.js +416 -0
  201. package/infrastructure/domains/shared/providers/azure-provider-adapter.stub.js +93 -0
  202. package/infrastructure/domains/shared/providers/cloud-provider-adapter.js +136 -0
  203. package/infrastructure/domains/shared/providers/gcp-provider-adapter.stub.js +82 -0
  204. package/infrastructure/domains/shared/providers/provider-factory.js +108 -0
  205. package/infrastructure/domains/shared/providers/provider-factory.test.js +170 -0
  206. package/infrastructure/domains/shared/resource-discovery.enhanced.test.js +306 -0
  207. package/infrastructure/domains/shared/resource-discovery.js +256 -0
  208. package/infrastructure/domains/shared/resource-discovery.test.js +757 -0
  209. package/infrastructure/domains/shared/types/app-definition.js +225 -0
  210. package/infrastructure/domains/shared/types/discovery-result.js +106 -0
  211. package/infrastructure/domains/shared/types/discovery-result.test.js +258 -0
  212. package/infrastructure/domains/shared/types/index.js +46 -0
  213. package/infrastructure/domains/shared/types/resource-ownership.js +108 -0
  214. package/infrastructure/domains/shared/types/resource-ownership.test.js +101 -0
  215. package/infrastructure/domains/shared/utilities/base-definition-factory.js +409 -0
  216. package/infrastructure/domains/shared/utilities/base-definition-factory.js.bak +338 -0
  217. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +319 -0
  218. package/infrastructure/domains/shared/utilities/handler-path-resolver.js +134 -0
  219. package/infrastructure/domains/shared/utilities/handler-path-resolver.test.js +268 -0
  220. package/infrastructure/domains/shared/utilities/nested-node-modules.js +53 -0
  221. package/infrastructure/domains/shared/utilities/nested-node-modules.test.js +61 -0
  222. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +159 -0
  223. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +444 -0
  224. package/infrastructure/domains/shared/validation/env-validator.js +78 -0
  225. package/infrastructure/domains/shared/validation/env-validator.test.js +173 -0
  226. package/infrastructure/domains/shared/validation/plugin-validator.js +187 -0
  227. package/infrastructure/domains/shared/validation/plugin-validator.test.js +323 -0
  228. package/infrastructure/esbuild.config.js +53 -0
  229. package/infrastructure/infrastructure-composer.js +168 -0
  230. package/infrastructure/infrastructure-composer.test.js +2042 -0
  231. package/infrastructure/integration.test.js +381 -0
  232. package/infrastructure/scripts/build-prisma-layer.js +701 -0
  233. package/infrastructure/scripts/build-prisma-layer.test.js +170 -0
  234. package/infrastructure/scripts/build-time-discovery.js +238 -0
  235. package/infrastructure/scripts/build-time-discovery.test.js +379 -0
  236. package/infrastructure/scripts/run-discovery.js +110 -0
  237. package/infrastructure/scripts/verify-prisma-layer.js +72 -0
  238. package/management-ui/README.md +203 -0
  239. package/package.json +48 -16
  240. package/test/index.js +2 -4
  241. package/test/mock-api.js +1 -3
  242. package/test/mock-integration.js +4 -14
  243. package/.eslintrc.json +0 -3
  244. package/CHANGELOG.md +0 -132
  245. package/infrastructure/serverless-template.js +0 -283
  246. package/infrastructure/webpack.config.js +0 -20
  247. package/test/auther-definition-tester.js +0 -125
@@ -0,0 +1,2001 @@
1
+ /**
2
+ * Tests for VPC Builder
3
+ *
4
+ * Tests VPC infrastructure building with various management modes
5
+ */
6
+
7
+ const { VpcBuilder } = require('./vpc-builder');
8
+ const { ValidationResult } = require('../shared/base-builder');
9
+
10
+ describe('VpcBuilder', () => {
11
+ let vpcBuilder;
12
+
13
+ beforeEach(() => {
14
+ vpcBuilder = new VpcBuilder();
15
+ delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
16
+ });
17
+
18
+ afterEach(() => {
19
+ delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
20
+ });
21
+
22
+ describe('shouldExecute()', () => {
23
+ it('should return true when VPC is enabled', () => {
24
+ const appDefinition = {
25
+ vpc: { enable: true },
26
+ };
27
+
28
+ expect(vpcBuilder.shouldExecute(appDefinition)).toBe(true);
29
+ });
30
+
31
+ it('should return false when VPC is disabled', () => {
32
+ const appDefinition = {
33
+ vpc: { enable: false },
34
+ };
35
+
36
+ expect(vpcBuilder.shouldExecute(appDefinition)).toBe(false);
37
+ });
38
+
39
+ it('should return false when VPC is not defined', () => {
40
+ const appDefinition = {};
41
+
42
+ expect(vpcBuilder.shouldExecute(appDefinition)).toBe(false);
43
+ });
44
+
45
+ it('should return false when FRIGG_SKIP_AWS_DISCOVERY is set (local mode)', () => {
46
+ process.env.FRIGG_SKIP_AWS_DISCOVERY = 'true';
47
+ const appDefinition = {
48
+ vpc: { enable: true },
49
+ };
50
+
51
+ expect(vpcBuilder.shouldExecute(appDefinition)).toBe(false);
52
+ });
53
+ });
54
+
55
+ describe('validate()', () => {
56
+ it('should pass validation for valid discover mode config', () => {
57
+ const appDefinition = {
58
+ vpc: {
59
+ enable: true,
60
+ management: 'discover',
61
+ },
62
+ };
63
+
64
+ const result = vpcBuilder.validate(appDefinition);
65
+
66
+ expect(result).toBeInstanceOf(ValidationResult);
67
+ expect(result.valid).toBe(true);
68
+ expect(result.errors).toEqual([]);
69
+ });
70
+
71
+ it('should pass validation for valid create-new mode config', () => {
72
+ const appDefinition = {
73
+ vpc: {
74
+ enable: true,
75
+ management: 'create-new',
76
+ },
77
+ };
78
+
79
+ const result = vpcBuilder.validate(appDefinition);
80
+
81
+ expect(result.valid).toBe(true);
82
+ });
83
+
84
+ it('should pass validation for valid use-existing mode with vpcId', () => {
85
+ const appDefinition = {
86
+ vpc: {
87
+ enable: true,
88
+ management: 'use-existing',
89
+ vpcId: 'vpc-123456',
90
+ securityGroupIds: ['sg-123'],
91
+ },
92
+ };
93
+
94
+ const result = vpcBuilder.validate(appDefinition);
95
+
96
+ expect(result.valid).toBe(true);
97
+ });
98
+
99
+ it('should error if VPC configuration is missing', () => {
100
+ const appDefinition = {};
101
+
102
+ const result = vpcBuilder.validate(appDefinition);
103
+
104
+ expect(result.valid).toBe(false);
105
+ expect(result.errors).toContain('VPC configuration is missing');
106
+ });
107
+
108
+ it('should error for invalid management mode', () => {
109
+ const appDefinition = {
110
+ vpc: {
111
+ enable: true,
112
+ management: 'invalid-mode',
113
+ },
114
+ };
115
+
116
+ const result = vpcBuilder.validate(appDefinition);
117
+
118
+ expect(result.valid).toBe(false);
119
+ expect(result.errors.some(err => err.includes('Invalid vpc.management'))).toBe(true);
120
+ });
121
+
122
+ it('should error when use-existing mode without vpcId', () => {
123
+ const appDefinition = {
124
+ vpc: {
125
+ enable: true,
126
+ management: 'use-existing',
127
+ },
128
+ };
129
+
130
+ const result = vpcBuilder.validate(appDefinition);
131
+
132
+ expect(result.valid).toBe(false);
133
+ expect(result.errors).toContain(
134
+ 'vpc.vpcId is required when management="use-existing"'
135
+ );
136
+ });
137
+
138
+ it('should warn when use-existing mode without security groups', () => {
139
+ const appDefinition = {
140
+ vpc: {
141
+ enable: true,
142
+ management: 'use-existing',
143
+ vpcId: 'vpc-123',
144
+ },
145
+ };
146
+
147
+ const result = vpcBuilder.validate(appDefinition);
148
+
149
+ expect(result.warnings.some(warn => warn.includes('securityGroupIds not provided'))).toBe(true);
150
+ });
151
+
152
+ it('should error for invalid CIDR block format', () => {
153
+ const appDefinition = {
154
+ vpc: {
155
+ enable: true,
156
+ cidrBlock: 'invalid-cidr',
157
+ },
158
+ };
159
+
160
+ const result = vpcBuilder.validate(appDefinition);
161
+
162
+ expect(result.valid).toBe(false);
163
+ expect(result.errors.some(err => err.includes('Invalid CIDR block format'))).toBe(true);
164
+ });
165
+
166
+ it('should accept valid CIDR block formats', () => {
167
+ const validCidrs = ['10.0.0.0/16', '172.31.0.0/16', '192.168.0.0/24'];
168
+
169
+ validCidrs.forEach(cidr => {
170
+ const appDefinition = {
171
+ vpc: {
172
+ enable: true,
173
+ cidrBlock: cidr,
174
+ },
175
+ };
176
+
177
+ const result = vpcBuilder.validate(appDefinition);
178
+ expect(result.valid).toBe(true);
179
+ });
180
+ });
181
+
182
+ it('should error when use-existing subnets without subnet IDs', () => {
183
+ const appDefinition = {
184
+ vpc: {
185
+ enable: true,
186
+ subnets: {
187
+ management: 'use-existing',
188
+ },
189
+ },
190
+ };
191
+
192
+ const result = vpcBuilder.validate(appDefinition);
193
+
194
+ expect(result.valid).toBe(false);
195
+ expect(result.errors.some(err => err.includes('At least 2 subnet IDs required'))).toBe(true);
196
+ });
197
+
198
+ it('should error when use-existing subnets with only 1 subnet', () => {
199
+ const appDefinition = {
200
+ vpc: {
201
+ enable: true,
202
+ subnets: {
203
+ management: 'use-existing',
204
+ ids: ['subnet-1'],
205
+ },
206
+ },
207
+ };
208
+
209
+ const result = vpcBuilder.validate(appDefinition);
210
+
211
+ expect(result.valid).toBe(false);
212
+ });
213
+
214
+ it('should pass when use-existing subnets with 2+ subnets', () => {
215
+ const appDefinition = {
216
+ vpc: {
217
+ enable: true,
218
+ subnets: {
219
+ management: 'use-existing',
220
+ ids: ['subnet-1', 'subnet-2'],
221
+ },
222
+ },
223
+ };
224
+
225
+ const result = vpcBuilder.validate(appDefinition);
226
+
227
+ expect(result.valid).toBe(true);
228
+ });
229
+
230
+ it('should default to discover mode when management not specified', () => {
231
+ const appDefinition = {
232
+ vpc: {
233
+ enable: true,
234
+ },
235
+ };
236
+
237
+ const result = vpcBuilder.validate(appDefinition);
238
+
239
+ expect(result.valid).toBe(true);
240
+ });
241
+ });
242
+
243
+ describe('build() - discover mode', () => {
244
+ it('should reuse stack-managed subnets when discovered from CloudFormation', async () => {
245
+ const appDefinition = {
246
+ vpc: { enable: true },
247
+ };
248
+
249
+ const discoveredResources = {
250
+ defaultVpcId: 'vpc-discovered',
251
+ privateSubnetId1: 'subnet-stack-private-1',
252
+ privateSubnetId2: 'subnet-stack-private-2',
253
+ publicSubnetId1: 'subnet-stack-public-1',
254
+ publicSubnetId2: 'subnet-stack-public-2',
255
+ };
256
+
257
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
258
+
259
+ // Should use discovered VPC
260
+ expect(result.vpcId).toBe('vpc-discovered');
261
+
262
+ // Should reuse stack-managed subnets (not create new ones)
263
+ expect(result.vpcConfig.subnetIds).toEqual([
264
+ 'subnet-stack-private-1',
265
+ 'subnet-stack-private-2',
266
+ ]);
267
+
268
+ // Should NOT create new subnet resources
269
+ expect(result.resources.FriggPrivateSubnet1).toBeUndefined();
270
+ expect(result.resources.FriggPrivateSubnet2).toBeUndefined();
271
+ });
272
+
273
+ it('should use discovered VPC but create stage-specific subnets when no stack subnets exist', async () => {
274
+ const appDefinition = {
275
+ vpc: {
276
+ enable: true,
277
+ management: 'discover',
278
+ },
279
+ };
280
+
281
+ const discoveredResources = {
282
+ defaultVpcId: 'vpc-discovered',
283
+ // No stack-managed subnets, so create new ones for stage isolation
284
+ defaultSecurityGroupId: 'sg-discovered',
285
+ };
286
+
287
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
288
+
289
+ // Should create new stage-specific subnets for isolation (prevent route table conflicts)
290
+ expect(result.vpcConfig.subnetIds).toEqual([
291
+ { Ref: 'FriggPrivateSubnet1' },
292
+ { Ref: 'FriggPrivateSubnet2' },
293
+ ]);
294
+ expect(result.resources.FriggPrivateSubnet1).toBeDefined();
295
+ expect(result.resources.FriggPrivateSubnet2).toBeDefined();
296
+ // In discover mode, we create FriggLambdaSecurityGroup in the discovered VPC
297
+ expect(result.vpcConfig.securityGroupIds).toEqual([{ Ref: 'FriggLambdaSecurityGroup' }]);
298
+ expect(result.resources.FriggLambdaSecurityGroup).toBeDefined();
299
+ expect(result.resources.FriggLambdaSecurityGroup.Properties.VpcId).toBe('vpc-discovered');
300
+ });
301
+
302
+ it('should allow sharing discovered subnets when explicitly configured', async () => {
303
+ const appDefinition = {
304
+ vpc: {
305
+ enable: true,
306
+ management: 'discover',
307
+ subnets: {
308
+ management: 'discover', // Explicitly opt-in to subnet sharing
309
+ },
310
+ },
311
+ };
312
+
313
+ const discoveredResources = {
314
+ defaultVpcId: 'vpc-discovered',
315
+ privateSubnetId1: 'subnet-shared-1',
316
+ privateSubnetId2: 'subnet-shared-2',
317
+ };
318
+
319
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
320
+
321
+ // OLD BEHAVIOR: When explicitly set to 'discover', reuse discovered subnets
322
+ expect(result.vpcConfig.subnetIds).toEqual(['subnet-shared-1', 'subnet-shared-2']);
323
+ expect(result.resources.FriggPrivateSubnet1).toBeUndefined();
324
+ });
325
+
326
+ it('should create VPC endpoints in discover mode with selfHeal when none exist', async () => {
327
+ const appDefinition = {
328
+ vpc: {
329
+ enable: true,
330
+ management: 'discover',
331
+ selfHeal: true,
332
+ },
333
+ };
334
+
335
+ const discoveredResources = {
336
+ defaultVpcId: 'vpc-discovered',
337
+ privateSubnetId1: 'subnet-private1',
338
+ privateSubnetId2: 'subnet-private2',
339
+ existingNatGatewayId: 'nat-123',
340
+ // No VPC endpoints discovered
341
+ };
342
+
343
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
344
+
345
+ // With selfHeal enabled and no VPC endpoints found, they should be created
346
+ expect(result.resources.FriggS3VPCEndpoint).toBeDefined();
347
+ expect(result.resources.FriggDynamoDBVPCEndpoint).toBeDefined();
348
+ expect(result.resources.FriggLambdaRouteTable).toBeDefined();
349
+ });
350
+
351
+ it('should NOT create VPC endpoints in discover mode when they already exist', async () => {
352
+ const appDefinition = {
353
+ vpc: {
354
+ enable: true,
355
+ management: 'discover',
356
+ selfHeal: true,
357
+ },
358
+ };
359
+
360
+ const discoveredResources = {
361
+ defaultVpcId: 'vpc-discovered',
362
+ privateSubnetId1: 'subnet-private1',
363
+ privateSubnetId2: 'subnet-private2',
364
+ existingNatGatewayId: 'nat-123',
365
+ // VPC endpoints already exist
366
+ s3VpcEndpointId: 'vpce-s3-123',
367
+ dynamodbVpcEndpointId: 'vpce-dynamodb-456',
368
+ };
369
+
370
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
371
+
372
+ // With existing VPC endpoints discovered, they should NOT be recreated
373
+ expect(result.resources.FriggS3VPCEndpoint).toBeUndefined();
374
+ expect(result.resources.FriggDynamoDBVPCEndpoint).toBeUndefined();
375
+ });
376
+
377
+ it('should create VPC endpoints with selfHeal when missing', async () => {
378
+ const appDefinition = {
379
+ vpc: {
380
+ enable: true,
381
+ management: 'discover',
382
+ selfHeal: true,
383
+ },
384
+ };
385
+
386
+ const discoveredResources = {
387
+ defaultVpcId: 'vpc-123',
388
+ privateSubnetId1: 'subnet-1',
389
+ privateSubnetId2: 'subnet-2',
390
+ defaultSecurityGroupId: 'sg-123',
391
+ // No VPC endpoints discovered - selfHeal should create them
392
+ };
393
+
394
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
395
+
396
+ expect(result.resources.FriggS3VPCEndpoint).toBeDefined();
397
+ expect(result.resources.FriggS3VPCEndpoint.Type).toBe('AWS::EC2::VPCEndpoint');
398
+ expect(result.resources.FriggS3VPCEndpoint.Properties.VpcId).toBe('vpc-123');
399
+ });
400
+
401
+ it('should add stack-managed security group back to template to prevent deletion', async () => {
402
+ const appDefinition = {
403
+ vpc: { enable: true },
404
+ };
405
+
406
+ const discoveredResources = {
407
+ fromCloudFormationStack: true,
408
+ stackName: 'test-stack',
409
+ existingLogicalIds: ['FriggLambdaSecurityGroup'],
410
+ defaultVpcId: 'vpc-123',
411
+ privateSubnetId1: 'subnet-1',
412
+ privateSubnetId2: 'subnet-2',
413
+ lambdaSecurityGroupId: 'sg-existing-stack', // Existing in stack
414
+ };
415
+
416
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
417
+
418
+ // CRITICAL: Must RE-ADD stack-managed SG to template or CloudFormation will DELETE it
419
+ expect(result.resources.FriggLambdaSecurityGroup).toBeDefined();
420
+ expect(result.resources.FriggLambdaSecurityGroup.Type).toBe('AWS::EC2::SecurityGroup');
421
+ expect(result.resources.FriggLambdaSecurityGroup.Properties.VpcId).toBe('vpc-123');
422
+ expect(result.resources.FriggLambdaSecurityGroup.Properties.GroupDescription).toBeDefined();
423
+
424
+ // Should use Ref in Lambda config (not recreating)
425
+ expect(result.vpcConfig.securityGroupIds).toContainEqual({ Ref: 'FriggLambdaSecurityGroup' });
426
+ });
427
+
428
+ it('should add stack-managed subnets back to template to prevent deletion', async () => {
429
+ const appDefinition = {
430
+ vpc: { enable: true },
431
+ };
432
+
433
+ const discoveredResources = {
434
+ fromCloudFormationStack: true,
435
+ stackName: 'test-stack',
436
+ existingLogicalIds: ['FriggPrivateSubnet1', 'FriggPrivateSubnet2'],
437
+ defaultVpcId: 'vpc-123',
438
+ // Subnets exist in stack with specific IDs
439
+ privateSubnetId1: 'subnet-existing-1',
440
+ privateSubnetId2: 'subnet-existing-2',
441
+ };
442
+
443
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
444
+
445
+ // CRITICAL: Must RE-ADD stack-managed subnets to template or CloudFormation will DELETE them
446
+ expect(result.resources.FriggPrivateSubnet1).toBeDefined();
447
+ expect(result.resources.FriggPrivateSubnet1.Type).toBe('AWS::EC2::Subnet');
448
+ expect(result.resources.FriggPrivateSubnet1.Properties.VpcId).toBe('vpc-123');
449
+
450
+ expect(result.resources.FriggPrivateSubnet2).toBeDefined();
451
+ expect(result.resources.FriggPrivateSubnet2.Type).toBe('AWS::EC2::Subnet');
452
+ expect(result.resources.FriggPrivateSubnet2.Properties.VpcId).toBe('vpc-123');
453
+
454
+ // Should use Refs (not external IDs)
455
+ expect(result.vpcConfig.subnetIds).toEqual([
456
+ { Ref: 'FriggPrivateSubnet1' },
457
+ { Ref: 'FriggPrivateSubnet2' }
458
+ ]);
459
+ });
460
+
461
+ it('should add stack-managed VPC endpoints back to template to prevent deletion', async () => {
462
+ const appDefinition = {
463
+ vpc: { enable: true },
464
+ encryption: { fieldLevelEncryptionMethod: 'kms' },
465
+ };
466
+
467
+ // Structured discovery from CloudFormation
468
+ const discoveredResources = {
469
+ fromCloudFormationStack: true,
470
+ stackName: 'test-stack',
471
+ existingLogicalIds: [
472
+ 'FriggLambdaSecurityGroup',
473
+ 'FriggLambdaRouteTable',
474
+ 'FriggS3VPCEndpoint',
475
+ 'FriggDynamoDBVPCEndpoint',
476
+ 'FriggKMSVPCEndpoint',
477
+ 'FriggSecretsManagerVPCEndpoint',
478
+ 'FriggSQSVPCEndpoint'
479
+ ],
480
+ defaultVpcId: 'vpc-123',
481
+ privateSubnetId1: 'subnet-1',
482
+ privateSubnetId2: 'subnet-2',
483
+ routeTableId: 'rtb-123',
484
+ lambdaSecurityGroupId: 'sg-123',
485
+ // VPC endpoints discovered in stack
486
+ s3VpcEndpointId: 'vpce-s3-stack',
487
+ dynamodbVpcEndpointId: 'vpce-ddb-stack',
488
+ kmsVpcEndpointId: 'vpce-kms-stack',
489
+ secretsManagerVpcEndpointId: 'vpce-sm-stack',
490
+ sqsVpcEndpointId: 'vpce-sqs-stack',
491
+ };
492
+
493
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
494
+
495
+ // CRITICAL: Must RE-ADD stack-managed endpoints to template or CloudFormation will DELETE them
496
+ expect(result.resources.FriggS3VPCEndpoint).toBeDefined();
497
+ expect(result.resources.FriggS3VPCEndpoint.Type).toBe('AWS::EC2::VPCEndpoint');
498
+ expect(result.resources.FriggS3VPCEndpoint.Properties.VpcEndpointType).toBe('Gateway');
499
+
500
+ expect(result.resources.FriggDynamoDBVPCEndpoint).toBeDefined();
501
+ expect(result.resources.FriggDynamoDBVPCEndpoint.Type).toBe('AWS::EC2::VPCEndpoint');
502
+ expect(result.resources.FriggDynamoDBVPCEndpoint.Properties.VpcEndpointType).toBe('Gateway');
503
+
504
+ expect(result.resources.FriggKMSVPCEndpoint).toBeDefined();
505
+ expect(result.resources.FriggKMSVPCEndpoint.Type).toBe('AWS::EC2::VPCEndpoint');
506
+ expect(result.resources.FriggKMSVPCEndpoint.Properties.VpcEndpointType).toBe('Interface');
507
+
508
+ expect(result.resources.FriggSecretsManagerVPCEndpoint).toBeDefined();
509
+ expect(result.resources.FriggSecretsManagerVPCEndpoint.Type).toBe('AWS::EC2::VPCEndpoint');
510
+ expect(result.resources.FriggSecretsManagerVPCEndpoint.Properties.VpcEndpointType).toBe('Interface');
511
+
512
+ expect(result.resources.FriggSQSVPCEndpoint).toBeDefined();
513
+ expect(result.resources.FriggSQSVPCEndpoint.Type).toBe('AWS::EC2::VPCEndpoint');
514
+ expect(result.resources.FriggSQSVPCEndpoint.Properties.VpcEndpointType).toBe('Interface');
515
+
516
+ // Should create VPC Endpoint Security Group for interface endpoints
517
+ expect(result.resources.FriggVPCEndpointSecurityGroup).toBeDefined();
518
+ expect(result.resources.FriggVPCEndpointSecurityGroup.Type).toBe('AWS::EC2::SecurityGroup');
519
+ });
520
+
521
+ it('should create VPC endpoints when discovered from AWS but not stack', async () => {
522
+ const appDefinition = {
523
+ vpc: { enable: true, enableVPCEndpoints: true, selfHeal: true },
524
+ encryption: { fieldLevelEncryptionMethod: 'kms' },
525
+ };
526
+ const discoveredResources = {
527
+ defaultVpcId: 'vpc-123',
528
+ privateSubnetId1: 'subnet-1',
529
+ privateSubnetId2: 'subnet-2',
530
+ // No VPC endpoints in stack (would be strings)
531
+ // existingEndpoints will be passed as empty
532
+ };
533
+
534
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
535
+
536
+ // Should create CloudFormation resources (not in stack)
537
+ expect(result.resources.FriggS3VPCEndpoint).toBeDefined();
538
+ expect(result.resources.FriggDynamoDBVPCEndpoint).toBeDefined();
539
+ expect(result.resources.FriggKMSVPCEndpoint).toBeDefined();
540
+ expect(result.resources.FriggSecretsManagerVPCEndpoint).toBeDefined();
541
+ expect(result.resources.FriggSQSVPCEndpoint).toBeDefined();
542
+ });
543
+
544
+ it('should skip VPC endpoints when disabled', async () => {
545
+ const appDefinition = {
546
+ vpc: {
547
+ enable: true,
548
+ management: 'discover',
549
+ enableVPCEndpoints: false,
550
+ },
551
+ };
552
+
553
+ const discoveredResources = {
554
+ defaultVpcId: 'vpc-123',
555
+ privateSubnetId1: 'subnet-1',
556
+ privateSubnetId2: 'subnet-2',
557
+ };
558
+
559
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
560
+
561
+ expect(result.resources.FriggS3VPCEndpoint).toBeUndefined();
562
+ });
563
+
564
+ it('should create route table associations when VPC endpoints exist but no NAT Gateway', async () => {
565
+ const appDefinition = {
566
+ vpc: { enable: true, enableVPCEndpoints: true, selfHeal: true },
567
+ };
568
+ const discoveredResources = {
569
+ defaultVpcId: 'vpc-123',
570
+ privateSubnetId1: 'subnet-1',
571
+ privateSubnetId2: 'subnet-2',
572
+ // No NAT Gateway, so associations won't be created by NAT Gateway routing
573
+ };
574
+
575
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
576
+
577
+ // Route table should be created for VPC endpoints
578
+ expect(result.resources.FriggLambdaRouteTable).toBeDefined();
579
+ expect(result.resources.FriggLambdaRouteTable.Type).toBe('AWS::EC2::RouteTable');
580
+
581
+ // Subnet associations should be created (healing)
582
+ expect(result.resources.FriggPrivateSubnet1RouteTableAssociation).toBeDefined();
583
+ expect(result.resources.FriggPrivateSubnet1RouteTableAssociation.Type).toBe('AWS::EC2::SubnetRouteTableAssociation');
584
+ expect(result.resources.FriggPrivateSubnet1RouteTableAssociation.Properties.SubnetId).toBe('subnet-1');
585
+
586
+ expect(result.resources.FriggPrivateSubnet2RouteTableAssociation).toBeDefined();
587
+ expect(result.resources.FriggPrivateSubnet2RouteTableAssociation.Properties.SubnetId).toBe('subnet-2');
588
+ });
589
+
590
+ it('should include IAM permissions for VPC operations', async () => {
591
+ const appDefinition = {
592
+ vpc: {
593
+ enable: true,
594
+ },
595
+ };
596
+
597
+ const discoveredResources = {
598
+ defaultVpcId: 'vpc-123',
599
+ privateSubnetId1: 'subnet-priv1',
600
+ privateSubnetId2: 'subnet-priv2',
601
+ };
602
+
603
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
604
+
605
+ const vpcPermissions = result.iamStatements.find(stmt =>
606
+ stmt.Action.includes('ec2:CreateNetworkInterface')
607
+ );
608
+
609
+ expect(vpcPermissions).toBeDefined();
610
+ expect(vpcPermissions.Action).toContain('ec2:DescribeNetworkInterfaces');
611
+ expect(vpcPermissions.Action).toContain('ec2:DeleteNetworkInterface');
612
+ });
613
+ });
614
+
615
+ describe('build() - create-new mode', () => {
616
+ it('should create complete VPC infrastructure', async () => {
617
+ const appDefinition = {
618
+ vpc: {
619
+ enable: true,
620
+ management: 'create-new',
621
+ },
622
+ };
623
+
624
+ const result = await vpcBuilder.build(appDefinition, {});
625
+
626
+ expect(result.resources.FriggVPC).toBeDefined();
627
+ expect(result.resources.FriggVPC.Type).toBe('AWS::EC2::VPC');
628
+ expect(result.resources.FriggVPC.Properties.CidrBlock).toBe('10.0.0.0/16');
629
+ });
630
+
631
+ it('should create private and public subnets', async () => {
632
+ const appDefinition = {
633
+ vpc: {
634
+ enable: true,
635
+ management: 'create-new',
636
+ },
637
+ };
638
+
639
+ const result = await vpcBuilder.build(appDefinition, {});
640
+
641
+ expect(result.resources.FriggPrivateSubnet1).toBeDefined();
642
+ expect(result.resources.FriggPrivateSubnet2).toBeDefined();
643
+ expect(result.resources.FriggPublicSubnet).toBeDefined();
644
+ });
645
+
646
+ it('should create security group for Lambda functions', async () => {
647
+ const appDefinition = {
648
+ vpc: {
649
+ enable: true,
650
+ management: 'create-new',
651
+ },
652
+ };
653
+
654
+ const result = await vpcBuilder.build(appDefinition, {});
655
+
656
+ expect(result.resources.FriggLambdaSecurityGroup).toBeDefined();
657
+ expect(result.resources.FriggLambdaSecurityGroup.Type).toBe('AWS::EC2::SecurityGroup');
658
+ });
659
+
660
+ it('should use CloudFormation references for new resources', async () => {
661
+ const appDefinition = {
662
+ vpc: {
663
+ enable: true,
664
+ management: 'create-new',
665
+ },
666
+ };
667
+
668
+ const result = await vpcBuilder.build(appDefinition, {});
669
+
670
+ expect(result.vpcConfig.securityGroupIds).toEqual([{ Ref: 'FriggLambdaSecurityGroup' }]);
671
+ expect(result.vpcConfig.subnetIds).toContainEqual({ Ref: 'FriggPrivateSubnet1' });
672
+ expect(result.vpcConfig.subnetIds).toContainEqual({ Ref: 'FriggPrivateSubnet2' });
673
+ });
674
+
675
+ it('should use custom CIDR block if provided', async () => {
676
+ const appDefinition = {
677
+ vpc: {
678
+ enable: true,
679
+ management: 'create-new',
680
+ cidrBlock: '192.168.0.0/16',
681
+ },
682
+ };
683
+
684
+ const result = await vpcBuilder.build(appDefinition, {});
685
+
686
+ expect(result.resources.FriggVPC.Properties.CidrBlock).toBe('192.168.0.0/16');
687
+ });
688
+ });
689
+
690
+ describe('build() - use-existing mode', () => {
691
+ it('should use provided VPC and subnet IDs', async () => {
692
+ const appDefinition = {
693
+ vpc: {
694
+ enable: true,
695
+ management: 'use-existing',
696
+ vpcId: 'vpc-custom',
697
+ subnets: {
698
+ ids: ['subnet-a', 'subnet-b'],
699
+ },
700
+ securityGroupIds: ['sg-custom'],
701
+ },
702
+ };
703
+
704
+ const result = await vpcBuilder.build(appDefinition, {});
705
+
706
+ expect(result.vpcConfig.subnetIds).toEqual(['subnet-a', 'subnet-b']);
707
+ expect(result.vpcConfig.securityGroupIds).toEqual(['sg-custom']);
708
+ });
709
+
710
+ it('should not create VPC resources in use-existing mode', async () => {
711
+ const appDefinition = {
712
+ vpc: {
713
+ enable: true,
714
+ management: 'use-existing',
715
+ vpcId: 'vpc-custom',
716
+ subnets: {
717
+ ids: ['subnet-a', 'subnet-b'],
718
+ },
719
+ },
720
+ };
721
+
722
+ const result = await vpcBuilder.build(appDefinition, {});
723
+
724
+ expect(result.resources.FriggVPC).toBeUndefined();
725
+ expect(result.resources.FriggPrivateSubnet1).toBeUndefined();
726
+ });
727
+ });
728
+
729
+ describe('getDependencies()', () => {
730
+ it('should have no dependencies', () => {
731
+ const deps = vpcBuilder.getDependencies();
732
+
733
+ expect(deps).toEqual([]);
734
+ });
735
+ });
736
+
737
+ describe('getName()', () => {
738
+ it('should return VpcBuilder', () => {
739
+ expect(vpcBuilder.getName()).toBe('VpcBuilder');
740
+ });
741
+ });
742
+
743
+ describe('NAT Gateway handling', () => {
744
+ it('should create NAT gateway when management is createAndManage', async () => {
745
+ const appDefinition = {
746
+ vpc: {
747
+ enable: true,
748
+ management: 'discover',
749
+ natGateway: {
750
+ management: 'createAndManage',
751
+ },
752
+ selfHeal: true,
753
+ },
754
+ };
755
+
756
+ const discoveredResources = {
757
+ defaultVpcId: 'vpc-123',
758
+ publicSubnetId: 'subnet-public',
759
+ };
760
+
761
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
762
+
763
+ expect(result.resources.FriggNATGateway).toBeDefined();
764
+ expect(result.resources.FriggNATGateway.Type).toBe('AWS::EC2::NatGateway');
765
+ });
766
+
767
+ it('should create route table associations for private subnets with NAT Gateway', async () => {
768
+ const appDefinition = {
769
+ vpc: {
770
+ enable: true,
771
+ management: 'discover',
772
+ subnets: { management: 'create' },
773
+ natGateway: {
774
+ management: 'createAndManage',
775
+ },
776
+ selfHeal: true,
777
+ },
778
+ };
779
+
780
+ const discoveredResources = {
781
+ defaultVpcId: 'vpc-123',
782
+ publicSubnetId: 'subnet-public',
783
+ };
784
+
785
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
786
+
787
+ // Verify route table is created
788
+ expect(result.resources.FriggLambdaRouteTable).toBeDefined();
789
+ expect(result.resources.FriggLambdaRouteTable.Type).toBe('AWS::EC2::RouteTable');
790
+
791
+ // Verify route to NAT Gateway
792
+ expect(result.resources.FriggPrivateRoute).toBeDefined();
793
+ expect(result.resources.FriggPrivateRoute.Properties.NatGatewayId).toEqual({ Ref: 'FriggNATGateway' });
794
+
795
+ // Verify subnet route table associations
796
+ expect(result.resources.FriggPrivateSubnet1RouteTableAssociation).toBeDefined();
797
+ expect(result.resources.FriggPrivateSubnet1RouteTableAssociation.Type).toBe('AWS::EC2::SubnetRouteTableAssociation');
798
+ expect(result.resources.FriggPrivateSubnet1RouteTableAssociation.Properties.SubnetId).toEqual({ Ref: 'FriggPrivateSubnet1' });
799
+ expect(result.resources.FriggPrivateSubnet1RouteTableAssociation.Properties.RouteTableId).toEqual({ Ref: 'FriggLambdaRouteTable' });
800
+
801
+ expect(result.resources.FriggPrivateSubnet2RouteTableAssociation).toBeDefined();
802
+ expect(result.resources.FriggPrivateSubnet2RouteTableAssociation.Type).toBe('AWS::EC2::SubnetRouteTableAssociation');
803
+ expect(result.resources.FriggPrivateSubnet2RouteTableAssociation.Properties.SubnetId).toEqual({ Ref: 'FriggPrivateSubnet2' });
804
+ expect(result.resources.FriggPrivateSubnet2RouteTableAssociation.Properties.RouteTableId).toEqual({ Ref: 'FriggLambdaRouteTable' });
805
+ });
806
+
807
+ it('should add UpdateReplacePolicy to force association recreation on updates', async () => {
808
+ const appDefinition = {
809
+ vpc: {
810
+ enable: true,
811
+ management: 'discover',
812
+ subnets: { management: 'discover' },
813
+ natGateway: { management: 'discover' },
814
+ },
815
+ };
816
+
817
+ const discoveredResources = {
818
+ vpcId: 'vpc-123',
819
+ privateSubnetId1: 'subnet-existing-1',
820
+ privateSubnetId2: 'subnet-existing-2',
821
+ natGatewayId: 'nat-existing',
822
+ routeTableId: 'rtb-old',
823
+ existingLogicalIds: ['FriggSubnet1RouteAssociation', 'FriggSubnet2RouteAssociation'],
824
+ };
825
+
826
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
827
+
828
+ // Verify associations have UpdateReplacePolicy to force recreation
829
+ expect(result.resources.FriggSubnet1RouteAssociation.UpdateReplacePolicy).toBe('Delete');
830
+ expect(result.resources.FriggSubnet2RouteAssociation.UpdateReplacePolicy).toBe('Delete');
831
+
832
+ // This forces CloudFormation to delete old associations and create new ones
833
+ // instead of trying to update them in-place (which doesn't work)
834
+ });
835
+
836
+ it('should not create NAT when existing NAT is properly placed', async () => {
837
+ const appDefinition = {
838
+ vpc: {
839
+ enable: true,
840
+ natGateway: {
841
+ management: 'createAndManage',
842
+ },
843
+ selfHeal: true,
844
+ },
845
+ };
846
+
847
+ const discoveredResources = {
848
+ defaultVpcId: 'vpc-123',
849
+ publicSubnetId: 'subnet-public',
850
+ existingNatGatewayId: 'nat-good',
851
+ natGatewayInPrivateSubnet: false,
852
+ };
853
+
854
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
855
+
856
+ expect(result.resources.FriggNATGateway).toBeUndefined();
857
+ });
858
+
859
+ it('should create new NAT when existing is in private subnet', async () => {
860
+ const appDefinition = {
861
+ vpc: {
862
+ enable: true,
863
+ natGateway: {
864
+ management: 'createAndManage',
865
+ },
866
+ selfHeal: true,
867
+ },
868
+ };
869
+
870
+ const discoveredResources = {
871
+ defaultVpcId: 'vpc-123',
872
+ publicSubnetId: 'subnet-public',
873
+ existingNatGatewayId: 'nat-misplaced',
874
+ natGatewayInPrivateSubnet: true, // WRONG placement
875
+ };
876
+
877
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
878
+
879
+ expect(result.resources.FriggNATGateway).toBeDefined();
880
+ });
881
+
882
+ it('should create new NAT Gateway when existing is in private subnet', async () => {
883
+ const appDefinition = {
884
+ vpc: {
885
+ enable: true,
886
+ natGateway: {
887
+ management: 'createAndManage',
888
+ },
889
+ selfHeal: false,
890
+ },
891
+ };
892
+
893
+ const discoveredResources = {
894
+ defaultVpcId: 'vpc-123',
895
+ privateSubnetId1: 'subnet-priv1',
896
+ privateSubnetId2: 'subnet-priv2',
897
+ publicSubnetId: 'subnet-public',
898
+ existingNatGatewayId: 'nat-misplaced',
899
+ natGatewayInPrivateSubnet: true,
900
+ };
901
+
902
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
903
+
904
+ // Should create new NAT Gateway instead of using the misplaced one
905
+ expect(result.resources.FriggNATGateway).toBeDefined();
906
+ expect(result.resources.FriggNATGateway.Type).toBe('AWS::EC2::NatGateway');
907
+ });
908
+
909
+ it('should reuse existing elastic IP allocation', async () => {
910
+ const appDefinition = {
911
+ vpc: {
912
+ enable: true,
913
+ natGateway: {
914
+ management: 'createAndManage',
915
+ },
916
+ selfHeal: true,
917
+ },
918
+ };
919
+
920
+ const discoveredResources = {
921
+ defaultVpcId: 'vpc-123',
922
+ publicSubnetId: 'subnet-public',
923
+ existingElasticIpAllocationId: 'eipalloc-123',
924
+ };
925
+
926
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
927
+
928
+ if (result.resources.FriggNATGateway) {
929
+ // When reusing existing EIP, it should be a CloudFormation reference
930
+ expect(result.resources.FriggNATGateway.Properties.AllocationId).toEqual(
931
+ { 'Fn::GetAtt': ['FriggNATGatewayEIP', 'AllocationId'] }
932
+ );
933
+ }
934
+ });
935
+ });
936
+
937
+ describe('VPC Endpoints', () => {
938
+ it('should create KMS endpoint when KMS encryption is enabled', async () => {
939
+ const appDefinition = {
940
+ vpc: {
941
+ enable: true,
942
+ management: 'create-new',
943
+ },
944
+ encryption: {
945
+ fieldLevelEncryptionMethod: 'kms',
946
+ },
947
+ };
948
+
949
+ const discoveredResources = {};
950
+
951
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
952
+
953
+ expect(result.resources.FriggKMSVPCEndpoint).toBeDefined();
954
+ });
955
+
956
+ it('should create Secrets Manager endpoint when enabled', async () => {
957
+ const appDefinition = {
958
+ vpc: {
959
+ enable: true,
960
+ management: 'create-new',
961
+ },
962
+ secretsManager: {
963
+ enable: true,
964
+ },
965
+ };
966
+
967
+ const discoveredResources = {};
968
+
969
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
970
+
971
+ expect(result.resources.FriggSecretsManagerVPCEndpoint).toBeDefined();
972
+ });
973
+
974
+ it('should not create KMS endpoint when encryption is AES', async () => {
975
+ const appDefinition = {
976
+ vpc: {
977
+ enable: true,
978
+ management: 'create-new',
979
+ },
980
+ encryption: {
981
+ fieldLevelEncryptionMethod: 'aes',
982
+ },
983
+ };
984
+
985
+ const discoveredResources = {};
986
+
987
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
988
+
989
+ expect(result.resources.FriggKMSVPCEndpoint).toBeUndefined();
990
+ });
991
+ });
992
+
993
+ describe('SSM VPC Endpoint', () => {
994
+ const originalSkipDiscovery = process.env.FRIGG_SKIP_AWS_DISCOVERY;
995
+
996
+ afterEach(() => {
997
+ if (originalSkipDiscovery === undefined) {
998
+ delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
999
+ } else {
1000
+ process.env.FRIGG_SKIP_AWS_DISCOVERY = originalSkipDiscovery;
1001
+ }
1002
+ });
1003
+
1004
+ it('should create SSM endpoint when offload is active and VPC is enabled', async () => {
1005
+ delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
1006
+ const appDefinition = {
1007
+ vpc: { enable: true, management: 'create-new' },
1008
+ ssm: { enable: true },
1009
+ environment: { FOO: 'ssm' },
1010
+ };
1011
+
1012
+ const result = await vpcBuilder.build(appDefinition, {});
1013
+
1014
+ expect(result.resources.FriggSSMVPCEndpoint).toBeDefined();
1015
+ expect(result.resources.FriggSSMVPCEndpoint.Type).toBe('AWS::EC2::VPCEndpoint');
1016
+ expect(result.resources.FriggSSMVPCEndpoint.Properties.VpcEndpointType).toBe('Interface');
1017
+ expect(result.resources.FriggSSMVPCEndpoint.Properties.ServiceName).toBe('com.amazonaws.${self:provider.region}.ssm');
1018
+ expect(result.resources.FriggSSMVPCEndpoint.Properties.PrivateDnsEnabled).toBe(true);
1019
+ });
1020
+
1021
+ it('should not create SSM endpoint when offload is not active', async () => {
1022
+ delete process.env.FRIGG_SKIP_AWS_DISCOVERY;
1023
+ const appDefinition = {
1024
+ vpc: { enable: true, management: 'create-new' },
1025
+ ssm: { enable: true },
1026
+ };
1027
+
1028
+ const result = await vpcBuilder.build(appDefinition, {});
1029
+
1030
+ expect(result.resources.FriggSSMVPCEndpoint).toBeUndefined();
1031
+ });
1032
+ });
1033
+
1034
+ describe('Self-healing', () => {
1035
+ it('should create missing subnets when selfHeal is enabled', async () => {
1036
+ const appDefinition = {
1037
+ vpc: {
1038
+ enable: true,
1039
+ management: 'discover',
1040
+ selfHeal: true,
1041
+ },
1042
+ };
1043
+
1044
+ const discoveredResources = {
1045
+ defaultVpcId: 'vpc-123',
1046
+ privateSubnetId1: null,
1047
+ privateSubnetId2: null,
1048
+ };
1049
+
1050
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
1051
+
1052
+ expect(result.resources.FriggPrivateSubnet1).toBeDefined();
1053
+ expect(result.resources.FriggPrivateSubnet2).toBeDefined();
1054
+ });
1055
+
1056
+ it('should throw error for missing subnets without selfHeal', async () => {
1057
+ const appDefinition = {
1058
+ vpc: {
1059
+ enable: true,
1060
+ management: 'discover',
1061
+ subnets: { management: 'discover' },
1062
+ selfHeal: false,
1063
+ },
1064
+ };
1065
+
1066
+ const discoveredResources = {
1067
+ defaultVpcId: 'vpc-123',
1068
+ privateSubnetId1: null,
1069
+ privateSubnetId2: null,
1070
+ };
1071
+
1072
+ await expect(vpcBuilder.build(appDefinition, discoveredResources)).rejects.toThrow(
1073
+ 'No subnets discovered'
1074
+ );
1075
+ });
1076
+ });
1077
+
1078
+ describe('Management Mode (Simplified API)', () => {
1079
+ it('should reuse stack VPC when managementMode=managed + vpcIsolation=isolated AND stack has VPC', async () => {
1080
+ const appDefinition = {
1081
+ managementMode: 'managed',
1082
+ vpcIsolation: 'isolated',
1083
+ vpc: {
1084
+ enable: true,
1085
+ management: 'create-new', // Should be IGNORED
1086
+ },
1087
+ };
1088
+
1089
+ // CloudFormation stack has VPC (from previous deployment of this stage)
1090
+ const discoveredResources = {
1091
+ defaultVpcId: 'vpc-stack-dev', // CloudFormation discovery sets this
1092
+ privateSubnetId1: 'subnet-private-1',
1093
+ privateSubnetId2: 'subnet-private-2',
1094
+ publicSubnetId1: 'subnet-public-1',
1095
+ publicSubnetId2: 'subnet-public-2',
1096
+ };
1097
+
1098
+ const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation();
1099
+
1100
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
1101
+
1102
+ // Should warn about ignored options
1103
+ expect(consoleLogSpy).toHaveBeenCalledWith(
1104
+ expect.stringContaining("managementMode='managed' ignoring")
1105
+ );
1106
+
1107
+ // Should log reusing stack VPC
1108
+ expect(consoleLogSpy).toHaveBeenCalledWith(
1109
+ expect.stringContaining("stack has VPC, reusing")
1110
+ );
1111
+
1112
+ // Should keep VPC definition in template (CloudFormation idempotency)
1113
+ // Even though VPC exists, we include the definition - CF won't recreate it
1114
+ expect(result.vpcId).toEqual({ Ref: 'FriggVPC' });
1115
+ expect(result.resources.FriggVPC).toBeDefined();
1116
+ expect(result.resources.FriggVPC.Type).toBe('AWS::EC2::VPC');
1117
+
1118
+ // Should keep subnet definitions in template and use Refs
1119
+ expect(result.vpcConfig.subnetIds).toEqual([
1120
+ { Ref: 'FriggPrivateSubnet1' },
1121
+ { Ref: 'FriggPrivateSubnet2' }
1122
+ ]);
1123
+ expect(result.resources.FriggPrivateSubnet1).toBeDefined();
1124
+ expect(result.resources.FriggPrivateSubnet2).toBeDefined();
1125
+
1126
+ consoleLogSpy.mockRestore();
1127
+ });
1128
+
1129
+ it('should create new VPC when managementMode=managed + vpcIsolation=isolated AND stack has NO VPC', async () => {
1130
+ const appDefinition = {
1131
+ managementMode: 'managed',
1132
+ vpcIsolation: 'isolated',
1133
+ vpc: {
1134
+ enable: true,
1135
+ management: 'discover', // Should be IGNORED
1136
+ },
1137
+ };
1138
+
1139
+ // No VPC in CloudFormation stack (fresh deployment)
1140
+ // Default VPC might exist in AWS, but not stack-managed
1141
+ const discoveredResources = {
1142
+ // No defaultVpcId means no VPC in CloudFormation stack
1143
+ };
1144
+
1145
+ const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation();
1146
+
1147
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
1148
+
1149
+ // Should warn about ignored options
1150
+ expect(consoleLogSpy).toHaveBeenCalledWith(
1151
+ expect.stringContaining("managementMode='managed' ignoring")
1152
+ );
1153
+
1154
+ // Should log creating new VPC
1155
+ expect(consoleLogSpy).toHaveBeenCalledWith(
1156
+ expect.stringContaining("no stack VPC, creating new")
1157
+ );
1158
+
1159
+ // Should create new isolated VPC
1160
+ expect(result.vpcId).toEqual({ Ref: 'FriggVPC' });
1161
+ expect(result.resources.FriggVPC).toBeDefined();
1162
+
1163
+ // Subnets should use CloudFormation Fn::Cidr
1164
+ expect(result.resources.FriggPrivateSubnet1.Properties.CidrBlock).toEqual({
1165
+ 'Fn::Select': [0, { 'Fn::Cidr': ['10.0.0.0/16', 4, 8] }]
1166
+ });
1167
+
1168
+ consoleLogSpy.mockRestore();
1169
+ });
1170
+
1171
+ it('should use managementMode=managed with vpcIsolation=shared to discover VPC', async () => {
1172
+ const appDefinition = {
1173
+ managementMode: 'managed',
1174
+ vpcIsolation: 'shared',
1175
+ vpc: {
1176
+ enable: true,
1177
+ subnets: { management: 'use-existing' }, // Should be IGNORED
1178
+ },
1179
+ };
1180
+
1181
+ const discoveredResources = {
1182
+ defaultVpcId: 'vpc-existing',
1183
+ };
1184
+
1185
+ const consoleLogSpy = jest.spyOn(console, 'log').mockImplementation();
1186
+
1187
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
1188
+
1189
+ // Should warn about ignored options
1190
+ expect(consoleLogSpy).toHaveBeenCalledWith(
1191
+ expect.stringContaining("ignoring")
1192
+ );
1193
+
1194
+ // Should discover existing VPC
1195
+ expect(result.vpcId).toBe('vpc-existing');
1196
+ expect(result.resources.FriggVPC).toBeUndefined();
1197
+
1198
+ // Should create new stage-specific subnets
1199
+ expect(result.resources.FriggPrivateSubnet1).toBeDefined();
1200
+
1201
+ consoleLogSpy.mockRestore();
1202
+ });
1203
+
1204
+ it('should default to discover mode for backwards compatibility', async () => {
1205
+ const appDefinition = {
1206
+ // No managementMode specified
1207
+ vpc: {
1208
+ enable: true,
1209
+ management: 'create-new', // Should be RESPECTED
1210
+ },
1211
+ };
1212
+
1213
+ const result = await vpcBuilder.build(appDefinition, {});
1214
+
1215
+ // Should respect legacy vpc.management
1216
+ expect(result.vpcId).toEqual({ Ref: 'FriggVPC' });
1217
+ expect(result.resources.FriggVPC).toBeDefined();
1218
+ });
1219
+ });
1220
+
1221
+ describe('VPC Sharing Control', () => {
1222
+ it('should share VPC across stages when shareAcrossStages is true (default)', async () => {
1223
+ const appDefinition = {
1224
+ vpc: {
1225
+ enable: true,
1226
+ shareAcrossStages: true, // Explicit opt-in to sharing
1227
+ },
1228
+ };
1229
+
1230
+ const discoveredResources = {
1231
+ defaultVpcId: 'vpc-shared',
1232
+ natGatewayId: 'nat-shared',
1233
+ };
1234
+
1235
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
1236
+
1237
+ // Should use discovered VPC (not create new one)
1238
+ expect(result.vpcId).toBe('vpc-shared');
1239
+ expect(result.resources.FriggVPC).toBeUndefined();
1240
+
1241
+ // Should create stage-specific subnets for isolation
1242
+ expect(result.resources.FriggPrivateSubnet1).toBeDefined();
1243
+ expect(result.resources.FriggPrivateSubnet2).toBeDefined();
1244
+
1245
+ // Should reuse discovered NAT Gateway
1246
+ expect(result.resources.FriggNATGateway).toBeUndefined();
1247
+ });
1248
+
1249
+ it('should create isolated VPC when shareAcrossStages is false', async () => {
1250
+ const appDefinition = {
1251
+ vpc: {
1252
+ enable: true,
1253
+ shareAcrossStages: false, // Explicit opt-out of sharing
1254
+ },
1255
+ };
1256
+
1257
+ const discoveredResources = {
1258
+ defaultVpcId: 'vpc-shared',
1259
+ natGatewayId: 'nat-shared',
1260
+ };
1261
+
1262
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
1263
+
1264
+ // Should create new VPC (ignore discovered resources)
1265
+ expect(result.vpcId).toEqual({ Ref: 'FriggVPC' });
1266
+ expect(result.resources.FriggVPC).toBeDefined();
1267
+ expect(result.resources.FriggVPC.Properties.CidrBlock).toBe('10.0.0.0/16');
1268
+
1269
+ // Should create stage-specific subnets with Fn::Cidr (dynamic from VPC CIDR)
1270
+ expect(result.resources.FriggPrivateSubnet1).toBeDefined();
1271
+ expect(result.resources.FriggPrivateSubnet2).toBeDefined();
1272
+
1273
+ // Subnets should use CloudFormation Fn::Cidr, NOT hardcoded 172.31.x.x
1274
+ expect(result.resources.FriggPrivateSubnet1.Properties.CidrBlock).toEqual({
1275
+ 'Fn::Select': [0, { 'Fn::Cidr': ['10.0.0.0/16', 4, 8] }]
1276
+ });
1277
+ expect(result.resources.FriggPrivateSubnet2.Properties.CidrBlock).toEqual({
1278
+ 'Fn::Select': [1, { 'Fn::Cidr': ['10.0.0.0/16', 4, 8] }]
1279
+ });
1280
+
1281
+ // Should create new NAT Gateway
1282
+ expect(result.resources.FriggNATGateway).toBeDefined();
1283
+ });
1284
+
1285
+ it('should default to shared VPC when shareAcrossStages is not specified', async () => {
1286
+ const appDefinition = {
1287
+ vpc: {
1288
+ enable: true,
1289
+ // shareAcrossStages not specified - should default to true
1290
+ },
1291
+ };
1292
+
1293
+ const discoveredResources = {
1294
+ defaultVpcId: 'vpc-discovered',
1295
+ };
1296
+
1297
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
1298
+
1299
+ // Should use discovered VPC by default (backwards compatibility)
1300
+ expect(result.vpcId).toBe('vpc-discovered');
1301
+ expect(result.resources.FriggVPC).toBeUndefined();
1302
+ });
1303
+ });
1304
+
1305
+ describe('generateSubnetCidrs()', () => {
1306
+ it('should use CloudFormation Fn::Cidr for create-new mode', () => {
1307
+ const cidrs = vpcBuilder.generateSubnetCidrs('create-new', {});
1308
+
1309
+ expect(cidrs.private1).toEqual({
1310
+ 'Fn::Select': [0, { 'Fn::Cidr': ['10.0.0.0/16', 4, 8] }]
1311
+ });
1312
+ expect(cidrs.private2).toEqual({
1313
+ 'Fn::Select': [1, { 'Fn::Cidr': ['10.0.0.0/16', 4, 8] }]
1314
+ });
1315
+ expect(cidrs.public1).toEqual({
1316
+ 'Fn::Select': [2, { 'Fn::Cidr': ['10.0.0.0/16', 4, 8] }]
1317
+ });
1318
+ expect(cidrs.public2).toEqual({
1319
+ 'Fn::Select': [3, { 'Fn::Cidr': ['10.0.0.0/16', 4, 8] }]
1320
+ });
1321
+ });
1322
+
1323
+ it('should use default static CIDRs when no existing subnets in VPC', () => {
1324
+ const discoveredResources = {
1325
+ subnets: []
1326
+ };
1327
+
1328
+ const cidrs = vpcBuilder.generateSubnetCidrs('discover', discoveredResources);
1329
+
1330
+ expect(cidrs.private1).toBe('172.31.240.0/24');
1331
+ expect(cidrs.private2).toBe('172.31.241.0/24');
1332
+ expect(cidrs.public1).toBe('172.31.250.0/24');
1333
+ expect(cidrs.public2).toBe('172.31.251.0/24');
1334
+ });
1335
+
1336
+ it('should avoid CIDR conflicts with existing subnets', () => {
1337
+ const discoveredResources = {
1338
+ subnets: [
1339
+ { CidrBlock: '172.31.240.0/24' }, // Conflicts with default private1
1340
+ { CidrBlock: '172.31.241.0/24' }, // Conflicts with default private2
1341
+ { CidrBlock: '172.31.0.0/20' }, // Default VPC subnet
1342
+ { CidrBlock: '172.31.16.0/20' }, // Default VPC subnet
1343
+ ]
1344
+ };
1345
+
1346
+ const cidrs = vpcBuilder.generateSubnetCidrs('discover', discoveredResources);
1347
+
1348
+ // Should skip 240 and 241 (already taken), use 242-243 for private, 250-251 for public
1349
+ expect(cidrs.private1).toBe('172.31.242.0/24');
1350
+ expect(cidrs.private2).toBe('172.31.243.0/24');
1351
+ expect(cidrs.public1).toBe('172.31.250.0/24'); // Public range starts at 250
1352
+ expect(cidrs.public2).toBe('172.31.251.0/24');
1353
+ });
1354
+
1355
+ it('should find first available CIDR blocks when some in range are taken', () => {
1356
+ const discoveredResources = {
1357
+ subnets: [
1358
+ { CidrBlock: '172.31.240.0/24' },
1359
+ { CidrBlock: '172.31.242.0/24' },
1360
+ { CidrBlock: '172.31.244.0/24' },
1361
+ ]
1362
+ };
1363
+
1364
+ const cidrs = vpcBuilder.generateSubnetCidrs('discover', discoveredResources);
1365
+
1366
+ // Should use 241, 243 for private (filling gaps), 250, 251 for public
1367
+ expect(cidrs.private1).toBe('172.31.241.0/24');
1368
+ expect(cidrs.private2).toBe('172.31.243.0/24');
1369
+ expect(cidrs.public1).toBe('172.31.250.0/24'); // Public range starts at 250
1370
+ expect(cidrs.public2).toBe('172.31.251.0/24');
1371
+ });
1372
+
1373
+ it('should handle missing discoveredResources gracefully', () => {
1374
+ const cidrs = vpcBuilder.generateSubnetCidrs('discover', null);
1375
+
1376
+ // Should fallback to default CIDRs
1377
+ expect(cidrs.private1).toBe('172.31.240.0/24');
1378
+ expect(cidrs.private2).toBe('172.31.241.0/24');
1379
+ });
1380
+
1381
+ it('should handle discoveredResources without subnets array', () => {
1382
+ const discoveredResources = { vpcId: 'vpc-123' };
1383
+
1384
+ const cidrs = vpcBuilder.generateSubnetCidrs('discover', discoveredResources);
1385
+
1386
+ // Should fallback to default CIDRs
1387
+ expect(cidrs.private1).toBe('172.31.240.0/24');
1388
+ expect(cidrs.private2).toBe('172.31.241.0/24');
1389
+ });
1390
+ });
1391
+
1392
+ describe('Outputs', () => {
1393
+ it.skip('should generate VPC ID output', async () => {
1394
+ const appDefinition = {
1395
+ vpc: {
1396
+ enable: true,
1397
+ management: 'create-new',
1398
+ },
1399
+ };
1400
+
1401
+ const result = await vpcBuilder.build(appDefinition, {});
1402
+
1403
+ expect(result.outputs.VpcId).toBeDefined();
1404
+ });
1405
+
1406
+ it.skip('should generate subnet outputs', async () => {
1407
+ const appDefinition = {
1408
+ vpc: {
1409
+ enable: true,
1410
+ management: 'create-new',
1411
+ },
1412
+ };
1413
+
1414
+ const result = await vpcBuilder.build(appDefinition, {});
1415
+
1416
+ expect(result.outputs.PrivateSubnet1Id).toBeDefined();
1417
+ expect(result.outputs.PrivateSubnet2Id).toBeDefined();
1418
+ });
1419
+ });
1420
+
1421
+ describe('External VPC with stack-managed routing infrastructure pattern', () => {
1422
+ it('should correctly handle external VPC with NEW logical IDs (FriggPrivateRoute pattern)', async () => {
1423
+ // This pattern occurs when VPC/subnets/NAT are external but routing (route tables,
1424
+ // VPC endpoints, security groups) are managed by CloudFormation stack
1425
+ // This tests the NEWER naming convention
1426
+ const appDefinition = {
1427
+ vpc: { enable: true },
1428
+ encryption: { fieldLevelEncryptionMethod: 'kms' },
1429
+ database: {
1430
+ dynamodb: { enable: true } // Enable DynamoDB to create DynamoDB VPC endpoint
1431
+ }
1432
+ };
1433
+
1434
+ // Discovery results from real-world production scenario (newer stack)
1435
+ const discoveredResources = {
1436
+ fromCloudFormationStack: true,
1437
+ stackName: 'test-production-stack',
1438
+ existingLogicalIds: [
1439
+ 'FriggLambdaSecurityGroup',
1440
+ 'FriggLambdaRouteTable',
1441
+ 'FriggPrivateRoute', // NEW naming
1442
+ 'FriggPrivateSubnet1RouteTableAssociation', // NEW naming
1443
+ 'FriggPrivateSubnet2RouteTableAssociation', // NEW naming
1444
+ 'FriggS3VPCEndpoint', // NEW naming
1445
+ 'FriggDynamoDBVPCEndpoint', // NEW naming
1446
+ 'FriggKMSVPCEndpoint' // NEW naming
1447
+ ],
1448
+ // Stack resources (from CloudFormation)
1449
+ lambdaSecurityGroupId: 'sg-01002240c6a446202',
1450
+ routeTableId: 'rtb-08af43bbf0775602d',
1451
+ s3VpcEndpointId: 'vpce-0d1ecb2c53ce9b4b8',
1452
+ dynamodbVpcEndpointId: 'vpce-0fb749b207f1020b0',
1453
+ kmsVpcEndpointId: 'vpce-0e38c25155b86de22',
1454
+ // External resources (discovered via queries)
1455
+ defaultVpcId: 'vpc-0cd17c0e06cb28b28',
1456
+ privateSubnetId1: 'subnet-034f6562dbbc16348',
1457
+ privateSubnetId2: 'subnet-0b8be2b82aeb5cdec',
1458
+ existingNatGatewayId: 'nat-022660c36a47e2d79'
1459
+ };
1460
+
1461
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
1462
+
1463
+ // === ASSERTIONS: Template Structure ===
1464
+
1465
+ // 1. VPC should be external (not in template)
1466
+ expect(result.resources.FriggVPC).toBeUndefined();
1467
+ expect(result.vpcId).toBe('vpc-0cd17c0e06cb28b28');
1468
+
1469
+ // 2. Security Group MUST be in template (stack-managed)
1470
+ expect(result.resources.FriggLambdaSecurityGroup).toBeDefined();
1471
+ expect(result.resources.FriggLambdaSecurityGroup.Type).toBe('AWS::EC2::SecurityGroup');
1472
+ expect(result.vpcConfig.securityGroupIds).toEqual([{ Ref: 'FriggLambdaSecurityGroup' }]);
1473
+
1474
+ // 3. Subnets should be external (use hardcoded IDs, not in template)
1475
+ expect(result.resources.FriggPrivateSubnet1).toBeUndefined();
1476
+ expect(result.resources.FriggPrivateSubnet2).toBeUndefined();
1477
+ expect(result.vpcConfig.subnetIds).toEqual([
1478
+ 'subnet-034f6562dbbc16348',
1479
+ 'subnet-0b8be2b82aeb5cdec'
1480
+ ]);
1481
+
1482
+ // 4. NAT Gateway should be external (not in template)
1483
+ expect(result.resources.FriggNATGateway).toBeUndefined();
1484
+ expect(result.resources.FriggNATGatewayEIP).toBeUndefined();
1485
+ expect(result.natGatewayId).toBe('nat-022660c36a47e2d79');
1486
+
1487
+ // 5. Route table MUST be in template (stack-managed)
1488
+ expect(result.resources.FriggLambdaRouteTable).toBeDefined();
1489
+ expect(result.resources.FriggLambdaRouteTable.Type).toBe('AWS::EC2::RouteTable');
1490
+
1491
+ // 6. Route table associations MUST be in template
1492
+ expect(result.resources.FriggPrivateSubnet1RouteTableAssociation).toBeDefined();
1493
+ expect(result.resources.FriggPrivateSubnet2RouteTableAssociation).toBeDefined();
1494
+
1495
+ // 7. VPC Endpoints MUST be in template (stack-managed, prevents deletion)
1496
+ expect(result.resources.FriggS3VPCEndpoint).toBeDefined();
1497
+ expect(result.resources.FriggS3VPCEndpoint.Properties.VpcEndpointType).toBe('Gateway');
1498
+
1499
+ expect(result.resources.FriggDynamoDBVPCEndpoint).toBeDefined();
1500
+ expect(result.resources.FriggDynamoDBVPCEndpoint.Properties.VpcEndpointType).toBe('Gateway');
1501
+
1502
+ expect(result.resources.FriggKMSVPCEndpoint).toBeDefined();
1503
+ expect(result.resources.FriggKMSVPCEndpoint.Properties.VpcEndpointType).toBe('Interface');
1504
+
1505
+ // 8. VPC Endpoint Security Group needed for interface endpoints
1506
+ expect(result.resources.FriggVPCEndpointSecurityGroup).toBeDefined();
1507
+
1508
+ // === ASSERTIONS: Resource Count ===
1509
+ const resourceKeys = Object.keys(result.resources);
1510
+ const friggResources = resourceKeys.filter(k => k.startsWith('Frigg') || k.startsWith('VPC'));
1511
+
1512
+ // Should have routing infrastructure + endpoints + security groups
1513
+ // NOT full VPC (no FriggVPC, FriggPrivateSubnet1/2, FriggNATGateway)
1514
+ expect(friggResources).toContain('FriggLambdaSecurityGroup');
1515
+ expect(friggResources).toContain('FriggLambdaRouteTable');
1516
+ expect(friggResources).toContain('FriggS3VPCEndpoint');
1517
+ expect(friggResources).toContain('FriggDynamoDBVPCEndpoint');
1518
+ expect(friggResources).toContain('FriggKMSVPCEndpoint');
1519
+ expect(friggResources).not.toContain('FriggVPC');
1520
+ expect(friggResources).not.toContain('FriggPrivateSubnet1');
1521
+ expect(friggResources).not.toContain('FriggNATGateway');
1522
+ });
1523
+
1524
+ it('should use OLD logical IDs for backwards compatibility (FriggNATRoute, VPCEndpointS3 pattern)', async () => {
1525
+ // CRITICAL TEST: Real Frontify production stack uses OLD naming convention
1526
+ // Stack currently has: FriggNATRoute, VPCEndpointS3, VPCEndpointDynamoDB
1527
+ // We MUST use these same logical IDs to avoid AlreadyExists errors
1528
+ const appDefinition = {
1529
+ vpc: {
1530
+ enable: true,
1531
+ ownership: {
1532
+ securityGroup: 'external'
1533
+ },
1534
+ external: {
1535
+ securityGroupIds: ['sg-0c5e0d0e4a2f5efcf']
1536
+ }
1537
+ },
1538
+ encryption: { fieldLevelEncryptionMethod: 'kms' },
1539
+ database: {
1540
+ dynamodb: { enable: true }
1541
+ }
1542
+ };
1543
+
1544
+ // Discovery results matching ACTUAL Frontify production stack
1545
+ const discoveredResources = {
1546
+ fromCloudFormationStack: true,
1547
+ stackName: 'create-frigg-app-production',
1548
+ existingLogicalIds: [
1549
+ 'FriggLambdaRouteTable',
1550
+ 'FriggNATRoute', // OLD naming
1551
+ 'FriggSubnet1RouteAssociation', // OLD naming
1552
+ 'FriggSubnet2RouteAssociation', // OLD naming
1553
+ 'VPCEndpointS3', // OLD naming
1554
+ 'VPCEndpointDynamoDB' // OLD naming
1555
+ ],
1556
+ // Structured discovery (what resolver needs)
1557
+ _structured: {
1558
+ stackManaged: [
1559
+ { logicalId: 'FriggLambdaRouteTable', physicalId: 'rtb-08af43bbf0775602d', resourceType: 'AWS::EC2::RouteTable' },
1560
+ { logicalId: 'FriggNATRoute', physicalId: 'rtb-08af43bbf0775602d|0.0.0.0/0', resourceType: 'AWS::EC2::Route' },
1561
+ { logicalId: 'VPCEndpointS3', physicalId: 'vpce-0352ceac2124c14be', resourceType: 'AWS::EC2::VPCEndpoint' },
1562
+ { logicalId: 'VPCEndpointDynamoDB', physicalId: 'vpce-0b06c4f631199ea68', resourceType: 'AWS::EC2::VPCEndpoint' }
1563
+ ],
1564
+ external: [
1565
+ { physicalId: 'vpc-01cd124575c683a17', resourceType: 'AWS::EC2::VPC' },
1566
+ { physicalId: 'sg-0c5e0d0e4a2f5efcf', resourceType: 'AWS::EC2::SecurityGroup' },
1567
+ { physicalId: 'subnet-0bbca02e9981df72c', resourceType: 'AWS::EC2::Subnet' },
1568
+ { physicalId: 'subnet-005f7092b91efaaeb', resourceType: 'AWS::EC2::Subnet' },
1569
+ { physicalId: 'nat-05a536cbe7056325f', resourceType: 'AWS::EC2::NatGateway' }
1570
+ ]
1571
+ },
1572
+ // Flat discovery (for backwards compatibility)
1573
+ routeTableId: 'rtb-08af43bbf0775602d',
1574
+ natRoute: 'rtb-08af43bbf0775602d|0.0.0.0/0',
1575
+ s3VpcEndpointId: 'vpce-0352ceac2124c14be',
1576
+ dynamodbVpcEndpointId: 'vpce-0b06c4f631199ea68',
1577
+ // External resources
1578
+ defaultVpcId: 'vpc-01cd124575c683a17',
1579
+ defaultSecurityGroupId: 'sg-0c5e0d0e4a2f5efcf',
1580
+ privateSubnetId1: 'subnet-0bbca02e9981df72c',
1581
+ privateSubnetId2: 'subnet-005f7092b91efaaeb',
1582
+ existingNatGatewayId: 'nat-05a536cbe7056325f'
1583
+ };
1584
+
1585
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
1586
+
1587
+ // CRITICAL: Must use OLD logical IDs to match existing stack
1588
+ expect(result.resources.FriggNATRoute).toBeDefined();
1589
+ expect(result.resources.FriggNATRoute.Type).toBe('AWS::EC2::Route');
1590
+ expect(result.resources.FriggPrivateRoute).toBeUndefined(); // Should NOT create new ID
1591
+
1592
+ expect(result.resources.FriggSubnet1RouteAssociation).toBeDefined();
1593
+ expect(result.resources.FriggSubnet2RouteAssociation).toBeDefined();
1594
+ expect(result.resources.FriggPrivateSubnet1RouteTableAssociation).toBeUndefined();
1595
+ expect(result.resources.FriggPrivateSubnet2RouteTableAssociation).toBeUndefined();
1596
+
1597
+ expect(result.resources.VPCEndpointS3).toBeDefined();
1598
+ expect(result.resources.VPCEndpointS3.Type).toBe('AWS::EC2::VPCEndpoint');
1599
+ expect(result.resources.FriggS3VPCEndpoint).toBeUndefined(); // Should NOT create new ID
1600
+
1601
+ expect(result.resources.VPCEndpointDynamoDB).toBeDefined();
1602
+ expect(result.resources.VPCEndpointDynamoDB.Type).toBe('AWS::EC2::VPCEndpoint');
1603
+ expect(result.resources.FriggDynamoDBVPCEndpoint).toBeUndefined(); // Should NOT create new ID
1604
+
1605
+ // Route table should still be created
1606
+ expect(result.resources.FriggLambdaRouteTable).toBeDefined();
1607
+ });
1608
+
1609
+ it('should convert OLD logical IDs to structured discovery stackManaged array', () => {
1610
+ // TDD test: Verify that VPCEndpointS3 in existingLogicalIds gets added to stackManaged
1611
+ const flatDiscovery = {
1612
+ fromCloudFormationStack: true,
1613
+ stackName: 'create-frigg-app-production',
1614
+ existingLogicalIds: [
1615
+ 'VPCEndpointS3', // OLD naming
1616
+ 'VPCEndpointDynamoDB', // OLD naming
1617
+ 'FriggNATRoute' // OLD naming
1618
+ ],
1619
+ s3VpcEndpointId: 'vpce-0352ceac2124c14be',
1620
+ dynamodbVpcEndpointId: 'vpce-0b06c4f631199ea68',
1621
+ natRoute: 'rtb-xxx|0.0.0.0/0'
1622
+ };
1623
+
1624
+ const structured = vpcBuilder.convertFlatDiscoveryToStructured(flatDiscovery);
1625
+
1626
+ // CRITICAL: Old logical IDs should be in stackManaged array
1627
+ expect(structured.stackManaged).toContainEqual(
1628
+ expect.objectContaining({
1629
+ logicalId: 'VPCEndpointS3',
1630
+ physicalId: 'vpce-0352ceac2124c14be',
1631
+ resourceType: 'AWS::EC2::VPCEndpoint'
1632
+ })
1633
+ );
1634
+ expect(structured.stackManaged).toContainEqual(
1635
+ expect.objectContaining({
1636
+ logicalId: 'VPCEndpointDynamoDB',
1637
+ physicalId: 'vpce-0b06c4f631199ea68',
1638
+ resourceType: 'AWS::EC2::VPCEndpoint'
1639
+ })
1640
+ );
1641
+ expect(structured.stackManaged).toContainEqual(
1642
+ expect.objectContaining({
1643
+ logicalId: 'FriggNATRoute',
1644
+ physicalId: 'rtb-xxx|0.0.0.0/0',
1645
+ resourceType: 'AWS::EC2::Route'
1646
+ })
1647
+ );
1648
+ });
1649
+ });
1650
+
1651
+ describe('convertFlatDiscoveryToStructured - Direct Properties', () => {
1652
+ it('should copy flat discovery properties to structured discovery for resolver access', () => {
1653
+ const flatDiscovery = {
1654
+ fromCloudFormationStack: true,
1655
+ defaultVpcId: 'vpc-123',
1656
+ defaultSecurityGroupId: 'sg-default-456',
1657
+ lambdaSecurityGroupId: 'sg-lambda-789',
1658
+ privateSubnetId1: 'subnet-1',
1659
+ privateSubnetId2: 'subnet-2',
1660
+ natGatewayId: 'nat-123'
1661
+ };
1662
+
1663
+ const result = vpcBuilder.convertFlatDiscoveryToStructured(flatDiscovery);
1664
+
1665
+ // Direct properties should be copied for resolver access
1666
+ expect(result.defaultVpcId).toBe('vpc-123');
1667
+ expect(result.defaultSecurityGroupId).toBe('sg-default-456');
1668
+ expect(result.lambdaSecurityGroupId).toBe('sg-lambda-789');
1669
+ expect(result.privateSubnetId1).toBe('subnet-1');
1670
+ expect(result.privateSubnetId2).toBe('subnet-2');
1671
+ expect(result.natGatewayId).toBe('nat-123');
1672
+ });
1673
+ });
1674
+
1675
+ describe('VPC Endpoint Security Group with External Lambda SG', () => {
1676
+ it('should use external Lambda SG ID (not Ref) for VPC endpoint SG when Lambda SG is external', async () => {
1677
+ const appDefinition = {
1678
+ vpc: {
1679
+ enable: true,
1680
+ enableVPCEndpoints: true,
1681
+ ownership: {
1682
+ securityGroup: 'external' // External Lambda SG
1683
+ }
1684
+ },
1685
+ encryption: { fieldLevelEncryptionMethod: 'kms' }
1686
+ };
1687
+ const discoveredResources = {
1688
+ fromCloudFormationStack: true,
1689
+ defaultVpcId: 'vpc-123',
1690
+ defaultSecurityGroupId: 'sg-default-456', // Default VPC SG
1691
+ lambdaSecurityGroupId: 'sg-stack-789', // Stack-managed SG (will be ignored)
1692
+ privateSubnetId1: 'subnet-1',
1693
+ privateSubnetId2: 'subnet-2',
1694
+ natGatewayId: 'nat-123',
1695
+ existingLogicalIds: ['FriggS3VPCEndpoint', 'FriggKMSVPCEndpoint'],
1696
+ s3VpcEndpointId: 'vpce-s3-stack',
1697
+ kmsVpcEndpointId: 'vpce-kms-stack'
1698
+ };
1699
+
1700
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
1701
+
1702
+ // VPC Endpoint SG should be created
1703
+ expect(result.resources.FriggVPCEndpointSecurityGroup).toBeDefined();
1704
+
1705
+ // CRITICAL: Should use external Lambda SG ID directly, NOT a CloudFormation Ref
1706
+ const ingressRule = result.resources.FriggVPCEndpointSecurityGroup.Properties.SecurityGroupIngress[0];
1707
+ expect(ingressRule.SourceSecurityGroupId).toBe('sg-default-456'); // Direct ID, not { Ref: 'FriggLambdaSecurityGroup' }
1708
+ expect(typeof ingressRule.SourceSecurityGroupId).toBe('string');
1709
+
1710
+ // Verify FriggLambdaSecurityGroup is NOT in the template
1711
+ expect(result.resources.FriggLambdaSecurityGroup).toBeUndefined();
1712
+ });
1713
+
1714
+ it('should use CloudFormation Ref when Lambda SG is stack-managed', async () => {
1715
+ const appDefinition = {
1716
+ vpc: {
1717
+ enable: true,
1718
+ enableVPCEndpoints: true,
1719
+ ownership: {
1720
+ securityGroup: 'stack' // Stack-managed Lambda SG
1721
+ }
1722
+ },
1723
+ encryption: { fieldLevelEncryptionMethod: 'kms' }
1724
+ };
1725
+ const discoveredResources = {
1726
+ defaultVpcId: 'vpc-123',
1727
+ privateSubnetId1: 'subnet-1',
1728
+ privateSubnetId2: 'subnet-2'
1729
+ };
1730
+
1731
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
1732
+
1733
+ // VPC Endpoint SG should be created
1734
+ expect(result.resources.FriggVPCEndpointSecurityGroup).toBeDefined();
1735
+
1736
+ // Should use CloudFormation Ref when Lambda SG is in stack
1737
+ const ingressRule = result.resources.FriggVPCEndpointSecurityGroup.Properties.SecurityGroupIngress[0];
1738
+ expect(ingressRule.SourceSecurityGroupId).toEqual({ Ref: 'FriggLambdaSecurityGroup' });
1739
+
1740
+ // Verify FriggLambdaSecurityGroup IS in the template
1741
+ expect(result.resources.FriggLambdaSecurityGroup).toBeDefined();
1742
+ });
1743
+ });
1744
+
1745
+ describe('convertFlatDiscoveryToStructured - VPC Endpoints from CloudFormation', () => {
1746
+ it('should add VPC endpoints to stackManaged when in existingLogicalIds', () => {
1747
+ const flatDiscovery = {
1748
+ fromCloudFormationStack: true,
1749
+ stackName: 'test-stack',
1750
+ existingLogicalIds: [
1751
+ 'FriggS3VPCEndpoint',
1752
+ 'FriggDynamoDBVPCEndpoint',
1753
+ 'FriggKMSVPCEndpoint'
1754
+ ],
1755
+ s3VpcEndpointId: 'vpce-s3-stack',
1756
+ dynamodbVpcEndpointId: 'vpce-ddb-stack',
1757
+ kmsVpcEndpointId: 'vpce-kms-stack'
1758
+ };
1759
+
1760
+ const result = vpcBuilder.convertFlatDiscoveryToStructured(flatDiscovery);
1761
+
1762
+ // VPC endpoints should be in stackManaged (not external)
1763
+ expect(result.stackManaged).toContainEqual(
1764
+ expect.objectContaining({
1765
+ logicalId: 'FriggS3VPCEndpoint',
1766
+ physicalId: 'vpce-s3-stack',
1767
+ resourceType: 'AWS::EC2::VPCEndpoint'
1768
+ })
1769
+ );
1770
+ expect(result.stackManaged).toContainEqual(
1771
+ expect.objectContaining({
1772
+ logicalId: 'FriggDynamoDBVPCEndpoint',
1773
+ physicalId: 'vpce-ddb-stack',
1774
+ resourceType: 'AWS::EC2::VPCEndpoint'
1775
+ })
1776
+ );
1777
+ expect(result.stackManaged).toContainEqual(
1778
+ expect.objectContaining({
1779
+ logicalId: 'FriggKMSVPCEndpoint',
1780
+ physicalId: 'vpce-kms-stack',
1781
+ resourceType: 'AWS::EC2::VPCEndpoint'
1782
+ })
1783
+ );
1784
+
1785
+ // Should NOT be in external array
1786
+ expect(result.external.some(r => r.physicalId === 'vpce-s3-stack')).toBe(false);
1787
+ expect(result.external.some(r => r.physicalId === 'vpce-ddb-stack')).toBe(false);
1788
+ expect(result.external.some(r => r.physicalId === 'vpce-kms-stack')).toBe(false);
1789
+ });
1790
+
1791
+ it('should add VPC endpoints to external when NOT in existingLogicalIds', () => {
1792
+ const flatDiscovery = {
1793
+ fromCloudFormationStack: false, // AWS API discovery
1794
+ s3VpcEndpointId: 'vpce-s3-external',
1795
+ dynamodbVpcEndpointId: 'vpce-ddb-external'
1796
+ };
1797
+
1798
+ const result = vpcBuilder.convertFlatDiscoveryToStructured(flatDiscovery);
1799
+
1800
+ // Should be in external (AWS discovery)
1801
+ expect(result.external).toContainEqual(
1802
+ expect.objectContaining({
1803
+ physicalId: 'vpce-s3-external',
1804
+ resourceType: 'AWS::EC2::VPCEndpoint',
1805
+ source: 'aws-discovery'
1806
+ })
1807
+ );
1808
+
1809
+ // Should NOT be in stackManaged
1810
+ expect(result.stackManaged.some(r => r.physicalId === 'vpce-s3-external')).toBe(false);
1811
+ });
1812
+
1813
+ it('should preserve existing VPC endpoints and only create missing ones', async () => {
1814
+ const appDefinition = {
1815
+ vpc: { enable: true },
1816
+ encryption: { fieldLevelEncryptionMethod: 'kms' },
1817
+ };
1818
+
1819
+ const discoveredResources = {
1820
+ fromCloudFormationStack: true,
1821
+ stackName: 'test-stack',
1822
+ existingLogicalIds: [
1823
+ 'FriggS3VPCEndpoint', // In stack
1824
+ 'FriggDynamoDBVPCEndpoint', // In stack
1825
+ 'FriggKMSVPCEndpoint' // In stack
1826
+ // SecretsManager and SQS NOT in stack (were deleted)
1827
+ ],
1828
+ defaultVpcId: 'vpc-123',
1829
+ privateSubnetId1: 'subnet-1',
1830
+ privateSubnetId2: 'subnet-2',
1831
+ lambdaSecurityGroupId: 'sg-123',
1832
+ routeTableId: 'rtb-123',
1833
+ // Endpoints in stack
1834
+ s3VpcEndpointId: 'vpce-s3-existing',
1835
+ dynamodbVpcEndpointId: 'vpce-ddb-existing',
1836
+ kmsVpcEndpointId: 'vpce-kms-existing'
1837
+ // secretsManagerVpcEndpointId and sqsVpcEndpointId NOT present
1838
+ };
1839
+
1840
+ const result = await vpcBuilder.build(appDefinition, discoveredResources);
1841
+
1842
+ // Existing endpoints MUST be in template (re-added)
1843
+ expect(result.resources.FriggS3VPCEndpoint).toBeDefined();
1844
+ expect(result.resources.FriggS3VPCEndpoint.Properties.VpcId).toBe('vpc-123');
1845
+
1846
+ expect(result.resources.FriggDynamoDBVPCEndpoint).toBeDefined();
1847
+ expect(result.resources.FriggDynamoDBVPCEndpoint.Properties.VpcId).toBe('vpc-123');
1848
+
1849
+ expect(result.resources.FriggKMSVPCEndpoint).toBeDefined();
1850
+ expect(result.resources.FriggKMSVPCEndpoint.Properties.VpcId).toBe('vpc-123');
1851
+
1852
+ // Missing endpoints should also be created
1853
+ expect(result.resources.FriggSecretsManagerVPCEndpoint).toBeDefined();
1854
+ expect(result.resources.FriggSQSVPCEndpoint).toBeDefined();
1855
+
1856
+ // VPC Endpoint Security Group should be created
1857
+ expect(result.resources.FriggVPCEndpointSecurityGroup).toBeDefined();
1858
+ });
1859
+ });
1860
+
1861
+ describe('convertFlatDiscoveryToStructured - CloudFormation query results', () => {
1862
+ it('should add VPC from CloudFormation query to external array', () => {
1863
+ const flatDiscovery = {
1864
+ fromCloudFormationStack: true,
1865
+ stackName: 'test-stack',
1866
+ existingLogicalIds: ['FriggLambdaRouteTable', 'FriggLambdaSecurityGroup'],
1867
+ // VPC ID was extracted from security group query (NOT a stack resource)
1868
+ defaultVpcId: 'vpc-extracted-from-sg',
1869
+ lambdaSecurityGroupId: 'sg-123',
1870
+ routeTableId: 'rtb-123'
1871
+ };
1872
+
1873
+ const result = vpcBuilder.convertFlatDiscoveryToStructured(flatDiscovery);
1874
+
1875
+ // VPC should be in external array (discovered via query, not in stack)
1876
+ const vpcExternal = result.external.find(r => r.resourceType === 'AWS::EC2::VPC');
1877
+ expect(vpcExternal).toBeDefined();
1878
+ expect(vpcExternal.physicalId).toBe('vpc-extracted-from-sg');
1879
+ expect(vpcExternal.source).toBe('cloudformation-query');
1880
+
1881
+ // Security group SHOULD be in stackManaged (is in stack)
1882
+ const sgStack = result.stackManaged.find(r => r.logicalId === 'FriggLambdaSecurityGroup');
1883
+ expect(sgStack).toBeDefined();
1884
+ expect(sgStack.physicalId).toBe('sg-123');
1885
+ });
1886
+
1887
+ it('should add subnets from route table associations to external array', () => {
1888
+ const flatDiscovery = {
1889
+ fromCloudFormationStack: true,
1890
+ stackName: 'test-stack',
1891
+ existingLogicalIds: ['FriggLambdaRouteTable'],
1892
+ routeTableId: 'rtb-123',
1893
+ // Subnets extracted from route table associations (NOT stack resources)
1894
+ privateSubnetId1: 'subnet-1',
1895
+ privateSubnetId2: 'subnet-2'
1896
+ };
1897
+
1898
+ const result = vpcBuilder.convertFlatDiscoveryToStructured(flatDiscovery);
1899
+
1900
+ // Subnets should be in external array
1901
+ const subnet1 = result.external.find(r => r.physicalId === 'subnet-1');
1902
+ const subnet2 = result.external.find(r => r.physicalId === 'subnet-2');
1903
+
1904
+ expect(subnet1).toBeDefined();
1905
+ expect(subnet1.resourceType).toBe('AWS::EC2::Subnet');
1906
+ expect(subnet1.source).toBe('cloudformation-query');
1907
+
1908
+ expect(subnet2).toBeDefined();
1909
+ expect(subnet2.resourceType).toBe('AWS::EC2::Subnet');
1910
+ expect(subnet2.source).toBe('cloudformation-query');
1911
+ });
1912
+
1913
+ it('should add NAT Gateway from route table queries to external array', () => {
1914
+ const flatDiscovery = {
1915
+ fromCloudFormationStack: true,
1916
+ stackName: 'test-stack',
1917
+ existingLogicalIds: ['FriggLambdaRouteTable', 'FriggPrivateRoute'],
1918
+ routeTableId: 'rtb-123',
1919
+ // NAT Gateway extracted from route table routes (NOT a stack resource)
1920
+ existingNatGatewayId: 'nat-extracted'
1921
+ };
1922
+
1923
+ const result = vpcBuilder.convertFlatDiscoveryToStructured(flatDiscovery);
1924
+
1925
+ // NAT should be in external array
1926
+ const natExternal = result.external.find(r => r.resourceType === 'AWS::EC2::NatGateway');
1927
+ expect(natExternal).toBeDefined();
1928
+ expect(natExternal.physicalId).toBe('nat-extracted');
1929
+ expect(natExternal.source).toBe('cloudformation-query');
1930
+ });
1931
+
1932
+ it('should NOT add resources to external if they are in stack', () => {
1933
+ const flatDiscovery = {
1934
+ fromCloudFormationStack: true,
1935
+ stackName: 'test-stack',
1936
+ existingLogicalIds: ['FriggVPC', 'FriggPrivateSubnet1'],
1937
+ // These ARE in the stack
1938
+ defaultVpcId: 'vpc-in-stack',
1939
+ privateSubnetId1: 'subnet-in-stack'
1940
+ };
1941
+
1942
+ const result = vpcBuilder.convertFlatDiscoveryToStructured(flatDiscovery);
1943
+
1944
+ // Should be in stackManaged, NOT external
1945
+ expect(result.stackManaged.some(r => r.logicalId === 'FriggVPC')).toBe(true);
1946
+ expect(result.stackManaged.some(r => r.logicalId === 'FriggPrivateSubnet1')).toBe(true);
1947
+
1948
+ // Should NOT be in external
1949
+ expect(result.external.some(r => r.physicalId === 'vpc-in-stack')).toBe(false);
1950
+ expect(result.external.some(r => r.physicalId === 'subnet-in-stack')).toBe(false);
1951
+ });
1952
+
1953
+ it('should handle external VPC pattern: stack resources + queried external references', () => {
1954
+ const flatDiscovery = {
1955
+ fromCloudFormationStack: true,
1956
+ stackName: 'test-production-stack',
1957
+ existingLogicalIds: [
1958
+ 'FriggLambdaSecurityGroup',
1959
+ 'FriggLambdaRouteTable',
1960
+ 'FriggPrivateRoute',
1961
+ 'FriggPrivateSubnet1RouteTableAssociation',
1962
+ 'FriggPrivateSubnet2RouteTableAssociation',
1963
+ 'FriggS3VPCEndpoint',
1964
+ 'FriggDynamoDBVPCEndpoint',
1965
+ 'FriggKMSVPCEndpoint'
1966
+ ],
1967
+ // Stack resources
1968
+ lambdaSecurityGroupId: 'sg-stack-123',
1969
+ routeTableId: 'rtb-stack-456',
1970
+ s3VpcEndpointId: 'vpce-s3-stack',
1971
+ // External resources (discovered via queries)
1972
+ defaultVpcId: 'vpc-external-123',
1973
+ privateSubnetId1: 'subnet-external-1',
1974
+ privateSubnetId2: 'subnet-external-2',
1975
+ existingNatGatewayId: 'nat-external-789'
1976
+ };
1977
+
1978
+ const result = vpcBuilder.convertFlatDiscoveryToStructured(flatDiscovery);
1979
+
1980
+ // Stack resources should be in stackManaged
1981
+ expect(result.stackManaged).toEqual(
1982
+ expect.arrayContaining([
1983
+ expect.objectContaining({ logicalId: 'FriggLambdaSecurityGroup', physicalId: 'sg-stack-123' }),
1984
+ expect.objectContaining({ logicalId: 'FriggLambdaRouteTable', physicalId: 'rtb-stack-456' }),
1985
+ expect.objectContaining({ logicalId: 'FriggS3VPCEndpoint', physicalId: 'vpce-s3-stack' })
1986
+ ])
1987
+ );
1988
+
1989
+ // External resources should be in external array
1990
+ expect(result.external).toEqual(
1991
+ expect.arrayContaining([
1992
+ expect.objectContaining({ physicalId: 'vpc-external-123', resourceType: 'AWS::EC2::VPC', source: 'cloudformation-query' }),
1993
+ expect.objectContaining({ physicalId: 'subnet-external-1', resourceType: 'AWS::EC2::Subnet', source: 'cloudformation-query' }),
1994
+ expect.objectContaining({ physicalId: 'subnet-external-2', resourceType: 'AWS::EC2::Subnet', source: 'cloudformation-query' }),
1995
+ expect.objectContaining({ physicalId: 'nat-external-789', resourceType: 'AWS::EC2::NatGateway', source: 'cloudformation-query' })
1996
+ ])
1997
+ );
1998
+ });
1999
+ });
2000
+ });
2001
+