@gugananuvem/aws-local-simulator 1.0.12 → 1.0.14

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 (57) hide show
  1. package/README.md +235 -11
  2. package/package.json +12 -2
  3. package/src/config/default-config.js +1 -0
  4. package/src/index.js +18 -2
  5. package/src/server.js +36 -32
  6. package/src/services/apigateway/index.js +5 -0
  7. package/src/services/apigateway/server.js +20 -0
  8. package/src/services/apigateway/simulator.js +13 -3
  9. package/src/services/athena/index.js +75 -0
  10. package/src/services/athena/server.js +101 -0
  11. package/src/services/athena/simulador.js +998 -0
  12. package/src/services/athena/simulator.js +346 -0
  13. package/src/services/cloudformation/index.js +106 -0
  14. package/src/services/cloudformation/server.js +417 -0
  15. package/src/services/cloudformation/simulador.js +1045 -0
  16. package/src/services/cloudtrail/index.js +84 -0
  17. package/src/services/cloudtrail/server.js +235 -0
  18. package/src/services/cloudtrail/simulador.js +719 -0
  19. package/src/services/cloudwatch/index.js +84 -0
  20. package/src/services/cloudwatch/server.js +366 -0
  21. package/src/services/cloudwatch/simulador.js +1173 -0
  22. package/src/services/cognito/index.js +5 -0
  23. package/src/services/cognito/simulator.js +4 -0
  24. package/src/services/config/index.js +96 -0
  25. package/src/services/config/server.js +215 -0
  26. package/src/services/config/simulador.js +1260 -0
  27. package/src/services/dynamodb/index.js +7 -3
  28. package/src/services/dynamodb/server.js +4 -2
  29. package/src/services/dynamodb/simulator.js +39 -29
  30. package/src/services/eventbridge/index.js +55 -51
  31. package/src/services/eventbridge/server.js +209 -0
  32. package/src/services/eventbridge/simulator.js +684 -0
  33. package/src/services/index.js +30 -4
  34. package/src/services/kms/index.js +75 -0
  35. package/src/services/kms/server.js +67 -0
  36. package/src/services/kms/simulator.js +324 -0
  37. package/src/services/lambda/index.js +5 -0
  38. package/src/services/lambda/simulator.js +48 -38
  39. package/src/services/parameter-store/index.js +80 -0
  40. package/src/services/parameter-store/server.js +50 -0
  41. package/src/services/parameter-store/simulator.js +201 -0
  42. package/src/services/s3/index.js +7 -3
  43. package/src/services/s3/server.js +20 -13
  44. package/src/services/s3/simulator.js +163 -407
  45. package/src/services/secret-manager/index.js +80 -0
  46. package/src/services/secret-manager/server.js +50 -0
  47. package/src/services/secret-manager/simulator.js +171 -0
  48. package/src/services/sns/index.js +55 -42
  49. package/src/services/sns/server.js +580 -0
  50. package/src/services/sns/simulator.js +1482 -0
  51. package/src/services/sqs/index.js +2 -4
  52. package/src/services/sqs/server.js +4 -2
  53. package/src/services/xray/index.js +83 -0
  54. package/src/services/xray/server.js +308 -0
  55. package/src/services/xray/simulador.js +994 -0
  56. package/src/utils/cloudtrail-audit.js +129 -0
  57. package/src/utils/local-store.js +18 -2
