-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathGuardService.ts
More file actions
916 lines (798 loc) · 34.2 KB
/
GuardService.ts
File metadata and controls
916 lines (798 loc) · 34.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
import { performance } from 'perf_hooks';
import { Diagnostic, DiagnosticSeverity, Range } from 'vscode-languageserver';
import { SyntaxTreeManager } from '../../context/syntaxtree/SyntaxTreeManager';
import { CloudFormationFileType } from '../../document/Document';
import { DocumentManager } from '../../document/DocumentManager';
import { ServerComponents } from '../../server/ServerComponents';
import { SettingsConfigurable, ISettingsSubscriber, SettingsSubscription } from '../../settings/ISettingsSubscriber';
import { DefaultSettings, GuardSettings } from '../../settings/Settings';
import { LoggerFactory } from '../../telemetry/LoggerFactory';
import { ScopedTelemetry } from '../../telemetry/ScopedTelemetry';
import { Count, Telemetry } from '../../telemetry/TelemetryDecorator';
import { Closeable } from '../../utils/Closeable';
import { CancellationError, Delayer } from '../../utils/Delayer';
import { extractErrorMessage } from '../../utils/Errors';
import { readFileIfExistsAsync } from '../../utils/File';
import { ReadinessContributor, ReadinessStatus } from '../../utils/ReadinessContributor';
import { byteSize } from '../../utils/String';
import { DiagnosticCoordinator } from '../DiagnosticCoordinator';
import { getRulesForPack, getAvailableRulePacks, GuardRuleData } from './GeneratedGuardRules';
import { GuardEngine, GuardViolation, GuardRule } from './GuardEngine';
import { RuleConfiguration } from './RuleConfiguration';
export enum ValidationTrigger {
OnOpen = 'onOpen',
OnChange = 'onChange',
OnSave = 'onSave',
}
/**
* GuardService provides policy-as-code validation for CloudFormation templates
* using AWS CloudFormation Guard rules. It follows the same pattern as CfnLintService
* for consistent integration with the LSP server.
*/
/**
* Validation queue entry for managing concurrent requests
*/
interface ValidationQueueEntry {
uri: string;
content: string;
timestamp: number;
resolve: (violations: GuardViolation[]) => void;
reject: (error: Error) => void;
}
export class GuardService implements SettingsConfigurable, Closeable, ReadinessContributor {
private static readonly CFN_GUARD_SOURCE = 'cfn-guard';
private settings: GuardSettings;
private settingsSubscription?: SettingsSubscription;
private readonly delayer: Delayer<void>;
private readonly guardEngine: GuardEngine;
private readonly ruleConfiguration: RuleConfiguration;
private readonly log = LoggerFactory.getLogger(GuardService);
// Track which packs each rule belongs to for proper violation reporting
private readonly ruleToPacksMap = new Map<string, Set<string>>();
// Track custom messages from rules files
private readonly ruleCustomMessages = new Map<string, string>();
// Cache loaded rules
private enabledRules: GuardRule[] = [];
// Track async rule loading state
private isLoadingRules = false;
// Validation queuing for concurrent requests
private readonly validationQueue: ValidationQueueEntry[] = [];
private readonly activeValidations = new Map<string, Promise<GuardViolation[]>>();
private isProcessingQueue = false;
@Telemetry() private readonly telemetry!: ScopedTelemetry;
constructor(
private readonly documentManager: DocumentManager,
private readonly diagnosticCoordinator: DiagnosticCoordinator,
private readonly syntaxTreeManager: SyntaxTreeManager,
guardEngine?: GuardEngine,
ruleConfiguration?: RuleConfiguration,
delayer?: Delayer<void>,
) {
this.settings = DefaultSettings.diagnostics.cfnGuard;
this.delayer = delayer ?? new Delayer<void>(this.settings.delayMs);
this.guardEngine = guardEngine ?? new GuardEngine();
this.ruleConfiguration = ruleConfiguration ?? new RuleConfiguration();
// Initialize rule configuration with current settings
this.ruleConfiguration.updateFromSettings(this.settings);
// Load initial rules
this.getEnabledRulesByConfiguration()
.then((rules) => {
this.enabledRules = rules;
})
.catch((error) => {
this.log.error(`Failed to load initial rules: ${extractErrorMessage(error)}`);
});
}
public isReady(): ReadinessStatus {
if (!this.settings.enabled) {
return { ready: true };
}
return { ready: !this.isLoadingRules && this.enabledRules.length > 0 };
}
/**
* Configure the GuardService with settings manager
* Sets up subscription to diagnostics settings changes
*/
configure(settingsManager: ISettingsSubscriber): void {
// Clean up existing subscription if present
if (this.settingsSubscription) {
this.settingsSubscription.unsubscribe();
}
this.settings = settingsManager.getCurrentSettings().diagnostics.cfnGuard;
// Load rules with current settings
this.getEnabledRulesByConfiguration()
.then((rules) => {
this.enabledRules = rules;
})
.catch((error) => {
this.log.error(`Failed to load rules during configuration: ${extractErrorMessage(error)}`);
});
// Subscribe to diagnostics settings changes
this.settingsSubscription = settingsManager.subscribe('diagnostics', (newDiagnosticsSettings) => {
this.onSettingsChanged(newDiagnosticsSettings.cfnGuard);
});
}
/**
* Handle settings changes
*/
private onSettingsChanged(newSettings: GuardSettings): void {
const previousSettings = this.settings;
this.settings = newSettings;
this.ruleConfiguration.updateFromSettings(newSettings);
const packListChanged =
previousSettings.enabledRulePacks.length !== newSettings.enabledRulePacks.length ||
!previousSettings.enabledRulePacks.every((pack, index) => pack === newSettings.enabledRulePacks[index]);
const rulesFileChanged = previousSettings.rulesFile !== newSettings.rulesFile;
if (packListChanged || rulesFileChanged) {
// Clear maps only when rule configuration actually changes
this.ruleToPacksMap.clear();
this.ruleCustomMessages.clear();
// Track async rule loading
this.isLoadingRules = true;
this.getEnabledRulesByConfiguration()
.then((rules) => {
this.enabledRules = rules;
})
.catch((error) => {
this.log.error(`Failed to preload rules after settings change: ${extractErrorMessage(error)}`);
})
.finally(() => {
this.isLoadingRules = false;
});
this.revalidateAllDocuments();
}
}
/**
* Re-validate all open documents
* Note: This is a simplified implementation that doesn't access all documents
* since DocumentManager doesn't expose a getAllDocuments method.
* In practice, document validation is triggered by document events.
*/
private revalidateAllDocuments(): void {
// Note: We don't have access to all open documents from DocumentManager
// Document validation will be triggered by normal document events (onChange, onSave, etc.)
}
/**
* Validate a CloudFormation template using Guard rules
*
* @param content The template content as a string
* @param uri The document URI
* @param forceUseContent If true, always use the provided content (for consistency with CfnLintService)
*/
@Count({ name: 'validate', captureErrorAttributes: true })
async validate(content: string, uri: string, _forceUseContent?: boolean): Promise<void> {
const fileType = this.documentManager.get(uri)?.cfnFileType;
if (
!fileType ||
fileType === CloudFormationFileType.Other ||
fileType === CloudFormationFileType.Unknown ||
fileType === CloudFormationFileType.Empty
) {
this.telemetry.count(`validate.file.skipped`, 1);
// Not a CloudFormation file, publish empty diagnostics to clear any previous issues
this.publishDiagnostics(uri, []);
return;
}
// Guard doesn't support GitSync deployment files (similar to cfn-lint handling)
if (fileType === CloudFormationFileType.GitSyncDeployment) {
this.telemetry.count(`validate.file.${CloudFormationFileType.GitSyncDeployment}`, 1);
this.publishDiagnostics(uri, []);
return;
}
this.telemetry.count(`validate.file.${CloudFormationFileType.Template}`, 1);
const startTime = performance.now();
const doc = this.documentManager.get(uri);
const sizeCategory = doc?.getTemplateSizeCategory() ?? 'unknown';
try {
// Validate rule configuration against available packs
const availablePacks = getAvailableRulePacks();
const validationErrors = this.validateRuleConfiguration(availablePacks);
if (validationErrors.length > 0) {
this.log.warn(`Rule configuration errors: ${validationErrors.join(', ')}`);
// Continue with validation but log the issues
}
// Wait for rules to be loaded if they're still loading
await this.ensureRulesLoaded();
if (this.enabledRules.length === 0) {
this.publishDiagnostics(uri, []);
return;
}
// Track rules being evaluated
this.telemetry.histogram('validate.rules.count', this.enabledRules.length, { unit: '1' });
// Execute Guard validation with queuing for concurrent requests
const violations = await this.queueValidation(uri, content, this.enabledRules);
// Track violations
this.telemetry.histogram('validate.violations.count', violations.length, { unit: '1' });
// Convert violations to LSP diagnostics
const diagnostics = this.convertViolationsToDiagnostics(uri, violations);
// Publish diagnostics
this.publishDiagnostics(uri, diagnostics);
this.telemetry.count('validate.success', 1, { attributes: { fileType } });
} catch (error) {
const errorMessage = extractErrorMessage(error);
// Check if this is a parsing error - these are common with malformed templates
// and should be handled more gracefully
if (errorMessage.includes('Parser Error') || errorMessage.includes('parsing data file')) {
// Publish empty diagnostics to clear any previous Guard diagnostics
this.publishDiagnostics(uri, []);
this.telemetry.error('parser.error', error, undefined, {
captureErrorAttributes: true,
attributes: { errorType: 'ParseError' },
});
// Parse errors are developer issues, not service availability issues
return;
}
// Check for WASM errors
if (errorMessage.includes('WASM') || errorMessage.includes('wasm')) {
this.telemetry.error('wasm.error', error, undefined, {
captureErrorAttributes: true,
attributes: { errorType: 'WasmError' },
});
}
// Check for memory errors
if (
errorMessage.includes('memory') ||
errorMessage.includes('Memory') ||
errorMessage.includes('out of memory')
) {
this.telemetry.error('memory.threshold.exceeded', error, undefined, { captureErrorAttributes: true });
}
// For other errors (WASM issues, timeouts, etc.), log as error and show diagnostic
this.publishErrorDiagnostics(uri, errorMessage);
this.telemetry.error('validate.error', error, undefined, {
captureErrorAttributes: true,
attributes: { fileType, errorType: 'Unknown' },
});
} finally {
this.telemetry.histogram('validate.duration', (performance.now() - startTime) / byteSize(content), {
unit: 'ms/byte',
attributes: { sizeCategory },
});
}
}
/**
* Convert Guard violations to LSP diagnostics
*/
private convertViolationsToDiagnostics(uri: string, violations: GuardViolation[]): Diagnostic[] {
// Group violations by location and message to consolidate rules with same fix
const violationGroups = new Map<
string,
{
violations: GuardViolation[];
ruleNames: Set<string>;
message: string;
location: { line: number; column: number; path?: string };
severity: DiagnosticSeverity;
}
>();
for (const violation of violations) {
// Get custom message if available, otherwise use violation message
const customMessage = this.ruleCustomMessages.get(violation.ruleName);
const message = customMessage ?? violation.message;
// Create group key based on location and message
const groupKey = `${violation.location.line}:${violation.location.column}:${message}`;
if (!violationGroups.has(groupKey)) {
violationGroups.set(groupKey, {
violations: [],
ruleNames: new Set(),
message,
location: violation.location,
severity: violation.severity,
});
}
const group = violationGroups.get(groupKey);
if (group) {
group.violations.push(violation);
group.ruleNames.add(violation.ruleName);
}
}
// Convert groups to diagnostics
const diagnostics: Diagnostic[] = [];
for (const group of violationGroups.values()) {
// Combine rule names with commas
const combinedRuleName = [...group.ruleNames].toSorted().join(', ');
const range = this.getViolationRange(uri, group.violations[0]);
const diagnostic: Diagnostic = {
severity: group.severity,
range,
message: group.message,
source: GuardService.CFN_GUARD_SOURCE,
code: combinedRuleName,
};
const firstViolation = group.violations[0];
const diagnosticId =
firstViolation.context ?? `guard-${firstViolation.location.line}-${firstViolation.location.column}`;
diagnostic.data = diagnosticId;
diagnostics.push(diagnostic);
}
return diagnostics;
}
/**
* Get precise range for a violation using syntax tree
*/
private getViolationRange(uri: string, violation: GuardViolation): Range {
// Use syntax tree to get node range
const syntaxTree = this.syntaxTreeManager.getSyntaxTree(uri);
if (syntaxTree) {
const startLine = Math.max(0, violation.location.line - 1);
const startCharacter = Math.max(0, violation.location.column - 1);
const node = syntaxTree.getNodeAtPosition({
line: startLine,
character: startCharacter,
});
return {
start: { line: node.startPosition.row, character: node.startPosition.column },
end: { line: node.endPosition.row, character: node.endPosition.column },
};
}
// Fallback: return zero-width range
const startLine = Math.max(0, violation.location.line - 1);
const startCharacter = Math.max(0, violation.location.column - 1);
return {
start: { line: startLine, character: startCharacter },
end: { line: startLine, character: startCharacter },
};
}
/**
* Validate a document with debouncing and proper trigger handling
*
* @param content The document content as a string
* @param uri The document URI (used as the debouncing key)
* @param trigger The trigger that initiated this validation request
* @param forceUseContent If true, always use the provided content (default: false)
*/
async validateDelayed(
content: string,
uri: string,
trigger: ValidationTrigger,
forceUseContent: boolean = false,
): Promise<void> {
if (!this.settings.enabled) {
return;
}
switch (trigger) {
case ValidationTrigger.OnOpen:
case ValidationTrigger.OnSave: {
// OnOpen and OnSave are controlled only by guard.enabled
break;
}
case ValidationTrigger.OnChange: {
if (!this.settings.validateOnChange) {
return;
}
break;
}
default: {
this.log.warn(`Unknown validation trigger: ${trigger as string}`);
return;
}
}
// Use delayer for debouncing with proper cancellation handling
try {
if (trigger === ValidationTrigger.OnSave) {
// For save operations: execute immediately (0ms delay)
await this.delayer.delay(uri, () => this.validate(content, uri, forceUseContent), 0);
} else {
// For other triggers: use normal delayed execution
await this.delayer.delay(uri, () => this.validate(content, uri, forceUseContent));
}
} catch (error) {
// Suppress cancellation errors as they are expected behavior
if (error instanceof CancellationError) {
return;
}
// For other errors, re-throw to be handled by caller
throw error;
}
}
/**
* Publish diagnostics through the diagnostic coordinator
*/
private publishDiagnostics(uri: string, diagnostics: Diagnostic[]): void {
this.diagnosticCoordinator
.publishDiagnostics(GuardService.CFN_GUARD_SOURCE, uri, diagnostics)
.catch((reason) => {
this.log.error(`Error publishing Guard diagnostics: ${extractErrorMessage(reason)}`);
});
}
/**
* Publish error diagnostics when validation fails
*/
private publishErrorDiagnostics(uri: string, errorMessage: string): void {
let friendlyMessage = errorMessage;
if (errorMessage.includes('WASM')) {
friendlyMessage = 'Guard validation engine failed to initialize. Please check your configuration.';
} else if (errorMessage.includes('timeout')) {
friendlyMessage = 'Guard validation timed out. Consider reducing template size or increasing timeout.';
} else if (errorMessage.includes('rule')) {
friendlyMessage = 'Guard rule validation failed. Please check your rule configuration.';
}
this.publishDiagnostics(uri, [
{
severity: 1, // Error severity
range: {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
},
message: `Guard Validation Error: ${friendlyMessage}`,
source: GuardService.CFN_GUARD_SOURCE,
code: 'GUARD_ERROR',
},
]);
}
/**
* Cancel any pending delayed validation requests for a specific URI
*/
public cancelDelayedValidation(uri: string): void {
this.delayer.cancel(uri);
}
/**
* Cancel all pending delayed validation requests
*/
public cancelAllDelayedValidation(): void {
this.delayer.cancelAll();
}
/**
* Queue validation request to manage concurrent executions
*/
private async queueValidation(uri: string, content: string, rules: GuardRule[]): Promise<GuardViolation[]> {
const existingValidation = this.activeValidations.get(uri);
if (existingValidation) {
// Cancel the existing validation and start a new one
this.activeValidations.delete(uri);
}
// Track concurrent validations
this.telemetry.countUpDown('validate.concurrent', this.activeValidations.size, { unit: '1' });
// If we're under the concurrent limit, execute immediately
if (this.activeValidations.size < this.settings.maxConcurrentValidations) {
return await this.executeValidation(uri, content, rules);
}
// Track when we hit max concurrency
this.telemetry.count('validate.concurrent.max', 1);
// Otherwise, queue the request
return await new Promise<GuardViolation[]>((resolve, reject) => {
const existingIndex = this.validationQueue.findIndex((entry) => entry.uri === uri);
if (existingIndex !== -1) {
const existingEntry = this.validationQueue[existingIndex];
this.validationQueue.splice(existingIndex, 1);
existingEntry.reject(new Error('Validation cancelled - newer request queued'));
}
if (this.validationQueue.length >= this.settings.maxQueueSize) {
this.telemetry.count('validate.queue.rejected', 1);
reject(new Error('Validation queue is full. Please try again later.'));
return;
}
this.validationQueue.push({
uri,
content,
timestamp: Date.now(),
resolve,
reject,
});
this.telemetry.count('validate.queue.enqueued', 1);
this.telemetry.countUpDown('validate.queue.depth', this.validationQueue.length, { unit: '1' });
// Process queue if not already processing
void this.processValidationQueue();
});
}
/**
* Execute validation and track it as active
*/
private async executeValidation(uri: string, content: string, rules: GuardRule[]): Promise<GuardViolation[]> {
const defaultSeverity = this.getDefaultSeverity();
const validationPromise = Promise.resolve(this.guardEngine.validateTemplate(content, rules, defaultSeverity));
// Track as active validation
this.activeValidations.set(uri, validationPromise);
try {
const result = await validationPromise;
return result;
} finally {
this.activeValidations.delete(uri);
// Process any queued validations
void this.processValidationQueue();
}
}
/**
* Process the validation queue
*/
private processValidationQueue(): void {
if (this.isProcessingQueue || this.validationQueue.length === 0) {
return;
}
if (this.activeValidations.size >= this.settings.maxConcurrentValidations) {
return;
}
this.isProcessingQueue = true;
try {
while (
this.validationQueue.length > 0 &&
this.activeValidations.size < this.settings.maxConcurrentValidations
) {
const entry = this.validationQueue.shift();
if (!entry) break;
const age = Date.now() - entry.timestamp;
if (age > 30_000) {
entry.reject(new Error('Validation request expired'));
continue;
}
// Execute the validation
this.executeValidation(entry.uri, entry.content, this.enabledRules)
.then(entry.resolve)
.catch(entry.reject);
}
} finally {
this.isProcessingQueue = false;
}
}
/**
* Get the number of pending delayed validation requests
*/
public getPendingValidationCount(): number {
return this.delayer.getPendingCount();
}
/**
* Get the number of queued validation requests
*/
public getQueuedValidationCount(): number {
return this.validationQueue.length;
}
/**
* Get the number of active validation requests
*/
public getActiveValidationCount(): number {
return this.activeValidations.size;
}
/**
* Validate rule configuration against available packs
*/
private validateRuleConfiguration(availablePackNames: string[]): string[] {
const errors: string[] = [];
const availablePackSet = new Set(availablePackNames);
for (const enabledPack of this.settings.enabledRulePacks) {
if (!availablePackSet.has(enabledPack)) {
errors.push(`Rule pack '${enabledPack}' is enabled but not available`);
}
}
return errors;
}
/**
* Ensure rules are loaded before validation
*/
private async ensureRulesLoaded(): Promise<void> {
if (this.enabledRules.length === 0) {
this.enabledRules = await this.getEnabledRulesByConfiguration();
}
}
/**
* Get enabled rules based on current configuration
*/
private async getEnabledRulesByConfiguration(): Promise<GuardRule[]> {
const enabledRules: GuardRule[] = [];
// If rulesFile is specified, load rules from file
if (this.settings.rulesFile) {
try {
const customRules = await this.loadRulesFromFile(this.settings.rulesFile);
enabledRules.push(...customRules);
this.telemetry.count('rules.custom.loaded', customRules.length);
this.log.info(`Loaded ${customRules.length} rules from custom file: ${this.settings.rulesFile}`);
} catch (error) {
this.telemetry.error('rules.load.error', error, undefined, {
captureErrorAttributes: true,
attributes: { errorType: 'CustomFile' },
});
this.log.error(
`Failed to load rules from file '${this.settings.rulesFile}': ${extractErrorMessage(error)}`,
);
throw error;
}
} else {
// Use rule packs if no custom rules file is specified
const enabledPackNames = this.settings.enabledRulePacks;
this.log.info(`Loading rules from ${enabledPackNames.length} rule packs: ${enabledPackNames.join(', ')}`);
for (const packName of enabledPackNames) {
const packStartTime = performance.now();
try {
const packRules = getRulesForPack(packName);
this.telemetry.count('rules.loaded', packRules.length, { attributes: { pack: packName } });
this.telemetry.histogram('rules.load.duration', performance.now() - packStartTime, {
unit: 'ms',
attributes: { pack: packName },
});
for (const ruleData of packRules) {
// Track which packs this rule belongs to
if (!this.ruleToPacksMap.has(ruleData.name)) {
this.ruleToPacksMap.set(ruleData.name, new Set());
}
this.ruleToPacksMap.get(ruleData.name)?.add(packName);
// Store custom message if available
if (ruleData.message) {
this.ruleCustomMessages.set(ruleData.name, ruleData.message);
}
enabledRules.push(this.convertRuleDataToGuardRule(ruleData));
}
} catch (error) {
this.telemetry.error('rules.load.error', error, undefined, {
captureErrorAttributes: true,
attributes: { pack: packName, errorType: 'PackLoad' },
});
this.log.error(`Failed to get rules for pack '${packName}': ${extractErrorMessage(error)}`);
}
}
}
// Track total enabled rules
this.telemetry.countUpDown('rules.enabled.count', enabledRules.length, { unit: '1' });
return enabledRules;
}
/**
* Load Guard rules from a file
*/
private async loadRulesFromFile(filePath: string): Promise<GuardRule[]> {
try {
const fileContent = await readFileIfExistsAsync(filePath, 'utf8');
return this.parseRulesFromContent(fileContent, filePath);
} catch (error) {
throw new Error(`Failed to read rules file '${filePath}': ${extractErrorMessage(error)}`);
}
}
/**
* Parse Guard rules from file content
*/
private parseRulesFromContent(content: string, filePath: string): GuardRule[] {
// Extract rule names and messages for metadata but keep entire content together
const ruleNames: string[] = [];
// Extract rule names
const ruleMatches = content.matchAll(/^rule\s+([A-Za-z_][A-Za-z0-9_]*)/gm);
for (const match of ruleMatches) {
ruleNames.push(match[1]);
}
// Extract messages from rule blocks and store them
const ruleBlockMatches = content.matchAll(
// eslint-disable-next-line security/detect-unsafe-regex
/^rule\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:when\s+[^{]+)?\s*\{([\s\S]*?)^\}/gm,
);
for (const match of ruleBlockMatches) {
const ruleName = match[1];
const ruleContent = match[0];
const extractedMessage = GuardEngine.extractRuleMessage(ruleContent);
if (extractedMessage) {
this.ruleCustomMessages.set(ruleName, extractedMessage);
}
}
if (ruleNames.length === 0) {
this.log.warn(`No valid rules found in file '${filePath}'`);
}
// Return single rule with entire content to preserve variable definitions
return [
{
name:
ruleNames.length > 0
? ruleNames.join(',')
: `rules-from-${
filePath
.split('/')
.pop()
?.replace(/\.[^.]*$/, '') ?? 'file'
}`,
content: content,
description: `Rules: ${ruleNames.join(', ')} from ${filePath}`,
severity: this.getDefaultSeverity(),
tags: ['custom', 'file'],
pack: 'custom',
message: undefined,
},
];
}
/**
* Parse a single rule block
*/
private parseRuleBlock(ruleName: string, fullRuleContent: string): GuardRule | null {
// Extract message from rule content if available
const extractedMessage = GuardEngine.extractRuleMessage(fullRuleContent);
const description = `Custom rule ${ruleName}`;
const message = extractedMessage ?? undefined; // Let Guard engine handle default messaging
return {
name: ruleName,
content: fullRuleContent,
description,
severity: this.getDefaultSeverity(),
tags: ['custom', 'file'],
pack: 'custom',
message,
};
}
/**
* Convert GuardRuleData to GuardRule format expected by GuardEngine
*/
private convertRuleDataToGuardRule(ruleData: GuardRuleData): GuardRule {
return {
name: ruleData.name,
content: ruleData.content,
description: ruleData.description,
severity: DiagnosticSeverity.Error, // All generated rules are errors
tags: ['aws', 'cloudformation'], // All generated rules have these tags
pack: 'generated', // All rules are from generated data
message: ruleData.message,
};
}
/**
* Convert severity string to DiagnosticSeverity enum
*/
private convertSeverityStringToDiagnosticSeverity(severity: string): DiagnosticSeverity {
switch (severity.toUpperCase()) {
case 'ERROR': {
return DiagnosticSeverity.Error;
}
case 'WARNING': {
return DiagnosticSeverity.Warning;
}
case 'INFO': {
return DiagnosticSeverity.Information;
}
case 'HINT': {
return DiagnosticSeverity.Hint;
}
default: {
return DiagnosticSeverity.Error;
}
}
}
/**
* Shutdown the Guard service and clean up resources
*/
close(): void {
// Unsubscribe from settings changes
if (this.settingsSubscription) {
this.settingsSubscription.unsubscribe();
this.settingsSubscription = undefined;
}
// Cancel all pending delayed requests
this.delayer.cancelAll();
// Clear validation queue
for (const entry of this.validationQueue) {
entry.reject(new Error('GuardService is shutting down'));
}
this.validationQueue.length = 0;
// Clear active validations (don't wait for them to complete)
this.activeValidations.clear();
}
/**
* Convert settings severity string to DiagnosticSeverity enum
*/
private getDefaultSeverity(): DiagnosticSeverity {
switch (this.settings.defaultSeverity) {
case 'error': {
return DiagnosticSeverity.Error;
}
case 'warning': {
return DiagnosticSeverity.Warning;
}
case 'information': {
return DiagnosticSeverity.Information;
}
case 'hint': {
return DiagnosticSeverity.Hint;
}
default: {
return DiagnosticSeverity.Information;
}
}
}
/**
* Factory method to create GuardService with dependencies
*/
static create(
components: ServerComponents,
guardEngine?: GuardEngine,
ruleConfiguration?: RuleConfiguration,
delayer?: Delayer<void>,
): GuardService {
return new GuardService(
components.documentManager,
components.diagnosticCoordinator,
components.syntaxTreeManager,
guardEngine,
ruleConfiguration,
delayer,
);
}
}