@gugananuvem/aws-local-simulator 1.0.33 → 1.0.34

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 (79) hide show
  1. package/README.md +834 -834
  2. package/aws-config +153 -153
  3. package/bin/aws-local-simulator.js +63 -63
  4. package/package.json +3 -2
  5. package/src/config/config-loader.js +114 -114
  6. package/src/config/default-config.js +79 -79
  7. package/src/config/env-loader.js +68 -68
  8. package/src/index.js +146 -146
  9. package/src/index.mjs +123 -123
  10. package/src/server.js +463 -463
  11. package/src/services/apigateway/index.js +75 -75
  12. package/src/services/apigateway/server.js +607 -607
  13. package/src/services/apigateway/simulator.js +1405 -1405
  14. package/src/services/athena/index.js +75 -75
  15. package/src/services/athena/server.js +101 -101
  16. package/src/services/athena/simulador.js +998 -998
  17. package/src/services/athena/simulator.js +346 -346
  18. package/src/services/cloudformation/index.js +106 -106
  19. package/src/services/cloudformation/server.js +417 -417
  20. package/src/services/cloudformation/simulador.js +1020 -1020
  21. package/src/services/cloudtrail/index.js +84 -84
  22. package/src/services/cloudtrail/server.js +235 -235
  23. package/src/services/cloudtrail/simulador.js +719 -719
  24. package/src/services/cloudwatch/index.js +84 -84
  25. package/src/services/cloudwatch/server.js +366 -366
  26. package/src/services/cloudwatch/simulador.js +1173 -1173
  27. package/src/services/cognito/index.js +79 -79
  28. package/src/services/cognito/server.js +297 -297
  29. package/src/services/cognito/simulator.js +1992 -1761
  30. package/src/services/config/index.js +96 -96
  31. package/src/services/config/server.js +215 -215
  32. package/src/services/config/simulador.js +1260 -1260
  33. package/src/services/dynamodb/index.js +74 -74
  34. package/src/services/dynamodb/server.js +139 -139
  35. package/src/services/dynamodb/simulator.js +1005 -994
  36. package/src/services/dynamodb/sqlite-store.js +722 -0
  37. package/src/services/ecs/index.js +65 -65
  38. package/src/services/ecs/server.js +235 -235
  39. package/src/services/ecs/simulator.js +844 -844
  40. package/src/services/eventbridge/index.js +89 -89
  41. package/src/services/eventbridge/server.js +209 -209
  42. package/src/services/eventbridge/simulator.js +684 -684
  43. package/src/services/index.js +45 -45
  44. package/src/services/kms/index.js +75 -75
  45. package/src/services/kms/server.js +81 -81
  46. package/src/services/kms/simulator.js +344 -344
  47. package/src/services/lambda/handler-loader.js +183 -183
  48. package/src/services/lambda/index.js +81 -81
  49. package/src/services/lambda/route-registry.js +274 -274
  50. package/src/services/lambda/server.js +191 -191
  51. package/src/services/lambda/simulator.js +364 -364
  52. package/src/services/parameter-store/index.js +80 -80
  53. package/src/services/parameter-store/server.js +50 -50
  54. package/src/services/parameter-store/simulator.js +201 -201
  55. package/src/services/s3/index.js +73 -73
  56. package/src/services/s3/server.js +350 -350
  57. package/src/services/s3/simulator.js +568 -568
  58. package/src/services/secret-manager/index.js +80 -80
  59. package/src/services/secret-manager/server.js +51 -51
  60. package/src/services/secret-manager/simulator.js +182 -182
  61. package/src/services/sns/index.js +89 -89
  62. package/src/services/sns/server.js +607 -607
  63. package/src/services/sns/simulator.js +1482 -1482
  64. package/src/services/sqs/index.js +98 -98
  65. package/src/services/sqs/server.js +360 -360
  66. package/src/services/sqs/simulator.js +509 -509
  67. package/src/services/sts/index.js +37 -37
  68. package/src/services/sts/server.js +144 -144
  69. package/src/services/sts/simulator.js +69 -69
  70. package/src/services/xray/index.js +83 -83
  71. package/src/services/xray/server.js +308 -308
  72. package/src/services/xray/simulador.js +994 -994
  73. package/src/template/aws-config-template.js +87 -87
  74. package/src/template/aws-config-template.mjs +90 -90
  75. package/src/template/config-template.json +203 -203
  76. package/src/utils/aws-config.js +91 -91
  77. package/src/utils/cloudtrail-audit.js +129 -129
  78. package/src/utils/local-store.js +83 -83
  79. package/src/utils/logger.js +59 -59