@@ -21,16 +21,14 @@ class SQSService {
21
21
  const logger = require('../../utils/logger');
22
22
  logger.debug(`Inicializando SQS Service na porta ${this.port}...`);
23
23
 
24
- // Cria o simulador
25
24
  this.simulator = new SQSSimulator(this.config, this.lambdaService);
26
-
27
- // Cria o servidor HTTP
25
+ await this.simulator.initialize();
26
+
28
27
  this.server = new SQSServer(this.port, this.config, this.lambdaService);
29
28
  this.server.simulator = this.simulator;
30
29
 
31
30
  await this.server.initialize();
32
31
 
33
- // Configura filas associadas a Lambdas
34
32
  await this.setupQueueTriggers();
35
33
 
36
34
  logger.debug('SQS Service inicializado');
@@ -51,8 +51,10 @@ class SQSServer {
51
51
  }
52
52
 
53
53
  async initialize() {
54
- this.simulator = new SQSSimulator(this.config, this.lambdaService);
55
- await this.simulator.initialize();
54
+ if (!this.simulator) {
55
+ this.simulator = new SQSSimulator(this.config, this.lambdaService);
56
+ await this.simulator.initialize();
57
+ }
56
58
  this.setupRoutes();
57
59
  }
58
60
 
@@ -0,0 +1,83 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @fileoverview X-Ray Service
5
+ * Porta padrão: 4015
6
+ */
7
+
8
+ const path = require('path');
9
+ const { XRaySimulator } = require('./simulador');
10
+ const { createXRayServer } = require('./server');
11
+ const LocalStore = require('../../utils/local-store');
12
+
13
+ class XRayService {
14
+ constructor(config) {
15
+ this.config = config;
16
+ this.logger = require('../../utils/logger');
17
+ this.name = 'xray';
18
+ this.port = config?.ports?.xray || config?.services?.xray?.port || 4015;
19
+ this.store = null;
20
+ this.simulator = null;
21
+ this._server = null;
22
+ this.isRunning = false;
23
+ }
24
+
25
+ async initialize() {
26
+ this.logger.debug(`Inicializando X-Ray Service na porta ${this.port}...`);
27
+ const dataDir = process.env.AWS_LOCAL_SIMULATOR_DATA_DIR;
28
+ this.store = new LocalStore(path.join(dataDir, 'xray'));
29
+ this.simulator = new XRaySimulator(this.config, this.store, this.logger);
30
+ await this.simulator.load();
31
+ this.logger.debug('X-Ray Service inicializado');
32
+ }
33
+
34
+ injectDependencies(server) {
35
+ if (!server) return;
36
+ const cw = server.getService('cloudwatch');
37
+ if (cw?.simulator) this.simulator.cloudwatchSimulator = cw.simulator;
38
+ const ct = server.getService('cloudtrail');
39
+ if (ct?.simulator) this.simulator.cloudtrailSimulator = ct.simulator;
40
+ }
41
+
42
+ async start() {
43
+ if (this.isRunning) return;
44
+ const httpServer = createXRayServer(this.simulator);
45
+ return new Promise((resolve, reject) => {
46
+ httpServer.listen(this.port, () => {
47
+ this._server = httpServer;
48
+ this.isRunning = true;
49
+ this.logger.debug(`X-Ray rodando na porta ${this.port}`);
50
+ resolve();
51
+ });
52
+ httpServer.on('error', reject);
53
+ });
54
+ }
55
+
56
+ async stop() {
57
+ if (!this.isRunning || !this._server) return;
58
+ return new Promise((resolve, reject) => {
59
+ this._server.close((err) => {
60
+ if (err) return reject(err);
61
+ this.isRunning = false;
62
+ resolve();
63
+ });
64
+ });
65
+ }
66
+
67
+ async reset() {
68
+ await this.simulator.reset();
69
+ }
70
+
71
+ getStatus() {
72
+ return {
73
+ running: this.isRunning,
74
+ port: this.port,
75
+ endpoint: `http://localhost:${this.port}`,
76
+ ...this.simulator?.getStatus(),
77
+ };
78
+ }
79
+
80
+ getSimulator() { return this.simulator; }
81
+ }
82
+
83
+ module.exports = { XRayService };
@@ -0,0 +1,308 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @fileoverview X-Ray HTTP Server
5
+ *
6
+ * Protocolo: JSON com header X-Amz-Target
7
+ * Compatível com @aws-sdk/client-xray (XRayClient)
8
+ *
9
+ * Target prefix: AmazonXRay
10
+ *
11
+ * Operações suportadas:
12
+ * - PutTraceSegments
13
+ * - BatchGetTraces
14
+ * - GetTraceSummaries
15
+ * - GetTraceGraph
16
+ * - GetServiceGraph
17
+ * - CreateGroup / UpdateGroup / DeleteGroup / GetGroup / GetGroups
18
+ * - CreateSamplingRule / UpdateSamplingRule / DeleteSamplingRule
19
+ * - GetSamplingRules / GetSamplingStatisticSummaries / GetSamplingTargets
20
+ * - PutEncryptionConfig / GetEncryptionConfig
21
+ * - TagResource / UntagResource / ListTagsForResource
22
+ * - GetInsight / GetInsightSummaries / GetInsightEvents / GetInsightImpactGraph
23
+ *
24
+ * Rotas admin:
25
+ * GET /__admin/traces - lista todos os traces
26
+ * GET /__admin/groups - lista todos os grupos
27
+ * GET /__admin/sampling-rules - lista sampling rules
28
+ * GET /__admin/status - status do simulador
29
+ * POST /__admin/reset - reseta todos os dados
30
+ * GET /__admin/health - health check
31
+ *
32
+ * Rota interna:
33
+ * POST /__internal/record-service-call - usada pelos outros serviços para registrar traces
34
+ */
35
+
36
+ const { XRaySimulator } = require('./simulador');
37
+
38
+ function parseBody(req) {
39
+ return new Promise((resolve, reject) => {
40
+ let body = '';
41
+ req.on('data', chunk => (body += chunk.toString()));
42
+ req.on('end', () => {
43
+ try {
44
+ resolve(body ? JSON.parse(body) : {});
45
+ } catch {
46
+ resolve({});
47
+ }
48
+ });
49
+ req.on('error', reject);
50
+ });
51
+ }
52
+
53
+ function sendJson(res, statusCode, data) {
54
+ const body = JSON.stringify(data);
55
+ res.writeHead(statusCode, {
56
+ 'Content-Type': 'application/json',
57
+ 'Content-Length': Buffer.byteLength(body),
58
+ 'x-amzn-RequestId': require('crypto').randomUUID(),
59
+ });
60
+ res.end(body);
61
+ }
62
+
63
+ function sendError(res, err) {
64
+ const statusCode = err.statusCode || 400;
65
+ sendJson(res, statusCode, {
66
+ __type: err.code || 'ServiceException',
67
+ message: err.message,
68
+ });
69
+ }
70
+
71
+ // ─── Mapa de operações ────────────────────────────────────────────────────────
72
+
73
+ const OPERATION_MAP = {
74
+ // Traces
75
+ 'PutTraceSegments': (sim, body) => sim.putTraceSegments(body),
76
+ 'BatchGetTraces': (sim, body) => sim.batchGetTraces(body),
77
+ 'GetTraceSummaries': (sim, body) => sim.getTraceSummaries(body),
78
+ 'GetTraceGraph': (sim, body) => sim.getTraceGraph(body),
79
+
80
+ // Service Graph
81
+ 'GetServiceGraph': (sim, body) => sim.getServiceGraph(body),
82
+
83
+ // Groups
84
+ 'CreateGroup': (sim, body) => sim.createGroup(body),
85
+ 'UpdateGroup': (sim, body) => sim.updateGroup(body),
86
+ 'DeleteGroup': (sim, body) => sim.deleteGroup(body),
87
+ 'GetGroup': (sim, body) => sim.getGroup(body),
88
+ 'GetGroups': (sim, body) => sim.getGroups(body),
89
+
90
+ // Sampling Rules
91
+ 'CreateSamplingRule': (sim, body) => sim.createSamplingRule(body),
92
+ 'UpdateSamplingRule': (sim, body) => sim.updateSamplingRule(body),
93
+ 'DeleteSamplingRule': (sim, body) => sim.deleteSamplingRule(body),
94
+ 'GetSamplingRules': (sim, body) => sim.getSamplingRules(body),
95
+ 'GetSamplingStatisticSummaries': (sim, body) => sim.getSamplingStatisticSummaries(body),
96
+ 'GetSamplingTargets': (sim, body) => sim.getSamplingTargets(body),
97
+
98
+ // Encryption
99
+ 'PutEncryptionConfig': (sim, body) => sim.putEncryptionConfig(body),
100
+ 'GetEncryptionConfig': (sim, body) => sim.getEncryptionConfig(),
101
+
102
+ // Tags
103
+ 'TagResource': (sim, body) => sim.tagResource(body),
104
+ 'UntagResource': (sim, body) => sim.untagResource(body),
105
+ 'ListTagsForResource': (sim, body) => sim.listTagsForResource(body),
106
+
107
+ // Insights
108
+ 'GetInsight': (sim, body) => sim.getInsight(body),
109
+ 'GetInsightSummaries': (sim, body) => sim.getInsightSummaries(body),
110
+ 'GetInsightEvents': (sim, body) => sim.getInsightEvents(body),
111
+ 'GetInsightImpactGraph': (sim, body) => sim.getInsightImpactGraph(body),
112
+ };
113
+
114
+ // ─── Factory do servidor HTTP ─────────────────────────────────────────────────
115
+
116
+ function createXRayServer(simulator) {
117
+ const http = require('http');
118
+
119
+ const server = http.createServer(async (req, res) => {
120
+ // CORS
121
+ res.setHeader('Access-Control-Allow-Origin', '*');
122
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
123
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Amz-Target, Authorization, X-Amz-Date, X-Api-Key');
124
+
125
+ if (req.method === 'OPTIONS') {
126
+ res.writeHead(204);
127
+ res.end();
128
+ return;
129
+ }
130
+
131
+ const url = new URL(req.url, `http://${req.headers.host}`);
132
+ const pathname = url.pathname;
133
+
134
+ // ── Rotas Admin ───────────────────────────────────────────────────────────
135
+
136
+ if (pathname.startsWith('/__admin/')) {
137
+ const body = req.method !== 'GET' ? await parseBody(req) : {};
138
+
139
+ try {
140
+ if (req.method === 'GET' && pathname === '/__admin/traces') {
141
+ const traces = Array.from(simulator._traces.values());
142
+ return sendJson(res, 200, { traces, total: traces.length });
143
+ }
144
+
145
+ if (req.method === 'GET' && pathname === '/__admin/groups') {
146
+ const groups = Array.from(simulator._groups.values());
147
+ return sendJson(res, 200, { groups, total: groups.length });
148
+ }
149
+
150
+ if (req.method === 'GET' && pathname === '/__admin/sampling-rules') {
151
+ const rules = Array.from(simulator._samplingRules.values());
152
+ return sendJson(res, 200, { samplingRules: rules, total: rules.length });
153
+ }
154
+
155
+ if (req.method === 'GET' && pathname === '/__admin/status') {
156
+ return sendJson(res, 200, simulator.getStatus());
157
+ }
158
+
159
+ if (req.method === 'GET' && pathname === '/__admin/health') {
160
+ return sendJson(res, 200, {
161
+ status: 'ok',
162
+ service: 'xray',
163
+ traces: simulator._traces.size,
164
+ uptime: process.uptime(),
165
+ });
166
+ }
167
+
168
+ if (req.method === 'POST' && pathname === '/__admin/reset') {
169
+ await simulator.reset();
170
+ return sendJson(res, 200, { message: 'X-Ray simulator reset successfully' });
171
+ }
172
+
173
+ return sendJson(res, 404, { message: 'Admin route not found' });
174
+ } catch (err) {
175
+ return sendError(res, err);
176
+ }
177
+ }
178
+
179
+ // ── Rota interna: registro de chamadas de outros serviços ─────────────────
180
+
181
+ if (req.method === 'POST' && pathname === '/__internal/record-service-call') {
182
+ try {
183
+ const body = await parseBody(req);
184
+ const traceId = simulator.recordServiceCall(body);
185
+ return sendJson(res, 200, { TraceId: traceId });
186
+ } catch (err) {
187
+ return sendError(res, err);
188
+ }
189
+ }
190
+
191
+ // ── API X-Ray via X-Amz-Target ───────────────────────────────────────────
192
+
193
+ const target = req.headers['x-amz-target'] || '';
194
+ // Aceita: AmazonXRay.PutTraceSegments ou xray.PutTraceSegments
195
+ const operation = target.split('.').pop();
196
+
197
+ if (operation && OPERATION_MAP[operation]) {
198
+ try {
199
+ const body = await parseBody(req);
200
+ const result = await OPERATION_MAP[operation](simulator, body);
201
+ return sendJson(res, 200, result);
202
+ } catch (err) {
203
+ return sendError(res, err);
204
+ }
205
+ }
206
+
207
+ // ── Rotas REST alternativas (path-based) ──────────────────────────────────
208
+
209
+ try {
210
+ const body = req.method !== 'GET' ? await parseBody(req) : {};
211
+
212
+ // POST /TraceSegments
213
+ if (req.method === 'POST' && pathname === '/TraceSegments') {
214
+ const result = await simulator.putTraceSegments(body);
215
+ return sendJson(res, 200, result);
216
+ }
217
+
218
+ // POST /Traces (BatchGetTraces)
219
+ if (req.method === 'POST' && pathname === '/Traces') {
220
+ const result = await simulator.batchGetTraces(body);
221
+ return sendJson(res, 200, result);
222
+ }
223
+
224
+ // GET /TraceSummaries
225
+ if (req.method === 'GET' && pathname === '/TraceSummaries') {
226
+ const params = Object.fromEntries(url.searchParams.entries());
227
+ const result = await simulator.getTraceSummaries({
228
+ StartTime: params.StartTime ? parseFloat(params.StartTime) : undefined,
229
+ EndTime: params.EndTime ? parseFloat(params.EndTime) : undefined,
230
+ FilterExpression: params.FilterExpression,
231
+ NextToken: params.NextToken,
232
+ });
233
+ return sendJson(res, 200, result);
234
+ }
235
+
236
+ // POST /TraceGraph
237
+ if (req.method === 'POST' && pathname === '/TraceGraph') {
238
+ const result = await simulator.getTraceGraph(body);
239
+ return sendJson(res, 200, result);
240
+ }
241
+
242
+ // GET /ServiceGraph
243
+ if (req.method === 'GET' && pathname === '/ServiceGraph') {
244
+ const params = Object.fromEntries(url.searchParams.entries());
245
+ const result = await simulator.getServiceGraph({
246
+ StartTime: params.StartTime ? parseFloat(params.StartTime) : undefined,
247
+ EndTime: params.EndTime ? parseFloat(params.EndTime) : undefined,
248
+ GroupName: params.GroupName,
249
+ GroupARN: params.GroupARN,
250
+ NextToken: params.NextToken,
251
+ });
252
+ return sendJson(res, 200, result);
253
+ }
254
+
255
+ // POST /Groups
256
+ if (req.method === 'POST' && pathname === '/Groups') {
257
+ const result = await simulator.createGroup(body);
258
+ return sendJson(res, 200, result);
259
+ }
260
+
261
+ // GET /Groups
262
+ if (req.method === 'GET' && pathname === '/Groups') {
263
+ const params = Object.fromEntries(url.searchParams.entries());
264
+ const result = await simulator.getGroups({ NextToken: params.NextToken });
265
+ return sendJson(res, 200, result);
266
+ }
267
+
268
+ // POST /SamplingRules
269
+ if (req.method === 'POST' && pathname === '/SamplingRules') {
270
+ const result = await simulator.createSamplingRule(body);
271
+ return sendJson(res, 201, result);
272
+ }
273
+
274
+ // GET /SamplingRules
275
+ if (req.method === 'GET' && pathname === '/SamplingRules') {
276
+ const params = Object.fromEntries(url.searchParams.entries());
277
+ const result = await simulator.getSamplingRules({ NextToken: params.NextToken });
278
+ return sendJson(res, 200, result);
279
+ }
280
+
281
+ // POST /SamplingTargets
282
+ if (req.method === 'POST' && pathname === '/SamplingTargets') {
283
+ const result = await simulator.getSamplingTargets(body);
284
+ return sendJson(res, 200, result);
285
+ }
286
+
287
+ // GET /EncryptionConfig
288
+ if (req.method === 'GET' && pathname === '/EncryptionConfig') {
289
+ const result = await simulator.getEncryptionConfig();
290
+ return sendJson(res, 200, result);
291
+ }
292
+
293
+ // PUT /EncryptionConfig
294
+ if (req.method === 'PUT' && pathname === '/EncryptionConfig') {
295
+ const result = await simulator.putEncryptionConfig(body);
296
+ return sendJson(res, 200, result);
297
+ }
298
+
299
+ return sendJson(res, 404, { message: `Route not found: ${req.method} ${pathname}` });
300
+ } catch (err) {
301
+ return sendError(res, err);
302
+ }
303
+ });
304
+
305
+ return server;
306
+ }
307
+
308
+ module.exports = { createXRayServer };