@gugananuvem/aws-local-simulator 1.0.15 → 1.0.16

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 (77) hide show
  1. package/README.md +789 -594
  2. package/bin/aws-local-simulator.js +63 -63
  3. package/package.json +2 -2
  4. package/src/config/config-loader.js +114 -114
  5. package/src/config/default-config.js +68 -68
  6. package/src/config/env-loader.js +68 -68
  7. package/src/index.js +146 -146
  8. package/src/index.mjs +123 -123
  9. package/src/server.js +227 -227
  10. package/src/services/apigateway/index.js +75 -73
  11. package/src/services/apigateway/server.js +570 -507
  12. package/src/services/apigateway/simulator.js +1261 -1261
  13. package/src/services/athena/index.js +75 -75
  14. package/src/services/athena/server.js +101 -101
  15. package/src/services/athena/simulador.js +998 -998
  16. package/src/services/athena/simulator.js +346 -346
  17. package/src/services/cloudformation/index.js +106 -106
  18. package/src/services/cloudformation/server.js +417 -417
  19. package/src/services/cloudformation/simulador.js +1045 -1045
  20. package/src/services/cloudtrail/index.js +84 -84
  21. package/src/services/cloudtrail/server.js +235 -235
  22. package/src/services/cloudtrail/simulador.js +719 -719
  23. package/src/services/cloudwatch/index.js +84 -84
  24. package/src/services/cloudwatch/server.js +366 -366
  25. package/src/services/cloudwatch/simulador.js +1173 -1173
  26. package/src/services/cognito/index.js +79 -79
  27. package/src/services/cognito/server.js +301 -301
  28. package/src/services/cognito/simulator.js +1655 -1655
  29. package/src/services/config/index.js +96 -96
  30. package/src/services/config/server.js +215 -215
  31. package/src/services/config/simulador.js +1260 -1260
  32. package/src/services/dynamodb/index.js +74 -74
  33. package/src/services/dynamodb/server.js +125 -125
  34. package/src/services/dynamodb/simulator.js +630 -630
  35. package/src/services/ecs/index.js +65 -65
  36. package/src/services/ecs/server.js +235 -235
  37. package/src/services/ecs/simulator.js +844 -844
  38. package/src/services/eventbridge/index.js +89 -89
  39. package/src/services/eventbridge/server.js +209 -209
  40. package/src/services/eventbridge/simulator.js +684 -684
  41. package/src/services/index.js +45 -45
  42. package/src/services/kms/index.js +75 -75
  43. package/src/services/kms/server.js +67 -67
  44. package/src/services/kms/simulator.js +324 -324
  45. package/src/services/lambda/handler-loader.js +183 -183
  46. package/src/services/lambda/index.js +78 -78
  47. package/src/services/lambda/route-registry.js +274 -274
  48. package/src/services/lambda/server.js +145 -145
  49. package/src/services/lambda/simulator.js +199 -199
  50. package/src/services/parameter-store/index.js +80 -80
  51. package/src/services/parameter-store/server.js +50 -50
  52. package/src/services/parameter-store/simulator.js +201 -201
  53. package/src/services/s3/index.js +73 -73
  54. package/src/services/s3/server.js +329 -329
  55. package/src/services/s3/simulator.js +565 -565
  56. package/src/services/secret-manager/index.js +80 -80
  57. package/src/services/secret-manager/server.js +50 -50
  58. package/src/services/secret-manager/simulator.js +171 -171
  59. package/src/services/sns/index.js +89 -89
  60. package/src/services/sns/server.js +580 -580
  61. package/src/services/sns/simulator.js +1482 -1482
  62. package/src/services/sqs/index.js +98 -93
  63. package/src/services/sqs/server.js +349 -349
  64. package/src/services/sqs/simulator.js +441 -441
  65. package/src/services/sts/index.js +37 -37
  66. package/src/services/sts/server.js +144 -144
  67. package/src/services/sts/simulator.js +69 -69
  68. package/src/services/xray/index.js +83 -83
  69. package/src/services/xray/server.js +308 -308
  70. package/src/services/xray/simulador.js +994 -994
  71. package/src/template/aws-config-template.js +87 -87
  72. package/src/template/aws-config-template.mjs +90 -90
  73. package/src/template/config-template.json +203 -203
  74. package/src/utils/aws-config.js +91 -91
  75. package/src/utils/cloudtrail-audit.js +129 -129
  76. package/src/utils/local-store.js +83 -83
  77. package/src/utils/logger.js +59 -59