package/README.md CHANGED
@@ -1,834 +1,834 @@
1
- # AWS Local Simulator
2
-
3
- [![npm version](https://badge.fury.io/js/aws-local-simulator.svg)](https://badge.fury.io/js/aws-local-simulator)
4
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
- [![Node.js Version](https://img.shields.io/node/v/aws-local-simulator.svg)](https://nodejs.org)
6
-
7
- Simulador local completo para serviços AWS. Desenvolva e teste suas aplicações AWS localmente sem custos!
8
-
9
- ## 🚀 Serviços Suportados
10
-
11
- | Serviço | Status | Porta Padrão | Descrição |
12
- |---------|--------|--------------|-----------|
13
- | DynamoDB | ✅ | 8000 | Banco de dados NoSQL |
14
- | S3 | ✅ | 4566 | Armazenamento de objetos |
15
- | SQS | ✅ | 9324 | Filas de mensagens |
16
- | Lambda | ✅ | 3001 | Funções serverless |
17
- | Cognito | ✅ | 9229 | Autenticação e autorização |
18
- | API Gateway | ✅ | 4567 | APIs REST e HTTP |
19
- | STS | ✅ | 9326 | Credenciais temporárias |
20
- | SNS | ✅ | 9911 | Notificações pub/sub |
21
- | EventBridge | ✅ | 4010 | Barramento de eventos |
22
- | KMS | ✅ | 4000 | Gerenciamento de chaves |
23
- | Secrets Manager | ✅ | 4001 | Gerenciamento de segredos |
24
- | Parameter Store | ✅ | 4002 | Armazenamento de parâmetros |
25
- | CloudWatch | ✅ | 4011 | Logs, métricas e alarmes |
26
- | CloudTrail | ✅ | 4012 | Auditoria de API calls |
27
- | AWS Config | ✅ | 4013 | Conformidade e configuração |
28
- | CloudFormation | ✅ | 4580 | Infraestrutura como código |
29
- | Athena | ✅ | 4599 | Consultas SQL em dados no S3 |
30
- | X-Ray | ✅ | 4015 | Rastreamento distribuído |
31
- | ECS/Fargate | 🚧 | 8080 | Orquestração de containers (em desenvolvimento) |
32
-
33
- ## 📦 Instalação
34
-
35
- ```bash
36
- npm install --save-dev @gugananuvem/aws-local-simulator
37
- ```
38
-
39
- ## 🚀 Uso Rápido
40
-
41
- ### 1. Crie um arquivo de configuração `aws-local-simulator.json`:
42
-
43
- ```json
44
- {
45
- "services": {
46
- "dynamodb": true,
47
- "s3": true,
48
- "sqs": true,
49
- "lambda": true,
50
- "cognito": true,
51
- "apigateway": true,
52
- "sts": true,
53
- "sns": true,
54
- "eventbridge": true,
55
- "kms": true,
56
- "secret-manager": true,
57
- "parameter-store": true,
58
- "cloudwatch": true,
59
- "cloudtrail": true,
60
- "cloudformation": true,
61
- "xray": true,
62
- "config": true,
63
- "athena": true
64
- },
65
- "lambdas": [
66
- {
67
- "name": "my-function",
68
- "handler": "./src/handlers/users.js",
69
- "env": {
70
- "TABLE_NAME": "users-table"
71
- }
72
- }
73
- ],
74
- "dynamodb": {
75
- "tables": [
76
- {
77
- "TableName": "users-table",
78
- "KeySchema": [{ "AttributeName": "id", "KeyType": "HASH" }],
79
- "AttributeDefinitions": [{ "AttributeName": "id", "AttributeType": "S" }]
80
- }
81
- ]
82
- },
83
- "s3": {
84
- "buckets": [
85
- { "name": "my-bucket", "region": "us-east-1" }
86
- ]
87
- },
88
- "sqs": {
89
- "queues": ["my-queue", "dead-letter-queue"]
90
- },
91
- "cognito": {
92
- "userPools": [
93
- {
94
- "PoolName": "my-user-pool",
95
- "AutoVerifiedAttributes": ["email"]
96
- }
97
- ]
98
- }
99
- }
100
- ```
101
-
102
- ### 2. Inicie o simulador:
103
-
104
- ```bash
105
- # Via CLI
106
- npx aws-local-simulator start
107
-
108
- # Ou via código
109
- const { AWSLocalSimulator } = require('aws-local-simulator');
110
- const simulator = new AWSLocalSimulator();
111
- await simulator.start();
112
- ```
113
-
114
- ### 3. Configure seu código para usar os serviços locais:
115
-
116
- ```javascript
117
- const { dynamoDB, s3, sqs, cognito } = require('aws-local-simulator/aws-config');
118
-
119
- await dynamoDB.send(new PutCommand({
120
- TableName: 'users-table',
121
- Item: { id: '123', name: 'John' }
122
- }));
123
- ```
124
-
125
- ## 🔧 Configuração por Variáveis de Ambiente
126
-
127
- | Variável | Descrição | Padrão |
128
- |---------|----------|-------|
129
- | AWS_LOCAL_SIMULATOR_DYNAMODB | Habilita DynamoDB | true |
130
- | AWS_LOCAL_SIMULATOR_S3 | Habilita S3 | true |
131
- | AWS_LOCAL_SIMULATOR_SQS | Habilita SQS | true |
132
- | AWS_LOCAL_SIMULATOR_LAMBDA | Habilita Lambda | true |
133
- | AWS_LOCAL_SIMULATOR_COGNITO | Habilita Cognito | false |
134
- | AWS_LOCAL_SIMULATOR_APIGATEWAY | Habilita API Gateway | false |
135
- | AWS_LOCAL_SIMULATOR_STS | Habilita STS | true |
136
- | AWS_LOCAL_SIMULATOR_SNS | Habilita SNS | false |
137
- | AWS_LOCAL_SIMULATOR_EVENTBRIDGE | Habilita EventBridge | false |
138
- | AWS_LOCAL_SIMULATOR_KMS | Habilita KMS | false |
139
- | AWS_LOCAL_SIMULATOR_SECRET_MANAGER | Habilita Secrets Manager | false |
140
- | AWS_LOCAL_SIMULATOR_PARAMETER_STORE | Habilita Parameter Store | false |
141
- | AWS_LOCAL_SIMULATOR_CLOUDWATCH | Habilita CloudWatch | false |
142
- | AWS_LOCAL_SIMULATOR_CLOUDTRAIL | Habilita CloudTrail | false |
143
- | AWS_LOCAL_SIMULATOR_CLOUDFORMATION | Habilita CloudFormation | false |
144
- | AWS_LOCAL_SIMULATOR_ATHENA | Habilita Athena | false |
145
- | AWS_LOCAL_SIMULATOR_XRAY | Habilita X-Ray | false |
146
- | AWS_LOCAL_SIMULATOR_CONFIG | Habilita AWS Config | false |
147
- | AWS_LOCAL_SIMULATOR_ECS | Habilita ECS/Fargate | false |
148
- | AWS_LOCAL_SIMULATOR_DYNAMODB_PORT | Porta DynamoDB | 8000 |
149
- | AWS_LOCAL_SIMULATOR_S3_PORT | Porta S3 | 4566 |
150
- | AWS_LOCAL_SIMULATOR_SQS_PORT | Porta SQS | 9324 |
151
- | AWS_LOCAL_SIMULATOR_LAMBDA_PORT | Porta Lambda | 3001 |
152
- | AWS_LOCAL_SIMULATOR_COGNITO_PORT | Porta Cognito | 9229 |
153
- | AWS_LOCAL_SIMULATOR_APIGATEWAY_PORT | Porta API Gateway | 4567 |
154
- | AWS_LOCAL_SIMULATOR_STS_PORT | Porta STS | 9326 |
155
- | AWS_LOCAL_SIMULATOR_SNS_PORT | Porta SNS | 9911 |
156
- | AWS_LOCAL_SIMULATOR_EVENTBRIDGE_PORT | Porta EventBridge | 4010 |
157
- | AWS_LOCAL_SIMULATOR_KMS_PORT | Porta KMS | 4000 |
158
- | AWS_LOCAL_SIMULATOR_SECRET_MANAGER_PORT | Porta Secrets Manager | 4001 |
159
- | AWS_LOCAL_SIMULATOR_PARAMETER_STORE_PORT | Porta Parameter Store | 4002 |
160
- | AWS_LOCAL_SIMULATOR_CLOUDWATCH_PORT | Porta CloudWatch | 4011 |
161
- | AWS_LOCAL_SIMULATOR_CLOUDTRAIL_PORT | Porta CloudTrail | 4012 |
162
- | AWS_LOCAL_SIMULATOR_CONFIG_PORT | Porta AWS Config | 4013 |
163
- | AWS_LOCAL_SIMULATOR_XRAY_PORT | Porta X-Ray | 4015 |
164
- | AWS_LOCAL_SIMULATOR_CLOUDFORMATION_PORT | Porta CloudFormation | 4580 |
165
- | AWS_LOCAL_SIMULATOR_ATHENA_PORT | Porta Athena | 4599 |
166
- | AWS_LOCAL_SIMULATOR_ECS_PORT | Porta ECS | 8080 |
167
- | AWS_LOCAL_SIMULATOR_DATA | Diretório de dados | ./aws-local-simulator-data |
168
- | AWS_LOCAL_SIMULATOR_LOG | Nível de log | info |
169
-
170
- ## 📝 Comandos CLI
171
-
172
- ```bash
173
- # Iniciar simulador
174
- npx aws-local-simulator start [configPath]
175
-
176
- # Parar simulador
177
- npx aws-local-simulator stop
178
-
179
- # Reiniciar
180
- npx aws-local-simulator restart
181
-
182
- # Resetar dados
183
- npx aws-local-simulator reset
184
-
185
- # Status
186
- npx aws-local-simulator status
187
- ```
188
-
189
- ## 🖥️ Management API
190
-
191
- O simulador expõe uma API de gerenciamento em tempo de execução na porta `9999` (configurável via `adminPort`). Ela permite habilitar e desabilitar serviços individualmente sem reiniciar o processo.
192
-
193
- ### Endpoints da Management API
194
-
195
- | Método | Rota | Descrição |
196
- |--------|------|-----------|
197
- | GET | `/__admin/services` | Lista todos os 19 serviços com status |
198
- | GET | `/__admin/services/:name` | Status de um serviço específico |
199
- | POST | `/__admin/services/:name/enable` | Habilita um serviço parado |
200
- | POST | `/__admin/services/:name/disable` | Desabilita um serviço em execução |
201
-
202
- ### Exemplos
203
-
204
- ```bash
205
- # Listar todos os serviços
206
- curl http://localhost:9999/__admin/services
207
-
208
- # Habilitar DynamoDB
209
- curl -X POST http://localhost:9999/__admin/services/dynamodb/enable
210
-
211
- # Desabilitar SQS
212
- curl -X POST http://localhost:9999/__admin/services/sqs/disable
213
-
214
- # Status de um serviço
215
- curl http://localhost:9999/__admin/services/lambda
216
- ```
217
-
218
- ### Configuração da porta admin
219
-
220
- ```json
221
- {
222
- "adminPort": 9999
223
- }
224
- ```
225
-
226
- Ou via variável de ambiente:
227
- ```bash
228
- AWS_LOCAL_SIMULATOR_ADMIN_PORT=9999 npx aws-local-simulator start
229
- ```
230
-
231
- > A Management API nunca persiste alterações em disco — todo o estado é mantido em memória. Para uso em desenvolvimento local apenas.
232
-
233
- ## 🔌 Endpoints
234
-
235
- | Serviço | Endpoint | Admin |
236
- |---------|----------|-------|
237
- | DynamoDB | http://localhost:8000 | http://localhost:8000/__admin/tables |
238
- | S3 | http://localhost:4566 | http://localhost:4566/__admin/buckets |
239
- | S3 Website | http://localhost:4566/website/{bucket}/ | — |
240
- | SQS | http://localhost:9324 | http://localhost:9324/__admin/queues |
241
- | Lambda | http://localhost:3001 | http://localhost:3001/__admin/functions |
242
- | Cognito | http://localhost:9229 | http://localhost:9229/__admin/userpools |
243
- | API Gateway | http://localhost:4567 | http://localhost:4567/__admin/apis |
244
- | STS | http://localhost:9326 | — |
245
- | SNS | http://localhost:9911 | http://localhost:9911/__admin/health |
246
- | EventBridge | http://localhost:4010 | — |
247
- | KMS | http://localhost:4000 | — |
248
- | Secrets Manager | http://localhost:4001 | — |
249
- | Parameter Store | http://localhost:4002 | — |
250
- | CloudWatch | http://localhost:4011 | — |
251
- | CloudTrail | http://localhost:4012 | — |
252
- | AWS Config | http://localhost:4013 | — |
253
- | X-Ray | http://localhost:4015 | — |
254
- | CloudFormation | http://localhost:4580 | http://localhost:4580/__admin/stacks |
255
- | Athena | http://localhost:4599 | http://localhost:4599/__admin/health |
256
- | ECS | http://localhost:8080 | http://localhost:8080/__admin/clusters |
257
- | Management API | http://localhost:9999 | http://localhost:9999/__admin/services |
258
-
259
- ## 🧪 Testando com AWS CLI
260
-
261
- ```bash
262
- # DynamoDB
263
- aws dynamodb list-tables --endpoint-url http://localhost:8000
264
-
265
- # S3
266
- aws s3 ls --endpoint-url http://localhost:4566
267
-
268
- # SQS
269
- aws sqs list-queues --endpoint-url http://localhost:9324
270
-
271
- # Lambda
272
- aws lambda invoke \
273
- --function-name my-function \
274
- --payload '{"key":"value"}' \
275
- --endpoint-url http://localhost:3001 \
276
- output.json
277
-
278
- # Cognito
279
- aws cognito-idp list-user-pools --max-results 10 --endpoint-url http://localhost:9229
280
-
281
- # Cognito cadastrar um usuario pelo adminstrador
282
- aws cognito-idp admin-create-user \
283
- --user-pool-id us-east-xxxx\
284
- --username usuario@email.com \
285
- --user-attributes \
286
- Name=email,Value=usuario@email.com \
287
- Name=email_verified,Value=false \
288
- Name=name,Value="nome usuario" \
289
- Name=custom:role,Value="user" \
290
- temporary-password "Teste@123456" \
291
- --message-action SUPPRESS \
292
- --endpoint-url http://localhost:9229
293
-
294
- # Cognito excluir um usuario
295
- aws cognito-idp admin-delete-user \
296
- --user-pool-id us-east-xxxx \
297
- --username usuario@email.com
298
- --endpoint-url http://localhost:9229
299
-
300
- # Cognito Registrar usuário
301
- aws cognito-idp sign-up \
302
- --client-id $CLIENT_ID \
303
- --username usuario@email.com \
304
- --password "Teste@123456" \
305
- --user-attributes Name=email,Value=usuario@email.com Name=name,Value="nome usuario"
306
- --endpoint-url http://localhost:9229
307
-
308
- # 2. Confirmar usuário administrativamente
309
- aws cognito-idp admin-confirm-sign-up \
310
- --user-pool-id us-east-xxxx \
311
- --username usuario@email.com
312
- --endpoint-url http://localhost:9229
313
-
314
- # O código chega no e-mail do usuário. Algo como: "Your confirmation code is 123456"
315
- aws cognito-idp confirm-sign-up \
316
- --client-id 3n4b5urk1ft4fl3mg5e62d9ado \
317
- --username usuario@email.com \
318
- --confirmation-code 123456
319
- --endpoint-url http://localhost:9229
320
-
321
- # STS
322
- aws sts get-caller-identity --endpoint-url http://localhost:9326
323
- aws sts assume-role \
324
- --role-arn "arn:aws:iam::123456789012:role/my-role" \
325
- --role-session-name "my-session" \
326
- --endpoint-url http://localhost:9326
327
-
328
- # SNS
329
- aws sns list-topics --endpoint-url http://localhost:9911
330
-
331
- # EventBridge
332
- aws events list-event-buses --endpoint-url http://localhost:4010
333
-
334
- # KMS
335
- aws kms list-keys --endpoint-url http://localhost:4000
336
-
337
- # Secrets Manager
338
- aws secretsmanager list-secrets --endpoint-url http://localhost:4001
339
-
340
- # Criar secret
341
- aws secretsmanager create-secret \
342
- --name "local/app/db-credentials" \
343
- --description "Credenciais do banco" \
344
- --secret-string '{"username":"admin","password":"secret123"}' \
345
- --endpoint-url http://localhost:4001
346
-
347
- # Ler secret
348
- aws secretsmanager get-secret-value \
349
- --secret-id "local/app/db-credentials" \
350
- --endpoint-url http://localhost:4001
351
-
352
- # Parameter Store
353
- aws ssm describe-parameters --endpoint-url http://localhost:4002
354
-
355
- # Criar parâmetro String
356
- aws ssm put-parameter \
357
- --name "/local/app/config" \
358
- --value '{"timeout":30,"maxRetries":3}' \
359
- --type String \
360
- --endpoint-url http://localhost:4002
361
-
362
- # Criar parâmetro SecureString
363
- aws ssm put-parameter \
364
- --name "/local/app/api-key" \
365
- --value "my-secret-api-key" \
366
- --type SecureString \
367
- --endpoint-url http://localhost:4002
368
-
369
- # Ler parâmetro
370
- aws ssm get-parameter \
371
- --name "/local/app/config" \
372
- --endpoint-url http://localhost:4002
373
-
374
- # CloudWatch
375
- aws cloudwatch list-metrics --endpoint-url http://localhost:4011
376
- aws logs describe-log-groups --endpoint-url http://localhost:4011
377
-
378
- # CloudTrail
379
- aws cloudtrail describe-trails --endpoint-url http://localhost:4012
380
-
381
- # CloudFormation
382
- aws cloudformation list-stacks --endpoint-url http://localhost:4580
383
-
384
- # X-Ray
385
- aws xray get-trace-summaries \
386
- --start-time $(date -d '1 hour ago' +%s) \
387
- --end-time $(date +%s) \
388
- --endpoint-url http://localhost:4015
389
-
390
- # AWS Config
391
- aws configservice describe-configuration-recorders --endpoint-url http://localhost:4013
392
-
393
- # API Gateway
394
- aws apigateway get-rest-apis --endpoint-url http://localhost:4567
395
-
396
- # Cloudformation
397
- aws cloudformation create-stack \
398
- --stack-name test-stack \
399
- --template-body file://templates/test-stack.yaml \
400
- --parameters \
401
- ParameterKey=Environment,ParameterValue=local \
402
- ParameterKey=BucketName,ParameterValue=meu-bucket \
403
- ParameterKey=QueueName,ParameterValue=minha-fila \
404
- ParameterKey=TableName,ParameterValue=minha-tabela \
405
- --endpoint-url http://localhost:4580
406
-
407
- # Ver Cloudformation resultado
408
- aws cloudformation describe-stacks \
409
- --stack-name test-stack \
410
- --endpoint-url http://localhost:4580
411
-
412
- # Athena
413
- # Criar workgroup
414
- aws athena create-work-group \
415
- --name my-workgroup \
416
- --configuration ResultConfiguration={OutputLocation=s3://meu-bucket/athena-results/} \
417
- --endpoint-url http://localhost:4599
418
-
419
- # Listar workgroups
420
- aws athena list-work-groups --endpoint-url http://localhost:4599
421
-
422
- # Executar query
423
- aws athena start-query-execution \
424
- --query-string "SELECT * FROM my_table LIMIT 10" \
425
- --query-execution-context Database=default \
426
- --result-configuration OutputLocation=s3://meu-bucket/athena-results/ \
427
- --endpoint-url http://localhost:4599
428
-
429
- # Verificar status da query
430
- aws athena get-query-execution \
431
- --query-execution-id <id-retornado> \
432
- --endpoint-url http://localhost:4599
433
-
434
- # Buscar resultados
435
- aws athena get-query-results \
436
- --query-execution-id <id-retornado> \
437
- --endpoint-url http://localhost:4599
438
-
439
- # Criar named query
440
- aws athena create-named-query \
441
- --name "my-saved-query" \
442
- --database default \
443
- --query-string "SELECT id, value FROM my_table WHERE status = 'active'" \
444
- --endpoint-url http://localhost:4599
445
-
446
- # Listar named queries
447
- aws athena list-named-queries --endpoint-url http://localhost:4599
448
- ```
449
-
450
- ## ⚙️ Configuração S3
451
-
452
- ### Buckets simples
453
-
454
- ```json
455
- {
456
- "s3": {
457
- "buckets": [
458
- "my-bucket"
459
- ]
460
- }
461
- }
462
- ```
463
-
464
- ### Buckets com região e website estático
465
-
466
- ```json
467
- {
468
- "s3": {
469
- "buckets": [
470
- { "name": "my-bucket", "region": "us-east-1" },
471
- {
472
- "name": "my-site-bucket",
473
- "region": "us-east-1",
474
- "websiteConfiguration": {
475
- "IndexDocument": { "Suffix": "index.html" },
476
- "ErrorDocument": { "Key": "error.html" }
477
- }
478
- }
479
- ]
480
- }
481
- }
482
- ```
483
-
484
- Quando `websiteConfiguration` está presente, o bucket serve arquivos estáticos.
485
-
486
- ### URL do website estático
487
-
488
- ```
489
- http://localhost:4566/website/{bucket-name}/
490
- http://localhost:4566/website/{bucket-name}/caminho/pagina.html
491
- ```
492
-
493
- Exemplos:
494
- ```
495
- http://localhost:4566/website/my-site-bucket/ → serve index.html
496
- http://localhost:4566/website/my-site-bucket/about.html → serve about.html
497
- http://localhost:4566/website/my-site-bucket/app/ → serve app/index.html
498
- ```
499
-
500
- ### Gerenciar website config via AWS CLI
501
-
502
- ```bash
503
- # Habilitar website em um bucket existente
504
- aws s3api put-bucket-website \
505
- --bucket my-site-bucket \
506
- --website-configuration '{"IndexDocument":{"Suffix":"index.html"},"ErrorDocument":{"Key":"error.html"}}' \
507
- --endpoint-url http://localhost:4566
508
-
509
- # Ver configuração de website
510
- aws s3api get-bucket-website \
511
- --bucket my-site-bucket \
512
- --endpoint-url http://localhost:4566
513
-
514
- # Remover website
515
- aws s3api delete-bucket-website \
516
- --bucket my-site-bucket \
517
- --endpoint-url http://localhost:4566
518
- ```
519
-
520
- ## ⚙️ Configuração de Lambdas
521
-
522
- Lambdas são registradas por **nome** e invocadas via API de invocação (igual à AWS real). O roteamento HTTP é feito pelo API Gateway.
523
-
524
- ```json
525
- {
526
- "lambdas": [
527
- {
528
- "name": "my-user-function",
529
- "handler": "./src/handlers/my-user-function.js",
530
- "env": {
531
- "TABLE_NAME": "users-table",
532
- "BUCKET_NAME": "my-bucket"
533
- }
534
- }
535
- ]
536
- }
537
- ```
538
-
539
- ## ⚙️ Configuração SQS com Lambda Trigger
540
-
541
- Para disparar uma Lambda automaticamente quando uma mensagem chega na fila, use o formato de objeto na lista de filas com `lambdaName`:
542
-
543
- ```json
544
- {
545
- "lambdas": [
546
- {
547
- "name": "process-orders",
548
- "handler": "./src/handlers/process-orders.js"
549
- }
550
- ],
551
- "sqs": {
552
- "queues": [
553
- "simple-queue",
554
- {
555
- "name": "orders-queue",
556
- "lambdaName": "process-orders",
557
- "batchSize": 5
558
- }
559
- ]
560
- }
561
- }
562
- ```
563
-
564
- - Filas simples (string) são criadas sem trigger
565
- - Filas com objeto aceitam `lambdaName` (nome da Lambda registrada) e `batchSize` (padrão: 10)
566
- - Quando uma mensagem é enviada para `orders-queue`, a Lambda `process-orders` é invocada automaticamente com o evento no formato SQS padrão da AWS
567
-
568
- O handler recebe o evento no formato padrão AWS SQS:
569
-
570
- ```javascript
571
- exports.handler = async (event) => {
572
- for (const record of event.Records) {
573
- const body = JSON.parse(record.body);
574
- console.log('Mensagem recebida:', body);
575
- // processar...
576
- }
577
-
578
- // Retornar batchItemFailures para reprocessar mensagens específicas
579
- return { batchItemFailures: [] };
580
- };
581
- ```
582
-
583
- ## ⚙️ Configuração API GATEWAY
584
-
585
- O valor do **lambdaName** deve igual ao nome Lambda que está registrada com o valor **name**. Ex: "my-user-function".
586
-
587
- ```json
588
- {
589
- "apigateway": {
590
- "apis": [
591
- {
592
- "name": "Users API",
593
- "description": "API para gerenciamento de usuários",
594
- "endpoints": [
595
- {
596
- "path": "/user",
597
- "method": "GET",
598
- "lambdaName": "my-user-function",
599
- "integrationType": "lambda"
600
- },
601
- {
602
- "path": "/user",
603
- "method": "POST",
604
- "lambdaName": "my-user-function",
605
- "integrationType": "lambda"
606
- },
607
- {
608
- "path": "/user/{id}",
609
- "method": "GET",
610
- "lambdaName": "my-user-function",
611
- "integrationType": "lambda"
612
- },
613
- {
614
- "path": "/user/{id}",
615
- "method": "DELETE",
616
- "lambdaName": "my-user-function",
617
- "integrationType": "lambda"
618
- },
619
- {
620
- "path": "/user/{id}",
621
- "method": "ANY",
622
- "lambdaName": "my-user-function",
623
- "integrationType": "lambda"
624
- }
625
- ]
626
- }
627
- ]
628
- }
629
- }
630
- ```
631
-
632
- ### Método ANY
633
-
634
- Use `"method": "ANY"` para registrar um endpoint que aceita todos os verbos HTTP (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS) — equivalente ao `ANY` do AWS API Gateway real.
635
-
636
- ```json
637
- {
638
- "path": "/webhook",
639
- "method": "ANY",
640
- "lambdaName": "my-webhook-handler",
641
- "integrationType": "lambda"
642
- }
643
- ```
644
-
645
- ### API Key
646
-
647
- O API Gateway suporta validação de API Key via header `x-api-key`. Para proteger um endpoint, declare as `apiKeys` na configuração e use `"apiKeyRequired": true` no endpoint:
648
-
649
- ```json
650
- {
651
- "apigateway": {
652
- "apiKeys": [
653
- {
654
- "name": "my-app-key",
655
- "value": "minha-chave-secreta-123"
656
- }
657
- ],
658
- "apis": [
659
- {
660
- "name": "Protected API",
661
- "endpoints": [
662
- {
663
- "path": "/protected",
664
- "method": "GET",
665
- "lambdaName": "my-user-function",
666
- "integrationType": "lambda",
667
- "apiKeyRequired": true
668
- },
669
- {
670
- "path": "/public",
671
- "method": "GET",
672
- "lambdaName": "my-user-function",
673
- "integrationType": "lambda"
674
- }
675
- ]
676
- }
677
- ]
678
- }
679
- }
680
- ```
681
-
682
- Ao chamar um endpoint protegido, envie o header:
683
-
684
- ```bash
685
- curl http://localhost:4567/protected \
686
- -H "x-api-key: minha-chave-secreta-123"
687
-
688
- # Sem a key → 403 Forbidden
689
- curl http://localhost:4567/protected
690
- ```
691
-
692
- > **Nota:** A validação de API Key só está ativa no fluxo de proxy (`/:apiId/:stageName/*`). Endpoints declarados diretamente no `aws-local-simulator.json` via `setupConfigRoutes` não aplicam a validação de API Key no momento.
693
-
694
- ### Cognito Authorizer
695
-
696
- O API Gateway suporta autenticação via Cognito User Pools. Configure um `authorizer` na API e marque os endpoints protegidos com `"authorizerRequired": true`:
697
-
698
- ```json
699
- {
700
- "cognito": {
701
- "userPools": [
702
- {
703
- "PoolName": "my-user-pool",
704
- "UserPoolId": "us-east-XXXXX",
705
- "ClientId": "XXXXXX",
706
- "AutoVerifiedAttributes": ["email"]
707
- }
708
- ]
709
- },
710
- "apigateway": {
711
- "apis": [
712
- {
713
- "name": "My API",
714
- "authorizer": {
715
- "type": "COGNITO_USER_POOLS",
716
- "userPoolId": "us-east-XXXXX"
717
- },
718
- "endpoints": [
719
- {
720
- "path": "/profile",
721
- "method": "GET",
722
- "lambdaName": "my-user-function",
723
- "integrationType": "lambda",
724
- "authorizerRequired": true
725
- },
726
- {
727
- "path": "/public",
728
- "method": "GET",
729
- "lambdaName": "my-user-function",
730
- "integrationType": "lambda"
731
- }
732
- ]
733
- }
734
- ]
735
- }
736
- }
737
- ```
738
-
739
- O simulador valida o JWT do Cognito local no header `Authorization: Bearer <token>`. Se o token for inválido ou ausente, retorna `401 Unauthorized`.
740
-
741
- ```bash
742
- # 1. Autenticar e obter o token
743
- TOKEN=$(curl -s -X POST http://localhost:9229/ \
744
- -H "Content-Type: application/x-amz-json-1.1" \
745
- -H "X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth" \
746
- -d '{
747
- "AuthFlow": "USER_PASSWORD_AUTH",
748
- "ClientId": "XXXXXX",
749
- "AuthParameters": {
750
- "USERNAME": "usuario@email.com",
751
- "PASSWORD": "Senha@123"
752
- }
753
- }' | jq -r '.AuthenticationResult.IdToken')
754
-
755
- # 2. Chamar endpoint protegido com o token
756
- curl http://localhost:4567/profile \
757
- -H "Authorization: Bearer $TOKEN"
758
-
759
- # Sem token → 401 Unauthorized
760
- curl http://localhost:4567/profile
761
- ```
762
-
763
- O token decodificado fica disponível no Lambda em `event.requestContext.authorizer.claims`:
764
-
765
- ```javascript
766
- exports.handler = async (event) => {
767
- const claims = event.requestContext.authorizer?.claims;
768
- const userId = claims?.sub;
769
- const email = claims?.email;
770
-
771
- return {
772
- statusCode: 200,
773
- body: JSON.stringify({ userId, email })
774
- };
775
- };
776
- ```
777
-
778
- O handler deve exportar uma função padrão:
779
-
780
- ```javascript
781
- exports.handler = async (event, context) => {
782
- return {
783
- statusCode: 200,
784
- body: JSON.stringify({ message: 'Hello from Lambda!' })
785
- };
786
- };
787
- ```
788
-
789
- ## 📁 Estrutura de Dados
790
-
791
- Os dados são persistidos em:
792
-
793
- ```text
794
- .aws-local-simulator-data/
795
- ├── dynamodb/
796
- ├── s3/
797
- ├── sqs/
798
- ├── cognito/
799
- ├── apigateway/
800
- ├── ecs/
801
- ├── kms/
802
- ├── secret-manager/
803
- ├── parameter-store/
804
- ├── cloudwatch/
805
- ├── cloudtrail/
806
- ├── cloudformation/
807
- ├── athena/
808
- ├── xray/
809
- └── config/
810
- ```
811
-
812
- ## 🐛 Debug
813
-
814
- ```bash
815
- AWS_LOCAL_SIMULATOR_LOG=verbose npx aws-local-simulator start
816
- ```
817
-
818
- ## 🤝 Contribuindo
819
-
820
- 1. Fork o projeto
821
- 2. Crie sua feature branch (`git checkout -b feature/AmazingFeature`)
822
- 3. Commit suas mudanças (`git commit -m 'Add some AmazingFeature'`)
823
- 4. Push para a branch (`git push origin feature/AmazingFeature`)
824
- 5. Abra um Pull Request
825
-
826
- ## 📄 Licença
827
-
828
- MIT © Luiz Gustavo Ribeiro
829
-
830
- ## ⚠️ Limitações
831
-
832
- - ECS/Fargate em desenvolvimento
833
- - WebSocket APIs em desenvolvimento
834
- - Para uso em desenvolvimento e testes apenas
1
+ # AWS Local Simulator
2
+
3
+ [![npm version](https://badge.fury.io/js/aws-local-simulator.svg)](https://badge.fury.io/js/aws-local-simulator)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![Node.js Version](https://img.shields.io/node/v/aws-local-simulator.svg)](https://nodejs.org)
6
+
7
+ Simulador local completo para serviços AWS. Desenvolva e teste suas aplicações AWS localmente sem custos!
8
+
9
+ ## 🚀 Serviços Suportados
10
+
11
+ | Serviço | Status | Porta Padrão | Descrição |
12
+ |---------|--------|--------------|-----------|
13
+ | DynamoDB | ✅ | 8000 | Banco de dados NoSQL |
14
+ | S3 | ✅ | 4566 | Armazenamento de objetos |
15
+ | SQS | ✅ | 9324 | Filas de mensagens |
16
+ | Lambda | ✅ | 3001 | Funções serverless |
17
+ | Cognito | ✅ | 9229 | Autenticação e autorização |
18
+ | API Gateway | ✅ | 4567 | APIs REST e HTTP |
19
+ | STS | ✅ | 9326 | Credenciais temporárias |
20
+ | SNS | ✅ | 9911 | Notificações pub/sub |
21
+ | EventBridge | ✅ | 4010 | Barramento de eventos |
22
+ | KMS | ✅ | 4000 | Gerenciamento de chaves |
23
+ | Secrets Manager | ✅ | 4001 | Gerenciamento de segredos |
24
+ | Parameter Store | ✅ | 4002 | Armazenamento de parâmetros |
25
+ | CloudWatch | ✅ | 4011 | Logs, métricas e alarmes |
26
+ | CloudTrail | ✅ | 4012 | Auditoria de API calls |
27
+ | AWS Config | ✅ | 4013 | Conformidade e configuração |
28
+ | CloudFormation | ✅ | 4580 | Infraestrutura como código |
29
+ | Athena | ✅ | 4599 | Consultas SQL em dados no S3 |
30
+ | X-Ray | ✅ | 4015 | Rastreamento distribuído |
31
+ | ECS/Fargate | 🚧 | 8080 | Orquestração de containers (em desenvolvimento) |
32
+
33
+ ## 📦 Instalação
34
+
35
+ ```bash
36
+ npm install --save-dev @gugananuvem/aws-local-simulator
37
+ ```
38
+
39
+ ## 🚀 Uso Rápido
40
+
41
+ ### 1. Crie um arquivo de configuração `aws-local-simulator.json`:
42
+
43
+ ```json
44
+ {
45
+ "services": {
46
+ "dynamodb": true,
47
+ "s3": true,
48
+ "sqs": true,
49
+ "lambda": true,
50
+ "cognito": true,
51
+ "apigateway": true,
52
+ "sts": true,
53
+ "sns": true,
54
+ "eventbridge": true,
55
+ "kms": true,
56
+ "secret-manager": true,
57
+ "parameter-store": true,
58
+ "cloudwatch": true,
59
+ "cloudtrail": true,
60
+ "cloudformation": true,
61
+ "xray": true,
62
+ "config": true,
63
+ "athena": true
64
+ },
65
+ "lambdas": [
66
+ {
67
+ "name": "my-function",
68
+ "handler": "./src/handlers/users.js",
69
+ "env": {
70
+ "TABLE_NAME": "users-table"
71
+ }
72
+ }
73
+ ],
74
+ "dynamodb": {
75
+ "tables": [
76
+ {
77
+ "TableName": "users-table",
78
+ "KeySchema": [{ "AttributeName": "id", "KeyType": "HASH" }],
79
+ "AttributeDefinitions": [{ "AttributeName": "id", "AttributeType": "S" }]
80
+ }
81
+ ]
82
+ },
83
+ "s3": {
84
+ "buckets": [
85
+ { "name": "my-bucket", "region": "us-east-1" }
86
+ ]
87
+ },
88
+ "sqs": {
89
+ "queues": ["my-queue", "dead-letter-queue"]
90
+ },
91
+ "cognito": {
92
+ "userPools": [
93
+ {
94
+ "PoolName": "my-user-pool",
95
+ "AutoVerifiedAttributes": ["email"]
96
+ }
97
+ ]
98
+ }
99
+ }
100
+ ```
101
+
102
+ ### 2. Inicie o simulador:
103
+
104
+ ```bash
105
+ # Via CLI
106
+ npx aws-local-simulator start
107
+
108
+ # Ou via código
109
+ const { AWSLocalSimulator } = require('aws-local-simulator');
110
+ const simulator = new AWSLocalSimulator();
111
+ await simulator.start();
112
+ ```
113
+
114
+ ### 3. Configure seu código para usar os serviços locais:
115
+
116
+ ```javascript
117
+ const { dynamoDB, s3, sqs, cognito } = require('aws-local-simulator/aws-config');
118
+
119
+ await dynamoDB.send(new PutCommand({
120
+ TableName: 'users-table',
121
+ Item: { id: '123', name: 'John' }
122
+ }));
123
+ ```
124
+
125
+ ## 🔧 Configuração por Variáveis de Ambiente
126
+
127
+ | Variável | Descrição | Padrão |
128
+ |---------|----------|-------|
129
+ | AWS_LOCAL_SIMULATOR_DYNAMODB | Habilita DynamoDB | true |
130
+ | AWS_LOCAL_SIMULATOR_S3 | Habilita S3 | true |
131
+ | AWS_LOCAL_SIMULATOR_SQS | Habilita SQS | true |
132
+ | AWS_LOCAL_SIMULATOR_LAMBDA | Habilita Lambda | true |
133
+ | AWS_LOCAL_SIMULATOR_COGNITO | Habilita Cognito | false |
134
+ | AWS_LOCAL_SIMULATOR_APIGATEWAY | Habilita API Gateway | false |
135
+ | AWS_LOCAL_SIMULATOR_STS | Habilita STS | true |
136
+ | AWS_LOCAL_SIMULATOR_SNS | Habilita SNS | false |
137
+ | AWS_LOCAL_SIMULATOR_EVENTBRIDGE | Habilita EventBridge | false |
138
+ | AWS_LOCAL_SIMULATOR_KMS | Habilita KMS | false |
139
+ | AWS_LOCAL_SIMULATOR_SECRET_MANAGER | Habilita Secrets Manager | false |
140
+ | AWS_LOCAL_SIMULATOR_PARAMETER_STORE | Habilita Parameter Store | false |
141
+ | AWS_LOCAL_SIMULATOR_CLOUDWATCH | Habilita CloudWatch | false |
142
+ | AWS_LOCAL_SIMULATOR_CLOUDTRAIL | Habilita CloudTrail | false |
143
+ | AWS_LOCAL_SIMULATOR_CLOUDFORMATION | Habilita CloudFormation | false |
144
+ | AWS_LOCAL_SIMULATOR_ATHENA | Habilita Athena | false |
145
+ | AWS_LOCAL_SIMULATOR_XRAY | Habilita X-Ray | false |
146
+ | AWS_LOCAL_SIMULATOR_CONFIG | Habilita AWS Config | false |
147
+ | AWS_LOCAL_SIMULATOR_ECS | Habilita ECS/Fargate | false |
148
+ | AWS_LOCAL_SIMULATOR_DYNAMODB_PORT | Porta DynamoDB | 8000 |
149
+ | AWS_LOCAL_SIMULATOR_S3_PORT | Porta S3 | 4566 |
150
+ | AWS_LOCAL_SIMULATOR_SQS_PORT | Porta SQS | 9324 |
151
+ | AWS_LOCAL_SIMULATOR_LAMBDA_PORT | Porta Lambda | 3001 |
152
+ | AWS_LOCAL_SIMULATOR_COGNITO_PORT | Porta Cognito | 9229 |
153
+ | AWS_LOCAL_SIMULATOR_APIGATEWAY_PORT | Porta API Gateway | 4567 |
154
+ | AWS_LOCAL_SIMULATOR_STS_PORT | Porta STS | 9326 |
155
+ | AWS_LOCAL_SIMULATOR_SNS_PORT | Porta SNS | 9911 |
156
+ | AWS_LOCAL_SIMULATOR_EVENTBRIDGE_PORT | Porta EventBridge | 4010 |
157
+ | AWS_LOCAL_SIMULATOR_KMS_PORT | Porta KMS | 4000 |
158
+ | AWS_LOCAL_SIMULATOR_SECRET_MANAGER_PORT | Porta Secrets Manager | 4001 |
159
+ | AWS_LOCAL_SIMULATOR_PARAMETER_STORE_PORT | Porta Parameter Store | 4002 |
160
+ | AWS_LOCAL_SIMULATOR_CLOUDWATCH_PORT | Porta CloudWatch | 4011 |
161
+ | AWS_LOCAL_SIMULATOR_CLOUDTRAIL_PORT | Porta CloudTrail | 4012 |
162
+ | AWS_LOCAL_SIMULATOR_CONFIG_PORT | Porta AWS Config | 4013 |
163
+ | AWS_LOCAL_SIMULATOR_XRAY_PORT | Porta X-Ray | 4015 |
164
+ | AWS_LOCAL_SIMULATOR_CLOUDFORMATION_PORT | Porta CloudFormation | 4580 |
165
+ | AWS_LOCAL_SIMULATOR_ATHENA_PORT | Porta Athena | 4599 |
166
+ | AWS_LOCAL_SIMULATOR_ECS_PORT | Porta ECS | 8080 |
167
+ | AWS_LOCAL_SIMULATOR_DATA | Diretório de dados | ./aws-local-simulator-data |
168
+ | AWS_LOCAL_SIMULATOR_LOG | Nível de log | info |
169
+
170
+ ## 📝 Comandos CLI
171
+
172
+ ```bash
173
+ # Iniciar simulador
174
+ npx aws-local-simulator start [configPath]
175
+
176
+ # Parar simulador
177
+ npx aws-local-simulator stop
178
+
179
+ # Reiniciar
180
+ npx aws-local-simulator restart
181
+
182
+ # Resetar dados
183
+ npx aws-local-simulator reset
184
+
185
+ # Status
186
+ npx aws-local-simulator status
187
+ ```
188
+
189
+ ## 🖥️ Management API
190
+
191
+ O simulador expõe uma API de gerenciamento em tempo de execução na porta `9999` (configurável via `adminPort`). Ela permite habilitar e desabilitar serviços individualmente sem reiniciar o processo.
192
+
193
+ ### Endpoints da Management API
194
+
195
+ | Método | Rota | Descrição |
196
+ |--------|------|-----------|
197
+ | GET | `/__admin/services` | Lista todos os 19 serviços com status |
198
+ | GET | `/__admin/services/:name` | Status de um serviço específico |
199
+ | POST | `/__admin/services/:name/enable` | Habilita um serviço parado |
200
+ | POST | `/__admin/services/:name/disable` | Desabilita um serviço em execução |
201
+
202
+ ### Exemplos
203
+
204
+ ```bash
205
+ # Listar todos os serviços
206
+ curl http://localhost:9999/__admin/services
207
+
208
+ # Habilitar DynamoDB
209
+ curl -X POST http://localhost:9999/__admin/services/dynamodb/enable
210
+
211
+ # Desabilitar SQS
212
+ curl -X POST http://localhost:9999/__admin/services/sqs/disable
213
+
214
+ # Status de um serviço
215
+ curl http://localhost:9999/__admin/services/lambda
216
+ ```
217
+
218
+ ### Configuração da porta admin
219
+
220
+ ```json
221
+ {
222
+ "adminPort": 9999
223
+ }
224
+ ```
225
+
226
+ Ou via variável de ambiente:
227
+ ```bash
228
+ AWS_LOCAL_SIMULATOR_ADMIN_PORT=9999 npx aws-local-simulator start
229
+ ```
230
+
231
+ > A Management API nunca persiste alterações em disco — todo o estado é mantido em memória. Para uso em desenvolvimento local apenas.
232
+
233
+ ## 🔌 Endpoints
234
+
235
+ | Serviço | Endpoint | Admin |
236
+ |---------|----------|-------|
237
+ | DynamoDB | http://localhost:8000 | http://localhost:8000/__admin/tables |
238
+ | S3 | http://localhost:4566 | http://localhost:4566/__admin/buckets |
239
+ | S3 Website | http://localhost:4566/website/{bucket}/ | — |
240
+ | SQS | http://localhost:9324 | http://localhost:9324/__admin/queues |
241
+ | Lambda | http://localhost:3001 | http://localhost:3001/__admin/functions |
242
+ | Cognito | http://localhost:9229 | http://localhost:9229/__admin/userpools |
243
+ | API Gateway | http://localhost:4567 | http://localhost:4567/__admin/apis |
244
+ | STS | http://localhost:9326 | — |
245
+ | SNS | http://localhost:9911 | http://localhost:9911/__admin/health |
246
+ | EventBridge | http://localhost:4010 | — |
247
+ | KMS | http://localhost:4000 | — |
248
+ | Secrets Manager | http://localhost:4001 | — |
249
+ | Parameter Store | http://localhost:4002 | — |
250
+ | CloudWatch | http://localhost:4011 | — |
251
+ | CloudTrail | http://localhost:4012 | — |
252
+ | AWS Config | http://localhost:4013 | — |
253
+ | X-Ray | http://localhost:4015 | — |
254
+ | CloudFormation | http://localhost:4580 | http://localhost:4580/__admin/stacks |
255
+ | Athena | http://localhost:4599 | http://localhost:4599/__admin/health |
256
+ | ECS | http://localhost:8080 | http://localhost:8080/__admin/clusters |
257
+ | Management API | http://localhost:9999 | http://localhost:9999/__admin/services |
258
+
259
+ ## 🧪 Testando com AWS CLI
260
+
261
+ ```bash
262
+ # DynamoDB
263
+ aws dynamodb list-tables --endpoint-url http://localhost:8000
264
+
265
+ # S3
266
+ aws s3 ls --endpoint-url http://localhost:4566
267
+
268
+ # SQS
269
+ aws sqs list-queues --endpoint-url http://localhost:9324
270
+
271
+ # Lambda
272
+ aws lambda invoke \
273
+ --function-name my-function \
274
+ --payload '{"key":"value"}' \
275
+ --endpoint-url http://localhost:3001 \
276
+ output.json
277
+
278
+ # Cognito
279
+ aws cognito-idp list-user-pools --max-results 10 --endpoint-url http://localhost:9229
280
+
281
+ # Cognito cadastrar um usuario pelo adminstrador
282
+ aws cognito-idp admin-create-user \
283
+ --user-pool-id us-east-xxxx\
284
+ --username usuario@email.com \
285
+ --user-attributes \
286
+ Name=email,Value=usuario@email.com \
287
+ Name=email_verified,Value=false \
288
+ Name=name,Value="nome usuario" \
289
+ Name=custom:role,Value="user" \
290
+ temporary-password "Teste@123456" \
291
+ --message-action SUPPRESS \
292
+ --endpoint-url http://localhost:9229
293
+
294
+ # Cognito excluir um usuario
295
+ aws cognito-idp admin-delete-user \
296
+ --user-pool-id us-east-xxxx \
297
+ --username usuario@email.com
298
+ --endpoint-url http://localhost:9229
299
+
300
+ # Cognito Registrar usuário
301
+ aws cognito-idp sign-up \
302
+ --client-id $CLIENT_ID \
303
+ --username usuario@email.com \
304
+ --password "Teste@123456" \
305
+ --user-attributes Name=email,Value=usuario@email.com Name=name,Value="nome usuario"
306
+ --endpoint-url http://localhost:9229
307
+
308
+ # 2. Confirmar usuário administrativamente
309
+ aws cognito-idp admin-confirm-sign-up \
310
+ --user-pool-id us-east-xxxx \
311
+ --username usuario@email.com
312
+ --endpoint-url http://localhost:9229
313
+
314
+ # O código chega no e-mail do usuário. Algo como: "Your confirmation code is 123456"
315
+ aws cognito-idp confirm-sign-up \
316
+ --client-id 3n4b5urk1ft4fl3mg5e62d9ado \
317
+ --username usuario@email.com \
318
+ --confirmation-code 123456
319
+ --endpoint-url http://localhost:9229
320
+
321
+ # STS
322
+ aws sts get-caller-identity --endpoint-url http://localhost:9326
323
+ aws sts assume-role \
324
+ --role-arn "arn:aws:iam::123456789012:role/my-role" \
325
+ --role-session-name "my-session" \
326
+ --endpoint-url http://localhost:9326
327
+
328
+ # SNS
329
+ aws sns list-topics --endpoint-url http://localhost:9911
330
+
331
+ # EventBridge
332
+ aws events list-event-buses --endpoint-url http://localhost:4010
333
+
334
+ # KMS
335
+ aws kms list-keys --endpoint-url http://localhost:4000
336
+
337
+ # Secrets Manager
338
+ aws secretsmanager list-secrets --endpoint-url http://localhost:4001
339
+
340
+ # Criar secret
341
+ aws secretsmanager create-secret \
342
+ --name "local/app/db-credentials" \
343
+ --description "Credenciais do banco" \
344
+ --secret-string '{"username":"admin","password":"secret123"}' \
345
+ --endpoint-url http://localhost:4001
346
+
347
+ # Ler secret
348
+ aws secretsmanager get-secret-value \
349
+ --secret-id "local/app/db-credentials" \
350
+ --endpoint-url http://localhost:4001
351
+
352
+ # Parameter Store
353
+ aws ssm describe-parameters --endpoint-url http://localhost:4002
354
+
355
+ # Criar parâmetro String
356
+ aws ssm put-parameter \
357
+ --name "/local/app/config" \
358
+ --value '{"timeout":30,"maxRetries":3}' \
359
+ --type String \
360
+ --endpoint-url http://localhost:4002
361
+
362
+ # Criar parâmetro SecureString
363
+ aws ssm put-parameter \
364
+ --name "/local/app/api-key" \
365
+ --value "my-secret-api-key" \
366
+ --type SecureString \
367
+ --endpoint-url http://localhost:4002
368
+
369
+ # Ler parâmetro
370
+ aws ssm get-parameter \
371
+ --name "/local/app/config" \
372
+ --endpoint-url http://localhost:4002
373
+
374
+ # CloudWatch
375
+ aws cloudwatch list-metrics --endpoint-url http://localhost:4011
376
+ aws logs describe-log-groups --endpoint-url http://localhost:4011
377
+
378
+ # CloudTrail
379
+ aws cloudtrail describe-trails --endpoint-url http://localhost:4012
380
+
381
+ # CloudFormation
382
+ aws cloudformation list-stacks --endpoint-url http://localhost:4580
383
+
384
+ # X-Ray
385
+ aws xray get-trace-summaries \
386
+ --start-time $(date -d '1 hour ago' +%s) \
387
+ --end-time $(date +%s) \
388
+ --endpoint-url http://localhost:4015
389
+
390
+ # AWS Config
391
+ aws configservice describe-configuration-recorders --endpoint-url http://localhost:4013
392
+
393
+ # API Gateway
394
+ aws apigateway get-rest-apis --endpoint-url http://localhost:4567
395
+
396
+ # Cloudformation
397
+ aws cloudformation create-stack \
398
+ --stack-name test-stack \
399
+ --template-body file://templates/test-stack.yaml \
400
+ --parameters \
401
+ ParameterKey=Environment,ParameterValue=local \
402
+ ParameterKey=BucketName,ParameterValue=meu-bucket \
403
+ ParameterKey=QueueName,ParameterValue=minha-fila \
404
+ ParameterKey=TableName,ParameterValue=minha-tabela \
405
+ --endpoint-url http://localhost:4580
406
+
407
+ # Ver Cloudformation resultado
408
+ aws cloudformation describe-stacks \
409
+ --stack-name test-stack \
410
+ --endpoint-url http://localhost:4580
411
+
412
+ # Athena
413
+ # Criar workgroup
414
+ aws athena create-work-group \
415
+ --name my-workgroup \
416
+ --configuration ResultConfiguration={OutputLocation=s3://meu-bucket/athena-results/} \
417
+ --endpoint-url http://localhost:4599
418
+
419
+ # Listar workgroups
420
+ aws athena list-work-groups --endpoint-url http://localhost:4599
421
+
422
+ # Executar query
423
+ aws athena start-query-execution \
424
+ --query-string "SELECT * FROM my_table LIMIT 10" \
425
+ --query-execution-context Database=default \
426
+ --result-configuration OutputLocation=s3://meu-bucket/athena-results/ \
427
+ --endpoint-url http://localhost:4599
428
+
429
+ # Verificar status da query
430
+ aws athena get-query-execution \
431
+ --query-execution-id <id-retornado> \
432
+ --endpoint-url http://localhost:4599
433
+
434
+ # Buscar resultados
435
+ aws athena get-query-results \
436
+ --query-execution-id <id-retornado> \
437
+ --endpoint-url http://localhost:4599
438
+
439
+ # Criar named query
440
+ aws athena create-named-query \
441
+ --name "my-saved-query" \
442
+ --database default \
443
+ --query-string "SELECT id, value FROM my_table WHERE status = 'active'" \
444
+ --endpoint-url http://localhost:4599
445
+
446
+ # Listar named queries
447
+ aws athena list-named-queries --endpoint-url http://localhost:4599
448
+ ```
449
+
450
+ ## ⚙️ Configuração S3
451
+
452
+ ### Buckets simples
453
+
454
+ ```json
455
+ {
456
+ "s3": {
457
+ "buckets": [
458
+ "my-bucket"
459
+ ]
460
+ }
461
+ }
462
+ ```
463
+
464
+ ### Buckets com região e website estático
465
+
466
+ ```json
467
+ {
468
+ "s3": {
469
+ "buckets": [
470
+ { "name": "my-bucket", "region": "us-east-1" },
471
+ {
472
+ "name": "my-site-bucket",
473
+ "region": "us-east-1",
474
+ "websiteConfiguration": {
475
+ "IndexDocument": { "Suffix": "index.html" },
476
+ "ErrorDocument": { "Key": "error.html" }
477
+ }
478
+ }
479
+ ]
480
+ }
481
+ }
482
+ ```
483
+
484
+ Quando `websiteConfiguration` está presente, o bucket serve arquivos estáticos.
485
+
486
+ ### URL do website estático
487
+
488
+ ```
489
+ http://localhost:4566/website/{bucket-name}/
490
+ http://localhost:4566/website/{bucket-name}/caminho/pagina.html
491
+ ```
492
+
493
+ Exemplos:
494
+ ```
495
+ http://localhost:4566/website/my-site-bucket/ → serve index.html
496
+ http://localhost:4566/website/my-site-bucket/about.html → serve about.html
497
+ http://localhost:4566/website/my-site-bucket/app/ → serve app/index.html
498
+ ```
499
+
500
+ ### Gerenciar website config via AWS CLI
501
+
502
+ ```bash
503
+ # Habilitar website em um bucket existente
504
+ aws s3api put-bucket-website \
505
+ --bucket my-site-bucket \
506
+ --website-configuration '{"IndexDocument":{"Suffix":"index.html"},"ErrorDocument":{"Key":"error.html"}}' \
507
+ --endpoint-url http://localhost:4566
508
+
509
+ # Ver configuração de website
510
+ aws s3api get-bucket-website \
511
+ --bucket my-site-bucket \
512
+ --endpoint-url http://localhost:4566
513
+
514
+ # Remover website
515
+ aws s3api delete-bucket-website \
516
+ --bucket my-site-bucket \
517
+ --endpoint-url http://localhost:4566
518
+ ```
519
+
520
+ ## ⚙️ Configuração de Lambdas
521
+
522
+ Lambdas são registradas por **nome** e invocadas via API de invocação (igual à AWS real). O roteamento HTTP é feito pelo API Gateway.
523
+
524
+ ```json
525
+ {
526
+ "lambdas": [
527
+ {
528
+ "name": "my-user-function",
529
+ "handler": "./src/handlers/my-user-function.js",
530
+ "env": {
531
+ "TABLE_NAME": "users-table",
532
+ "BUCKET_NAME": "my-bucket"
533
+ }
534
+ }
535
+ ]
536
+ }
537
+ ```
538
+
539
+ ## ⚙️ Configuração SQS com Lambda Trigger
540
+
541
+ Para disparar uma Lambda automaticamente quando uma mensagem chega na fila, use o formato de objeto na lista de filas com `lambdaName`:
542
+
543
+ ```json
544
+ {
545
+ "lambdas": [
546
+ {
547
+ "name": "process-orders",
548
+ "handler": "./src/handlers/process-orders.js"
549
+ }
550
+ ],
551
+ "sqs": {
552
+ "queues": [
553
+ "simple-queue",
554
+ {
555
+ "name": "orders-queue",
556
+ "lambdaName": "process-orders",
557
+ "batchSize": 5
558
+ }
559
+ ]
560
+ }
561
+ }
562
+ ```
563
+
564
+ - Filas simples (string) são criadas sem trigger
565
+ - Filas com objeto aceitam `lambdaName` (nome da Lambda registrada) e `batchSize` (padrão: 10)
566
+ - Quando uma mensagem é enviada para `orders-queue`, a Lambda `process-orders` é invocada automaticamente com o evento no formato SQS padrão da AWS
567
+
568
+ O handler recebe o evento no formato padrão AWS SQS:
569
+
570
+ ```javascript
571
+ exports.handler = async (event) => {
572
+ for (const record of event.Records) {
573
+ const body = JSON.parse(record.body);
574
+ console.log('Mensagem recebida:', body);
575
+ // processar...
576
+ }
577
+
578
+ // Retornar batchItemFailures para reprocessar mensagens específicas
579
+ return { batchItemFailures: [] };
580
+ };
581
+ ```
582
+
583
+ ## ⚙️ Configuração API GATEWAY
584
+
585
+ O valor do **lambdaName** deve igual ao nome Lambda que está registrada com o valor **name**. Ex: "my-user-function".
586
+
587
+ ```json
588
+ {
589
+ "apigateway": {
590
+ "apis": [
591
+ {
592
+ "name": "Users API",
593
+ "description": "API para gerenciamento de usuários",
594
+ "endpoints": [
595
+ {
596
+ "path": "/user",
597
+ "method": "GET",
598
+ "lambdaName": "my-user-function",
599
+ "integrationType": "lambda"
600
+ },
601
+ {
602
+ "path": "/user",
603
+ "method": "POST",
604
+ "lambdaName": "my-user-function",
605
+ "integrationType": "lambda"
606
+ },
607
+ {
608
+ "path": "/user/{id}",
609
+ "method": "GET",
610
+ "lambdaName": "my-user-function",
611
+ "integrationType": "lambda"
612
+ },
613
+ {
614
+ "path": "/user/{id}",
615
+ "method": "DELETE",
616
+ "lambdaName": "my-user-function",
617
+ "integrationType": "lambda"
618
+ },
619
+ {
620
+ "path": "/user/{id}",
621
+ "method": "ANY",
622
+ "lambdaName": "my-user-function",
623
+ "integrationType": "lambda"
624
+ }
625
+ ]
626
+ }
627
+ ]
628
+ }
629
+ }
630
+ ```
631
+
632
+ ### Método ANY
633
+
634
+ Use `"method": "ANY"` para registrar um endpoint que aceita todos os verbos HTTP (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS) — equivalente ao `ANY` do AWS API Gateway real.
635
+
636
+ ```json
637
+ {
638
+ "path": "/webhook",
639
+ "method": "ANY",
640
+ "lambdaName": "my-webhook-handler",
641
+ "integrationType": "lambda"
642
+ }
643
+ ```
644
+
645
+ ### API Key
646
+
647
+ O API Gateway suporta validação de API Key via header `x-api-key`. Para proteger um endpoint, declare as `apiKeys` na configuração e use `"apiKeyRequired": true` no endpoint:
648
+
649
+ ```json
650
+ {
651
+ "apigateway": {
652
+ "apiKeys": [
653
+ {
654
+ "name": "my-app-key",
655
+ "value": "minha-chave-secreta-123"
656
+ }
657
+ ],
658
+ "apis": [
659
+ {
660
+ "name": "Protected API",
661
+ "endpoints": [
662
+ {
663
+ "path": "/protected",
664
+ "method": "GET",
665
+ "lambdaName": "my-user-function",
666
+ "integrationType": "lambda",
667
+ "apiKeyRequired": true
668
+ },
669
+ {
670
+ "path": "/public",
671
+ "method": "GET",
672
+ "lambdaName": "my-user-function",
673
+ "integrationType": "lambda"
674
+ }
675
+ ]
676
+ }
677
+ ]
678
+ }
679
+ }
680
+ ```
681
+
682
+ Ao chamar um endpoint protegido, envie o header:
683
+
684
+ ```bash
685
+ curl http://localhost:4567/protected \
686
+ -H "x-api-key: minha-chave-secreta-123"
687
+
688
+ # Sem a key → 403 Forbidden
689
+ curl http://localhost:4567/protected
690
+ ```
691
+
692
+ > **Nota:** A validação de API Key só está ativa no fluxo de proxy (`/:apiId/:stageName/*`). Endpoints declarados diretamente no `aws-local-simulator.json` via `setupConfigRoutes` não aplicam a validação de API Key no momento.
693
+
694
+ ### Cognito Authorizer
695
+
696
+ O API Gateway suporta autenticação via Cognito User Pools. Configure um `authorizer` na API e marque os endpoints protegidos com `"authorizerRequired": true`:
697
+
698
+ ```json
699
+ {
700
+ "cognito": {
701
+ "userPools": [
702
+ {
703
+ "PoolName": "my-user-pool",
704
+ "UserPoolId": "us-east-XXXXX",
705
+ "ClientId": "XXXXXX",
706
+ "AutoVerifiedAttributes": ["email"]
707
+ }
708
+ ]
709
+ },
710
+ "apigateway": {
711
+ "apis": [
712
+ {
713
+ "name": "My API",
714
+ "authorizer": {
715
+ "type": "COGNITO_USER_POOLS",
716
+ "userPoolId": "us-east-XXXXX"
717
+ },
718
+ "endpoints": [
719
+ {
720
+ "path": "/profile",
721
+ "method": "GET",
722
+ "lambdaName": "my-user-function",
723
+ "integrationType": "lambda",
724
+ "authorizerRequired": true
725
+ },
726
+ {
727
+ "path": "/public",
728
+ "method": "GET",
729
+ "lambdaName": "my-user-function",
730
+ "integrationType": "lambda"
731
+ }
732
+ ]
733
+ }
734
+ ]
735
+ }
736
+ }
737
+ ```
738
+
739
+ O simulador valida o JWT do Cognito local no header `Authorization: Bearer <token>`. Se o token for inválido ou ausente, retorna `401 Unauthorized`.
740
+
741
+ ```bash
742
+ # 1. Autenticar e obter o token
743
+ TOKEN=$(curl -s -X POST http://localhost:9229/ \
744
+ -H "Content-Type: application/x-amz-json-1.1" \
745
+ -H "X-Amz-Target: AWSCognitoIdentityProviderService.InitiateAuth" \
746
+ -d '{
747
+ "AuthFlow": "USER_PASSWORD_AUTH",
748
+ "ClientId": "XXXXXX",
749
+ "AuthParameters": {
750
+ "USERNAME": "usuario@email.com",
751
+ "PASSWORD": "Senha@123"
752
+ }
753
+ }' | jq -r '.AuthenticationResult.IdToken')
754
+
755
+ # 2. Chamar endpoint protegido com o token
756
+ curl http://localhost:4567/profile \
757
+ -H "Authorization: Bearer $TOKEN"
758
+
759
+ # Sem token → 401 Unauthorized
760
+ curl http://localhost:4567/profile
761
+ ```
762
+
763
+ O token decodificado fica disponível no Lambda em `event.requestContext.authorizer.claims`:
764
+
765
+ ```javascript
766
+ exports.handler = async (event) => {
767
+ const claims = event.requestContext.authorizer?.claims;
768
+ const userId = claims?.sub;
769
+ const email = claims?.email;
770
+
771
+ return {
772
+ statusCode: 200,
773
+ body: JSON.stringify({ userId, email })
774
+ };
775
+ };
776
+ ```
777
+
778
+ O handler deve exportar uma função padrão:
779
+
780
+ ```javascript
781
+ exports.handler = async (event, context) => {
782
+ return {
783
+ statusCode: 200,
784
+ body: JSON.stringify({ message: 'Hello from Lambda!' })
785
+ };
786
+ };
787
+ ```
788
+
789
+ ## 📁 Estrutura de Dados
790
+
791
+ Os dados são persistidos em:
792
+
793
+ ```text
794
+ .aws-local-simulator-data/
795
+ ├── dynamodb/
796
+ ├── s3/
797
+ ├── sqs/
798
+ ├── cognito/
799
+ ├── apigateway/
800
+ ├── ecs/
801
+ ├── kms/
802
+ ├── secret-manager/
803
+ ├── parameter-store/
804
+ ├── cloudwatch/
805
+ ├── cloudtrail/
806
+ ├── cloudformation/
807
+ ├── athena/
808
+ ├── xray/
809
+ └── config/
810
+ ```
811
+
812
+ ## 🐛 Debug
813
+
814
+ ```bash
815
+ AWS_LOCAL_SIMULATOR_LOG=verbose npx aws-local-simulator start
816
+ ```
817
+
818
+ ## 🤝 Contribuindo
819
+
820
+ 1. Fork o projeto
821
+ 2. Crie sua feature branch (`git checkout -b feature/AmazingFeature`)
822
+ 3. Commit suas mudanças (`git commit -m 'Add some AmazingFeature'`)
823
+ 4. Push para a branch (`git push origin feature/AmazingFeature`)
824
+ 5. Abra um Pull Request
825
+
826
+ ## 📄 Licença
827
+
828
+ MIT © Luiz Gustavo Ribeiro
829
+
830
+ ## ⚠️ Limitações
831
+
832
+ - ECS/Fargate em desenvolvimento
833
+ - WebSocket APIs em desenvolvimento
834
+ - Para uso em desenvolvimento e testes apenas