@friggframework/devtools 2.0.0-next.45 → 2.0.0-next.47

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 (212) hide show
  1. package/infrastructure/ARCHITECTURE.md +487 -0
  2. package/infrastructure/HEALTH.md +468 -0
  3. package/infrastructure/README.md +51 -0
  4. package/infrastructure/__tests__/postgres-config.test.js +914 -0
  5. package/infrastructure/__tests__/template-generation.test.js +687 -0
  6. package/infrastructure/create-frigg-infrastructure.js +1 -1
  7. package/infrastructure/docs/POSTGRES-CONFIGURATION.md +630 -0
  8. package/infrastructure/{DEPLOYMENT-INSTRUCTIONS.md → docs/deployment-instructions.md} +3 -3
  9. package/infrastructure/{IAM-POLICY-TEMPLATES.md → docs/iam-policy-templates.md} +9 -10
  10. package/infrastructure/domains/database/aurora-builder.js +809 -0
  11. package/infrastructure/domains/database/aurora-builder.test.js +950 -0
  12. package/infrastructure/domains/database/aurora-discovery.js +87 -0
  13. package/infrastructure/domains/database/aurora-discovery.test.js +188 -0
  14. package/infrastructure/domains/database/aurora-resolver.js +210 -0
  15. package/infrastructure/domains/database/aurora-resolver.test.js +347 -0
  16. package/infrastructure/domains/database/migration-builder.js +695 -0
  17. package/infrastructure/domains/database/migration-builder.test.js +294 -0
  18. package/infrastructure/domains/database/migration-resolver.js +163 -0
  19. package/infrastructure/domains/database/migration-resolver.test.js +337 -0
  20. package/infrastructure/domains/health/application/ports/IPropertyReconciler.js +164 -0
  21. package/infrastructure/domains/health/application/ports/IResourceDetector.js +129 -0
  22. package/infrastructure/domains/health/application/ports/IResourceImporter.js +142 -0
  23. package/infrastructure/domains/health/application/ports/IStackRepository.js +131 -0
  24. package/infrastructure/domains/health/application/ports/index.js +26 -0
  25. package/infrastructure/domains/health/application/use-cases/__tests__/execute-resource-import-use-case.test.js +679 -0
  26. package/infrastructure/domains/health/application/use-cases/__tests__/mismatch-analyzer-method-name.test.js +167 -0
  27. package/infrastructure/domains/health/application/use-cases/__tests__/repair-via-import-use-case.test.js +1130 -0
  28. package/infrastructure/domains/health/application/use-cases/execute-resource-import-use-case.js +221 -0
  29. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.js +152 -0
  30. package/infrastructure/domains/health/application/use-cases/reconcile-properties-use-case.test.js +343 -0
  31. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.js +535 -0
  32. package/infrastructure/domains/health/application/use-cases/repair-via-import-use-case.test.js +376 -0
  33. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.js +213 -0
  34. package/infrastructure/domains/health/application/use-cases/run-health-check-use-case.test.js +441 -0
  35. package/infrastructure/domains/health/docs/ACME-DEV-DRIFT-ANALYSIS.md +267 -0
  36. package/infrastructure/domains/health/docs/BUILD-VS-DEPLOYED-TEMPLATE-ANALYSIS.md +324 -0
  37. package/infrastructure/domains/health/docs/ORPHAN-DETECTION-ANALYSIS.md +386 -0
  38. package/infrastructure/domains/health/docs/SPEC-CLEANUP-COMMAND.md +1419 -0
  39. package/infrastructure/domains/health/docs/TDD-IMPLEMENTATION-SUMMARY.md +391 -0
  40. package/infrastructure/domains/health/docs/TEMPLATE-COMPARISON-IMPLEMENTATION.md +551 -0
  41. package/infrastructure/domains/health/domain/entities/issue.js +299 -0
  42. package/infrastructure/domains/health/domain/entities/issue.test.js +528 -0
  43. package/infrastructure/domains/health/domain/entities/property-mismatch.js +108 -0
  44. package/infrastructure/domains/health/domain/entities/property-mismatch.test.js +275 -0
  45. package/infrastructure/domains/health/domain/entities/resource.js +159 -0
  46. package/infrastructure/domains/health/domain/entities/resource.test.js +432 -0
  47. package/infrastructure/domains/health/domain/entities/stack-health-report.js +306 -0
  48. package/infrastructure/domains/health/domain/entities/stack-health-report.test.js +601 -0
  49. package/infrastructure/domains/health/domain/services/__tests__/health-score-percentage-based.test.js +380 -0
  50. package/infrastructure/domains/health/domain/services/__tests__/import-progress-monitor.test.js +971 -0
  51. package/infrastructure/domains/health/domain/services/__tests__/import-template-generator.test.js +1150 -0
  52. package/infrastructure/domains/health/domain/services/__tests__/logical-id-mapper.test.js +672 -0
  53. package/infrastructure/domains/health/domain/services/__tests__/template-parser.test.js +496 -0
  54. package/infrastructure/domains/health/domain/services/__tests__/update-progress-monitor.test.js +419 -0
  55. package/infrastructure/domains/health/domain/services/health-score-calculator.js +248 -0
  56. package/infrastructure/domains/health/domain/services/health-score-calculator.test.js +504 -0
  57. package/infrastructure/domains/health/domain/services/import-progress-monitor.js +195 -0
  58. package/infrastructure/domains/health/domain/services/import-template-generator.js +435 -0
  59. package/infrastructure/domains/health/domain/services/logical-id-mapper.js +345 -0
  60. package/infrastructure/domains/health/domain/services/mismatch-analyzer.js +234 -0
  61. package/infrastructure/domains/health/domain/services/mismatch-analyzer.test.js +431 -0
  62. package/infrastructure/domains/health/domain/services/property-mutability-config.js +382 -0
  63. package/infrastructure/domains/health/domain/services/template-parser.js +245 -0
  64. package/infrastructure/domains/health/domain/services/update-progress-monitor.js +192 -0
  65. package/infrastructure/domains/health/domain/value-objects/health-score.js +138 -0
  66. package/infrastructure/domains/health/domain/value-objects/health-score.test.js +267 -0
  67. package/infrastructure/domains/health/domain/value-objects/property-mutability.js +161 -0
  68. package/infrastructure/domains/health/domain/value-objects/property-mutability.test.js +198 -0
  69. package/infrastructure/domains/health/domain/value-objects/resource-state.js +167 -0
  70. package/infrastructure/domains/health/domain/value-objects/resource-state.test.js +196 -0
  71. package/infrastructure/domains/health/domain/value-objects/stack-identifier.js +192 -0
  72. package/infrastructure/domains/health/domain/value-objects/stack-identifier.test.js +262 -0
  73. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-cfn-tagged.test.js +312 -0
  74. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-multi-stack.test.js +367 -0
  75. package/infrastructure/domains/health/infrastructure/adapters/__tests__/orphan-detection-relationship-analysis.test.js +432 -0
  76. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.js +784 -0
  77. package/infrastructure/domains/health/infrastructure/adapters/aws-property-reconciler.test.js +1133 -0
  78. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.js +565 -0
  79. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-detector.test.js +554 -0
  80. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.js +318 -0
  81. package/infrastructure/domains/health/infrastructure/adapters/aws-resource-importer.test.js +398 -0
  82. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.js +777 -0
  83. package/infrastructure/domains/health/infrastructure/adapters/aws-stack-repository.test.js +580 -0
  84. package/infrastructure/domains/integration/integration-builder.js +397 -0
  85. package/infrastructure/domains/integration/integration-builder.test.js +593 -0
  86. package/infrastructure/domains/integration/integration-resolver.js +170 -0
  87. package/infrastructure/domains/integration/integration-resolver.test.js +369 -0
  88. package/infrastructure/domains/integration/websocket-builder.js +69 -0
  89. package/infrastructure/domains/integration/websocket-builder.test.js +195 -0
  90. package/infrastructure/domains/networking/vpc-builder.js +1829 -0
  91. package/infrastructure/domains/networking/vpc-builder.test.js +1262 -0
  92. package/infrastructure/domains/networking/vpc-discovery.js +177 -0
  93. package/infrastructure/domains/networking/vpc-discovery.test.js +350 -0
  94. package/infrastructure/domains/networking/vpc-resolver.js +324 -0
  95. package/infrastructure/domains/networking/vpc-resolver.test.js +501 -0
  96. package/infrastructure/domains/parameters/ssm-builder.js +79 -0
  97. package/infrastructure/domains/parameters/ssm-builder.test.js +189 -0
  98. package/infrastructure/domains/parameters/ssm-discovery.js +84 -0
  99. package/infrastructure/domains/parameters/ssm-discovery.test.js +210 -0
  100. package/infrastructure/{iam-generator.js → domains/security/iam-generator.js} +2 -2
  101. package/infrastructure/domains/security/kms-builder.js +366 -0
  102. package/infrastructure/domains/security/kms-builder.test.js +374 -0
  103. package/infrastructure/domains/security/kms-discovery.js +80 -0
  104. package/infrastructure/domains/security/kms-discovery.test.js +177 -0
  105. package/infrastructure/domains/security/kms-resolver.js +96 -0
  106. package/infrastructure/domains/security/kms-resolver.test.js +216 -0
  107. package/infrastructure/domains/shared/base-builder.js +112 -0
  108. package/infrastructure/domains/shared/base-resolver.js +186 -0
  109. package/infrastructure/domains/shared/base-resolver.test.js +305 -0
  110. package/infrastructure/domains/shared/builder-orchestrator.js +212 -0
  111. package/infrastructure/domains/shared/builder-orchestrator.test.js +213 -0
  112. package/infrastructure/domains/shared/cloudformation-discovery-v2.js +334 -0
  113. package/infrastructure/domains/shared/cloudformation-discovery.js +375 -0
  114. package/infrastructure/domains/shared/cloudformation-discovery.test.js +590 -0
  115. package/infrastructure/domains/shared/environment-builder.js +119 -0
  116. package/infrastructure/domains/shared/environment-builder.test.js +247 -0
  117. package/infrastructure/domains/shared/providers/aws-provider-adapter.js +544 -0
  118. package/infrastructure/domains/shared/providers/aws-provider-adapter.test.js +377 -0
  119. package/infrastructure/domains/shared/providers/azure-provider-adapter.stub.js +93 -0
  120. package/infrastructure/domains/shared/providers/cloud-provider-adapter.js +136 -0
  121. package/infrastructure/domains/shared/providers/gcp-provider-adapter.stub.js +82 -0
  122. package/infrastructure/domains/shared/providers/provider-factory.js +108 -0
  123. package/infrastructure/domains/shared/providers/provider-factory.test.js +170 -0
  124. package/infrastructure/domains/shared/resource-discovery.js +192 -0
  125. package/infrastructure/domains/shared/resource-discovery.test.js +552 -0
  126. package/infrastructure/domains/shared/types/app-definition.js +205 -0
  127. package/infrastructure/domains/shared/types/discovery-result.js +106 -0
  128. package/infrastructure/domains/shared/types/discovery-result.test.js +258 -0
  129. package/infrastructure/domains/shared/types/index.js +46 -0
  130. package/infrastructure/domains/shared/types/resource-ownership.js +108 -0
  131. package/infrastructure/domains/shared/types/resource-ownership.test.js +101 -0
  132. package/infrastructure/domains/shared/utilities/base-definition-factory.js +380 -0
  133. package/infrastructure/domains/shared/utilities/base-definition-factory.js.bak +338 -0
  134. package/infrastructure/domains/shared/utilities/base-definition-factory.test.js +248 -0
  135. package/infrastructure/domains/shared/utilities/handler-path-resolver.js +134 -0
  136. package/infrastructure/domains/shared/utilities/handler-path-resolver.test.js +268 -0
  137. package/infrastructure/domains/shared/utilities/prisma-layer-manager.js +55 -0
  138. package/infrastructure/domains/shared/utilities/prisma-layer-manager.test.js +138 -0
  139. package/infrastructure/{env-validator.js → domains/shared/validation/env-validator.js} +2 -1
  140. package/infrastructure/domains/shared/validation/env-validator.test.js +173 -0
  141. package/infrastructure/esbuild.config.js +53 -0
  142. package/infrastructure/infrastructure-composer.js +87 -0
  143. package/infrastructure/{serverless-template.test.js → infrastructure-composer.test.js} +115 -24
  144. package/infrastructure/scripts/build-prisma-layer.js +553 -0
  145. package/infrastructure/scripts/build-prisma-layer.test.js +102 -0
  146. package/infrastructure/{build-time-discovery.js → scripts/build-time-discovery.js} +80 -48
  147. package/infrastructure/{build-time-discovery.test.js → scripts/build-time-discovery.test.js} +5 -4
  148. package/layers/prisma/nodejs/package.json +8 -0
  149. package/management-ui/server/utils/cliIntegration.js +1 -1
  150. package/management-ui/server/utils/environment/awsParameterStore.js +29 -18
  151. package/package.json +11 -11
  152. package/frigg-cli/.eslintrc.js +0 -141
  153. package/frigg-cli/__tests__/unit/commands/build.test.js +0 -251
  154. package/frigg-cli/__tests__/unit/commands/db-setup.test.js +0 -548
  155. package/frigg-cli/__tests__/unit/commands/install.test.js +0 -400
  156. package/frigg-cli/__tests__/unit/commands/ui.test.js +0 -346
  157. package/frigg-cli/__tests__/unit/utils/database-validator.test.js +0 -366
  158. package/frigg-cli/__tests__/unit/utils/error-messages.test.js +0 -304
  159. package/frigg-cli/__tests__/unit/utils/prisma-runner.test.js +0 -486
  160. package/frigg-cli/__tests__/utils/mock-factory.js +0 -270
  161. package/frigg-cli/__tests__/utils/prisma-mock.js +0 -194
  162. package/frigg-cli/__tests__/utils/test-fixtures.js +0 -463
  163. package/frigg-cli/__tests__/utils/test-setup.js +0 -287
  164. package/frigg-cli/build-command/index.js +0 -65
  165. package/frigg-cli/db-setup-command/index.js +0 -193
  166. package/frigg-cli/deploy-command/index.js +0 -175
  167. package/frigg-cli/generate-command/__tests__/generate-command.test.js +0 -301
  168. package/frigg-cli/generate-command/azure-generator.js +0 -43
  169. package/frigg-cli/generate-command/gcp-generator.js +0 -47
  170. package/frigg-cli/generate-command/index.js +0 -332
  171. package/frigg-cli/generate-command/terraform-generator.js +0 -555
  172. package/frigg-cli/generate-iam-command.js +0 -118
  173. package/frigg-cli/index.js +0 -75
  174. package/frigg-cli/index.test.js +0 -158
  175. package/frigg-cli/init-command/backend-first-handler.js +0 -756
  176. package/frigg-cli/init-command/index.js +0 -93
  177. package/frigg-cli/init-command/template-handler.js +0 -143
  178. package/frigg-cli/install-command/backend-js.js +0 -33
  179. package/frigg-cli/install-command/commit-changes.js +0 -16
  180. package/frigg-cli/install-command/environment-variables.js +0 -127
  181. package/frigg-cli/install-command/environment-variables.test.js +0 -136
  182. package/frigg-cli/install-command/index.js +0 -54
  183. package/frigg-cli/install-command/install-package.js +0 -13
  184. package/frigg-cli/install-command/integration-file.js +0 -30
  185. package/frigg-cli/install-command/logger.js +0 -12
  186. package/frigg-cli/install-command/template.js +0 -90
  187. package/frigg-cli/install-command/validate-package.js +0 -75
  188. package/frigg-cli/jest.config.js +0 -124
  189. package/frigg-cli/package.json +0 -54
  190. package/frigg-cli/start-command/index.js +0 -149
  191. package/frigg-cli/start-command/start-command.test.js +0 -297
  192. package/frigg-cli/test/init-command.test.js +0 -180
  193. package/frigg-cli/test/npm-registry.test.js +0 -319
  194. package/frigg-cli/ui-command/index.js +0 -154
  195. package/frigg-cli/utils/app-resolver.js +0 -319
  196. package/frigg-cli/utils/backend-path.js +0 -25
  197. package/frigg-cli/utils/database-validator.js +0 -161
  198. package/frigg-cli/utils/error-messages.js +0 -257
  199. package/frigg-cli/utils/npm-registry.js +0 -167
  200. package/frigg-cli/utils/prisma-runner.js +0 -280
  201. package/frigg-cli/utils/process-manager.js +0 -199
  202. package/frigg-cli/utils/repo-detection.js +0 -405
  203. package/infrastructure/aws-discovery.js +0 -1176
  204. package/infrastructure/aws-discovery.test.js +0 -1220
  205. package/infrastructure/serverless-template.js +0 -2094
  206. /package/infrastructure/{WEBSOCKET-CONFIGURATION.md → docs/WEBSOCKET-CONFIGURATION.md} +0 -0
  207. /package/infrastructure/{GENERATE-IAM-DOCS.md → docs/generate-iam-command.md} +0 -0
  208. /package/infrastructure/{iam-generator.test.js → domains/security/iam-generator.test.js} +0 -0
  209. /package/infrastructure/{frigg-deployment-iam-stack.yaml → domains/security/templates/frigg-deployment-iam-stack.yaml} +0 -0
  210. /package/infrastructure/{iam-policy-basic.json → domains/security/templates/iam-policy-basic.json} +0 -0
  211. /package/infrastructure/{iam-policy-full.json → domains/security/templates/iam-policy-full.json} +0 -0
  212. /package/infrastructure/{run-discovery.js → scripts/run-discovery.js} +0 -0