@@ -1,417 +1,417 @@
1
- 'use strict';
2
-
3
- /**
4
- * @fileoverview CloudFormation HTTP Server
5
- *
6
- * Protocolo: application/x-www-form-urlencoded (Query API)
7
- * Action via body: Action=CreateStack&...
8
- * Compatível com AWS SDK v3 CloudFormationClient
9
- *
10
- * Ações suportadas:
11
- * CreateStack, UpdateStack, DeleteStack
12
- * DescribeStacks, ListStacks
13
- * ValidateTemplate, GetTemplate
14
- * DescribeStackResources, ListStackResources
15
- * CreateChangeSet, DescribeChangeSet, ExecuteChangeSet, DeleteChangeSet, ListChangeSets
16
- */
17
-
18
- const express = require('express');
19
- const cors = require('cors');
20
-
21
- /**
22
- * Converte objeto JS em XML CloudFormation simples
23
- */
24
- function toXml(tag, value, indent = '') {
25
- if (value === null || value === undefined) return '';
26
-
27
- if (Array.isArray(value)) {
28
- if (value.length === 0) return `${indent}<${tag}/>`;
29
- return `${indent}<${tag}>${value.map(v => toXml('member', v, indent + ' ')).join('')}</${tag}>`;
30
- }
31
-
32
- if (typeof value === 'object') {
33
- const inner = Object.entries(value)
34
- .map(([k, v]) => toXml(k, v, indent + ' '))
35
- .join('');
36
- return `${indent}<${tag}>${inner}</${tag}>`;
37
- }
38
-
39
- return `${indent}<${tag}>${String(value)}</${tag}>`;
40
- }
41
-
42
- /**
43
- * Envolve uma resposta no padrão de wrapper XML da CloudFormation
44
- */
45
- function wrapResponse(action, data) {
46
- const inner = Object.entries(data)
47
- .map(([k, v]) => toXml(k, v, ' '))
48
- .join('');
49
-
50
- return `<?xml version="1.0" encoding="UTF-8"?>
51
- <${action}Response xmlns="http://cloudformation.amazonaws.com/doc/2010-05-15/">
52
- <${action}Result>
53
- ${inner}
54
- </${action}Result>
55
- <ResponseMetadata>
56
- <RequestId>${require('crypto').randomUUID()}</RequestId>
57
- </ResponseMetadata>
58
- </${action}Response>`;
59
- }
60
-
61
- /**
62
- * Envolve erro no padrão XML da CloudFormation
63
- */
64
- function wrapError(code, message) {
65
- return `<?xml version="1.0" encoding="UTF-8"?>
66
- <ErrorResponse xmlns="http://cloudformation.amazonaws.com/doc/2010-05-15/">
67
- <Error>
68
- <Type>Sender</Type>
69
- <Code>${code}</Code>
70
- <Message>${message}</Message>
71
- </Error>
72
- <RequestId>${require('crypto').randomUUID()}</RequestId>
73
- </ErrorResponse>`;
74
- }
75
-
76
- /**
77
- * Parse de form-encoded body para objeto (inclui membros da AWS como param.1.key=, etc.)
78
- */
79
- function parseFormBody(body) {
80
- if (!body || typeof body !== 'object') return body || {};
81
- return body;
82
- }
83
-
84
- /**
85
- * Converte Parameters.member.N.ParameterKey/Value para array
86
- */
87
- function extractParameters(body) {
88
- const params = [];
89
- let i = 1;
90
- while (body[`Parameters.member.${i}.ParameterKey`]) {
91
- params.push({
92
- ParameterKey: body[`Parameters.member.${i}.ParameterKey`],
93
- ParameterValue: body[`Parameters.member.${i}.ParameterValue`] || '',
94
- UsePreviousValue: body[`Parameters.member.${i}.UsePreviousValue`] === 'true',
95
- });
96
- i++;
97
- }
98
- return params;
99
- }
100
-
101
- /**
102
- * Converte Tags.member.N.Key/Value para array
103
- */
104
- function extractTags(body) {
105
- const tags = [];
106
- let i = 1;
107
- while (body[`Tags.member.${i}.Key`]) {
108
- tags.push({
109
- Key: body[`Tags.member.${i}.Key`],
110
- Value: body[`Tags.member.${i}.Value`] || '',
111
- });
112
- i++;
113
- }
114
- return tags;
115
- }
116
-
117
- /**
118
- * Converte Capabilities.member.N para array
119
- */
120
- function extractCapabilities(body) {
121
- const caps = [];
122
- let i = 1;
123
- while (body[`Capabilities.member.${i}`]) {
124
- caps.push(body[`Capabilities.member.${i}`]);
125
- i++;
126
- }
127
- return caps;
128
- }
129
-
130
- /**
131
- * Converte StackStatusFilter.member.N para array
132
- */
133
- function extractStackStatusFilter(body) {
134
- const filters = [];
135
- let i = 1;
136
- while (body[`StackStatusFilter.member.${i}`]) {
137
- filters.push(body[`StackStatusFilter.member.${i}`]);
138
- i++;
139
- }
140
- return filters;
141
- }
142
-
143
- /**
144
- * Cria Express app do CloudFormation
145
- */
146
- function createCloudFormationServer(simulator, config, logger) {
147
- const app = express();
148
-
149
- // ── Middlewares ──────────────────────────────────────────────────
150
- if (config.cors?.enabled !== false) {
151
- app.use(cors({ origin: config.cors?.origin || '*' }));
152
- }
153
-
154
- // Suporte a form-encoded (protocolo Query da CloudFormation)
155
- app.use(express.urlencoded({ extended: true, limit: '10mb' }));
156
- app.use(express.json({ limit: '10mb' }));
157
-
158
- // Logger
159
- app.use((req, _res, next) => {
160
- const action = req.body?.Action || req.query?.Action || '';
161
- if (action) logger.debug(`[CloudFormation] ${req.method} ${req.path} Action=${action}`);
162
- next();
163
- });
164
-
165
- // ── Rota principal ───────────────────────────────────────────────
166
- app.post('/', async (req, res) => {
167
- const body = parseFormBody(req.body || {});
168
- const action = body.Action || req.query?.Action;
169
-
170
- if (!action) {
171
- res.status(400).type('application/xml').send(wrapError('MissingAction', 'Action is required'));
172
- return;
173
- }
174
-
175
- try {
176
- return await dispatch(action, body, simulator, res, logger);
177
- } catch (err) {
178
- logger.error(`[CloudFormation] [${action}] ${err.message}`);
179
- const statusCode = err.statusCode || 500;
180
- res.status(statusCode).type('application/xml').send(
181
- wrapError(err.code || 'InternalError', err.message)
182
- );
183
- }
184
- });
185
-
186
- // ── Admin routes ─────────────────────────────────────────────────
187
- app.get('/__admin/health', (_req, res) => {
188
- res.json({
189
- status: 'healthy',
190
- service: 'cloudformation',
191
- ...simulator.getStats(),
192
- timestamp: new Date().toISOString(),
193
- });
194
- });
195
-
196
- app.get('/__admin/stacks', (_req, res) => {
197
- try {
198
- const result = simulator.describeStacks({});
199
- res.json({ stacks: result.Stacks });
200
- } catch (err) {
201
- res.status(500).json({ error: err.message });
202
- }
203
- });
204
-
205
- app.get('/__admin/stacks/:name', (req, res) => {
206
- try {
207
- const result = simulator.describeStacks({ StackName: req.params.name });
208
- res.json(result.Stacks[0] || {});
209
- } catch (err) {
210
- res.status(404).json({ error: err.message });
211
- }
212
- });
213
-
214
- app.get('/__admin/stacks/:name/resources', (req, res) => {
215
- try {
216
- const result = simulator.listStackResources({ StackName: req.params.name });
217
- res.json(result);
218
- } catch (err) {
219
- res.status(404).json({ error: err.message });
220
- }
221
- });
222
-
223
- app.get('/__admin/changesets', (req, res) => {
224
- try {
225
- const stackName = req.query.stackName || '';
226
- if (stackName) {
227
- const result = simulator.listChangeSets({ StackName: stackName });
228
- res.json(result);
229
- } else {
230
- // Retorna todos os change sets
231
- const all = Array.from(simulator.changeSets.values());
232
- res.json({ Summaries: all });
233
- }
234
- } catch (err) {
235
- res.status(500).json({ error: err.message });
236
- }
237
- });
238
-
239
- app.post('/__admin/reset', async (_req, res) => {
240
- await simulator.reset();
241
- res.json({ message: 'CloudFormation data reset complete' });
242
- });
243
-
244
- // ── Catch-all ─────────────────────────────────────────────────────
245
- app.use((req, res) => {
246
- res.status(404).type('application/xml').send(
247
- wrapError('NotFound', `Route not found: ${req.method} ${req.path}`)
248
- );
249
- });
250
-
251
- return app;
252
- }
253
-
254
- // ─── Dispatcher ───────────────────────────────────────────────────────────────
255
-
256
- async function dispatch(action, body, simulator, res, logger) {
257
- switch (action) {
258
- // ── Stacks ──────────────────────────────────────────────────────
259
- case 'CreateStack': {
260
- const result = await simulator.createStack({
261
- StackName: body.StackName,
262
- TemplateBody: body.TemplateBody,
263
- TemplateURL: body.TemplateURL,
264
- Parameters: extractParameters(body),
265
- Capabilities: extractCapabilities(body),
266
- Tags: extractTags(body),
267
- OnFailure: body.OnFailure,
268
- TimeoutInMinutes: body.TimeoutInMinutes ? parseInt(body.TimeoutInMinutes) : undefined,
269
- DisableRollback: body.DisableRollback === 'true',
270
- RoleARN: body.RoleARN,
271
- });
272
- res.type('application/xml').send(wrapResponse('CreateStack', result));
273
- return;
274
- }
275
-
276
- case 'UpdateStack': {
277
- const result = await simulator.updateStack({
278
- StackName: body.StackName,
279
- TemplateBody: body.TemplateBody,
280
- UsePreviousTemplate: body.UsePreviousTemplate === 'true',
281
- Parameters: extractParameters(body),
282
- Capabilities: extractCapabilities(body),
283
- Tags: extractTags(body).length ? extractTags(body) : undefined,
284
- RoleARN: body.RoleARN,
285
- });
286
- res.type('application/xml').send(wrapResponse('UpdateStack', result));
287
- return;
288
- }
289
-
290
- case 'DeleteStack': {
291
- await simulator.deleteStack({
292
- StackName: body.StackName,
293
- });
294
- res.type('application/xml').send(wrapResponse('DeleteStack', {}));
295
- return;
296
- }
297
-
298
- case 'DescribeStacks': {
299
- const result = simulator.describeStacks({ StackName: body.StackName });
300
- // Envolve Stacks no formato member esperado pelo AWS CLI
301
- res.type('application/xml').send(wrapResponse('DescribeStacks', {
302
- Stacks: result.Stacks
303
- }));
304
- return;
305
- }
306
-
307
- case 'ListStacks': {
308
- const result = simulator.listStacks({
309
- StackStatusFilter: extractStackStatusFilter(body),
310
- NextToken: body.NextToken,
311
- });
312
- res.type('application/xml').send(wrapResponse('ListStacks', result));
313
- return;
314
- }
315
-
316
- // ── Template ────────────────────────────────────────────────────
317
- case 'ValidateTemplate': {
318
- const result = simulator.validateTemplate({
319
- TemplateBody: body.TemplateBody,
320
- TemplateURL: body.TemplateURL,
321
- });
322
- res.type('application/xml').send(wrapResponse('ValidateTemplate', result));
323
- return;
324
- }
325
-
326
- case 'GetTemplate': {
327
- const result = simulator.getTemplate({
328
- StackName: body.StackName,
329
- TemplateStage: body.TemplateStage,
330
- });
331
- res.type('application/xml').send(wrapResponse('GetTemplate', result));
332
- return;
333
- }
334
-
335
- // ── StackResources ──────────────────────────────────────────────
336
- case 'DescribeStackResources': {
337
- const result = simulator.describeStackResources({
338
- StackName: body.StackName,
339
- LogicalResourceId: body.LogicalResourceId,
340
- });
341
- res.type('application/xml').send(wrapResponse('DescribeStackResources', result));
342
- return;
343
- }
344
-
345
- case 'ListStackResources': {
346
- const result = simulator.listStackResources({
347
- StackName: body.StackName,
348
- NextToken: body.NextToken,
349
- });
350
- res.type('application/xml').send(wrapResponse('ListStackResources', result));
351
- return;
352
- }
353
-
354
- // ── ChangeSets ──────────────────────────────────────────────────
355
- case 'CreateChangeSet': {
356
- const result = await simulator.createChangeSet({
357
- StackName: body.StackName,
358
- ChangeSetName: body.ChangeSetName,
359
- TemplateBody: body.TemplateBody,
360
- UsePreviousTemplate: body.UsePreviousTemplate === 'true',
361
- Parameters: extractParameters(body),
362
- Capabilities: extractCapabilities(body),
363
- Tags: extractTags(body),
364
- Description: body.Description || '',
365
- ChangeSetType: body.ChangeSetType || 'UPDATE',
366
- });
367
- res.type('application/xml').send(wrapResponse('CreateChangeSet', result));
368
- return;
369
- }
370
-
371
- case 'DescribeChangeSet': {
372
- const result = simulator.describeChangeSet({
373
- ChangeSetName: body.ChangeSetName,
374
- StackName: body.StackName,
375
- NextToken: body.NextToken,
376
- });
377
- res.type('application/xml').send(wrapResponse('DescribeChangeSet', result));
378
- return;
379
- }
380
-
381
- case 'ExecuteChangeSet': {
382
- const result = await simulator.executeChangeSet({
383
- ChangeSetName: body.ChangeSetName,
384
- StackName: body.StackName,
385
- ClientRequestToken: body.ClientRequestToken,
386
- });
387
- res.type('application/xml').send(wrapResponse('ExecuteChangeSet', result));
388
- return;
389
- }
390
-
391
- case 'DeleteChangeSet': {
392
- await simulator.deleteChangeSet({
393
- ChangeSetName: body.ChangeSetName,
394
- StackName: body.StackName,
395
- });
396
- res.type('application/xml').send(wrapResponse('DeleteChangeSet', {}));
397
- return;
398
- }
399
-
400
- case 'ListChangeSets': {
401
- const result = simulator.listChangeSets({
402
- StackName: body.StackName,
403
- NextToken: body.NextToken,
404
- });
405
- res.type('application/xml').send(wrapResponse('ListChangeSets', result));
406
- return;
407
- }
408
-
409
- default: {
410
- res.status(400).type('application/xml').send(
411
- wrapError('InvalidAction', `Action not supported: ${action}`)
412
- );
413
- }
414
- }
415
- }
416
-
417
- module.exports = { createCloudFormationServer };
1
+ 'use strict';
2
+
3
+ /**
4
+ * @fileoverview CloudFormation HTTP Server
5
+ *
6
+ * Protocolo: application/x-www-form-urlencoded (Query API)
7
+ * Action via body: Action=CreateStack&...
8
+ * Compatível com AWS SDK v3 CloudFormationClient
9
+ *
10
+ * Ações suportadas:
11
+ * CreateStack, UpdateStack, DeleteStack
12
+ * DescribeStacks, ListStacks
13
+ * ValidateTemplate, GetTemplate
14
+ * DescribeStackResources, ListStackResources
15
+ * CreateChangeSet, DescribeChangeSet, ExecuteChangeSet, DeleteChangeSet, ListChangeSets
16
+ */
17
+
18
+ const express = require('express');
19
+ const cors = require('cors');
20
+
21
+ /**
22
+ * Converte objeto JS em XML CloudFormation simples
23
+ */
24
+ function toXml(tag, value, indent = '') {
25
+ if (value === null || value === undefined) return '';
26
+
27
+ if (Array.isArray(value)) {
28
+ if (value.length === 0) return `${indent}<${tag}/>`;
29
+ return `${indent}<${tag}>${value.map(v => toXml('member', v, indent + ' ')).join('')}</${tag}>`;
30
+ }
31
+
32
+ if (typeof value === 'object') {
33
+ const inner = Object.entries(value)
34
+ .map(([k, v]) => toXml(k, v, indent + ' '))
35
+ .join('');
36
+ return `${indent}<${tag}>${inner}</${tag}>`;
37
+ }
38
+
39
+ return `${indent}<${tag}>${String(value)}</${tag}>`;
40
+ }
41
+
42
+ /**
43
+ * Envolve uma resposta no padrão de wrapper XML da CloudFormation
44
+ */
45
+ function wrapResponse(action, data) {
46
+ const inner = Object.entries(data)
47
+ .map(([k, v]) => toXml(k, v, ' '))
48
+ .join('');
49
+
50
+ return `<?xml version="1.0" encoding="UTF-8"?>
51
+ <${action}Response xmlns="http://cloudformation.amazonaws.com/doc/2010-05-15/">
52
+ <${action}Result>
53
+ ${inner}
54
+ </${action}Result>
55
+ <ResponseMetadata>
56
+ <RequestId>${require('crypto').randomUUID()}</RequestId>
57
+ </ResponseMetadata>
58
+ </${action}Response>`;
59
+ }
60
+
61
+ /**
62
+ * Envolve erro no padrão XML da CloudFormation
63
+ */
64
+ function wrapError(code, message) {
65
+ return `<?xml version="1.0" encoding="UTF-8"?>
66
+ <ErrorResponse xmlns="http://cloudformation.amazonaws.com/doc/2010-05-15/">
67
+ <Error>
68
+ <Type>Sender</Type>
69
+ <Code>${code}</Code>
70
+ <Message>${message}</Message>
71
+ </Error>
72
+ <RequestId>${require('crypto').randomUUID()}</RequestId>
73
+ </ErrorResponse>`;
74
+ }
75
+
76
+ /**
77
+ * Parse de form-encoded body para objeto (inclui membros da AWS como param.1.key=, etc.)
78
+ */
79
+ function parseFormBody(body) {
80
+ if (!body || typeof body !== 'object') return body || {};
81
+ return body;
82
+ }
83
+
84
+ /**
85
+ * Converte Parameters.member.N.ParameterKey/Value para array
86
+ */
87
+ function extractParameters(body) {
88
+ const params = [];
89
+ let i = 1;
90
+ while (body[`Parameters.member.${i}.ParameterKey`]) {
91
+ params.push({
92
+ ParameterKey: body[`Parameters.member.${i}.ParameterKey`],
93
+ ParameterValue: body[`Parameters.member.${i}.ParameterValue`] || '',
94
+ UsePreviousValue: body[`Parameters.member.${i}.UsePreviousValue`] === 'true',
95
+ });
96
+ i++;
97
+ }
98
+ return params;
99
+ }
100
+
101
+ /**
102
+ * Converte Tags.member.N.Key/Value para array
103
+ */
104
+ function extractTags(body) {
105
+ const tags = [];
106
+ let i = 1;
107
+ while (body[`Tags.member.${i}.Key`]) {
108
+ tags.push({
109
+ Key: body[`Tags.member.${i}.Key`],
110
+ Value: body[`Tags.member.${i}.Value`] || '',
111
+ });
112
+ i++;
113
+ }
114
+ return tags;
115
+ }
116
+
117
+ /**
118
+ * Converte Capabilities.member.N para array
119
+ */
120
+ function extractCapabilities(body) {
121
+ const caps = [];
122
+ let i = 1;
123
+ while (body[`Capabilities.member.${i}`]) {
124
+ caps.push(body[`Capabilities.member.${i}`]);
125
+ i++;
126
+ }
127
+ return caps;
128
+ }
129
+
130
+ /**
131
+ * Converte StackStatusFilter.member.N para array
132
+ */
133
+ function extractStackStatusFilter(body) {
134
+ const filters = [];
135
+ let i = 1;
136
+ while (body[`StackStatusFilter.member.${i}`]) {
137
+ filters.push(body[`StackStatusFilter.member.${i}`]);
138
+ i++;
139
+ }
140
+ return filters;
141
+ }
142
+
143
+ /**
144
+ * Cria Express app do CloudFormation
145
+ */
146
+ function createCloudFormationServer(simulator, config, logger) {
147
+ const app = express();
148
+
149
+ // ── Middlewares ──────────────────────────────────────────────────
150
+ if (config.cors?.enabled !== false) {
151
+ app.use(cors({ origin: config.cors?.origin || '*' }));
152
+ }
153
+
154
+ // Suporte a form-encoded (protocolo Query da CloudFormation)
155
+ app.use(express.urlencoded({ extended: true, limit: '10mb' }));
156
+ app.use(express.json({ limit: '10mb' }));
157
+
158
+ // Logger
159
+ app.use((req, _res, next) => {
160
+ const action = req.body?.Action || req.query?.Action || '';
161
+ if (action) logger.debug(`[CloudFormation] ${req.method} ${req.path} Action=${action}`);
162
+ next();
163
+ });
164
+
165
+ // ── Rota principal ───────────────────────────────────────────────
166
+ app.post('/', async (req, res) => {
167
+ const body = parseFormBody(req.body || {});
168
+ const action = body.Action || req.query?.Action;
169
+
170
+ if (!action) {
171
+ res.status(400).type('application/xml').send(wrapError('MissingAction', 'Action is required'));
172
+ return;
173
+ }
174
+
175
+ try {
176
+ return await dispatch(action, body, simulator, res, logger);
177
+ } catch (err) {
178
+ logger.error(`[CloudFormation] [${action}] ${err.message}`);
179
+ const statusCode = err.statusCode || 500;
180
+ res.status(statusCode).type('application/xml').send(
181
+ wrapError(err.code || 'InternalError', err.message)
182
+ );
183
+ }
184
+ });
185
+
186
+ // ── Admin routes ─────────────────────────────────────────────────
187
+ app.get('/__admin/health', (_req, res) => {
188
+ res.json({
189
+ status: 'healthy',
190
+ service: 'cloudformation',
191
+ ...simulator.getStats(),
192
+ timestamp: new Date().toISOString(),
193
+ });
194
+ });
195
+
196
+ app.get('/__admin/stacks', (_req, res) => {
197
+ try {
198
+ const result = simulator.describeStacks({});
199
+ res.json({ stacks: result.Stacks });
200
+ } catch (err) {
201
+ res.status(500).json({ error: err.message });
202
+ }
203
+ });
204
+
205
+ app.get('/__admin/stacks/:name', (req, res) => {
206
+ try {
207
+ const result = simulator.describeStacks({ StackName: req.params.name });
208
+ res.json(result.Stacks[0] || {});
209
+ } catch (err) {
210
+ res.status(404).json({ error: err.message });
211
+ }
212
+ });
213
+
214
+ app.get('/__admin/stacks/:name/resources', (req, res) => {
215
+ try {
216
+ const result = simulator.listStackResources({ StackName: req.params.name });
217
+ res.json(result);
218
+ } catch (err) {
219
+ res.status(404).json({ error: err.message });
220
+ }
221
+ });
222
+
223
+ app.get('/__admin/changesets', (req, res) => {
224
+ try {
225
+ const stackName = req.query.stackName || '';
226
+ if (stackName) {
227
+ const result = simulator.listChangeSets({ StackName: stackName });
228
+ res.json(result);
229
+ } else {
230
+ // Retorna todos os change sets
231
+ const all = Array.from(simulator.changeSets.values());
232
+ res.json({ Summaries: all });
233
+ }
234
+ } catch (err) {
235
+ res.status(500).json({ error: err.message });
236
+ }
237
+ });
238
+
239
+ app.post('/__admin/reset', async (_req, res) => {
240
+ await simulator.reset();
241
+ res.json({ message: 'CloudFormation data reset complete' });
242
+ });
243
+
244
+ // ── Catch-all ─────────────────────────────────────────────────────
245
+ app.use((req, res) => {
246
+ res.status(404).type('application/xml').send(
247
+ wrapError('NotFound', `Route not found: ${req.method} ${req.path}`)
248
+ );
249
+ });
250
+
251
+ return app;
252
+ }
253
+
254
+ // ─── Dispatcher ───────────────────────────────────────────────────────────────
255
+
256
+ async function dispatch(action, body, simulator, res, logger) {
257
+ switch (action) {
258
+ // ── Stacks ──────────────────────────────────────────────────────
259
+ case 'CreateStack': {
260
+ const result = await simulator.createStack({
261
+ StackName: body.StackName,
262
+ TemplateBody: body.TemplateBody,
263
+ TemplateURL: body.TemplateURL,
264
+ Parameters: extractParameters(body),
265
+ Capabilities: extractCapabilities(body),
266
+ Tags: extractTags(body),
267
+ OnFailure: body.OnFailure,
268
+ TimeoutInMinutes: body.TimeoutInMinutes ? parseInt(body.TimeoutInMinutes) : undefined,
269
+ DisableRollback: body.DisableRollback === 'true',
270
+ RoleARN: body.RoleARN,
271
+ });
272
+ res.type('application/xml').send(wrapResponse('CreateStack', result));
273
+ return;
274
+ }
275
+
276
+ case 'UpdateStack': {
277
+ const result = await simulator.updateStack({
278
+ StackName: body.StackName,
279
+ TemplateBody: body.TemplateBody,
280
+ UsePreviousTemplate: body.UsePreviousTemplate === 'true',
281
+ Parameters: extractParameters(body),
282
+ Capabilities: extractCapabilities(body),
283
+ Tags: extractTags(body).length ? extractTags(body) : undefined,
284
+ RoleARN: body.RoleARN,
285
+ });
286
+ res.type('application/xml').send(wrapResponse('UpdateStack', result));
287
+ return;
288
+ }
289
+
290
+ case 'DeleteStack': {
291
+ await simulator.deleteStack({
292
+ StackName: body.StackName,
293
+ });
294
+ res.type('application/xml').send(wrapResponse('DeleteStack', {}));
295
+ return;
296
+ }
297
+
298
+ case 'DescribeStacks': {
299
+ const result = simulator.describeStacks({ StackName: body.StackName });
300
+ // Envolve Stacks no formato member esperado pelo AWS CLI
301
+ res.type('application/xml').send(wrapResponse('DescribeStacks', {
302
+ Stacks: result.Stacks
303
+ }));
304
+ return;
305
+ }
306
+
307
+ case 'ListStacks': {
308
+ const result = simulator.listStacks({
309
+ StackStatusFilter: extractStackStatusFilter(body),
310
+ NextToken: body.NextToken,
311
+ });
312
+ res.type('application/xml').send(wrapResponse('ListStacks', result));
313
+ return;
314
+ }
315
+
316
+ // ── Template ────────────────────────────────────────────────────
317
+ case 'ValidateTemplate': {
318
+ const result = simulator.validateTemplate({
319
+ TemplateBody: body.TemplateBody,
320
+ TemplateURL: body.TemplateURL,
321
+ });
322
+ res.type('application/xml').send(wrapResponse('ValidateTemplate', result));
323
+ return;
324
+ }
325
+
326
+ case 'GetTemplate': {
327
+ const result = simulator.getTemplate({
328
+ StackName: body.StackName,
329
+ TemplateStage: body.TemplateStage,
330
+ });
331
+ res.type('application/xml').send(wrapResponse('GetTemplate', result));
332
+ return;
333
+ }
334
+
335
+ // ── StackResources ──────────────────────────────────────────────
336
+ case 'DescribeStackResources': {
337
+ const result = simulator.describeStackResources({
338
+ StackName: body.StackName,
339
+ LogicalResourceId: body.LogicalResourceId,
340
+ });
341
+ res.type('application/xml').send(wrapResponse('DescribeStackResources', result));
342
+ return;
343
+ }
344
+
345
+ case 'ListStackResources': {
346
+ const result = simulator.listStackResources({
347
+ StackName: body.StackName,
348
+ NextToken: body.NextToken,
349
+ });
350
+ res.type('application/xml').send(wrapResponse('ListStackResources', result));
351
+ return;
352
+ }
353
+
354
+ // ── ChangeSets ──────────────────────────────────────────────────
355
+ case 'CreateChangeSet': {
356
+ const result = await simulator.createChangeSet({
357
+ StackName: body.StackName,
358
+ ChangeSetName: body.ChangeSetName,
359
+ TemplateBody: body.TemplateBody,
360
+ UsePreviousTemplate: body.UsePreviousTemplate === 'true',
361
+ Parameters: extractParameters(body),
362
+ Capabilities: extractCapabilities(body),
363
+ Tags: extractTags(body),
364
+ Description: body.Description || '',
365
+ ChangeSetType: body.ChangeSetType || 'UPDATE',
366
+ });
367
+ res.type('application/xml').send(wrapResponse('CreateChangeSet', result));
368
+ return;
369
+ }
370
+
371
+ case 'DescribeChangeSet': {
372
+ const result = simulator.describeChangeSet({
373
+ ChangeSetName: body.ChangeSetName,
374
+ StackName: body.StackName,
375
+ NextToken: body.NextToken,
376
+ });
377
+ res.type('application/xml').send(wrapResponse('DescribeChangeSet', result));
378
+ return;
379
+ }
380
+
381
+ case 'ExecuteChangeSet': {
382
+ const result = await simulator.executeChangeSet({
383
+ ChangeSetName: body.ChangeSetName,
384
+ StackName: body.StackName,
385
+ ClientRequestToken: body.ClientRequestToken,
386
+ });
387
+ res.type('application/xml').send(wrapResponse('ExecuteChangeSet', result));
388
+ return;
389
+ }
390
+
391
+ case 'DeleteChangeSet': {
392
+ await simulator.deleteChangeSet({
393
+ ChangeSetName: body.ChangeSetName,
394
+ StackName: body.StackName,
395
+ });
396
+ res.type('application/xml').send(wrapResponse('DeleteChangeSet', {}));
397
+ return;
398
+ }
399
+
400
+ case 'ListChangeSets': {
401
+ const result = simulator.listChangeSets({
402
+ StackName: body.StackName,
403
+ NextToken: body.NextToken,
404
+ });
405
+ res.type('application/xml').send(wrapResponse('ListChangeSets', result));
406
+ return;
407
+ }
408
+
409
+ default: {
410
+ res.status(400).type('application/xml').send(
411
+ wrapError('InvalidAction', `Action not supported: ${action}`)
412
+ );
413
+ }
414
+ }
415
+ }
416
+
417
+ module.exports = { createCloudFormationServer };