@gugananuvem/aws-local-simulator 1.0.12 → 1.0.15

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 +594 -257
  2. package/bin/aws-local-simulator.js +63 -63
  3. package/package.json +21 -10
  4. package/src/config/config-loader.js +114 -114
  5. package/src/config/default-config.js +68 -67
  6. package/src/config/env-loader.js +68 -68
  7. package/src/index.js +146 -130
  8. package/src/index.mjs +123 -123
  9. package/src/server.js +227 -223
  10. package/src/services/apigateway/index.js +73 -68
  11. package/src/services/apigateway/server.js +507 -487
  12. package/src/services/apigateway/simulator.js +1261 -1251
  13. package/src/services/athena/index.js +75 -0
  14. package/src/services/athena/server.js +101 -0
  15. package/src/services/athena/simulador.js +998 -0
  16. package/src/services/athena/simulator.js +346 -0
  17. package/src/services/cloudformation/index.js +106 -0
  18. package/src/services/cloudformation/server.js +417 -0
  19. package/src/services/cloudformation/simulador.js +1045 -0
  20. package/src/services/cloudtrail/index.js +84 -0
  21. package/src/services/cloudtrail/server.js +235 -0
  22. package/src/services/cloudtrail/simulador.js +719 -0
  23. package/src/services/cloudwatch/index.js +84 -0
  24. package/src/services/cloudwatch/server.js +366 -0
  25. package/src/services/cloudwatch/simulador.js +1173 -0
  26. package/src/services/cognito/index.js +79 -65
  27. package/src/services/cognito/server.js +301 -279
  28. package/src/services/cognito/simulator.js +1655 -1115
  29. package/src/services/config/index.js +96 -0
  30. package/src/services/config/server.js +215 -0
  31. package/src/services/config/simulador.js +1260 -0
  32. package/src/services/dynamodb/index.js +74 -70
  33. package/src/services/dynamodb/server.js +125 -121
  34. package/src/services/dynamodb/simulator.js +630 -620
  35. package/src/services/ecs/index.js +65 -65
  36. package/src/services/ecs/server.js +235 -233
  37. package/src/services/ecs/simulator.js +844 -844
  38. package/src/services/eventbridge/index.js +89 -85
  39. package/src/services/eventbridge/server.js +209 -0
  40. package/src/services/eventbridge/simulator.js +684 -0
  41. package/src/services/index.js +45 -19
  42. package/src/services/kms/index.js +75 -0
  43. package/src/services/kms/server.js +67 -0
  44. package/src/services/kms/simulator.js +324 -0
  45. package/src/services/lambda/handler-loader.js +183 -183
  46. package/src/services/lambda/index.js +78 -73
  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 -172
  50. package/src/services/parameter-store/index.js +80 -0
  51. package/src/services/parameter-store/server.js +50 -0
  52. package/src/services/parameter-store/simulator.js +201 -0
  53. package/src/services/s3/index.js +73 -69
  54. package/src/services/s3/server.js +329 -238
  55. package/src/services/s3/simulator.js +565 -740
  56. package/src/services/secret-manager/index.js +80 -0
  57. package/src/services/secret-manager/server.js +50 -0
  58. package/src/services/secret-manager/simulator.js +171 -0
  59. package/src/services/sns/index.js +89 -76
  60. package/src/services/sns/server.js +580 -0
  61. package/src/services/sns/simulator.js +1482 -0
  62. package/src/services/sqs/index.js +93 -95
  63. package/src/services/sqs/server.js +349 -345
  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 -142
  67. package/src/services/sts/simulator.js +69 -69
  68. package/src/services/xray/index.js +83 -0
  69. package/src/services/xray/server.js +308 -0
  70. package/src/services/xray/simulador.js +994 -0
  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 -0
  76. package/src/utils/local-store.js +83 -67
  77. package/src/utils/logger.js +59 -59
