@friggframework/devtools 2.0.0--canary.474.884529c.0 → 2.0.0--canary.474.988ec0b.0

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.
@@ -0,0 +1,376 @@
1
+ /**
2
+ * Tests for RepairViaImportUseCase
3
+ *
4
+ * Use case for importing orphaned resources into CloudFormation stack
5
+ * (frigg repair --import command)
6
+ */
7
+
8
+ const RepairViaImportUseCase = require('./repair-via-import-use-case');
9
+ const StackIdentifier = require('../../domain/value-objects/stack-identifier');
10
+
11
+ describe('RepairViaImportUseCase', () => {
12
+ let useCase;
13
+ let mockResourceImporter;
14
+ let mockResourceDetector;
15
+
16
+ beforeEach(() => {
17
+ // Mock repositories
18
+ mockResourceImporter = {
19
+ validateImport: jest.fn(),
20
+ importResource: jest.fn(),
21
+ importMultipleResources: jest.fn(),
22
+ getImportStatus: jest.fn(),
23
+ generateTemplateSnippet: jest.fn(),
24
+ };
25
+
26
+ mockResourceDetector = {
27
+ getResourceDetails: jest.fn(),
28
+ };
29
+
30
+ useCase = new RepairViaImportUseCase({
31
+ resourceImporter: mockResourceImporter,
32
+ resourceDetector: mockResourceDetector,
33
+ });
34
+ });
35
+
36
+ describe('importSingleResource', () => {
37
+ it('should import a single orphaned resource', async () => {
38
+ const stackIdentifier = new StackIdentifier({
39
+ stackName: 'my-app-prod',
40
+ region: 'us-east-1',
41
+ });
42
+
43
+ const resourceToImport = {
44
+ logicalId: 'OrphanedDBCluster',
45
+ physicalId: 'my-orphan-cluster',
46
+ resourceType: 'AWS::RDS::DBCluster',
47
+ };
48
+
49
+ // Mock validation
50
+ mockResourceImporter.validateImport.mockResolvedValue({
51
+ canImport: true,
52
+ reason: null,
53
+ warnings: [],
54
+ });
55
+
56
+ // Mock resource details retrieval
57
+ mockResourceDetector.getResourceDetails.mockResolvedValue({
58
+ physicalId: 'my-orphan-cluster',
59
+ resourceType: 'AWS::RDS::DBCluster',
60
+ properties: {
61
+ Engine: 'aurora-postgresql',
62
+ EngineVersion: '13.7',
63
+ MasterUsername: 'admin',
64
+ },
65
+ tags: [
66
+ { Key: 'frigg:stack', Value: 'my-app-prod' },
67
+ ],
68
+ });
69
+
70
+ // Mock import operation
71
+ mockResourceImporter.importResource.mockResolvedValue({
72
+ operationId: 'arn:aws:cloudformation:us-east-1:123456789012:changeSet/import-xyz',
73
+ status: 'IN_PROGRESS',
74
+ message: 'Resource import initiated',
75
+ });
76
+
77
+ const result = await useCase.importSingleResource({
78
+ stackIdentifier,
79
+ logicalId: resourceToImport.logicalId,
80
+ physicalId: resourceToImport.physicalId,
81
+ resourceType: resourceToImport.resourceType,
82
+ });
83
+
84
+ expect(result.success).toBe(true);
85
+ expect(result.operationId).toBeDefined();
86
+ expect(result.status).toBe('IN_PROGRESS');
87
+ expect(mockResourceImporter.validateImport).toHaveBeenCalledWith({
88
+ resourceType: 'AWS::RDS::DBCluster',
89
+ physicalId: 'my-orphan-cluster',
90
+ region: 'us-east-1',
91
+ });
92
+ expect(mockResourceImporter.importResource).toHaveBeenCalled();
93
+ });
94
+
95
+ it('should fail if resource cannot be imported', async () => {
96
+ const stackIdentifier = new StackIdentifier({
97
+ stackName: 'my-app-prod',
98
+ region: 'us-east-1',
99
+ });
100
+
101
+ // Mock validation failure
102
+ mockResourceImporter.validateImport.mockResolvedValue({
103
+ canImport: false,
104
+ reason: 'Resource type AWS::Lambda::Function does not support import',
105
+ warnings: [],
106
+ });
107
+
108
+ await expect(
109
+ useCase.importSingleResource({
110
+ stackIdentifier,
111
+ logicalId: 'MyFunction',
112
+ physicalId: 'my-function',
113
+ resourceType: 'AWS::Lambda::Function',
114
+ })
115
+ ).rejects.toThrow('Resource type AWS::Lambda::Function does not support import');
116
+ });
117
+
118
+ it('should include warnings in result', async () => {
119
+ const stackIdentifier = new StackIdentifier({
120
+ stackName: 'my-app-prod',
121
+ region: 'us-east-1',
122
+ });
123
+
124
+ // Mock validation with warnings
125
+ mockResourceImporter.validateImport.mockResolvedValue({
126
+ canImport: true,
127
+ reason: null,
128
+ warnings: ['Resource has manual configuration changes that may be lost'],
129
+ });
130
+
131
+ mockResourceDetector.getResourceDetails.mockResolvedValue({
132
+ physicalId: 'vpc-123',
133
+ resourceType: 'AWS::EC2::VPC',
134
+ properties: {
135
+ CidrBlock: '10.0.0.0/16',
136
+ },
137
+ tags: [],
138
+ });
139
+
140
+ mockResourceImporter.importResource.mockResolvedValue({
141
+ operationId: 'arn:aws:cloudformation:us-east-1:123456789012:changeSet/import-xyz',
142
+ status: 'IN_PROGRESS',
143
+ message: 'Resource import initiated',
144
+ });
145
+
146
+ const result = await useCase.importSingleResource({
147
+ stackIdentifier,
148
+ logicalId: 'MyVPC',
149
+ physicalId: 'vpc-123',
150
+ resourceType: 'AWS::EC2::VPC',
151
+ });
152
+
153
+ expect(result.success).toBe(true);
154
+ expect(result.warnings).toHaveLength(1);
155
+ expect(result.warnings[0]).toContain('manual configuration changes');
156
+ });
157
+ });
158
+
159
+ describe('importMultipleResources', () => {
160
+ it('should import multiple orphaned resources in batch', async () => {
161
+ const stackIdentifier = new StackIdentifier({
162
+ stackName: 'my-app-prod',
163
+ region: 'us-east-1',
164
+ });
165
+
166
+ const resourcesToImport = [
167
+ {
168
+ logicalId: 'OrphanedVPC',
169
+ physicalId: 'vpc-123',
170
+ resourceType: 'AWS::EC2::VPC',
171
+ },
172
+ {
173
+ logicalId: 'OrphanedSubnet',
174
+ physicalId: 'subnet-456',
175
+ resourceType: 'AWS::EC2::Subnet',
176
+ },
177
+ ];
178
+
179
+ // Mock validation for both resources
180
+ mockResourceImporter.validateImport.mockResolvedValue({
181
+ canImport: true,
182
+ reason: null,
183
+ warnings: [],
184
+ });
185
+
186
+ // Mock resource details
187
+ mockResourceDetector.getResourceDetails
188
+ .mockResolvedValueOnce({
189
+ physicalId: 'vpc-123',
190
+ resourceType: 'AWS::EC2::VPC',
191
+ properties: { CidrBlock: '10.0.0.0/16' },
192
+ tags: [],
193
+ })
194
+ .mockResolvedValueOnce({
195
+ physicalId: 'subnet-456',
196
+ resourceType: 'AWS::EC2::Subnet',
197
+ properties: { CidrBlock: '10.0.1.0/24' },
198
+ tags: [],
199
+ });
200
+
201
+ // Mock batch import
202
+ mockResourceImporter.importMultipleResources.mockResolvedValue({
203
+ operationId: 'arn:aws:cloudformation:us-east-1:123456789012:changeSet/batch-import-xyz',
204
+ status: 'IN_PROGRESS',
205
+ importedCount: 2,
206
+ failedCount: 0,
207
+ message: 'Batch import initiated',
208
+ details: [
209
+ { logicalId: 'OrphanedVPC', status: 'IN_PROGRESS' },
210
+ { logicalId: 'OrphanedSubnet', status: 'IN_PROGRESS' },
211
+ ],
212
+ });
213
+
214
+ const result = await useCase.importMultipleResources({
215
+ stackIdentifier,
216
+ resources: resourcesToImport,
217
+ });
218
+
219
+ expect(result.success).toBe(true);
220
+ expect(result.importedCount).toBe(2);
221
+ expect(result.failedCount).toBe(0);
222
+ expect(mockResourceImporter.importMultipleResources).toHaveBeenCalled();
223
+ });
224
+
225
+ it('should handle partial failures in batch import', async () => {
226
+ const stackIdentifier = new StackIdentifier({
227
+ stackName: 'my-app-prod',
228
+ region: 'us-east-1',
229
+ });
230
+
231
+ const resourcesToImport = [
232
+ {
233
+ logicalId: 'OrphanedVPC',
234
+ physicalId: 'vpc-123',
235
+ resourceType: 'AWS::EC2::VPC',
236
+ },
237
+ {
238
+ logicalId: 'InvalidResource',
239
+ physicalId: 'invalid-123',
240
+ resourceType: 'AWS::Lambda::Function',
241
+ },
242
+ ];
243
+
244
+ // Mock validation - first passes, second fails
245
+ mockResourceImporter.validateImport
246
+ .mockResolvedValueOnce({
247
+ canImport: true,
248
+ reason: null,
249
+ warnings: [],
250
+ })
251
+ .mockResolvedValueOnce({
252
+ canImport: false,
253
+ reason: 'Resource does not exist',
254
+ warnings: [],
255
+ });
256
+
257
+ // Mock resource details for first resource only
258
+ mockResourceDetector.getResourceDetails.mockResolvedValueOnce({
259
+ physicalId: 'vpc-123',
260
+ resourceType: 'AWS::EC2::VPC',
261
+ properties: { CidrBlock: '10.0.0.0/16' },
262
+ tags: [],
263
+ });
264
+
265
+ const result = await useCase.importMultipleResources({
266
+ stackIdentifier,
267
+ resources: resourcesToImport,
268
+ });
269
+
270
+ expect(result.success).toBe(false); // Overall failure due to partial failure
271
+ expect(result.importedCount).toBe(0); // No resources actually imported yet
272
+ expect(result.failedCount).toBe(1);
273
+ expect(result.validationErrors).toHaveLength(1);
274
+ expect(result.validationErrors[0].logicalId).toBe('InvalidResource');
275
+ });
276
+ });
277
+
278
+ describe('getImportStatus', () => {
279
+ it('should get status of import operation', async () => {
280
+ const operationId = 'arn:aws:cloudformation:us-east-1:123456789012:changeSet/import-xyz';
281
+
282
+ mockResourceImporter.getImportStatus.mockResolvedValue({
283
+ operationId,
284
+ status: 'COMPLETE',
285
+ progress: 100,
286
+ message: 'Resource import completed successfully',
287
+ completedTime: new Date('2024-01-15T12:00:00Z'),
288
+ });
289
+
290
+ const status = await useCase.getImportStatus({ operationId });
291
+
292
+ expect(status.status).toBe('COMPLETE');
293
+ expect(status.progress).toBe(100);
294
+ expect(mockResourceImporter.getImportStatus).toHaveBeenCalledWith(operationId);
295
+ });
296
+
297
+ it('should return in-progress status for ongoing import', async () => {
298
+ const operationId = 'arn:aws:cloudformation:us-east-1:123456789012:changeSet/import-xyz';
299
+
300
+ mockResourceImporter.getImportStatus.mockResolvedValue({
301
+ operationId,
302
+ status: 'IN_PROGRESS',
303
+ progress: 50,
304
+ message: 'Importing resources...',
305
+ completedTime: null,
306
+ });
307
+
308
+ const status = await useCase.getImportStatus({ operationId });
309
+
310
+ expect(status.status).toBe('IN_PROGRESS');
311
+ expect(status.progress).toBe(50);
312
+ expect(status.completedTime).toBeNull();
313
+ });
314
+ });
315
+
316
+ describe('previewImport', () => {
317
+ it('should preview template changes for import', async () => {
318
+ const stackIdentifier = new StackIdentifier({
319
+ stackName: 'my-app-prod',
320
+ region: 'us-east-1',
321
+ });
322
+
323
+ // Mock resource details
324
+ mockResourceDetector.getResourceDetails.mockResolvedValue({
325
+ physicalId: 'my-orphan-cluster',
326
+ resourceType: 'AWS::RDS::DBCluster',
327
+ properties: {
328
+ Engine: 'aurora-postgresql',
329
+ EngineVersion: '13.7',
330
+ },
331
+ tags: [],
332
+ });
333
+
334
+ // Mock template snippet generation
335
+ mockResourceImporter.generateTemplateSnippet.mockResolvedValue({
336
+ OrphanedDBCluster: {
337
+ Type: 'AWS::RDS::DBCluster',
338
+ Properties: {
339
+ Engine: 'aurora-postgresql',
340
+ EngineVersion: '13.7',
341
+ },
342
+ },
343
+ });
344
+
345
+ const preview = await useCase.previewImport({
346
+ stackIdentifier,
347
+ logicalId: 'OrphanedDBCluster',
348
+ physicalId: 'my-orphan-cluster',
349
+ resourceType: 'AWS::RDS::DBCluster',
350
+ });
351
+
352
+ expect(preview.logicalId).toBe('OrphanedDBCluster');
353
+ expect(preview.physicalId).toBe('my-orphan-cluster');
354
+ expect(preview.templateSnippet).toBeDefined();
355
+ expect(preview.templateSnippet.OrphanedDBCluster.Type).toBe('AWS::RDS::DBCluster');
356
+ });
357
+ });
358
+
359
+ describe('constructor', () => {
360
+ it('should require resourceImporter', () => {
361
+ expect(() => {
362
+ new RepairViaImportUseCase({
363
+ resourceDetector: mockResourceDetector,
364
+ });
365
+ }).toThrow('resourceImporter is required');
366
+ });
367
+
368
+ it('should require resourceDetector', () => {
369
+ expect(() => {
370
+ new RepairViaImportUseCase({
371
+ resourceImporter: mockResourceImporter,
372
+ });
373
+ }).toThrow('resourceDetector is required');
374
+ });
375
+ });
376
+ });
@@ -0,0 +1,180 @@
1
+ /**
2
+ * RunHealthCheckUseCase - Orchestrate Complete Stack Health Check
3
+ *
4
+ * Application Layer - Use Case
5
+ *
6
+ * Business logic for the "frigg doctor" command. Orchestrates multiple
7
+ * repositories and domain services to produce a comprehensive health report.
8
+ *
9
+ * Responsibilities:
10
+ * - Coordinate stack information retrieval
11
+ * - Detect drift at stack and resource level
12
+ * - Find orphaned resources
13
+ * - Analyze property mismatches
14
+ * - Calculate health score
15
+ * - Build comprehensive health report
16
+ */
17
+
18
+ const StackHealthReport = require('../../domain/entities/stack-health-report');
19
+ const Resource = require('../../domain/entities/resource');
20
+ const Issue = require('../../domain/entities/issue');
21
+ const ResourceState = require('../../domain/value-objects/resource-state');
22
+
23
+ class RunHealthCheckUseCase {
24
+ /**
25
+ * Create use case with required dependencies
26
+ *
27
+ * @param {Object} params
28
+ * @param {IStackRepository} params.stackRepository - Stack operations
29
+ * @param {IResourceDetector} params.resourceDetector - Resource discovery
30
+ * @param {MismatchAnalyzer} params.mismatchAnalyzer - Property drift analysis
31
+ * @param {HealthScoreCalculator} params.healthScoreCalculator - Health scoring
32
+ */
33
+ constructor({ stackRepository, resourceDetector, mismatchAnalyzer, healthScoreCalculator }) {
34
+ if (!stackRepository) {
35
+ throw new Error('stackRepository is required');
36
+ }
37
+ if (!resourceDetector) {
38
+ throw new Error('resourceDetector is required');
39
+ }
40
+ if (!mismatchAnalyzer) {
41
+ throw new Error('mismatchAnalyzer is required');
42
+ }
43
+ if (!healthScoreCalculator) {
44
+ throw new Error('healthScoreCalculator is required');
45
+ }
46
+
47
+ this.stackRepository = stackRepository;
48
+ this.resourceDetector = resourceDetector;
49
+ this.mismatchAnalyzer = mismatchAnalyzer;
50
+ this.healthScoreCalculator = healthScoreCalculator;
51
+ }
52
+
53
+ /**
54
+ * Execute complete health check for a stack
55
+ *
56
+ * @param {Object} params
57
+ * @param {StackIdentifier} params.stackIdentifier - Stack to check
58
+ * @returns {Promise<StackHealthReport>} Comprehensive health report
59
+ */
60
+ async execute({ stackIdentifier }) {
61
+ // 1. Verify stack exists
62
+ await this.stackRepository.getStack(stackIdentifier);
63
+
64
+ // 2. Detect stack-level drift
65
+ const driftDetection = await this.stackRepository.detectStackDrift(stackIdentifier);
66
+
67
+ // 3. Get all stack resources
68
+ const stackResources = await this.stackRepository.listResources(stackIdentifier);
69
+
70
+ // 4. Build resource entities with drift status
71
+ const resources = [];
72
+ const issues = [];
73
+
74
+ for (const stackResource of stackResources) {
75
+ let resourceState;
76
+
77
+ // Determine resource state
78
+ if (!stackResource.physicalId || stackResource.driftStatus === 'DELETED') {
79
+ // Missing resource (defined in template but doesn't exist in cloud)
80
+ resourceState = ResourceState.MISSING;
81
+
82
+ // Create issue for missing resource using factory method
83
+ issues.push(
84
+ Issue.missingResource({
85
+ resourceType: stackResource.resourceType,
86
+ resourceId: stackResource.logicalId,
87
+ description: `CloudFormation resource ${stackResource.logicalId} (${stackResource.resourceType}) is defined in the template but does not exist in the cloud.`,
88
+ })
89
+ );
90
+ } else if (stackResource.driftStatus === 'MODIFIED') {
91
+ // Drifted resource - get detailed drift information
92
+ resourceState = ResourceState.DRIFTED;
93
+
94
+ const resourceDrift = await this.stackRepository.getResourceDrift(
95
+ stackIdentifier,
96
+ stackResource.logicalId
97
+ );
98
+
99
+ // Analyze property mismatches using domain service
100
+ if (
101
+ resourceDrift.propertyDifferences &&
102
+ resourceDrift.propertyDifferences.length > 0
103
+ ) {
104
+ const propertyMismatches = this.mismatchAnalyzer.analyzePropertyMismatches(
105
+ resourceDrift.propertyDifferences,
106
+ stackResource.resourceType
107
+ );
108
+
109
+ // Create issue for each property mismatch using factory method
110
+ for (const mismatch of propertyMismatches) {
111
+ issues.push(
112
+ Issue.propertyMismatch({
113
+ resourceType: stackResource.resourceType,
114
+ resourceId: stackResource.physicalId,
115
+ mismatch,
116
+ })
117
+ );
118
+ }
119
+ }
120
+ } else {
121
+ // Resource is in sync
122
+ resourceState = ResourceState.IN_STACK;
123
+ }
124
+
125
+ // Create resource entity
126
+ // For missing resources, use placeholder physicalId since they don't exist in cloud
127
+ const resource = new Resource({
128
+ logicalId: stackResource.logicalId,
129
+ physicalId: stackResource.physicalId || `missing-${stackResource.logicalId}`,
130
+ resourceType: stackResource.resourceType,
131
+ state: resourceState,
132
+ });
133
+
134
+ resources.push(resource);
135
+ }
136
+
137
+ // 5. Find orphaned resources (exist in cloud but not in stack)
138
+ const orphanedResources = await this.resourceDetector.findOrphanedResources({
139
+ stackIdentifier,
140
+ stackResources,
141
+ });
142
+
143
+ for (const orphan of orphanedResources) {
144
+ // Create resource entity for orphan
145
+ const orphanResource = new Resource({
146
+ logicalId: null, // No logical ID (not in template)
147
+ physicalId: orphan.physicalId,
148
+ resourceType: orphan.resourceType,
149
+ state: ResourceState.ORPHANED,
150
+ });
151
+
152
+ resources.push(orphanResource);
153
+
154
+ // Create issue for orphaned resource using factory method
155
+ issues.push(
156
+ Issue.orphanedResource({
157
+ resourceType: orphan.resourceType,
158
+ resourceId: orphan.physicalId,
159
+ description: `Resource ${orphan.physicalId} exists in the cloud but is not managed by CloudFormation stack ${stackIdentifier.stackName}.`,
160
+ })
161
+ );
162
+ }
163
+
164
+ // 6. Calculate health score using domain service
165
+ const healthScore = this.healthScoreCalculator.calculate({ resources, issues });
166
+
167
+ // 7. Build comprehensive health report (aggregate root)
168
+ const report = new StackHealthReport({
169
+ stackIdentifier,
170
+ healthScore,
171
+ resources,
172
+ issues,
173
+ timestamp: new Date(),
174
+ });
175
+
176
+ return report;
177
+ }
178
+ }
179
+
180
+ module.exports = RunHealthCheckUseCase;