@@ -0,0 +1,1133 @@
1
+ /**
2
+ * Tests for AWSPropertyReconciler Adapter
3
+ *
4
+ * Tests property drift reconciliation operations
5
+ */
6
+
7
+ const AWSPropertyReconciler = require('./aws-property-reconciler');
8
+ const StackIdentifier = require('../../domain/value-objects/stack-identifier');
9
+ const PropertyMismatch = require('../../domain/entities/property-mismatch');
10
+ const PropertyMutability = require('../../domain/value-objects/property-mutability');
11
+
12
+ // Mock AWS SDK
13
+ jest.mock('@aws-sdk/client-cloudformation', () => ({
14
+ CloudFormationClient: jest.fn(),
15
+ UpdateStackCommand: jest.fn(),
16
+ GetTemplateCommand: jest.fn(),
17
+ }));
18
+
19
+ jest.mock('@aws-sdk/client-ec2', () => ({
20
+ EC2Client: jest.fn(),
21
+ ModifyVpcAttributeCommand: jest.fn(),
22
+ }));
23
+
24
+ jest.mock('@aws-sdk/client-lambda', () => ({
25
+ LambdaClient: jest.fn(),
26
+ UpdateFunctionConfigurationCommand: jest.fn(),
27
+ }));
28
+
29
+ describe('AWSPropertyReconciler', () => {
30
+ let reconciler;
31
+ let mockCFSend;
32
+ let mockEC2Send;
33
+
34
+ beforeEach(() => {
35
+ jest.clearAllMocks();
36
+
37
+ // Mock CloudFormation client
38
+ mockCFSend = jest.fn();
39
+ const { CloudFormationClient } = require('@aws-sdk/client-cloudformation');
40
+ CloudFormationClient.mockImplementation(() => ({ send: mockCFSend }));
41
+
42
+ // Mock EC2 client
43
+ mockEC2Send = jest.fn();
44
+ const { EC2Client } = require('@aws-sdk/client-ec2');
45
+ EC2Client.mockImplementation(() => ({ send: mockEC2Send }));
46
+
47
+ reconciler = new AWSPropertyReconciler({ region: 'us-east-1' });
48
+ });
49
+
50
+ describe('canReconcile', () => {
51
+ it('should return true for mutable property mismatch', async () => {
52
+ const mismatch = new PropertyMismatch({
53
+ propertyPath: 'Properties.Tags',
54
+ expectedValue: { Environment: 'production' },
55
+ actualValue: { Environment: 'staging' },
56
+ mutability: PropertyMutability.MUTABLE,
57
+ });
58
+
59
+ const canReconcile = await reconciler.canReconcile(mismatch);
60
+ expect(canReconcile).toBe(true);
61
+ });
62
+
63
+ it('should return false for immutable property mismatch', async () => {
64
+ const mismatch = new PropertyMismatch({
65
+ propertyPath: 'Properties.CidrBlock',
66
+ expectedValue: '10.0.0.0/16',
67
+ actualValue: '10.1.0.0/16',
68
+ mutability: PropertyMutability.IMMUTABLE,
69
+ });
70
+
71
+ const canReconcile = await reconciler.canReconcile(mismatch);
72
+ expect(canReconcile).toBe(false);
73
+ });
74
+
75
+ it('should return true for conditional property mismatch', async () => {
76
+ const mismatch = new PropertyMismatch({
77
+ propertyPath: 'Properties.EngineVersion',
78
+ expectedValue: '13.7',
79
+ actualValue: '13.8',
80
+ mutability: PropertyMutability.CONDITIONAL,
81
+ });
82
+
83
+ const canReconcile = await reconciler.canReconcile(mismatch);
84
+ expect(canReconcile).toBe(true);
85
+ });
86
+ });
87
+
88
+ describe('reconcileProperty - template mode', () => {
89
+ it('should reconcile property by updating template', async () => {
90
+ const stackIdentifier = new StackIdentifier({
91
+ stackName: 'my-app-prod',
92
+ region: 'us-east-1',
93
+ });
94
+
95
+ const mismatch = new PropertyMismatch({
96
+ propertyPath: 'Properties.EnableDnsSupport',
97
+ expectedValue: true,
98
+ actualValue: false,
99
+ mutability: PropertyMutability.MUTABLE,
100
+ });
101
+
102
+ // Mock GetTemplate
103
+ mockCFSend.mockResolvedValueOnce({
104
+ TemplateBody: JSON.stringify({
105
+ Resources: {
106
+ MyVPC: {
107
+ Type: 'AWS::EC2::VPC',
108
+ Properties: {
109
+ CidrBlock: '10.0.0.0/16',
110
+ EnableDnsSupport: true,
111
+ },
112
+ },
113
+ },
114
+ }),
115
+ });
116
+
117
+ // Mock UpdateStack
118
+ mockCFSend.mockResolvedValueOnce({
119
+ StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/my-app-prod/guid',
120
+ });
121
+
122
+ const result = await reconciler.reconcileProperty({
123
+ stackIdentifier,
124
+ logicalId: 'MyVPC',
125
+ mismatch,
126
+ mode: 'template',
127
+ });
128
+
129
+ expect(result).toEqual({
130
+ success: true,
131
+ mode: 'template',
132
+ propertyPath: 'Properties.EnableDnsSupport',
133
+ oldValue: true,
134
+ newValue: false,
135
+ message: 'Template updated to match actual resource state',
136
+ });
137
+
138
+ expect(mockCFSend).toHaveBeenCalledTimes(2);
139
+ });
140
+ });
141
+
142
+ describe('reconcileProperty - resource mode', () => {
143
+ it('should reconcile property by updating resource', async () => {
144
+ const stackIdentifier = new StackIdentifier({
145
+ stackName: 'my-app-prod',
146
+ region: 'us-east-1',
147
+ });
148
+
149
+ const mismatch = new PropertyMismatch({
150
+ propertyPath: 'Properties.EnableDnsSupport',
151
+ expectedValue: true,
152
+ actualValue: false,
153
+ mutability: PropertyMutability.MUTABLE,
154
+ });
155
+
156
+ // Mock EC2 ModifyVpcAttribute
157
+ mockEC2Send.mockResolvedValue({});
158
+
159
+ const result = await reconciler.reconcileProperty({
160
+ stackIdentifier,
161
+ logicalId: 'MyVPC',
162
+ mismatch,
163
+ mode: 'resource',
164
+ });
165
+
166
+ expect(result.success).toBe(true);
167
+ expect(result.mode).toBe('resource');
168
+ expect(result.propertyPath).toBe('Properties.EnableDnsSupport');
169
+ });
170
+
171
+ it('should throw error for unsupported resource update', async () => {
172
+ const stackIdentifier = new StackIdentifier({
173
+ stackName: 'my-app-prod',
174
+ region: 'us-east-1',
175
+ });
176
+
177
+ const mismatch = new PropertyMismatch({
178
+ propertyPath: 'Properties.SomeUnsupportedProperty',
179
+ expectedValue: 'value1',
180
+ actualValue: 'value2',
181
+ mutability: PropertyMutability.MUTABLE,
182
+ });
183
+
184
+ await expect(
185
+ reconciler.reconcileProperty({
186
+ stackIdentifier,
187
+ logicalId: 'MyVPC',
188
+ mismatch,
189
+ mode: 'resource',
190
+ })
191
+ ).rejects.toThrow('Resource property update not supported');
192
+ });
193
+ });
194
+
195
+ describe('reconcileMultipleProperties', () => {
196
+ it('should reconcile multiple properties in single UpdateStack call', async () => {
197
+ const stackIdentifier = new StackIdentifier({
198
+ stackName: 'my-app-prod',
199
+ region: 'us-east-1',
200
+ });
201
+
202
+ const mismatches = [
203
+ new PropertyMismatch({
204
+ propertyPath: 'Properties.EnableDnsSupport',
205
+ expectedValue: true,
206
+ actualValue: false,
207
+ mutability: PropertyMutability.MUTABLE,
208
+ }),
209
+ new PropertyMismatch({
210
+ propertyPath: 'Properties.EnableDnsHostnames',
211
+ expectedValue: true,
212
+ actualValue: false,
213
+ mutability: PropertyMutability.MUTABLE,
214
+ }),
215
+ ];
216
+
217
+ // Mock GetTemplate - should be called ONCE
218
+ mockCFSend.mockResolvedValueOnce({
219
+ TemplateBody: JSON.stringify({
220
+ Resources: {
221
+ MyVPC: {
222
+ Type: 'AWS::EC2::VPC',
223
+ Properties: {
224
+ CidrBlock: '10.0.0.0/16',
225
+ EnableDnsSupport: true,
226
+ EnableDnsHostnames: true,
227
+ },
228
+ },
229
+ },
230
+ }),
231
+ });
232
+
233
+ // Mock UpdateStack - should be called ONCE with both property updates
234
+ mockCFSend.mockResolvedValueOnce({
235
+ StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/my-app-prod/guid',
236
+ });
237
+
238
+ const result = await reconciler.reconcileMultipleProperties({
239
+ stackIdentifier,
240
+ logicalId: 'MyVPC',
241
+ mismatches,
242
+ mode: 'template',
243
+ });
244
+
245
+ // Verify only 2 AWS SDK calls: 1 GetTemplate + 1 UpdateStack (not 3+ like before)
246
+ expect(mockCFSend).toHaveBeenCalledTimes(2);
247
+
248
+ // Verify result
249
+ expect(result.reconciledCount).toBe(2);
250
+ expect(result.failedCount).toBe(0);
251
+ expect(result.results).toHaveLength(2);
252
+ expect(result.message).toContain('single UpdateStack call');
253
+
254
+ // Verify both properties were marked as successfully reconciled
255
+ expect(result.results[0].success).toBe(true);
256
+ expect(result.results[0].propertyPath).toBe('Properties.EnableDnsSupport');
257
+ expect(result.results[1].success).toBe(true);
258
+ expect(result.results[1].propertyPath).toBe('Properties.EnableDnsHostnames');
259
+ });
260
+ });
261
+
262
+ describe('previewReconciliation', () => {
263
+ it('should preview template reconciliation', async () => {
264
+ const stackIdentifier = new StackIdentifier({
265
+ stackName: 'my-app-prod',
266
+ region: 'us-east-1',
267
+ });
268
+
269
+ const mismatch = new PropertyMismatch({
270
+ propertyPath: 'Properties.EnableDnsSupport',
271
+ expectedValue: true,
272
+ actualValue: false,
273
+ mutability: PropertyMutability.MUTABLE,
274
+ });
275
+
276
+ const preview = await reconciler.previewReconciliation({
277
+ stackIdentifier,
278
+ logicalId: 'MyVPC',
279
+ mismatch,
280
+ mode: 'template',
281
+ });
282
+
283
+ expect(preview).toEqual({
284
+ canReconcile: true,
285
+ mode: 'template',
286
+ propertyPath: 'Properties.EnableDnsSupport',
287
+ currentValue: true,
288
+ proposedValue: false,
289
+ impact: 'Will update CloudFormation template to match actual resource state',
290
+ warnings: [],
291
+ });
292
+ });
293
+
294
+ it('should preview resource reconciliation', async () => {
295
+ const stackIdentifier = new StackIdentifier({
296
+ stackName: 'my-app-prod',
297
+ region: 'us-east-1',
298
+ });
299
+
300
+ const mismatch = new PropertyMismatch({
301
+ propertyPath: 'Properties.EnableDnsSupport',
302
+ expectedValue: true,
303
+ actualValue: false,
304
+ mutability: PropertyMutability.MUTABLE,
305
+ });
306
+
307
+ const preview = await reconciler.previewReconciliation({
308
+ stackIdentifier,
309
+ logicalId: 'MyVPC',
310
+ mismatch,
311
+ mode: 'resource',
312
+ });
313
+
314
+ expect(preview.canReconcile).toBe(true);
315
+ expect(preview.mode).toBe('resource');
316
+ expect(preview.impact).toContain('Will update cloud resource');
317
+ });
318
+
319
+ it('should warn for immutable property', async () => {
320
+ const stackIdentifier = new StackIdentifier({
321
+ stackName: 'my-app-prod',
322
+ region: 'us-east-1',
323
+ });
324
+
325
+ const mismatch = new PropertyMismatch({
326
+ propertyPath: 'Properties.CidrBlock',
327
+ expectedValue: '10.0.0.0/16',
328
+ actualValue: '10.1.0.0/16',
329
+ mutability: PropertyMutability.IMMUTABLE,
330
+ });
331
+
332
+ const preview = await reconciler.previewReconciliation({
333
+ stackIdentifier,
334
+ logicalId: 'MyVPC',
335
+ mismatch,
336
+ mode: 'template',
337
+ });
338
+
339
+ expect(preview.canReconcile).toBe(false);
340
+ expect(preview.warnings).toContain(
341
+ 'Property is immutable - requires resource replacement'
342
+ );
343
+ });
344
+ });
345
+
346
+ describe('updateTemplateProperty', () => {
347
+ it('should update CloudFormation template property', async () => {
348
+ const stackIdentifier = new StackIdentifier({
349
+ stackName: 'my-app-prod',
350
+ region: 'us-east-1',
351
+ });
352
+
353
+ // Mock GetTemplate
354
+ mockCFSend.mockResolvedValueOnce({
355
+ TemplateBody: JSON.stringify({
356
+ Resources: {
357
+ MyVPC: {
358
+ Type: 'AWS::EC2::VPC',
359
+ Properties: {
360
+ CidrBlock: '10.0.0.0/16',
361
+ EnableDnsSupport: true,
362
+ },
363
+ },
364
+ },
365
+ }),
366
+ });
367
+
368
+ // Mock UpdateStack
369
+ mockCFSend.mockResolvedValueOnce({
370
+ StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/my-app-prod/guid',
371
+ });
372
+
373
+ const result = await reconciler.updateTemplateProperty({
374
+ stackIdentifier,
375
+ logicalId: 'MyVPC',
376
+ propertyPath: 'Properties.EnableDnsSupport',
377
+ newValue: false,
378
+ });
379
+
380
+ expect(result.success).toBe(true);
381
+ expect(result.changeSetId).toBeDefined();
382
+ });
383
+ });
384
+
385
+ describe('updateResourceProperty', () => {
386
+ it('should update VPC DNS support', async () => {
387
+ mockEC2Send.mockResolvedValue({});
388
+
389
+ const result = await reconciler.updateResourceProperty({
390
+ resourceType: 'AWS::EC2::VPC',
391
+ physicalId: 'vpc-123',
392
+ region: 'us-east-1',
393
+ propertyPath: 'Properties.EnableDnsSupport',
394
+ newValue: false,
395
+ });
396
+
397
+ expect(result.success).toBe(true);
398
+ expect(result.updatedAt).toBeInstanceOf(Date);
399
+ });
400
+
401
+ it('should throw error for unsupported resource type', async () => {
402
+ await expect(
403
+ reconciler.updateResourceProperty({
404
+ resourceType: 'AWS::Lambda::Function',
405
+ physicalId: 'my-function',
406
+ region: 'us-east-1',
407
+ propertyPath: 'Properties.MemorySize',
408
+ newValue: 512,
409
+ })
410
+ ).rejects.toThrow('Resource type AWS::Lambda::Function updates not supported');
411
+ });
412
+ });
413
+
414
+ describe('getReconciliationStrategy', () => {
415
+ it('should get strategy for VPC', async () => {
416
+ const strategy = await reconciler.getReconciliationStrategy('AWS::EC2::VPC');
417
+
418
+ expect(strategy).toEqual({
419
+ supportsTemplateUpdate: true,
420
+ supportsResourceUpdate: true,
421
+ recommendedMode: 'template',
422
+ limitations: [
423
+ 'Some VPC properties require resource replacement (e.g., CidrBlock)',
424
+ ],
425
+ });
426
+ });
427
+
428
+ it('should get strategy for RDS DBCluster', async () => {
429
+ const strategy = await reconciler.getReconciliationStrategy(
430
+ 'AWS::RDS::DBCluster'
431
+ );
432
+
433
+ expect(strategy.supportsTemplateUpdate).toBe(true);
434
+ expect(strategy.supportsResourceUpdate).toBe(false);
435
+ expect(strategy.recommendedMode).toBe('template');
436
+ });
437
+
438
+ it('should throw error for unsupported type', async () => {
439
+ await expect(
440
+ reconciler.getReconciliationStrategy('AWS::UnsupportedType::Resource')
441
+ ).rejects.toThrow('Resource type AWS::UnsupportedType::Resource not supported');
442
+ });
443
+
444
+ it('should get strategy for Lambda Function', async () => {
445
+ const strategy = await reconciler.getReconciliationStrategy(
446
+ 'AWS::Lambda::Function'
447
+ );
448
+
449
+ expect(strategy.supportsTemplateUpdate).toBe(true);
450
+ expect(strategy.supportsResourceUpdate).toBe(false);
451
+ expect(strategy.recommendedMode).toBe('template');
452
+ expect(strategy.limitations).toContain(
453
+ 'VpcConfig changes may take several minutes to propagate'
454
+ );
455
+ });
456
+ });
457
+
458
+ describe('Lambda Function VpcConfig Reconciliation (TDD)', () => {
459
+ let stackIdentifier;
460
+
461
+ beforeEach(() => {
462
+ stackIdentifier = new StackIdentifier({
463
+ stackName: 'test-stack',
464
+ region: 'us-east-1',
465
+ });
466
+ });
467
+
468
+ describe('reconcile Lambda VpcConfig.SubnetIds', () => {
469
+ it('should reconcile Lambda SubnetIds property mismatch', async () => {
470
+ const mismatch = new PropertyMismatch({
471
+ propertyPath: 'Properties.VpcConfig.SubnetIds',
472
+ expectedValue: ['subnet-111', 'subnet-222'],
473
+ actualValue: ['subnet-333', 'subnet-444'],
474
+ mutability: PropertyMutability.MUTABLE,
475
+ });
476
+
477
+ // Mock GetTemplate
478
+ mockCFSend.mockResolvedValueOnce({
479
+ TemplateBody: JSON.stringify({
480
+ Resources: {
481
+ AttioLambdaFunction: {
482
+ Type: 'AWS::Lambda::Function',
483
+ Properties: {
484
+ FunctionName: 'attio-lambda',
485
+ Runtime: 'nodejs20.x',
486
+ VpcConfig: {
487
+ SubnetIds: ['subnet-111', 'subnet-222'],
488
+ SecurityGroupIds: ['sg-111'],
489
+ },
490
+ },
491
+ },
492
+ },
493
+ }),
494
+ });
495
+
496
+ // Mock UpdateStack
497
+ mockCFSend.mockResolvedValueOnce({
498
+ StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/guid',
499
+ });
500
+
501
+ const result = await reconciler.reconcileProperty({
502
+ stackIdentifier,
503
+ logicalId: 'AttioLambdaFunction',
504
+ mismatch,
505
+ mode: 'template',
506
+ });
507
+
508
+ expect(result.success).toBe(true);
509
+ expect(result.mode).toBe('template');
510
+ expect(result.propertyPath).toBe('Properties.VpcConfig.SubnetIds');
511
+ expect(result.oldValue).toEqual(['subnet-111', 'subnet-222']);
512
+ expect(result.newValue).toEqual(['subnet-333', 'subnet-444']);
513
+ expect(result.message).toContain('Template updated to match actual resource state');
514
+ });
515
+
516
+ it('should recognize SubnetIds as mutable (no replacement required)', async () => {
517
+ const mismatch = new PropertyMismatch({
518
+ propertyPath: 'Properties.VpcConfig.SubnetIds',
519
+ expectedValue: ['subnet-111'],
520
+ actualValue: ['subnet-333'],
521
+ mutability: PropertyMutability.MUTABLE,
522
+ });
523
+
524
+ const canReconcile = await reconciler.canReconcile(mismatch);
525
+ expect(canReconcile).toBe(true);
526
+ });
527
+ });
528
+
529
+ describe('reconcile Lambda VpcConfig.SecurityGroupIds', () => {
530
+ it('should reconcile Lambda SecurityGroupIds property mismatch', async () => {
531
+ const mismatch = new PropertyMismatch({
532
+ propertyPath: 'Properties.VpcConfig.SecurityGroupIds',
533
+ expectedValue: ['sg-111'],
534
+ actualValue: ['sg-222', 'sg-333'],
535
+ mutability: PropertyMutability.MUTABLE,
536
+ });
537
+
538
+ // Mock GetTemplate
539
+ mockCFSend.mockResolvedValueOnce({
540
+ TemplateBody: JSON.stringify({
541
+ Resources: {
542
+ HealthLambdaFunction: {
543
+ Type: 'AWS::Lambda::Function',
544
+ Properties: {
545
+ FunctionName: 'health-lambda',
546
+ Runtime: 'nodejs20.x',
547
+ VpcConfig: {
548
+ SubnetIds: ['subnet-111', 'subnet-222'],
549
+ SecurityGroupIds: ['sg-111'],
550
+ },
551
+ },
552
+ },
553
+ },
554
+ }),
555
+ });
556
+
557
+ // Mock UpdateStack
558
+ mockCFSend.mockResolvedValueOnce({
559
+ StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/guid',
560
+ });
561
+
562
+ const result = await reconciler.reconcileProperty({
563
+ stackIdentifier,
564
+ logicalId: 'HealthLambdaFunction',
565
+ mismatch,
566
+ mode: 'template',
567
+ });
568
+
569
+ expect(result.success).toBe(true);
570
+ expect(result.mode).toBe('template');
571
+ expect(result.propertyPath).toBe('Properties.VpcConfig.SecurityGroupIds');
572
+ expect(result.newValue).toEqual(['sg-222', 'sg-333']);
573
+ });
574
+ });
575
+
576
+ describe('reconcile multiple Lambda VpcConfig properties', () => {
577
+ it('should reconcile both SubnetIds and SecurityGroupIds for same Lambda', async () => {
578
+ const mismatches = [
579
+ new PropertyMismatch({
580
+ propertyPath: 'Properties.VpcConfig.SubnetIds',
581
+ expectedValue: ['subnet-111', 'subnet-222'],
582
+ actualValue: ['subnet-333', 'subnet-444'],
583
+ mutability: PropertyMutability.MUTABLE,
584
+ }),
585
+ new PropertyMismatch({
586
+ propertyPath: 'Properties.VpcConfig.SecurityGroupIds',
587
+ expectedValue: ['sg-111'],
588
+ actualValue: ['sg-222'],
589
+ mutability: PropertyMutability.MUTABLE,
590
+ }),
591
+ ];
592
+
593
+ // Mock GetTemplate for first property (SubnetIds)
594
+ mockCFSend.mockResolvedValueOnce({
595
+ TemplateBody: JSON.stringify({
596
+ Resources: {
597
+ UserLambdaFunction: {
598
+ Type: 'AWS::Lambda::Function',
599
+ Properties: {
600
+ FunctionName: 'user-lambda',
601
+ Runtime: 'nodejs20.x',
602
+ VpcConfig: {
603
+ SubnetIds: ['subnet-111', 'subnet-222'],
604
+ SecurityGroupIds: ['sg-111'],
605
+ },
606
+ },
607
+ },
608
+ },
609
+ }),
610
+ });
611
+
612
+ // Mock UpdateStack for first property
613
+ mockCFSend.mockResolvedValueOnce({
614
+ StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/guid',
615
+ });
616
+
617
+ // Mock GetTemplate for second property (SecurityGroupIds)
618
+ mockCFSend.mockResolvedValueOnce({
619
+ TemplateBody: JSON.stringify({
620
+ Resources: {
621
+ UserLambdaFunction: {
622
+ Type: 'AWS::Lambda::Function',
623
+ Properties: {
624
+ FunctionName: 'user-lambda',
625
+ Runtime: 'nodejs20.x',
626
+ VpcConfig: {
627
+ SubnetIds: ['subnet-333', 'subnet-444'], // Updated from first reconciliation
628
+ SecurityGroupIds: ['sg-111'],
629
+ },
630
+ },
631
+ },
632
+ },
633
+ }),
634
+ });
635
+
636
+ // Mock UpdateStack for second property
637
+ mockCFSend.mockResolvedValueOnce({
638
+ StackId: 'arn:aws:cloudformation:us-east-1:123456789012:stack/test-stack/guid',
639
+ });
640
+
641
+ const result = await reconciler.reconcileMultipleProperties({
642
+ stackIdentifier,
643
+ logicalId: 'UserLambdaFunction',
644
+ mismatches,
645
+ mode: 'template',
646
+ });
647
+
648
+ expect(result.reconciledCount).toBe(2);
649
+ expect(result.failedCount).toBe(0);
650
+ expect(result.results).toHaveLength(2);
651
+ });
652
+ });
653
+
654
+ describe('Lambda reconciliation strategy', () => {
655
+ it('should provide reconciliation strategy for Lambda Function', async () => {
656
+ const strategy = await reconciler.getReconciliationStrategy(
657
+ 'AWS::Lambda::Function'
658
+ );
659
+
660
+ expect(strategy).toEqual({
661
+ supportsTemplateUpdate: true,
662
+ supportsResourceUpdate: false,
663
+ recommendedMode: 'template',
664
+ limitations: expect.arrayContaining([
665
+ 'VpcConfig changes may take several minutes to propagate',
666
+ ]),
667
+ });
668
+ });
669
+ });
670
+
671
+ describe('real-world drift scenario - 17 Lambda functions', () => {
672
+ it('should reconcile VpcConfig drift for multiple Lambda functions', async () => {
673
+ // Simulate real drift from user's test-stack stack
674
+ // 17 Lambda functions with 2 mismatches each (SubnetIds + SecurityGroupIds)
675
+ const lambdaFunctions = [
676
+ 'AttioLambdaFunction',
677
+ 'AttioQueueWorkerLambdaFunction',
678
+ 'HealthLambdaFunction',
679
+ ];
680
+
681
+ let totalReconciled = 0;
682
+
683
+ for (const logicalId of lambdaFunctions) {
684
+ const mismatches = [
685
+ new PropertyMismatch({
686
+ propertyPath: 'Properties.VpcConfig.SubnetIds',
687
+ expectedValue: ['subnet-old1', 'subnet-old2'],
688
+ actualValue: ['subnet-new1', 'subnet-new2'],
689
+ mutability: PropertyMutability.MUTABLE,
690
+ }),
691
+ new PropertyMismatch({
692
+ propertyPath: 'Properties.VpcConfig.SecurityGroupIds',
693
+ expectedValue: ['sg-old'],
694
+ actualValue: ['sg-new'],
695
+ mutability: PropertyMutability.MUTABLE,
696
+ }),
697
+ ];
698
+
699
+ // Mock GetTemplate + UpdateStack ONCE (batches both properties)
700
+ mockCFSend
701
+ .mockResolvedValueOnce({
702
+ TemplateBody: JSON.stringify({
703
+ Resources: {
704
+ [logicalId]: {
705
+ Type: 'AWS::Lambda::Function',
706
+ Properties: {
707
+ VpcConfig: {
708
+ SubnetIds: ['subnet-old1', 'subnet-old2'],
709
+ SecurityGroupIds: ['sg-old'],
710
+ },
711
+ },
712
+ },
713
+ },
714
+ }),
715
+ })
716
+ .mockResolvedValueOnce({ StackId: 'arn:...' });
717
+
718
+ const result = await reconciler.reconcileMultipleProperties({
719
+ stackIdentifier,
720
+ logicalId,
721
+ mismatches,
722
+ mode: 'template',
723
+ });
724
+
725
+ totalReconciled += result.reconciledCount;
726
+ }
727
+
728
+ // 3 functions × 2 properties each = 6 total reconciliations
729
+ expect(totalReconciled).toBe(6);
730
+ });
731
+ });
732
+ });
733
+
734
+ describe('large template handling (> 51KB limit)', () => {
735
+ it('should use S3 upload when template exceeds 51KB', async () => {
736
+ const stackIdentifier = new StackIdentifier({
737
+ stackName: 'test-stack',
738
+ region: 'us-east-1',
739
+ });
740
+
741
+ // Create large template that exceeds 51,200 bytes
742
+ const largeTemplate = {
743
+ Resources: {},
744
+ Outputs: {},
745
+ };
746
+
747
+ // Add many resources to exceed limit (need ~250 resources with outputs to reach 51KB+)
748
+ for (let i = 0; i < 250; i++) {
749
+ largeTemplate.Resources[`LambdaFunction${i}`] = {
750
+ Type: 'AWS::Lambda::Function',
751
+ Properties: {
752
+ FunctionName: `my-integration-function-${i}`,
753
+ Runtime: 'nodejs18.x',
754
+ Handler: 'index.handler',
755
+ Role: { 'Fn::GetAtt': ['LambdaExecutionRole', 'Arn'] },
756
+ Code: {
757
+ S3Bucket: 'my-deployment-bucket',
758
+ S3Key: `serverless/my-stack/dev/${Date.now()}/function-${i}.zip`,
759
+ },
760
+ VpcConfig: {
761
+ SubnetIds: ['subnet-33333333', 'subnet-44444444'],
762
+ SecurityGroupIds: ['sg-12345678'],
763
+ },
764
+ Environment: {
765
+ Variables: {
766
+ NODE_ENV: 'production',
767
+ DB_HOST: 'my-db-host',
768
+ DB_NAME: 'my-database',
769
+ },
770
+ },
771
+ },
772
+ };
773
+ largeTemplate.Outputs[`LambdaFunction${i}QualifiedArn`] = {
774
+ Description: `Current Lambda function version for function ${i}`,
775
+ Value: { 'Fn::GetAtt': [`LambdaFunction${i}`, 'Arn'] },
776
+ Export: { Name: { 'Fn::Sub': `\${AWS::StackName}-LambdaFunction${i}QualifiedArn` } },
777
+ };
778
+ }
779
+
780
+ const templateBody = JSON.stringify(largeTemplate);
781
+ expect(templateBody.length).toBeGreaterThan(51200);
782
+
783
+ // Mock CloudFormation repository with uploadTemplate and monitoring methods
784
+ const mockCFRepo = {
785
+ uploadTemplate: jest.fn().mockResolvedValue('https://bucket.s3.amazonaws.com/template.json'),
786
+ getStackEvents: jest.fn().mockResolvedValue([
787
+ {
788
+ LogicalResourceId: 'LambdaFunction0',
789
+ ResourceStatus: 'UPDATE_COMPLETE',
790
+ Timestamp: new Date(),
791
+ },
792
+ ]),
793
+ getStackStatus: jest.fn().mockResolvedValue('UPDATE_COMPLETE'),
794
+ };
795
+
796
+ const reconciler = new AWSPropertyReconciler({
797
+ region: 'us-east-1',
798
+ cloudFormationRepository: mockCFRepo,
799
+ });
800
+
801
+ const mismatch = new PropertyMismatch({
802
+ propertyPath: 'Properties.FunctionName',
803
+ expectedValue: 'old-function-name',
804
+ actualValue: 'my-integration-function-0',
805
+ mutability: PropertyMutability.MUTABLE,
806
+ });
807
+
808
+ // Mock GetTemplate
809
+ mockCFSend.mockResolvedValueOnce({
810
+ TemplateBody: templateBody,
811
+ });
812
+
813
+ // Mock UpdateStack (should use TemplateURL, not TemplateBody)
814
+ mockCFSend.mockResolvedValueOnce({ StackId: 'arn:...' });
815
+
816
+ const result = await reconciler.reconcileMultipleProperties({
817
+ stackIdentifier,
818
+ logicalId: 'LambdaFunction0', // Match resource in template
819
+ mismatches: [mismatch],
820
+ mode: 'template',
821
+ });
822
+
823
+ // Verify S3 upload was called with large template
824
+ expect(mockCFRepo.uploadTemplate).toHaveBeenCalledWith({
825
+ stackName: 'test-stack',
826
+ templateBody: expect.any(String),
827
+ });
828
+
829
+ // Verify template body passed to S3 is the large template
830
+ const uploadedTemplate = mockCFRepo.uploadTemplate.mock.calls[0][0].templateBody;
831
+ expect(uploadedTemplate.length).toBeGreaterThan(51200);
832
+
833
+ // Verify GetTemplate and UpdateStack were called
834
+ expect(mockCFSend).toHaveBeenCalledTimes(2);
835
+
836
+ // Success - reconciled the property
837
+ expect(result.reconciledCount).toBe(1);
838
+ expect(result.failedCount).toBe(0);
839
+ });
840
+
841
+ it('should use TemplateBody when template is under 51KB', async () => {
842
+ const stackIdentifier = new StackIdentifier({
843
+ stackName: 'small-stack',
844
+ region: 'us-east-1',
845
+ });
846
+
847
+ const smallTemplate = {
848
+ Resources: {
849
+ MyVPC: {
850
+ Type: 'AWS::EC2::VPC',
851
+ Properties: {
852
+ CidrBlock: '10.0.0.0/16',
853
+ },
854
+ },
855
+ },
856
+ };
857
+
858
+ const templateBody = JSON.stringify(smallTemplate);
859
+ expect(templateBody.length).toBeLessThan(51200);
860
+
861
+ const reconciler = new AWSPropertyReconciler({ region: 'us-east-1' });
862
+
863
+ const mismatch = new PropertyMismatch({
864
+ propertyPath: 'Properties.EnableDnsSupport',
865
+ expectedValue: true,
866
+ actualValue: false,
867
+ mutability: PropertyMutability.MUTABLE,
868
+ });
869
+
870
+ // Mock GetTemplate
871
+ mockCFSend.mockResolvedValueOnce({
872
+ TemplateBody: templateBody,
873
+ });
874
+
875
+ // Mock UpdateStack
876
+ mockCFSend.mockResolvedValueOnce({ StackId: 'arn:...' });
877
+
878
+ const result = await reconciler.reconcileMultipleProperties({
879
+ stackIdentifier,
880
+ logicalId: 'MyVPC',
881
+ mismatches: [mismatch],
882
+ mode: 'template',
883
+ });
884
+
885
+ // Verify 2 SDK calls: GetTemplate + UpdateStack
886
+ expect(mockCFSend).toHaveBeenCalledTimes(2);
887
+
888
+ // Success - small template doesn't require S3 upload
889
+ expect(result.reconciledCount).toBe(1);
890
+ expect(result.failedCount).toBe(0);
891
+ });
892
+ });
893
+
894
+ describe('resource mode batch reconciliation (TDD)', () => {
895
+ let stackIdentifier;
896
+ let mockLambdaSend;
897
+
898
+ beforeEach(() => {
899
+ stackIdentifier = new StackIdentifier({
900
+ stackName: 'test-stack',
901
+ region: 'us-east-1',
902
+ });
903
+
904
+ // Mock Lambda client
905
+ mockLambdaSend = jest.fn();
906
+ const { LambdaClient } = require('@aws-sdk/client-lambda');
907
+ LambdaClient.mockImplementation(() => ({ send: mockLambdaSend }));
908
+
909
+ // Re-create reconciler to get new Lambda client
910
+ reconciler = new AWSPropertyReconciler({ region: 'us-east-1' });
911
+ });
912
+
913
+ describe('reconcileMultipleProperties in resource mode', () => {
914
+ it('should batch Lambda VpcConfig updates via UpdateFunctionConfiguration', async () => {
915
+ const mismatches = [
916
+ new PropertyMismatch({
917
+ propertyPath: 'VpcConfig.SubnetIds',
918
+ expectedValue: ['subnet-11111111', 'subnet-22222222'],
919
+ actualValue: ['subnet-33333333', 'subnet-44444444'],
920
+ mutability: PropertyMutability.MUTABLE,
921
+ }),
922
+ new PropertyMismatch({
923
+ propertyPath: 'VpcConfig.SecurityGroupIds',
924
+ expectedValue: ['sg-expected'],
925
+ actualValue: ['sg-actual'],
926
+ mutability: PropertyMutability.MUTABLE,
927
+ }),
928
+ ];
929
+
930
+ // Mock Lambda UpdateFunctionConfiguration
931
+ mockLambdaSend.mockResolvedValueOnce({
932
+ FunctionName: 'test-stack-health',
933
+ VpcConfig: {
934
+ SubnetIds: ['subnet-11111111', 'subnet-22222222'],
935
+ SecurityGroupIds: ['sg-expected'],
936
+ },
937
+ });
938
+
939
+ const result = await reconciler.reconcileMultipleProperties({
940
+ stackIdentifier,
941
+ logicalId: 'HealthLambdaFunction',
942
+ physicalId: 'test-stack-health',
943
+ resourceType: 'AWS::Lambda::Function',
944
+ mismatches,
945
+ mode: 'resource',
946
+ });
947
+
948
+ expect(result.reconciledCount).toBe(2);
949
+ expect(result.failedCount).toBe(0);
950
+ expect(result.results).toHaveLength(2);
951
+ expect(result.results[0].success).toBe(true);
952
+ expect(result.results[0].mode).toBe('resource');
953
+ expect(result.message).toContain('Lambda VpcConfig updated');
954
+
955
+ // Verify UpdateFunctionConfiguration was called once with all changes
956
+ expect(mockLambdaSend).toHaveBeenCalledTimes(1);
957
+
958
+ // Verify the command was constructed correctly
959
+ // AWS SDK v3 UpdateFunctionConfigurationCommand wraps input in the command object
960
+ const { UpdateFunctionConfigurationCommand } = require('@aws-sdk/client-lambda');
961
+ expect(UpdateFunctionConfigurationCommand).toHaveBeenCalledWith({
962
+ FunctionName: 'test-stack-health',
963
+ VpcConfig: {
964
+ SubnetIds: ['subnet-11111111', 'subnet-22222222'],
965
+ SecurityGroupIds: ['sg-expected'],
966
+ },
967
+ });
968
+ });
969
+
970
+ it('should handle multiple Lambda functions in parallel', async () => {
971
+ // This test verifies that the reconciler can handle multiple Lambda functions
972
+ // Each Lambda should get its own UpdateFunctionConfiguration call
973
+ const lambdas = [
974
+ {
975
+ logicalId: 'HealthLambdaFunction',
976
+ physicalId: 'test-stack-health',
977
+ mismatches: [
978
+ new PropertyMismatch({
979
+ propertyPath: 'VpcConfig.SubnetIds',
980
+ expectedValue: ['subnet-111'],
981
+ actualValue: ['subnet-999'],
982
+ mutability: PropertyMutability.MUTABLE,
983
+ }),
984
+ ],
985
+ },
986
+ {
987
+ logicalId: 'UserLambdaFunction',
988
+ physicalId: 'test-stack-user',
989
+ mismatches: [
990
+ new PropertyMismatch({
991
+ propertyPath: 'VpcConfig.SubnetIds',
992
+ expectedValue: ['subnet-222'],
993
+ actualValue: ['subnet-888'],
994
+ mutability: PropertyMutability.MUTABLE,
995
+ }),
996
+ ],
997
+ },
998
+ ];
999
+
1000
+ // Mock successful responses for each Lambda
1001
+ mockLambdaSend.mockResolvedValue({
1002
+ VpcConfig: { SubnetIds: [], SecurityGroupIds: [] },
1003
+ });
1004
+
1005
+ // Reconcile first Lambda
1006
+ const result1 = await reconciler.reconcileMultipleProperties({
1007
+ stackIdentifier,
1008
+ logicalId: lambdas[0].logicalId,
1009
+ physicalId: lambdas[0].physicalId,
1010
+ resourceType: 'AWS::Lambda::Function',
1011
+ mismatches: lambdas[0].mismatches,
1012
+ mode: 'resource',
1013
+ });
1014
+
1015
+ // Reconcile second Lambda
1016
+ const result2 = await reconciler.reconcileMultipleProperties({
1017
+ stackIdentifier,
1018
+ logicalId: lambdas[1].logicalId,
1019
+ physicalId: lambdas[1].physicalId,
1020
+ resourceType: 'AWS::Lambda::Function',
1021
+ mismatches: lambdas[1].mismatches,
1022
+ mode: 'resource',
1023
+ });
1024
+
1025
+ expect(result1.reconciledCount).toBe(1);
1026
+ expect(result2.reconciledCount).toBe(1);
1027
+ expect(mockLambdaSend).toHaveBeenCalledTimes(2);
1028
+ });
1029
+
1030
+ it('should handle Lambda update failures gracefully', async () => {
1031
+ const mismatches = [
1032
+ new PropertyMismatch({
1033
+ propertyPath: 'VpcConfig.SubnetIds',
1034
+ expectedValue: ['subnet-111'],
1035
+ actualValue: ['subnet-999'],
1036
+ mutability: PropertyMutability.MUTABLE,
1037
+ }),
1038
+ ];
1039
+
1040
+ // Mock Lambda API error
1041
+ mockLambdaSend.mockRejectedValueOnce(
1042
+ new Error('InvalidParameterValueException: Subnets not in same VPC')
1043
+ );
1044
+
1045
+ const result = await reconciler.reconcileMultipleProperties({
1046
+ stackIdentifier,
1047
+ logicalId: 'HealthLambdaFunction',
1048
+ physicalId: 'test-stack-health',
1049
+ resourceType: 'AWS::Lambda::Function',
1050
+ mismatches,
1051
+ mode: 'resource',
1052
+ });
1053
+
1054
+ expect(result.reconciledCount).toBe(0);
1055
+ expect(result.failedCount).toBe(1);
1056
+ expect(result.message).toContain('Failed to update Lambda');
1057
+ expect(result.results[0].success).toBe(false);
1058
+ });
1059
+
1060
+ it('should skip immutable properties in resource mode', async () => {
1061
+ const mismatches = [
1062
+ new PropertyMismatch({
1063
+ propertyPath: 'VpcConfig.SubnetIds',
1064
+ expectedValue: ['subnet-111'],
1065
+ actualValue: ['subnet-999'],
1066
+ mutability: PropertyMutability.MUTABLE,
1067
+ }),
1068
+ new PropertyMismatch({
1069
+ propertyPath: 'FunctionName',
1070
+ expectedValue: 'old-name',
1071
+ actualValue: 'new-name',
1072
+ mutability: PropertyMutability.IMMUTABLE,
1073
+ }),
1074
+ ];
1075
+
1076
+ mockLambdaSend.mockResolvedValue({
1077
+ VpcConfig: { SubnetIds: ['subnet-111'], SecurityGroupIds: [] },
1078
+ });
1079
+
1080
+ const result = await reconciler.reconcileMultipleProperties({
1081
+ stackIdentifier,
1082
+ logicalId: 'HealthLambdaFunction',
1083
+ physicalId: 'test-stack-health',
1084
+ resourceType: 'AWS::Lambda::Function',
1085
+ mismatches,
1086
+ mode: 'resource',
1087
+ });
1088
+
1089
+ // Only mutable property should be reconciled
1090
+ expect(result.reconciledCount).toBe(1);
1091
+ expect(result.skippedCount).toBe(1);
1092
+ expect(result.results).toHaveLength(2);
1093
+ expect(result.results[0].success).toBe(true); // VpcConfig
1094
+ expect(result.results[1].success).toBe(false); // FunctionName
1095
+ expect(result.results[1].message).toContain('immutable');
1096
+ });
1097
+
1098
+ it('should throw error for unsupported resource types in resource mode', async () => {
1099
+ const mismatches = [
1100
+ new PropertyMismatch({
1101
+ propertyPath: 'SomeProperty',
1102
+ expectedValue: 'value1',
1103
+ actualValue: 'value2',
1104
+ mutability: PropertyMutability.MUTABLE,
1105
+ }),
1106
+ ];
1107
+
1108
+ await expect(
1109
+ reconciler.reconcileMultipleProperties({
1110
+ stackIdentifier,
1111
+ logicalId: 'MyUnsupportedResource',
1112
+ physicalId: 'resource-123',
1113
+ resourceType: 'AWS::Unsupported::Resource',
1114
+ mismatches,
1115
+ mode: 'resource',
1116
+ })
1117
+ ).rejects.toThrow('Resource mode reconciliation not supported for AWS::Unsupported::Resource');
1118
+ });
1119
+ });
1120
+ });
1121
+
1122
+ describe('constructor', () => {
1123
+ it('should create instance with default region', () => {
1124
+ const rec = new AWSPropertyReconciler();
1125
+ expect(rec).toBeInstanceOf(AWSPropertyReconciler);
1126
+ });
1127
+
1128
+ it('should create instance with custom region', () => {
1129
+ const rec = new AWSPropertyReconciler({ region: 'eu-west-1' });
1130
+ expect(rec).toBeInstanceOf(AWSPropertyReconciler);
1131
+ });
1132
+ });
1133
+ });