@friggframework/devtools 2.0.0-next.60 → 2.0.0-next.62

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 (305) hide show
  1. package/package.json +14 -7
  2. package/.eslintrc.json +0 -3
  3. package/CHANGELOG.md +0 -132
  4. package/infrastructure/ARCHITECTURE.md +0 -487
  5. package/infrastructure/CLAUDE.md +0 -481
  6. package/infrastructure/HEALTH.md +0 -468
  7. package/infrastructure/README.md +0 -522
  8. package/infrastructure/__tests__/fixtures/mock-aws-resources.js +0 -391
  9. package/infrastructure/__tests__/helpers/test-utils.js +0 -277
  10. package/infrastructure/__tests__/postgres-config.test.js +0 -914
  11. package/infrastructure/__tests__/template-generation.test.js +0 -687
  12. package/infrastructure/create-frigg-infrastructure.js +0 -147
  13. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +0 -630
  14. package/infrastructure/docs/PRE-DEPLOYMENT-HEALTH-CHECK-SPEC.md +0 -1317
  15. package/infrastructure/docs/WEBSOCKET-CONFIGURATION.md +0 -105
  16. package/infrastructure/docs/deployment-instructions.md +0 -268
  17. package/infrastructure/docs/generate-iam-command.md +0 -278
  18. package/infrastructure/docs/iam-policy-templates.md +0 -193
  19. package/infrastructure/domains/database/aurora-builder.js +0 -809
  20. package/infrastructure/domains/database/aurora-builder.test.js +0 -950
  21. package/infrastructure/domains/database/aurora-discovery.js +0 -87
  22. package/infrastructure/domains/database/aurora-discovery.test.js +0 -188
  23. package/infrastructure/domains/database/aurora-resolver.js +0 -210
  24. package/infrastructure/domains/database/aurora-resolver.test.js +0 -347
  25. package/infrastructure/domains/database/migration-builder.js +0 -701
  26. package/infrastructure/domains/database/migration-builder.test.js +0 -321
  27. package/infrastructure/domains/database/migration-resolver.js +0 -163
  28. package/infrastructure/domains/database/migration-resolver.test.js +0 -337
  29. package/infrastructure/domains/health/application/ports/IPropertyReconciler.js +0 -164
  30. package/infrastructure/domains/health/application/ports/IResourceDetector.js +0 -129
  31. package/infrastructure/domains/health/application/ports/IResourceImporter.js +0 -142
  32. package/infrastructure/domains/health/application/ports/IStackRepository.js +0 -131
  33. package/infrastructure/domains/health/application/ports/index.js +0 -26
  34. package/infrastructure/domains/health/application/use-cases/__tests__/execute-resource-import-use-case.test.js +0 -679
  35. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +0 -167
  36. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +0 -1130
  37. package/infrastructure/domains/health/application/use-cases/execute-resource-import-use-case.js +0 -221
  38. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.js +0 -152
  39. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.test.js +0 -343
  40. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.js +0 -535
  41. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.test.js +0 -376
  42. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.js +0 -213
  43. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +0 -441
  44. package/infrastructure/domains/health/docs/ACME-DEV-DRIFT-ANALYSIS.md +0 -267
  45. package/infrastructure/domains/health/docs/BUILD-VS-DEPLOYED-TEMPLATE-ANALYSIS.md +0 -324
  46. package/infrastructure/domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md +0 -386
  47. package/infrastructure/domains/health/docs/SPEC-CLEANUP-COMMAND.md +0 -1419
  48. package/infrastructure/domains/health/docs/TDD-IMPLEMENTATION-SUMMARY.md +0 -391
  49. package/infrastructure/domains/health/docs/TEMPLATE-COMPARISON-IMPLEMENTATION.md +0 -551
  50. package/infrastructure/domains/health/domain/entities/issue.js +0 -299
  51. package/infrastructure/domains/health/domain/entities/issue.test.js +0 -528
  52. package/infrastructure/domains/health/domain/entities/property-mismatch.js +0 -108
  53. package/infrastructure/domains/health/domain/entities/property-mismatch.test.js +0 -275
  54. package/infrastructure/domains/health/domain/entities/resource.js +0 -159
  55. package/infrastructure/domains/health/domain/entities/resource.test.js +0 -432
  56. package/infrastructure/domains/health/domain/entities/stack-health-report.js +0 -306
  57. package/infrastructure/domains/health/domain/entities/stack-health-report.test.js +0 -601
  58. package/infrastructure/domains/health/domain/services/__tests__/health-score-percentage-based.test.js +0 -380
  59. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +0 -971
  60. package/infrastructure/domains/health/domain/services/__tests__/import-template-generator.test.js +0 -1150
  61. package/infrastructure/domains/health/domain/services/__tests__/logical-id-mapper.test.js +0 -672
  62. package/infrastructure/domains/health/domain/services/__tests__/template-parser.test.js +0 -496
  63. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +0 -419
  64. package/infrastructure/domains/health/domain/services/health-score-calculator.js +0 -248
  65. package/infrastructure/domains/health/domain/services/health-score-calculator.test.js +0 -504
  66. package/infrastructure/domains/health/domain/services/import-progress-monitor.js +0 -195
  67. package/infrastructure/domains/health/domain/services/import-template-generator.js +0 -435
  68. package/infrastructure/domains/health/domain/services/logical-id-mapper.js +0 -345
  69. package/infrastructure/domains/health/domain/services/mismatch-analyzer.js +0 -234
  70. package/infrastructure/domains/health/domain/services/mismatch-analyzer.test.js +0 -431
  71. package/infrastructure/domains/health/domain/services/property-mutability-config.js +0 -382
  72. package/infrastructure/domains/health/domain/services/template-parser.js +0 -245
  73. package/infrastructure/domains/health/domain/services/update-progress-monitor.js +0 -192
  74. package/infrastructure/domains/health/domain/value-objects/health-score.js +0 -138
  75. package/infrastructure/domains/health/domain/value-objects/health-score.test.js +0 -267
  76. package/infrastructure/domains/health/domain/value-objects/property-mutability.js +0 -161
  77. package/infrastructure/domains/health/domain/value-objects/property-mutability.test.js +0 -198
  78. package/infrastructure/domains/health/domain/value-objects/resource-state.js +0 -167
  79. package/infrastructure/domains/health/domain/value-objects/resource-state.test.js +0 -196
  80. package/infrastructure/domains/health/domain/value-objects/stack-identifier.js +0 -192
  81. package/infrastructure/domains/health/domain/value-objects/stack-identifier.test.js +0 -262
  82. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-cfn-tagged.test.js +0 -312
  83. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-multi-stack.test.js +0 -367
  84. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +0 -432
  85. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.js +0 -784
  86. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +0 -1133
  87. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.js +0 -565
  88. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +0 -554
  89. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.js +0 -318
  90. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.test.js +0 -398
  91. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.js +0 -777
  92. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.test.js +0 -580
  93. package/infrastructure/domains/integration/integration-builder.js +0 -404
  94. package/infrastructure/domains/integration/integration-builder.test.js +0 -690
  95. package/infrastructure/domains/integration/integration-resolver.js +0 -170
  96. package/infrastructure/domains/integration/integration-resolver.test.js +0 -369
  97. package/infrastructure/domains/integration/websocket-builder.js +0 -69
  98. package/infrastructure/domains/integration/websocket-builder.test.js +0 -195
  99. package/infrastructure/domains/networking/vpc-builder.js +0 -2051
  100. package/infrastructure/domains/networking/vpc-builder.test.js +0 -1960
  101. package/infrastructure/domains/networking/vpc-discovery.js +0 -177
  102. package/infrastructure/domains/networking/vpc-discovery.test.js +0 -350
  103. package/infrastructure/domains/networking/vpc-resolver.js +0 -505
  104. package/infrastructure/domains/networking/vpc-resolver.test.js +0 -801
  105. package/infrastructure/domains/parameters/ssm-builder.js +0 -79
  106. package/infrastructure/domains/parameters/ssm-builder.test.js +0 -189
  107. package/infrastructure/domains/parameters/ssm-discovery.js +0 -84
  108. package/infrastructure/domains/parameters/ssm-discovery.test.js +0 -210
  109. package/infrastructure/domains/security/iam-generator.js +0 -816
  110. package/infrastructure/domains/security/iam-generator.test.js +0 -204
  111. package/infrastructure/domains/security/kms-builder.js +0 -415
  112. package/infrastructure/domains/security/kms-builder.test.js +0 -392
  113. package/infrastructure/domains/security/kms-discovery.js +0 -80
  114. package/infrastructure/domains/security/kms-discovery.test.js +0 -177
  115. package/infrastructure/domains/security/kms-resolver.js +0 -96
  116. package/infrastructure/domains/security/kms-resolver.test.js +0 -216
  117. package/infrastructure/domains/security/templates/frigg-deployment-iam-stack.yaml +0 -401
  118. package/infrastructure/domains/security/templates/iam-policy-basic.json +0 -218
  119. package/infrastructure/domains/security/templates/iam-policy-full.json +0 -288
  120. package/infrastructure/domains/shared/base-builder.js +0 -112
  121. package/infrastructure/domains/shared/base-resolver.js +0 -186
  122. package/infrastructure/domains/shared/base-resolver.test.js +0 -305
  123. package/infrastructure/domains/shared/builder-orchestrator.js +0 -212
  124. package/infrastructure/domains/shared/builder-orchestrator.test.js +0 -213
  125. package/infrastructure/domains/shared/cloudformation-discovery-v2.js +0 -334
  126. package/infrastructure/domains/shared/cloudformation-discovery.js +0 -672
  127. package/infrastructure/domains/shared/cloudformation-discovery.test.js +0 -985
  128. package/infrastructure/domains/shared/environment-builder.js +0 -119
  129. package/infrastructure/domains/shared/environment-builder.test.js +0 -247
  130. package/infrastructure/domains/shared/providers/aws-provider-adapter.js +0 -579
  131. package/infrastructure/domains/shared/providers/aws-provider-adapter.test.js +0 -416
  132. package/infrastructure/domains/shared/providers/azure-provider-adapter.stub.js +0 -93
  133. package/infrastructure/domains/shared/providers/cloud-provider-adapter.js +0 -136
  134. package/infrastructure/domains/shared/providers/gcp-provider-adapter.stub.js +0 -82
  135. package/infrastructure/domains/shared/providers/provider-factory.js +0 -108
  136. package/infrastructure/domains/shared/providers/provider-factory.test.js +0 -170
  137. package/infrastructure/domains/shared/resource-discovery.enhanced.test.js +0 -306
  138. package/infrastructure/domains/shared/resource-discovery.js +0 -233
  139. package/infrastructure/domains/shared/resource-discovery.test.js +0 -588
  140. package/infrastructure/domains/shared/types/app-definition.js +0 -205
  141. package/infrastructure/domains/shared/types/discovery-result.js +0 -106
  142. package/infrastructure/domains/shared/types/discovery-result.test.js +0 -258
  143. package/infrastructure/domains/shared/types/index.js +0 -46
  144. package/infrastructure/domains/shared/types/resource-ownership.js +0 -108
  145. package/infrastructure/domains/shared/types/resource-ownership.test.js +0 -101
  146. package/infrastructure/domains/shared/utilities/base-definition-factory.js +0 -394
  147. package/infrastructure/domains/shared/utilities/base-definition-factory.js.bak +0 -338
  148. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +0 -291
  149. package/infrastructure/domains/shared/utilities/handler-path-resolver.js +0 -134
  150. package/infrastructure/domains/shared/utilities/handler-path-resolver.test.js +0 -268
  151. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +0 -159
  152. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +0 -444
  153. package/infrastructure/domains/shared/validation/env-validator.js +0 -78
  154. package/infrastructure/domains/shared/validation/env-validator.test.js +0 -173
  155. package/infrastructure/domains/shared/validation/plugin-validator.js +0 -187
  156. package/infrastructure/domains/shared/validation/plugin-validator.test.js +0 -323
  157. package/infrastructure/esbuild.config.js +0 -53
  158. package/infrastructure/index.js +0 -4
  159. package/infrastructure/infrastructure-composer.js +0 -117
  160. package/infrastructure/infrastructure-composer.test.js +0 -1895
  161. package/infrastructure/integration.test.js +0 -383
  162. package/infrastructure/scripts/build-prisma-layer.js +0 -701
  163. package/infrastructure/scripts/build-prisma-layer.test.js +0 -170
  164. package/infrastructure/scripts/build-time-discovery.js +0 -238
  165. package/infrastructure/scripts/build-time-discovery.test.js +0 -379
  166. package/infrastructure/scripts/run-discovery.js +0 -110
  167. package/infrastructure/scripts/verify-prisma-layer.js +0 -72
  168. package/layers/prisma/.build-complete +0 -3
  169. package/layers/prisma/nodejs/package.json +0 -8
  170. package/management-ui/.eslintrc.js +0 -22
  171. package/management-ui/components.json +0 -21
  172. package/management-ui/docs/phase2-integration-guide.md +0 -320
  173. package/management-ui/index.html +0 -13
  174. package/management-ui/package.json +0 -76
  175. package/management-ui/packages/devtools/frigg-cli/ui-command/index.js +0 -302
  176. package/management-ui/postcss.config.js +0 -6
  177. package/management-ui/server/api/backend.js +0 -256
  178. package/management-ui/server/api/cli.js +0 -315
  179. package/management-ui/server/api/codegen.js +0 -663
  180. package/management-ui/server/api/connections.js +0 -857
  181. package/management-ui/server/api/discovery.js +0 -185
  182. package/management-ui/server/api/environment/index.js +0 -1
  183. package/management-ui/server/api/environment/router.js +0 -378
  184. package/management-ui/server/api/environment.js +0 -328
  185. package/management-ui/server/api/integrations.js +0 -876
  186. package/management-ui/server/api/logs.js +0 -248
  187. package/management-ui/server/api/monitoring.js +0 -282
  188. package/management-ui/server/api/open-ide.js +0 -31
  189. package/management-ui/server/api/project.js +0 -1029
  190. package/management-ui/server/api/users/sessions.js +0 -371
  191. package/management-ui/server/api/users/simulation.js +0 -254
  192. package/management-ui/server/api/users.js +0 -362
  193. package/management-ui/server/api-contract.md +0 -275
  194. package/management-ui/server/index.js +0 -873
  195. package/management-ui/server/middleware/errorHandler.js +0 -93
  196. package/management-ui/server/middleware/security.js +0 -32
  197. package/management-ui/server/processManager.js +0 -296
  198. package/management-ui/server/server.js +0 -346
  199. package/management-ui/server/services/aws-monitor.js +0 -413
  200. package/management-ui/server/services/npm-registry.js +0 -347
  201. package/management-ui/server/services/template-engine.js +0 -538
  202. package/management-ui/server/utils/cliIntegration.js +0 -220
  203. package/management-ui/server/utils/environment/auditLogger.js +0 -471
  204. package/management-ui/server/utils/environment/awsParameterStore.js +0 -275
  205. package/management-ui/server/utils/environment/encryption.js +0 -278
  206. package/management-ui/server/utils/environment/envFileManager.js +0 -286
  207. package/management-ui/server/utils/import-commonjs.js +0 -28
  208. package/management-ui/server/utils/response.js +0 -83
  209. package/management-ui/server/websocket/handler.js +0 -325
  210. package/management-ui/src/App.jsx +0 -25
  211. package/management-ui/src/assets/FriggLogo.svg +0 -1
  212. package/management-ui/src/components/AppRouter.jsx +0 -65
  213. package/management-ui/src/components/Button.jsx +0 -70
  214. package/management-ui/src/components/Card.jsx +0 -97
  215. package/management-ui/src/components/EnvironmentCompare.jsx +0 -400
  216. package/management-ui/src/components/EnvironmentEditor.jsx +0 -372
  217. package/management-ui/src/components/EnvironmentImportExport.jsx +0 -469
  218. package/management-ui/src/components/EnvironmentSchema.jsx +0 -491
  219. package/management-ui/src/components/EnvironmentSecurity.jsx +0 -463
  220. package/management-ui/src/components/ErrorBoundary.jsx +0 -73
  221. package/management-ui/src/components/IntegrationCard.jsx +0 -481
  222. package/management-ui/src/components/IntegrationCardEnhanced.jsx +0 -770
  223. package/management-ui/src/components/IntegrationExplorer.jsx +0 -379
  224. package/management-ui/src/components/IntegrationStatus.jsx +0 -336
  225. package/management-ui/src/components/Layout.jsx +0 -716
  226. package/management-ui/src/components/LoadingSpinner.jsx +0 -113
  227. package/management-ui/src/components/RepositoryPicker.jsx +0 -248
  228. package/management-ui/src/components/SessionMonitor.jsx +0 -350
  229. package/management-ui/src/components/StatusBadge.jsx +0 -208
  230. package/management-ui/src/components/UserContextSwitcher.jsx +0 -212
  231. package/management-ui/src/components/UserSimulation.jsx +0 -327
  232. package/management-ui/src/components/Welcome.jsx +0 -434
  233. package/management-ui/src/components/codegen/APIEndpointGenerator.jsx +0 -637
  234. package/management-ui/src/components/codegen/APIModuleSelector.jsx +0 -227
  235. package/management-ui/src/components/codegen/CodeGenerationWizard.jsx +0 -247
  236. package/management-ui/src/components/codegen/CodePreviewEditor.jsx +0 -316
  237. package/management-ui/src/components/codegen/DynamicModuleForm.jsx +0 -271
  238. package/management-ui/src/components/codegen/FormBuilder.jsx +0 -737
  239. package/management-ui/src/components/codegen/IntegrationGenerator.jsx +0 -855
  240. package/management-ui/src/components/codegen/ProjectScaffoldWizard.jsx +0 -797
  241. package/management-ui/src/components/codegen/SchemaBuilder.jsx +0 -303
  242. package/management-ui/src/components/codegen/TemplateSelector.jsx +0 -586
  243. package/management-ui/src/components/codegen/index.js +0 -10
  244. package/management-ui/src/components/connections/ConnectionConfigForm.jsx +0 -362
  245. package/management-ui/src/components/connections/ConnectionHealthMonitor.jsx +0 -182
  246. package/management-ui/src/components/connections/ConnectionTester.jsx +0 -200
  247. package/management-ui/src/components/connections/EntityRelationshipMapper.jsx +0 -292
  248. package/management-ui/src/components/connections/OAuthFlow.jsx +0 -204
  249. package/management-ui/src/components/connections/index.js +0 -5
  250. package/management-ui/src/components/index.js +0 -21
  251. package/management-ui/src/components/monitoring/APIGatewayMetrics.jsx +0 -222
  252. package/management-ui/src/components/monitoring/LambdaMetrics.jsx +0 -169
  253. package/management-ui/src/components/monitoring/MetricsChart.jsx +0 -197
  254. package/management-ui/src/components/monitoring/MonitoringDashboard.jsx +0 -393
  255. package/management-ui/src/components/monitoring/SQSMetrics.jsx +0 -246
  256. package/management-ui/src/components/monitoring/index.js +0 -6
  257. package/management-ui/src/components/monitoring/monitoring.css +0 -218
  258. package/management-ui/src/components/theme-provider.jsx +0 -52
  259. package/management-ui/src/components/theme-toggle.jsx +0 -39
  260. package/management-ui/src/components/ui/badge.tsx +0 -36
  261. package/management-ui/src/components/ui/button.test.jsx +0 -56
  262. package/management-ui/src/components/ui/button.tsx +0 -57
  263. package/management-ui/src/components/ui/card.tsx +0 -76
  264. package/management-ui/src/components/ui/dropdown-menu.tsx +0 -199
  265. package/management-ui/src/components/ui/select.tsx +0 -157
  266. package/management-ui/src/components/ui/skeleton.jsx +0 -15
  267. package/management-ui/src/hooks/useFrigg.jsx +0 -387
  268. package/management-ui/src/hooks/useSocket.jsx +0 -58
  269. package/management-ui/src/index.css +0 -193
  270. package/management-ui/src/lib/utils.ts +0 -6
  271. package/management-ui/src/main.jsx +0 -10
  272. package/management-ui/src/pages/CodeGeneration.jsx +0 -14
  273. package/management-ui/src/pages/Connections.jsx +0 -252
  274. package/management-ui/src/pages/ConnectionsEnhanced.jsx +0 -633
  275. package/management-ui/src/pages/Dashboard.jsx +0 -311
  276. package/management-ui/src/pages/Environment.jsx +0 -314
  277. package/management-ui/src/pages/IntegrationConfigure.jsx +0 -669
  278. package/management-ui/src/pages/IntegrationDiscovery.jsx +0 -567
  279. package/management-ui/src/pages/IntegrationTest.jsx +0 -742
  280. package/management-ui/src/pages/Integrations.jsx +0 -253
  281. package/management-ui/src/pages/Monitoring.jsx +0 -17
  282. package/management-ui/src/pages/Simulation.jsx +0 -155
  283. package/management-ui/src/pages/Users.jsx +0 -492
  284. package/management-ui/src/services/api.js +0 -41
  285. package/management-ui/src/services/apiModuleService.js +0 -193
  286. package/management-ui/src/services/websocket-handlers.js +0 -120
  287. package/management-ui/src/test/api/project.test.js +0 -273
  288. package/management-ui/src/test/components/Welcome.test.jsx +0 -378
  289. package/management-ui/src/test/mocks/server.js +0 -178
  290. package/management-ui/src/test/setup.js +0 -61
  291. package/management-ui/src/test/utils/test-utils.jsx +0 -134
  292. package/management-ui/src/utils/repository.js +0 -98
  293. package/management-ui/src/utils/repository.test.js +0 -118
  294. package/management-ui/src/workflows/phase2-integration-workflows.js +0 -884
  295. package/management-ui/tailwind.config.js +0 -63
  296. package/management-ui/tsconfig.json +0 -37
  297. package/management-ui/tsconfig.node.json +0 -10
  298. package/management-ui/vite.config.js +0 -26
  299. package/management-ui/vitest.config.js +0 -38
  300. package/test/auther-definition-method-tester.js +0 -45
  301. package/test/index.js +0 -9
  302. package/test/integration-validator.js +0 -2
  303. package/test/mock-api-readme.md +0 -102
  304. package/test/mock-api.js +0 -284
  305. package/test/mock-integration.js +0 -78