@@ -0,0 +1,80 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * @fileoverview Parameter Store Service
5
+ * Porta padrão: 4002
6
+ */
7
+
8
+ const http = require('http');
9
+ const path = require('path');
10
+ const { ParameterStoreSimulator } = require('./simulator');
11
+ const { ParameterStoreServer } = require('./server');
12
+ const LocalStore = require('../../utils/local-store');
13
+
14
+ class ParameterStoreService {
15
+ constructor(config) {
16
+ this.config = config;
17
+ this.logger = require('../../utils/logger');
18
+ this.name = 'parameter-store';
19
+ this.port = config?.ports?.parameterStore || config?.services?.parameterStore?.port || 4002;
20
+ this.store = null;
21
+ this.simulator = null;
22
+ this.httpServer = null;
23
+ this.isRunning = false;
24
+ }
25
+
26
+ async initialize() {
27
+ this.logger.debug(`Inicializando Parameter Store Service na porta ${this.port}...`);
28
+ const dataDir = process.env.AWS_LOCAL_SIMULATOR_DATA_DIR;
29
+ this.store = new LocalStore(path.join(dataDir, 'parameter-store'));
30
+ this.simulator = new ParameterStoreSimulator(this.store, this.logger, this.config);
31
+ await this.simulator.initialize();
32
+ this.app = new ParameterStoreServer(this.simulator, this.logger, this.config).getApp();
33
+ this.logger.debug('Parameter Store Service inicializado');
34
+ }
35
+
36
+ injectDependencies(server) {
37
+ const ct = server.getService('cloudtrail');
38
+ if (ct?.simulator) this.simulator.audit.setTrail(ct.simulator);
39
+ }
40
+
41
+ async start() {
42
+ if (this.isRunning) return;
43
+ return new Promise((resolve, reject) => {
44
+ this.httpServer = http.createServer(this.app);
45
+ this.httpServer.listen(this.port, () => {
46
+ this.isRunning = true;
47
+ this.logger.debug(`Parameter Store rodando na porta ${this.port}`);
48
+ resolve();
49
+ });
50
+ this.httpServer.on('error', reject);
51
+ });
52
+ }
53
+
54
+ async stop() {
55
+ if (!this.isRunning || !this.httpServer) return;
56
+ return new Promise((resolve) => {
57
+ this.httpServer.close(() => {
58
+ this.isRunning = false;
59
+ resolve();
60
+ });
61
+ });
62
+ }
63
+
64
+ async reset() {
65
+ await this.simulator.reset();
66
+ }
67
+
68
+ getStatus() {
69
+ return {
70
+ running: this.isRunning,
71
+ port: this.port,
72
+ endpoint: `http://localhost:${this.port}`,
73
+ parameters: this.simulator?.parameters.size || 0,
74
+ };
75
+ }
76
+
77
+ getSimulator() { return this.simulator; }
78
+ }
79
+
80
+ module.exports = { ParameterStoreService };
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ const express = require('express');
4
+ const cors = require('cors');
5
+
6
+ class ParameterStoreServer {
7
+ constructor(simulator, logger, config) {
8
+ this.simulator = simulator; this.logger = logger; this.config = config;
9
+ this.app = express();
10
+ this._setupMiddleware(); this._setupRoutes();
11
+ }
12
+ _setupMiddleware() {
13
+ if (this.config.cors?.enabled !== false) this.app.use(cors({ origin: this.config.cors?.origin || '*' }));
14
+ this.app.use(express.json({ limit: '5mb', type: ['application/json', 'application/x-amz-json-1.1'] }));
15
+ }
16
+ _getOperation(target) {
17
+ const map = {
18
+ 'AmazonSSM.PutParameter': 'putParameter',
19
+ 'AmazonSSM.GetParameter': 'getParameter',
20
+ 'AmazonSSM.GetParameters': 'getParameters',
21
+ 'AmazonSSM.GetParametersByPath': 'getParametersByPath',
22
+ 'AmazonSSM.DeleteParameter': 'deleteParameter',
23
+ 'AmazonSSM.DeleteParameters': 'deleteParameters',
24
+ 'AmazonSSM.DescribeParameters': 'describeParameters',
25
+ 'AmazonSSM.GetParameterHistory': 'getParameterHistory',
26
+ 'AmazonSSM.AddTagsToResource': 'addTagsToResource',
27
+ 'AmazonSSM.RemoveTagsFromResource': 'removeTagsFromResource',
28
+ };
29
+ return map[target];
30
+ }
31
+ _setupRoutes() {
32
+ this.app.get('/__admin/health', (req, res) => res.json({ status: 'healthy', service: 'parameter-store', timestamp: new Date().toISOString() }));
33
+ this.app.post('/', async (req, res) => {
34
+ const target = req.headers['x-amz-target'];
35
+ const operation = this._getOperation(target);
36
+ if (!operation) return res.status(400).json({ __type: 'InvalidAction', message: `Unknown: ${target}` });
37
+ try {
38
+ const result = await this.simulator[operation](req.body || {});
39
+ res.json(result || {});
40
+ } catch (err) {
41
+ this.logger.error(`ParameterStore ${target}: ${err.message}`, 'parameter-store');
42
+ const statusCodes = { ParameterNotFound: 400, ParameterAlreadyExists: 400, ParameterPatternMismatch: 400 };
43
+ res.status(statusCodes[err.code] || 500).json({ __type: err.code || 'InternalServerError', message: err.message });
44
+ }
45
+ });
46
+ }
47
+ getApp() { return this.app; }
48
+ }
49
+
50
+ module.exports = { ParameterStoreServer };
@@ -0,0 +1,201 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('crypto');
4
+ const { v4: uuidv4 } = require('uuid');
5
+ const { CloudTrailAudit } = require('../../utils/cloudtrail-audit');
6
+
7
+ /**
8
+ * Parameter Store (SSM) Simulator
9
+ */
10
+ class ParameterStoreSimulator {
11
+ constructor(store, logger, config) {
12
+ this.store = store; this.logger = logger; this.config = config;
13
+ this.parameters = new Map();
14
+ this.history = new Map();
15
+ this.audit = new CloudTrailAudit('ssm.amazonaws.com');
16
+ }
17
+
18
+ async initialize() {
19
+ try {
20
+ const params = await this.store.read('parameter-store/parameters');
21
+ if (Array.isArray(params)) for (const p of params) this.parameters.set(p.Name, p);
22
+ const history = await this.store.read('parameter-store/history');
23
+ if (Array.isArray(history)) for (const h of history) this.history.set(h.name, h.versions);
24
+ this.logger.info('ParameterStore: dados carregados', 'parameter-store');
25
+ } catch { this.logger.debug('ParameterStore: sem dados anteriores', 'parameter-store'); }
26
+ }
27
+
28
+ async _persist() {
29
+ await this.store.write('parameter-store/parameters', null, Array.from(this.parameters.values()));
30
+ const histArr = Array.from(this.history.entries()).map(([name, versions]) => ({ name, versions }));
31
+ await this.store.write('parameter-store/history', null, histArr);
32
+ }
33
+
34
+ _require(name) {
35
+ const p = this.parameters.get(name);
36
+ if (!p) { const err = new Error(`Parameter not found: ${name}`); err.code = 'ParameterNotFound'; throw err; }
37
+ return p;
38
+ }
39
+
40
+ async putParameter(params) {
41
+ const { Name, Value, Type = 'String', Description, Overwrite, Tags = [], KeyId, AllowedPattern, DataType = 'text' } = params;
42
+ if (this.parameters.has(Name) && !Overwrite) {
43
+ const err = new Error(`Parameter already exists: ${Name}`); err.code = 'ParameterAlreadyExists'; throw err;
44
+ }
45
+ if (AllowedPattern && !new RegExp(AllowedPattern).test(Value)) {
46
+ const err = new Error(`Value doesn't match pattern: ${AllowedPattern}`); err.code = 'ParameterPatternMismatch'; throw err;
47
+ }
48
+ const existing = this.parameters.get(Name);
49
+ const version = existing ? existing.Version + 1 : 1;
50
+ const storedValue = Type === 'SecureString' ? this._encrypt(Value) : Value;
51
+ const param = {
52
+ Name, Value: storedValue, Type, Description: Description || '', Version: version,
53
+ LastModifiedDate: new Date().toISOString(),
54
+ LastModifiedUser: 'local',
55
+ ARN: `arn:aws:ssm:local:000000000000:parameter${Name}`,
56
+ DataType, Tags: Tags || [], KeyId: Type === 'SecureString' ? (KeyId || 'aws/ssm') : undefined
57
+ };
58
+ this.parameters.set(Name, param);
59
+ // History
60
+ if (!this.history.has(Name)) this.history.set(Name, []);
61
+ this.history.get(Name).push({ ...param, Value });
62
+ await this._persist();
63
+ this.logger.info(`ParameterStore: parâmetro definido: ${Name}`, 'parameter-store');
64
+ this.audit.record({ eventName: 'PutParameter', readOnly: false, isDataEvent: true, resources: [{ ARN: param.ARN, type: 'AWS::SSM::Parameter' }], requestParameters: { name: Name, type: Type } });
65
+ return { Version: version, Tier: 'Standard' };
66
+ }
67
+
68
+ async getParameter(params) {
69
+ const { Name, WithDecryption } = params;
70
+ const param = this._require(Name);
71
+ const value = (WithDecryption && param.Type === 'SecureString') ? this._decrypt(param.Value) : param.Value;
72
+ this.audit.record({ eventName: 'GetParameter', readOnly: true, isDataEvent: true, resources: [{ ARN: param.ARN, type: 'AWS::SSM::Parameter' }], requestParameters: { name: Name } });
73
+ return { Parameter: { ...param, Value: value } };
74
+ }
75
+
76
+ async getParameters(params) {
77
+ const { Names, WithDecryption } = params;
78
+ const found = []; const invalid = [];
79
+ for (const name of Names) {
80
+ try {
81
+ const param = this._require(name);
82
+ const value = (WithDecryption && param.Type === 'SecureString') ? this._decrypt(param.Value) : param.Value;
83
+ found.push({ ...param, Value: value });
84
+ } catch { invalid.push(name); }
85
+ }
86
+ return { Parameters: found, InvalidParameters: invalid };
87
+ }
88
+
89
+ async getParametersByPath(params) {
90
+ const { Path, Recursive, WithDecryption, MaxResults = 10, NextToken, ParameterFilters = [] } = params;
91
+ let results = Array.from(this.parameters.values()).filter(p => {
92
+ if (Recursive) return p.Name.startsWith(Path);
93
+ const rest = p.Name.slice(Path.length);
94
+ return p.Name.startsWith(Path) && !rest.includes('/');
95
+ });
96
+ for (const filter of ParameterFilters) {
97
+ if (filter.Key === 'Type') results = results.filter(p => filter.Values.includes(p.Type));
98
+ }
99
+ let startIdx = 0;
100
+ if (NextToken) startIdx = parseInt(NextToken);
101
+ const slice = results.slice(startIdx, startIdx + MaxResults);
102
+ return {
103
+ Parameters: slice.map(p => ({
104
+ ...p, Value: (WithDecryption && p.Type === 'SecureString') ? this._decrypt(p.Value) : p.Value
105
+ })),
106
+ NextToken: results.length > startIdx + MaxResults ? String(startIdx + MaxResults) : undefined
107
+ };
108
+ }
109
+
110
+ async deleteParameter(params) {
111
+ const p = this._require(params.Name);
112
+ this.parameters.delete(params.Name);
113
+ await this._persist();
114
+ this.audit.record({ eventName: 'DeleteParameter', readOnly: false, resources: [{ ARN: p.ARN, type: 'AWS::SSM::Parameter' }], requestParameters: { name: params.Name } });
115
+ return {};
116
+ }
117
+
118
+ async deleteParameters(params) {
119
+ const { Names } = params;
120
+ const deleted = []; const invalid = [];
121
+ for (const name of Names) {
122
+ if (this.parameters.has(name)) { this.parameters.delete(name); deleted.push(name); }
123
+ else invalid.push(name);
124
+ }
125
+ await this._persist();
126
+ return { DeletedParameters: deleted, InvalidParameters: invalid };
127
+ }
128
+
129
+ async describeParameters(params) {
130
+ const { Filters = [], ParameterFilters = [], MaxResults = 50, NextToken } = params || {};
131
+ let results = Array.from(this.parameters.values());
132
+ for (const f of Filters) {
133
+ if (f.Key === 'Name') results = results.filter(p => f.Values.some(v => p.Name.includes(v)));
134
+ if (f.Key === 'Type') results = results.filter(p => f.Values.includes(p.Type));
135
+ }
136
+ let startIdx = 0;
137
+ if (NextToken) startIdx = parseInt(NextToken);
138
+ const slice = results.slice(startIdx, startIdx + MaxResults);
139
+ return {
140
+ Parameters: slice.map(({ Value, ...p }) => p),
141
+ NextToken: results.length > startIdx + MaxResults ? String(startIdx + MaxResults) : undefined
142
+ };
143
+ }
144
+
145
+ async getParameterHistory(params) {
146
+ const { Name, MaxResults = 50, NextToken } = params;
147
+ this._require(Name);
148
+ const history = this.history.get(Name) || [];
149
+ let startIdx = 0;
150
+ if (NextToken) startIdx = parseInt(NextToken);
151
+ const slice = history.slice(startIdx, startIdx + MaxResults);
152
+ return {
153
+ Parameters: slice,
154
+ NextToken: history.length > startIdx + MaxResults ? String(startIdx + MaxResults) : undefined
155
+ };
156
+ }
157
+
158
+ async addTagsToResource(params) {
159
+ const { ResourceType, ResourceId, Tags } = params;
160
+ if (ResourceType === 'Parameter') {
161
+ const param = this._require(ResourceId);
162
+ for (const tag of Tags) { const idx = param.Tags.findIndex(t => t.Key === tag.Key); if (idx >= 0) param.Tags[idx] = tag; else param.Tags.push(tag); }
163
+ await this._persist();
164
+ }
165
+ return {};
166
+ }
167
+
168
+ async removeTagsFromResource(params) {
169
+ const { ResourceType, ResourceId, TagKeys } = params;
170
+ if (ResourceType === 'Parameter') {
171
+ const param = this._require(ResourceId);
172
+ param.Tags = param.Tags.filter(t => !TagKeys.includes(t.Key));
173
+ await this._persist();
174
+ }
175
+ return {};
176
+ }
177
+
178
+ _encrypt(value) {
179
+ const key = crypto.createHash('sha256').update('local-ssm-key').digest();
180
+ const iv = crypto.randomBytes(12);
181
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
182
+ const enc = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
183
+ const tag = cipher.getAuthTag();
184
+ return Buffer.concat([iv, tag, enc]).toString('base64');
185
+ }
186
+
187
+ _decrypt(encrypted) {
188
+ try {
189
+ const key = crypto.createHash('sha256').update('local-ssm-key').digest();
190
+ const buf = Buffer.from(encrypted, 'base64');
191
+ const iv = buf.slice(0, 12); const tag = buf.slice(12, 28); const enc = buf.slice(28);
192
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
193
+ decipher.setAuthTag(tag);
194
+ return Buffer.concat([decipher.update(enc), decipher.final()]).toString('utf8');
195
+ } catch { return encrypted; }
196
+ }
197
+
198
+ async reset() { this.parameters.clear(); this.history.clear(); await this.store.clear('parameter-store'); }
199
+ }
200
+
201
+ module.exports = { ParameterStoreSimulator };
@@ -1,70 +1,74 @@
1
- /**
2
- * S3 Service - Ponto de entrada
3
- * Exporta o serviço principal e seus componentes
4
- */
5
-
6
- const S3Server = require('./server');
7
- const S3Simulator = require('./simulator');
8
-
9
- class S3Service {
10
- constructor(config) {
11
- this.config = config;
12
- this.name = 's3';
13
- this.port = config.ports.s3;
14
- this.server = null;
15
- this.simulator = null;
16
- this.isRunning = false;
17
- }
18
-
19
- async initialize() {
20
- const logger = require('../../utils/logger');
21
- logger.debug(`Inicializando S3 Service na porta ${this.port}...`);
22
-
23
- // Cria o simulador
24
- this.simulator = new S3Simulator(this.config);
25
-
26
- // Cria o servidor HTTP
27
- this.server = new S3Server(this.port, this.config);
28
- this.server.simulator = this.simulator;
29
-
30
- await this.server.initialize();
31
-
32
- logger.debug('S3 Service inicializado');
33
- }
34
-
35
- async start() {
36
- if (this.isRunning) return;
37
- await this.server.start();
38
- this.isRunning = true;
39
- }
40
-
41
- async stop() {
42
- if (!this.isRunning) return;
43
- await this.server.stop();
44
- this.isRunning = false;
45
- }
46
-
47
- async reset() {
48
- await this.simulator.reset();
49
- }
50
-
51
- getStatus() {
52
- return {
53
- running: this.isRunning,
54
- port: this.port,
55
- endpoint: `http://localhost:${this.port}`,
56
- bucketsCount: this.simulator?.getBucketsCount() || 0,
57
- objectsCount: this.simulator?.getTotalObjectsCount() || 0
58
- };
59
- }
60
-
61
- getSimulator() {
62
- return this.simulator;
63
- }
64
-
65
- getServer() {
66
- return this.server;
67
- }
68
- }
69
-
1
+ /**
2
+ * S3 Service - Ponto de entrada
3
+ * Exporta o serviço principal e seus componentes
4
+ */
5
+
6
+ const S3Server = require('./server');
7
+ const S3Simulator = require('./simulator');
8
+
9
+ class S3Service {
10
+ constructor(config) {
11
+ this.config = config;
12
+ this.name = 's3';
13
+ this.port = config.ports.s3;
14
+ this.server = null;
15
+ this.simulator = null;
16
+ this.isRunning = false;
17
+ }
18
+
19
+ async initialize() {
20
+ const logger = require('../../utils/logger');
21
+ logger.debug(`Inicializando S3 Service na porta ${this.port}...`);
22
+
23
+ this.simulator = new S3Simulator(this.config);
24
+ await this.simulator.initialize();
25
+
26
+ this.server = new S3Server(this.port, this.config);
27
+ this.server.simulator = this.simulator;
28
+
29
+ await this.server.initialize();
30
+
31
+ logger.debug('S3 Service inicializado');
32
+ }
33
+
34
+ injectDependencies(server) {
35
+ const ct = server.getService('cloudtrail');
36
+ if (ct?.simulator) this.simulator.audit.setTrail(ct.simulator);
37
+ }
38
+
39
+ async start() {
40
+ if (this.isRunning) return;
41
+ await this.server.start();
42
+ this.isRunning = true;
43
+ }
44
+
45
+ async stop() {
46
+ if (!this.isRunning) return;
47
+ await this.server.stop();
48
+ this.isRunning = false;
49
+ }
50
+
51
+ async reset() {
52
+ await this.simulator.reset();
53
+ }
54
+
55
+ getStatus() {
56
+ return {
57
+ running: this.isRunning,
58
+ port: this.port,
59
+ endpoint: `http://localhost:${this.port}`,
60
+ bucketsCount: this.simulator?.getBucketsCount() || 0,
61
+ objectsCount: this.simulator?.getTotalObjectsCount() || 0
62
+ };
63
+ }
64
+
65
+ getSimulator() {
66
+ return this.simulator;
67
+ }
68
+
69
+ getServer() {
70
+ return this.server;
71
+ }
72
+ }
73
+
70
74
  module.exports = S3Service;