@@ -1,672 +0,0 @@
1
- /**
2
- * CloudFormation-based Resource Discovery
3
- *
4
- * Domain Service - Hexagonal Architecture
5
- *
6
- * Discovers resources from existing CloudFormation stacks as the primary
7
- * source of truth before falling back to direct AWS API discovery.
8
- *
9
- * Benefits:
10
- * - Faster discovery (1 CF call vs multiple AWS API calls)
11
- * - More accurate (stack is source of truth)
12
- * - Eliminates tagging dependencies
13
- * - Idempotent (discover mode reuses stack resources)
14
- */
15
-
16
- class CloudFormationDiscovery {
17
- constructor(provider, config = {}) {
18
- this.provider = provider;
19
- this.serviceName = config.serviceName;
20
- this.stage = config.stage;
21
- }
22
-
23
- /**
24
- * Discover resources from an existing CloudFormation stack
25
- *
26
- * @param {string} stackName - Name of the CloudFormation stack
27
- * @returns {Promise<Object|null>} Discovered resources or null if stack doesn't exist
28
- */
29
- async discoverFromStack(stackName) {
30
- try {
31
- // Store stack name for use in helper methods
32
- this.currentStackName = stackName;
33
-
34
- // Try to get the stack
35
- const stack = await this.provider.describeStack(stackName);
36
-
37
- // Get stack resources
38
- const resources = await this.provider.listStackResources(stackName);
39
-
40
- // Extract discovered resources from outputs and resources
41
- const discovered = {
42
- // Metadata to indicate resources came from CloudFormation stack
43
- fromCloudFormationStack: true,
44
- stackName: stackName,
45
- existingLogicalIds: []
46
- };
47
-
48
- // Extract from outputs
49
- if (stack.Outputs && stack.Outputs.length > 0) {
50
- this._extractFromOutputs(stack.Outputs, discovered);
51
- }
52
-
53
- // Extract from resources (now async to query AWS for details)
54
- // Always call this even if resources is empty, as it may query AWS for resources
55
- await this._extractFromResources(resources || [], discovered);
56
-
57
- // Clean up metadata if no resources were discovered
58
- if (discovered.existingLogicalIds.length === 0) {
59
- delete discovered.existingLogicalIds;
60
- }
61
-
62
- return discovered;
63
- } catch (error) {
64
- // Stack doesn't exist - return null to trigger fallback discovery
65
- if (error.message && error.message.includes('does not exist')) {
66
- return null;
67
- }
68
-
69
- // Other errors - log and return null
70
- console.warn(`⚠️ CloudFormation discovery failed: ${error.message}`);
71
- return null;
72
- }
73
- }
74
-
75
- /**
76
- * Extract discovered resources from CloudFormation stack outputs
77
- *
78
- * @private
79
- * @param {Array} outputs - CloudFormation stack outputs
80
- * @param {Object} discovered - Object to populate with discovered resources
81
- */
82
- _extractFromOutputs(outputs, discovered) {
83
- const outputMap = outputs.reduce((acc, output) => {
84
- acc[output.OutputKey] = output.OutputValue;
85
- return acc;
86
- }, {});
87
-
88
- // VPC outputs
89
- if (outputMap.VpcId) {
90
- discovered.defaultVpcId = outputMap.VpcId; // VpcBuilder expects 'defaultVpcId'
91
- }
92
-
93
- if (outputMap.PrivateSubnetIds) {
94
- // Handle comma-separated subnet IDs
95
- discovered.privateSubnetIds = outputMap.PrivateSubnetIds.split(',').map(id => id.trim());
96
- }
97
-
98
- if (outputMap.PublicSubnetId) {
99
- discovered.publicSubnetId = outputMap.PublicSubnetId;
100
- }
101
-
102
- if (outputMap.SecurityGroupId) {
103
- discovered.securityGroupId = outputMap.SecurityGroupId;
104
- }
105
-
106
- // KMS outputs
107
- if (outputMap.KMS_KEY_ARN) {
108
- discovered.defaultKmsKeyId = outputMap.KMS_KEY_ARN;
109
- }
110
-
111
- // Database outputs (if exposed)
112
- if (outputMap.DatabaseEndpoint) {
113
- discovered.databaseEndpoint = outputMap.DatabaseEndpoint;
114
- }
115
- }
116
-
117
- /**
118
- * Extract external resource references from stack resource properties
119
- *
120
- * When VPC/subnets/NAT are external, they're referenced in routing resources' properties.
121
- * We query EC2 to get the actual VPC ID, NAT Gateway ID, and subnet IDs from the route table.
122
- *
123
- * @private
124
- * @param {Array} resources - CloudFormation stack resources
125
- * @param {Object} discovered - Object to populate with discovered resources
126
- */
127
- async _extractExternalReferencesFromStackResources(resources, discovered) {
128
- if (!this.provider || !this.provider.getEC2Client) {
129
- console.log(' ℹ Skipping external reference extraction (EC2 client not available)');
130
- return;
131
- }
132
-
133
- try {
134
- // If we found a route table in the stack, query EC2 for its details
135
- // This gives us VPC ID, NAT Gateway ID, and subnet IDs
136
- if (discovered.routeTableId) {
137
- try {
138
- console.log(` ℹ Querying route table ${discovered.routeTableId} for external references...`);
139
- const { DescribeRouteTablesCommand } = require('@aws-sdk/client-ec2');
140
- const ec2 = this.provider.getEC2Client();
141
- const rtResponse = await ec2.send(new DescribeRouteTablesCommand({
142
- RouteTableIds: [discovered.routeTableId]
143
- }));
144
-
145
- if (rtResponse.RouteTables && rtResponse.RouteTables.length > 0) {
146
- const routeTable = rtResponse.RouteTables[0];
147
-
148
- // Extract VPC ID
149
- if (routeTable.VpcId && !discovered.defaultVpcId) {
150
- discovered.defaultVpcId = routeTable.VpcId;
151
- console.log(` ✓ Extracted VPC ID from route table: ${routeTable.VpcId}`);
152
- }
153
-
154
- // Extract NAT Gateway ID from routes
155
- const natRoute = routeTable.Routes?.find(r => r.NatGatewayId);
156
- if (natRoute && natRoute.NatGatewayId && !discovered.natGatewayId) {
157
- discovered.natGatewayId = natRoute.NatGatewayId;
158
- discovered.existingNatGatewayId = natRoute.NatGatewayId;
159
- console.log(` ✓ Extracted NAT Gateway ID from routes: ${natRoute.NatGatewayId}`);
160
- }
161
-
162
- // Extract subnet IDs from route table associations
163
- const associations = routeTable.Associations || [];
164
- const subnetAssociations = associations.filter(a => a.SubnetId);
165
-
166
-
167
- if (subnetAssociations.length >= 1 && !discovered.privateSubnetId1) {
168
- discovered.privateSubnetId1 = subnetAssociations[0].SubnetId;
169
- console.log(` ✓ Extracted private subnet 1 from associations: ${subnetAssociations[0].SubnetId}`);
170
- }
171
- if (subnetAssociations.length >= 2 && !discovered.privateSubnetId2) {
172
- discovered.privateSubnetId2 = subnetAssociations[1].SubnetId;
173
- console.log(` ✓ Extracted private subnet 2 from associations: ${subnetAssociations[1].SubnetId}`);
174
- }
175
-
176
- // Query for default security group in the VPC (matches canary behavior)
177
- if (routeTable.VpcId && !discovered.defaultSecurityGroupId) {
178
- try {
179
- const { DescribeSecurityGroupsCommand } = require('@aws-sdk/client-ec2');
180
- const sgResponse = await ec2.send(new DescribeSecurityGroupsCommand({
181
- Filters: [
182
- { Name: 'vpc-id', Values: [routeTable.VpcId] },
183
- { Name: 'group-name', Values: ['default'] }
184
- ]
185
- }));
186
-
187
- if (sgResponse.SecurityGroups && sgResponse.SecurityGroups.length > 0) {
188
- discovered.defaultSecurityGroupId = sgResponse.SecurityGroups[0].GroupId;
189
- console.log(` ✓ Extracted default security group: ${discovered.defaultSecurityGroupId}`);
190
- }
191
- } catch (error) {
192
- console.warn(` ⚠️ Could not query default security group: ${error.message}`);
193
- }
194
- }
195
- }
196
- } catch (error) {
197
- console.warn(` ⚠️ Could not query route table for external references: ${error.message}`);
198
- }
199
- }
200
- } catch (error) {
201
- console.warn(` ⚠️ Error extracting external references: ${error.message}`);
202
- }
203
- }
204
-
205
- /**
206
- * Extract discovered resources from CloudFormation stack resources
207
- *
208
- * @private
209
- * @param {Array} resources - CloudFormation stack resources
210
- * @param {Object} discovered - Object to populate with discovered resources
211
- */
212
- async _extractFromResources(resources, discovered) {
213
-
214
- // Initialize existingLogicalIds array if not present
215
- if (!discovered.existingLogicalIds) {
216
- discovered.existingLogicalIds = [];
217
- }
218
-
219
- for (const resource of resources) {
220
- const { LogicalResourceId, PhysicalResourceId, ResourceType } = resource;
221
-
222
- // Track Frigg-managed resources by logical ID
223
- // Include VPC endpoints with legacy naming (VPCEndpointS3, VPCEndpointDynamoDB, etc.)
224
- if (LogicalResourceId.startsWith('Frigg') ||
225
- LogicalResourceId.includes('Migration') ||
226
- LogicalResourceId.startsWith('VPCEndpoint')) {
227
- discovered.existingLogicalIds.push(LogicalResourceId);
228
- }
229
-
230
-
231
- // Security Group - use to get VPC ID
232
- if (LogicalResourceId === 'FriggLambdaSecurityGroup' && ResourceType === 'AWS::EC2::SecurityGroup') {
233
- discovered.securityGroupId = PhysicalResourceId;
234
- console.log(` ✓ Found security group in stack: ${PhysicalResourceId}`);
235
-
236
- // Query security group to get VPC ID (required because SG resource doesn't include VPC ID)
237
- if (this.provider && this.provider.getEC2Client && !discovered.defaultVpcId) {
238
- try {
239
- console.log(` Querying EC2 to get VPC ID from security group...`);
240
- const { DescribeSecurityGroupsCommand } = require('@aws-sdk/client-ec2');
241
- const ec2Client = this.provider.getEC2Client();
242
- const sgDetails = await ec2Client.send(
243
- new DescribeSecurityGroupsCommand({
244
- GroupIds: [PhysicalResourceId]
245
- })
246
- );
247
-
248
- if (sgDetails.SecurityGroups && sgDetails.SecurityGroups.length > 0) {
249
- const vpcId = sgDetails.SecurityGroups[0].VpcId;
250
- discovered.defaultVpcId = vpcId;
251
- console.log(` ✓ Extracted VPC ID from security group: ${vpcId}`);
252
-
253
- // Now query for the default security group in this VPC
254
- if (!discovered.defaultSecurityGroupId) {
255
- try {
256
- console.log(` Querying for default security group in VPC...`);
257
- const defaultSgResponse = await ec2Client.send(
258
- new DescribeSecurityGroupsCommand({
259
- Filters: [
260
- { Name: 'vpc-id', Values: [vpcId] },
261
- { Name: 'group-name', Values: ['default'] }
262
- ]
263
- })
264
- );
265
-
266
- if (defaultSgResponse.SecurityGroups && defaultSgResponse.SecurityGroups.length > 0) {
267
- discovered.defaultSecurityGroupId = defaultSgResponse.SecurityGroups[0].GroupId;
268
- console.log(` ✓ Discovered default security group: ${discovered.defaultSecurityGroupId}`);
269
- }
270
- } catch (error) {
271
- console.warn(` ⚠️ Could not query default security group: ${error.message}`);
272
- }
273
- }
274
- } else {
275
- console.warn(` ⚠️ Security group query returned no results`);
276
- }
277
- } catch (error) {
278
- console.warn(` ⚠️ Could not get VPC from security group: ${error.message}`);
279
- }
280
- }
281
- }
282
-
283
- // Aurora cluster - query AWS to get endpoint details
284
- if (LogicalResourceId === 'FriggAuroraCluster' && ResourceType === 'AWS::RDS::DBCluster') {
285
- discovered.auroraClusterId = PhysicalResourceId;
286
- console.log(` ✓ Found Aurora cluster in stack: ${PhysicalResourceId}`);
287
-
288
- // Query RDS to get cluster endpoint
289
- if (this.provider && !discovered.auroraClusterEndpoint) {
290
- try {
291
- console.log(` Querying RDS to get Aurora endpoint...`);
292
- const { DescribeDBClustersCommand } = require('@aws-sdk/client-rds');
293
- const { RDSClient } = require('@aws-sdk/client-rds');
294
-
295
- const rdsClient = new RDSClient({ region: this.provider.region });
296
- const clusterDetails = await rdsClient.send(
297
- new DescribeDBClustersCommand({
298
- DBClusterIdentifier: PhysicalResourceId
299
- })
300
- );
301
-
302
- if (clusterDetails.DBClusters && clusterDetails.DBClusters.length > 0) {
303
- const cluster = clusterDetails.DBClusters[0];
304
- discovered.auroraClusterEndpoint = cluster.Endpoint;
305
- discovered.auroraClusterPort = cluster.Port;
306
- discovered.auroraClusterIdentifier = cluster.DBClusterIdentifier;
307
- console.log(` ✓ Extracted Aurora endpoint: ${cluster.Endpoint}:${cluster.Port}`);
308
- } else {
309
- console.warn(` ⚠️ RDS cluster query returned no results`);
310
- }
311
- } catch (error) {
312
- console.warn(` ⚠️ Could not get endpoint from Aurora cluster: ${error.message}`);
313
- }
314
- }
315
- }
316
-
317
- // Migration status bucket
318
- if (LogicalResourceId === 'FriggMigrationStatusBucket' && ResourceType === 'AWS::S3::Bucket') {
319
- discovered.migrationStatusBucket = PhysicalResourceId;
320
- }
321
-
322
- // Migration queue
323
- if (LogicalResourceId === 'DbMigrationQueue' && ResourceType === 'AWS::SQS::Queue') {
324
- discovered.migrationQueueUrl = PhysicalResourceId;
325
- }
326
-
327
- // NAT Gateway
328
- if (LogicalResourceId === 'FriggNatGateway' && ResourceType === 'AWS::EC2::NatGateway') {
329
- discovered.natGatewayId = PhysicalResourceId;
330
- }
331
-
332
- // Route Table (Lambda route table for external VPC pattern)
333
- if (LogicalResourceId === 'FriggLambdaRouteTable' && ResourceType === 'AWS::EC2::RouteTable') {
334
- discovered.routeTableId = PhysicalResourceId;
335
- discovered.privateRouteTableId = PhysicalResourceId;
336
- console.log(` ✓ Found route table in stack: ${PhysicalResourceId}`);
337
- }
338
-
339
- // NAT Route (proves NAT configuration exists) - support both naming patterns
340
- if ((LogicalResourceId === 'FriggNATRoute' || LogicalResourceId === 'FriggPrivateRoute') &&
341
- ResourceType === 'AWS::EC2::Route') {
342
- discovered.natRoute = PhysicalResourceId;
343
- console.log(` ✓ Found NAT route in stack: ${LogicalResourceId}`);
344
- }
345
-
346
- // Route Table Associations (links subnets to route table)
347
- if (LogicalResourceId.includes('RouteAssociation') &&
348
- ResourceType === 'AWS::EC2::SubnetRouteTableAssociation') {
349
- if (!discovered.routeTableAssociations) {
350
- discovered.routeTableAssociations = [];
351
- }
352
- discovered.routeTableAssociations.push(PhysicalResourceId);
353
- console.log(` ✓ Found route table association: ${LogicalResourceId}`);
354
-
355
- // Store association ID to query later for subnet extraction (after loop)
356
- if (this.provider && this.provider.getEC2Client &&
357
- (LogicalResourceId === 'FriggSubnet1RouteAssociation' || LogicalResourceId === 'FriggPrivateSubnet1RouteTableAssociation')) {
358
- discovered._subnet1AssociationId = PhysicalResourceId;
359
- }
360
- if (this.provider && this.provider.getEC2Client &&
361
- (LogicalResourceId === 'FriggSubnet2RouteAssociation' || LogicalResourceId === 'FriggPrivateSubnet2RouteTableAssociation')) {
362
- discovered._subnet2AssociationId = PhysicalResourceId;
363
- }
364
- }
365
-
366
- // VPC - direct extraction (primary method)
367
- if (LogicalResourceId === 'FriggVPC' && ResourceType === 'AWS::EC2::VPC') {
368
- discovered.defaultVpcId = PhysicalResourceId;
369
- console.log(` ✓ Found VPC in stack: ${PhysicalResourceId}`);
370
- }
371
-
372
- // KMS Key (alternative to output)
373
- if (LogicalResourceId === 'FriggKMSKey' && ResourceType === 'AWS::KMS::Key') {
374
- // Note: For KMS, we prefer the ARN from outputs, but this is a fallback
375
- if (!discovered.defaultKmsKeyId) {
376
- discovered.defaultKmsKeyId = PhysicalResourceId;
377
- }
378
- }
379
-
380
- // KMS Key Alias - query to get the actual key ARN
381
- if (LogicalResourceId === 'FriggKMSKeyAlias' && ResourceType === 'AWS::KMS::Alias') {
382
- discovered.kmsKeyAlias = PhysicalResourceId;
383
- console.log(` ✓ Found KMS key alias in stack: ${PhysicalResourceId}`);
384
-
385
- // Query KMS to get the key ARN that this alias points to
386
- // Always query even if key is already set, to ensure consistency
387
- if (this.provider && this.provider.describeKmsKey) {
388
- try {
389
- console.log(` Querying KMS to get key ARN from alias...`);
390
- const keyMetadata = await this.provider.describeKmsKey(PhysicalResourceId);
391
-
392
- if (keyMetadata) {
393
- discovered.defaultKmsKeyId = keyMetadata.Arn;
394
- console.log(` ✓ Extracted KMS key ARN from alias: ${discovered.defaultKmsKeyId}`);
395
- } else {
396
- console.warn(` ⚠️ KMS key query returned no metadata`);
397
- }
398
- } catch (error) {
399
- console.warn(` ⚠️ Could not get key ARN from alias: ${error.message}`);
400
- }
401
- }
402
- }
403
-
404
- // Subnets
405
- if (LogicalResourceId === 'FriggPrivateSubnet1' && ResourceType === 'AWS::EC2::Subnet') {
406
- discovered.privateSubnetId1 = PhysicalResourceId;
407
- }
408
- if (LogicalResourceId === 'FriggPrivateSubnet2' && ResourceType === 'AWS::EC2::Subnet') {
409
- discovered.privateSubnetId2 = PhysicalResourceId;
410
- }
411
- if (LogicalResourceId === 'FriggPublicSubnet' && ResourceType === 'AWS::EC2::Subnet') {
412
- discovered.publicSubnetId1 = PhysicalResourceId;
413
- }
414
- if (LogicalResourceId === 'FriggPublicSubnet2' && ResourceType === 'AWS::EC2::Subnet') {
415
- discovered.publicSubnetId2 = PhysicalResourceId;
416
- }
417
-
418
- // Route Tables
419
- if (LogicalResourceId === 'FriggLambdaRouteTable' && ResourceType === 'AWS::EC2::RouteTable') {
420
- discovered.routeTableId = PhysicalResourceId;
421
- }
422
-
423
- // VPC Endpoint Security Group
424
- if (LogicalResourceId === 'FriggVPCEndpointSecurityGroup' && ResourceType === 'AWS::EC2::SecurityGroup') {
425
- discovered.vpcEndpointSecurityGroupId = PhysicalResourceId;
426
- console.log(` ✓ Found VPC endpoint security group in stack: ${PhysicalResourceId}`);
427
- }
428
-
429
- // Lambda Security Group (if created in stack)
430
- if (LogicalResourceId === 'FriggLambdaSecurityGroup' && ResourceType === 'AWS::EC2::SecurityGroup') {
431
- discovered.lambdaSecurityGroupId = PhysicalResourceId;
432
- // DO NOT overwrite defaultSecurityGroupId - that should only be the VPC's default SG
433
- console.log(` ✓ Found Lambda security group in stack: ${PhysicalResourceId}`);
434
- }
435
-
436
- // VPC Endpoints - support both old and new naming conventions
437
- // Initialize vpcEndpoints object for structured access
438
- if (!discovered.vpcEndpoints) {
439
- discovered.vpcEndpoints = {};
440
- }
441
-
442
- // S3 Endpoint (both naming patterns)
443
- if ((LogicalResourceId === 'FriggS3VPCEndpoint' || LogicalResourceId === 'VPCEndpointS3') &&
444
- ResourceType === 'AWS::EC2::VPCEndpoint') {
445
- discovered.s3VpcEndpointId = PhysicalResourceId;
446
- discovered.vpcEndpoints.s3 = PhysicalResourceId;
447
- console.log(` ✓ Found S3 VPC endpoint in stack: ${PhysicalResourceId}`);
448
- }
449
-
450
- // DynamoDB Endpoint (both naming patterns)
451
- if ((LogicalResourceId === 'FriggDynamoDBVPCEndpoint' || LogicalResourceId === 'VPCEndpointDynamoDB') &&
452
- ResourceType === 'AWS::EC2::VPCEndpoint') {
453
- discovered.dynamodbVpcEndpointId = PhysicalResourceId; // Note: all lowercase for consistency
454
- discovered.vpcEndpoints.dynamodb = PhysicalResourceId;
455
- console.log(` ✓ Found DynamoDB VPC endpoint in stack: ${PhysicalResourceId}`);
456
- }
457
-
458
- // KMS Endpoint (both naming patterns)
459
- if ((LogicalResourceId === 'FriggKMSVPCEndpoint' || LogicalResourceId === 'VPCEndpointKMS') &&
460
- ResourceType === 'AWS::EC2::VPCEndpoint') {
461
- discovered.kmsVpcEndpointId = PhysicalResourceId;
462
- discovered.vpcEndpoints.kms = PhysicalResourceId;
463
- console.log(` ✓ Found KMS VPC endpoint in stack: ${PhysicalResourceId}`);
464
- }
465
-
466
- // Secrets Manager Endpoint
467
- if (LogicalResourceId === 'FriggSecretsManagerVPCEndpoint' && ResourceType === 'AWS::EC2::VPCEndpoint') {
468
- discovered.secretsManagerVpcEndpointId = PhysicalResourceId;
469
- discovered.vpcEndpoints.secretsManager = PhysicalResourceId;
470
- }
471
-
472
- // SQS Endpoint
473
- if (LogicalResourceId === 'FriggSQSVPCEndpoint' && ResourceType === 'AWS::EC2::VPCEndpoint') {
474
- discovered.sqsVpcEndpointId = PhysicalResourceId;
475
- discovered.vpcEndpoints.sqs = PhysicalResourceId;
476
- }
477
- }
478
-
479
- // Extract VPC ID and other external references from routing resource properties
480
- // This handles the pattern where VPC is external but routing is in the stack
481
- await this._extractExternalReferencesFromStackResources(resources, discovered);
482
-
483
- // If we have a VPC ID but no subnet IDs, query EC2 for Frigg-managed subnets
484
- if (discovered.defaultVpcId && this.provider &&
485
- !discovered.privateSubnetId1 && !discovered.publicSubnetId1) {
486
- try {
487
- console.log(' Querying EC2 for Frigg-managed subnets...');
488
- const { DescribeSubnetsCommand } = require('@aws-sdk/client-ec2');
489
- const subnetResponse = await this.provider.getEC2Client().send(
490
- new DescribeSubnetsCommand({
491
- Filters: [
492
- { Name: 'vpc-id', Values: [discovered.defaultVpcId] },
493
- { Name: 'tag:ManagedBy', Values: ['Frigg'] },
494
- ],
495
- })
496
- );
497
-
498
- if (subnetResponse.Subnets && subnetResponse.Subnets.length > 0) {
499
- // Extract subnet IDs by logical ID from tags
500
- const subnets = subnetResponse.Subnets.map(subnet => ({
501
- subnetId: subnet.SubnetId,
502
- logicalId: subnet.Tags?.find(t => t.Key === 'aws:cloudformation:logical-id')?.Value,
503
- isPublic: subnet.MapPublicIpOnLaunch,
504
- }));
505
-
506
- // Find private subnets
507
- const privateSubnets = subnets.filter(s => !s.isPublic).sort((a, b) =>
508
- a.logicalId?.localeCompare(b.logicalId) || 0
509
- );
510
- if (privateSubnets.length >= 1) {
511
- discovered.privateSubnetId1 = privateSubnets[0].subnetId;
512
- }
513
- if (privateSubnets.length >= 2) {
514
- discovered.privateSubnetId2 = privateSubnets[1].subnetId;
515
- }
516
-
517
- // Find public subnets
518
- const publicSubnets = subnets.filter(s => s.isPublic).sort((a, b) =>
519
- a.logicalId?.localeCompare(b.logicalId) || 0
520
- );
521
- if (publicSubnets.length >= 1) {
522
- discovered.publicSubnetId1 = publicSubnets[0].subnetId;
523
- }
524
- if (publicSubnets.length >= 2) {
525
- discovered.publicSubnetId2 = publicSubnets[1].subnetId;
526
- }
527
-
528
- console.log(` ✓ Found ${subnets.length} Frigg-managed subnets via EC2 query`);
529
- }
530
- } catch (error) {
531
- console.warn(` ⚠️ Could not query EC2 for subnets: ${error.message}`);
532
- }
533
- }
534
-
535
- // If we have VPC and route table but no subnets, query VPC for all subnets and filter by route table
536
- // This approach queries by VPC ID (vpc-id filter) and route table ID (RouteTableIds parameter)
537
- // Handles edge case where route table Associations array is empty in DescribeRouteTables response
538
- if (discovered.defaultVpcId && !discovered.privateSubnetId1 &&
539
- discovered.routeTableId && this.provider && this.provider.getEC2Client) {
540
- try {
541
- console.log(` Querying ALL subnets in VPC ${discovered.defaultVpcId}...`);
542
- const { DescribeSubnetsCommand } = require('@aws-sdk/client-ec2');
543
- const ec2 = this.provider.getEC2Client();
544
-
545
- const subnetsResponse = await ec2.send(new DescribeSubnetsCommand({
546
- Filters: [{ Name: 'vpc-id', Values: [discovered.defaultVpcId] }]
547
- }));
548
-
549
- console.log(` Found ${subnetsResponse.Subnets?.length || 0} total subnets in VPC`);
550
-
551
- if (subnetsResponse.Subnets && subnetsResponse.Subnets.length > 0) {
552
- // Get route table to find associated subnets
553
- const { DescribeRouteTablesCommand } = require('@aws-sdk/client-ec2');
554
- const rtResponse = await ec2.send(new DescribeRouteTablesCommand({
555
- RouteTableIds: [discovered.routeTableId]
556
- }));
557
-
558
- if (rtResponse.RouteTables && rtResponse.RouteTables[0]) {
559
- const associations = rtResponse.RouteTables[0].Associations || [];
560
- const associatedSubnetIds = associations
561
- .filter(a => a.SubnetId)
562
- .map(a => a.SubnetId);
563
-
564
- console.log(` Route table has ${associatedSubnetIds.length} associated subnets: ${associatedSubnetIds.join(', ')}`);
565
-
566
- // Use the associated subnets if available
567
- if (associatedSubnetIds.length >= 2) {
568
- discovered.privateSubnetId1 = associatedSubnetIds[0];
569
- discovered.privateSubnetId2 = associatedSubnetIds[1];
570
- console.log(` ✓ Extracted subnets from route table associations: ${discovered.privateSubnetId1}, ${discovered.privateSubnetId2}`);
571
- } else if (associatedSubnetIds.length === 1) {
572
- // Only 1 associated subnet, use another subnet from VPC as backup
573
- discovered.privateSubnetId1 = associatedSubnetIds[0];
574
- discovered.privateSubnetId2 = subnetsResponse.Subnets.find(s => s.SubnetId !== associatedSubnetIds[0])?.SubnetId;
575
- console.log(` ✓ Extracted subnets (1 from route table, 1 fallback): ${discovered.privateSubnetId1}, ${discovered.privateSubnetId2}`);
576
- } else if (subnetsResponse.Subnets.length >= 2) {
577
- // Edge case: route table Associations array is empty even when queried by ID
578
- // This can happen when associations exist in CloudFormation but AWS API doesn't return them
579
- // Fallback: Use first 2 subnets from VPC (all subnets in same VPC should work)
580
- discovered.privateSubnetId1 = subnetsResponse.Subnets[0].SubnetId;
581
- discovered.privateSubnetId2 = subnetsResponse.Subnets[1].SubnetId;
582
- console.log(` ✓ Using first 2 subnets from VPC (route table Associations empty): ${discovered.privateSubnetId1}, ${discovered.privateSubnetId2}`);
583
- }
584
- }
585
- }
586
- } catch (error) {
587
- console.warn(` ⚠️ Could not query subnets from VPC: ${error.message}`);
588
- }
589
- }
590
-
591
- // FALLBACK: Extract subnet IDs from route table associations (if VPC query didn't work)
592
- if (!discovered.privateSubnetId1 && discovered._subnet1AssociationId && this.provider && this.provider.getEC2Client) {
593
- try {
594
- console.log(` Querying EC2 for subnet from association ${discovered._subnet1AssociationId}...`);
595
- const { DescribeRouteTablesCommand } = require('@aws-sdk/client-ec2');
596
- const ec2 = this.provider.getEC2Client();
597
-
598
- // Query route table by association ID to get subnet
599
- const rtResponse = await ec2.send(new DescribeRouteTablesCommand({
600
- Filters: [
601
- { Name: 'association.route-table-association-id', Values: [discovered._subnet1AssociationId] }
602
- ]
603
- }));
604
-
605
- if (rtResponse.RouteTables && rtResponse.RouteTables[0]) {
606
- const assoc = rtResponse.RouteTables[0].Associations.find(a =>
607
- a.RouteTableAssociationId === discovered._subnet1AssociationId
608
- );
609
- if (assoc && assoc.SubnetId) {
610
- discovered.privateSubnetId1 = assoc.SubnetId;
611
- console.log(` ✓ Extracted private subnet 1 from association query: ${assoc.SubnetId}`);
612
- }
613
- }
614
- } catch (error) {
615
- console.warn(` ⚠️ Could not query subnet from association: ${error.message}`);
616
- }
617
- }
618
-
619
- if (!discovered.privateSubnetId2 && discovered._subnet2AssociationId && this.provider && this.provider.getEC2Client) {
620
- try {
621
- const { DescribeRouteTablesCommand } = require('@aws-sdk/client-ec2');
622
- const ec2 = this.provider.getEC2Client();
623
-
624
- const rtResponse = await ec2.send(new DescribeRouteTablesCommand({
625
- Filters: [
626
- { Name: 'association.route-table-association-id', Values: [discovered._subnet2AssociationId] }
627
- ]
628
- }));
629
-
630
- if (rtResponse.RouteTables && rtResponse.RouteTables[0]) {
631
- const assoc = rtResponse.RouteTables[0].Associations.find(a =>
632
- a.RouteTableAssociationId === discovered._subnet2AssociationId
633
- );
634
- if (assoc && assoc.SubnetId) {
635
- discovered.privateSubnetId2 = assoc.SubnetId;
636
- console.log(` ✓ Extracted private subnet 2 from association query: ${assoc.SubnetId}`);
637
- }
638
- }
639
- } catch (error) {
640
- console.warn(` ⚠️ Could not query subnet from association: ${error.message}`);
641
- }
642
- }
643
-
644
- // Clean up temporary association IDs
645
- delete discovered._subnet1AssociationId;
646
- delete discovered._subnet2AssociationId;
647
-
648
- // Check for KMS key alias via AWS API if not found in stack resources
649
- // This handles cases where the alias was created outside CloudFormation
650
- if (!discovered.defaultKmsKeyId && !discovered.kmsKeyAlias &&
651
- this.provider && this.provider.describeKmsKey && this.serviceName && this.stage) {
652
- try {
653
- const aliasName = `alias/${this.serviceName}-${this.stage}-frigg-kms`;
654
- console.log(` Querying KMS for alias: ${aliasName}...`);
655
-
656
- const keyMetadata = await this.provider.describeKmsKey(aliasName);
657
-
658
- if (keyMetadata) {
659
- discovered.defaultKmsKeyId = keyMetadata.Arn;
660
- discovered.kmsKeyAlias = aliasName;
661
- console.log(` ✓ Found KMS key via alias query: ${discovered.defaultKmsKeyId}`);
662
- }
663
- } catch (error) {
664
- // Alias not found - this is expected if no KMS key exists yet
665
- console.log(` ℹ No KMS key alias found via AWS API`);
666
- }
667
- }
668
- }
669
- }
670
-
671
- module.exports = { CloudFormationDiscovery };
672
-