-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsarif-utils.ts
More file actions
974 lines (860 loc) · 29.9 KB
/
sarif-utils.ts
File metadata and controls
974 lines (860 loc) · 29.9 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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
/**
* Shared SARIF decomposition, visualization, and overlap analysis utilities.
*
* All functions are pure (no side effects, no I/O) for easy testing and reuse.
* Used by:
* - Cache model (Part 1) — decomposing database_analyze SARIF into per-rule entries
* - sarif_extract_rule tool (Part 2)
* - sarif_rule_to_markdown tool (Part 4)
* - sarif_compare_alerts tool (Part 5)
*/
import type { SarifDocument, SarifResult, SarifRule } from '../types/sarif';
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/** Overlap analysis mode */
export type OverlapMode = 'any-location' | 'fingerprint' | 'full-path' | 'sink' | 'source';
/** A shared location between two alerts */
export interface SharedLocation {
endColumn?: number;
endLine?: number;
startColumn?: number;
startLine?: number;
uri: string;
}
/** Result of comparing two SARIF results for location overlap */
export interface OverlapResult {
fingerprintMatch?: boolean;
matchedFingerprints?: Record<string, string>;
overlaps: boolean;
overlapMode: OverlapMode;
pathSimilarity?: number;
sharedLocations: SharedLocation[];
}
/** An overlapping alert pair found by findOverlappingAlerts */
export interface AlertOverlap {
overlapDetails: OverlapResult;
resultA: SarifResult;
resultAIndex: number;
resultB: SarifResult;
resultBIndex: number;
ruleIdA: string;
ruleIdB: string;
}
/** Rule summary returned by listSarifRules */
export interface SarifRuleSummary {
kind?: string;
name?: string;
precision?: string;
resultCount: number;
ruleId: string;
severity?: string;
tags?: string[];
tool?: string;
toolVersion?: string;
}
/** A rule whose result count changed between two SARIF runs */
export interface ChangedRule {
countA: number;
countB: number;
delta: number;
ruleId: string;
}
/** Result of diffing two SARIF documents */
export interface SarifDiffResult {
addedRules: SarifRuleSummary[];
changedRules: ChangedRule[];
removedRules: SarifRuleSummary[];
summary: {
totalResultsA: number;
totalResultsB: number;
totalRulesA: number;
totalRulesB: number;
toolA?: string;
toolB?: string;
toolVersionA?: string;
toolVersionB?: string;
};
unchangedRules: SarifRuleSummary[];
}
/** A file changed in a git diff, with optional line ranges. */
export interface DiffFileEntry {
/** Changed line ranges (hunks). Empty array means file-level only. */
hunks: Array<{ startLine: number; lineCount: number }>;
/** File path relative to the repository root. */
path: string;
}
/** Granularity for matching SARIF results against a git diff. */
export type DiffGranularity = 'file' | 'line';
/** A SARIF result classified by its relationship to a git diff. */
export interface ClassifiedResult {
/** File path of the primary location. */
file: string;
/** Line number of the primary location (if available). */
line?: number;
/** Original result index in the SARIF run. */
resultIndex: number;
/** The rule ID that produced this result. */
ruleId: string;
}
/** Result of partitioning SARIF results by git diff overlap. */
export interface SarifDiffByCommitsResult {
/** Granularity used for the classification. */
granularity: DiffGranularity;
/** Results whose primary location is in a file (and optionally line range) touched by the diff. */
newResults: ClassifiedResult[];
/** Results whose primary location is NOT in a changed file/line. */
preExistingResults: ClassifiedResult[];
/** Summary statistics. */
summary: {
/** Number of files in the diff. */
diffFileCount: number;
/** Git ref range used. */
refRange: string;
/** Total SARIF results examined. */
totalResults: number;
/** Number of results classified as new. */
totalNew: number;
/** Number of results classified as pre-existing. */
totalPreExisting: number;
};
}
// ---------------------------------------------------------------------------
// SARIF rule helpers
// ---------------------------------------------------------------------------
/**
* Get the human-readable display name for a SARIF rule.
*
* Priority: `shortDescription.text` → `name` → `id` (fallback).
* This is the single authoritative function for deriving a rule's
* display name from its SARIF definition.
*/
export function getRuleDisplayName(rule: SarifRule): string {
return rule.shortDescription?.text ?? rule.name ?? rule.id;
}
/**
* Collect all rule definitions from a SARIF run.
*
* Rules may live in `tool.driver.rules` (standard) or in
* `tool.extensions[].rules` (when `--sarif-group-rules-by-pack` is used).
* This function merges both sources into a single array.
*/
export function collectAllRules(run: SarifDocument['runs'][0]): SarifRule[] {
const driverRules = run.tool.driver.rules ?? [];
const extensionRules: SarifRule[] = [];
for (const ext of run.tool.extensions ?? []) {
if (ext.rules) {
extensionRules.push(...ext.rules);
}
}
return [...driverRules, ...extensionRules];
}
// ---------------------------------------------------------------------------
// Location extraction helpers
// ---------------------------------------------------------------------------
interface NormalizedLocation {
endColumn?: number;
endLine?: number;
startColumn?: number;
startLine?: number;
uri: string;
}
function extractPrimaryLocations(result: SarifResult): NormalizedLocation[] {
return (result.locations ?? [])
.filter(loc => loc.physicalLocation?.artifactLocation?.uri)
.map(loc => ({
endColumn: loc.physicalLocation!.region?.endColumn,
endLine: loc.physicalLocation!.region?.endLine ?? loc.physicalLocation!.region?.startLine,
startColumn: loc.physicalLocation!.region?.startColumn,
startLine: loc.physicalLocation!.region?.startLine,
uri: loc.physicalLocation!.artifactLocation!.uri!,
}));
}
function extractSourceLocations(result: SarifResult): NormalizedLocation[] {
const flows = result.codeFlows ?? [];
const sources: NormalizedLocation[] = [];
for (const flow of flows) {
for (const tf of flow.threadFlows ?? []) {
const steps = tf.locations ?? [];
if (steps.length > 0) {
const firstStep = steps[0];
const loc = firstStep.location?.physicalLocation;
if (loc?.artifactLocation?.uri) {
sources.push({
endColumn: loc.region?.endColumn,
endLine: loc.region?.endLine ?? loc.region?.startLine,
startColumn: loc.region?.startColumn,
startLine: loc.region?.startLine,
uri: loc.artifactLocation.uri,
});
}
}
}
}
return sources;
}
function extractAllLocations(result: SarifResult): NormalizedLocation[] {
const locs: NormalizedLocation[] = [...extractPrimaryLocations(result)];
// Related locations
for (const rl of result.relatedLocations ?? []) {
if (rl.physicalLocation?.artifactLocation?.uri) {
locs.push({
endColumn: rl.physicalLocation.region?.endColumn,
endLine: rl.physicalLocation.region?.endLine ?? rl.physicalLocation.region?.startLine,
startColumn: rl.physicalLocation.region?.startColumn,
startLine: rl.physicalLocation.region?.startLine,
uri: rl.physicalLocation.artifactLocation.uri,
});
}
}
// CodeFlow steps
for (const flow of result.codeFlows ?? []) {
for (const tf of flow.threadFlows ?? []) {
for (const step of tf.locations ?? []) {
const loc = step.location?.physicalLocation;
if (loc?.artifactLocation?.uri) {
locs.push({
endColumn: loc.region?.endColumn,
endLine: loc.region?.endLine ?? loc.region?.startLine,
startColumn: loc.region?.startColumn,
startLine: loc.region?.startLine,
uri: loc.artifactLocation.uri,
});
}
}
}
}
return locs;
}
function extractFullPathLocations(result: SarifResult): NormalizedLocation[] {
const flows = result.codeFlows ?? [];
const locs: NormalizedLocation[] = [];
for (const flow of flows) {
for (const tf of flow.threadFlows ?? []) {
for (const step of tf.locations ?? []) {
const loc = step.location?.physicalLocation;
if (loc?.artifactLocation?.uri) {
locs.push({
endColumn: loc.region?.endColumn,
endLine: loc.region?.endLine ?? loc.region?.startLine,
startColumn: loc.region?.startColumn,
startLine: loc.region?.startLine,
uri: loc.artifactLocation.uri,
});
}
}
}
}
return locs;
}
/**
* Normalize a SARIF URI for comparison purposes.
*
* Handles differences between:
* - Absolute file:// URIs from `bqrs interpret` (e.g. "file:///Users/dev/project/src/db.js")
* - Relative URIs from `database analyze` (e.g. "src/db.js")
* - URIs with %SRCROOT% base ID
*
* Returns the shortest suffix that identifies the file, enabling cross-run comparison.
*/
function normalizeUri(uri: string): string {
let normalized = uri;
// Strip file:// scheme and decode
if (normalized.startsWith('file:///')) {
normalized = normalized.substring(7);
} else if (normalized.startsWith('file://')) {
normalized = normalized.substring(5);
}
// Decode percent-encoded characters
try {
normalized = decodeURIComponent(normalized);
} catch { /* keep as-is if decoding fails */ }
// Normalize path separators
normalized = normalized.replace(/\\/g, '/');
// Remove leading slashes for consistent comparison
normalized = normalized.replace(/^\/+/, '');
return normalized;
}
/**
* Check if two URIs refer to the same file.
* Uses suffix matching: if one URI is a suffix of the other, they match.
*/
function urisMatch(uriA: string, uriB: string): boolean {
const a = normalizeUri(uriA);
const b = normalizeUri(uriB);
if (a === b) return true;
// Suffix match: the shorter path must be a suffix of the longer one
return a.endsWith(b) || b.endsWith(a);
}
/** Check if two regions in the same file overlap. */
function regionsOverlap(a: NormalizedLocation, b: NormalizedLocation): boolean {
if (!urisMatch(a.uri, b.uri)) return false;
const aStartLine = a.startLine ?? 0;
const aEndLine = a.endLine ?? aStartLine;
const bStartLine = b.startLine ?? 0;
const bEndLine = b.endLine ?? bStartLine;
// No line overlap → no overlap
if (aEndLine < bStartLine || bEndLine < aStartLine) return false;
// Lines overlap. If on the same line, check columns.
if (aStartLine === aEndLine && bStartLine === bEndLine && aStartLine === bStartLine) {
const aStartCol = a.startColumn ?? 0;
const aEndCol = a.endColumn ?? Infinity;
const bStartCol = b.startColumn ?? 0;
const bEndCol = b.endColumn ?? Infinity;
if (aEndCol < bStartCol || bEndCol < aStartCol) return false;
}
return true;
}
function locationKey(loc: NormalizedLocation): string {
return `${normalizeUri(loc.uri)}:${loc.startLine ?? '?'}:${loc.startColumn ?? '?'}`;
}
function findSharedLocations(
locsA: NormalizedLocation[],
locsB: NormalizedLocation[],
): SharedLocation[] {
const shared: SharedLocation[] = [];
const seen = new Set<string>();
for (const a of locsA) {
for (const b of locsB) {
if (regionsOverlap(a, b)) {
const key = `${locationKey(a)}|${locationKey(b)}`;
if (!seen.has(key)) {
seen.add(key);
shared.push({
endColumn: a.endColumn,
endLine: a.endLine,
startColumn: a.startColumn,
startLine: a.startLine,
uri: a.uri,
});
}
}
}
}
return shared;
}
// ---------------------------------------------------------------------------
// Core SARIF functions
// ---------------------------------------------------------------------------
/**
* Extract results and rule definition for a specific ruleId from SARIF.
*
* Returns a valid SARIF document containing only the matching rule and results,
* with tool extensions preserved.
*/
export function extractRuleFromSarif(sarif: SarifDocument, ruleId: string): SarifDocument {
const run = sarif.runs[0];
if (!run) {
return { ...sarif, runs: [{ tool: { driver: { name: 'CodeQL', rules: [] } }, results: [] }] };
}
// Collect rules from both driver and extensions (supports --sarif-group-rules-by-pack)
const allRules = collectAllRules(run);
const matchingRules = allRules.filter(r => r.id === ruleId);
const matchingResults = (run.results ?? [])
.filter(r => r.ruleId === ruleId)
.map(r => ({ ...r, ruleIndex: 0 }));
const extractedRun: SarifDocument['runs'][0] = {
tool: {
driver: {
...run.tool.driver,
rules: matchingRules,
},
extensions: run.tool.extensions,
},
results: matchingResults,
};
// Preserve run properties if present
if (run.properties) {
extractedRun.properties = run.properties;
}
return {
version: sarif.version,
$schema: sarif.$schema,
runs: [extractedRun],
};
}
/**
* Decompose multi-rule SARIF into per-rule SARIF subsets.
*
* Returns a Map from ruleId to a SARIF document containing only
* the results and rule definition for that rule.
*/
export function decomposeSarifByRule(sarif: SarifDocument): Map<string, SarifDocument> {
const run = sarif.runs[0];
if (!run) return new Map();
const results = run.results ?? [];
const ruleIds = new Set(results.map(r => r.ruleId));
const map = new Map<string, SarifDocument>();
for (const ruleId of ruleIds) {
map.set(ruleId, extractRuleFromSarif(sarif, ruleId));
}
return map;
}
// ---------------------------------------------------------------------------
// Mermaid diagram generation
// ---------------------------------------------------------------------------
/** Sanitize a string for use inside a Mermaid node label (double-quoted). */
function sanitizeMermaidLabel(text: string): string {
// Escape quotes and limit length
let sanitized = text.replace(/"/g, '#quot;');
if (sanitized.length > 60) {
sanitized = sanitized.substring(0, 57) + '...';
}
return sanitized;
}
/**
* Convert a SARIF result with codeFlows to a Mermaid dataflow diagram.
*
* Returns an empty string for results without codeFlows (problem-kind results).
* For path-problem results, generates a `flowchart LR` diagram showing the
* dataflow path from source (green) to sink (red).
*/
export function sarifResultToMermaid(result: SarifResult, _rule: SarifRule): string {
const flows = result.codeFlows;
if (!flows || flows.length === 0) return '';
const threadFlow = flows[0]?.threadFlows?.[0];
if (!threadFlow || !threadFlow.locations || threadFlow.locations.length === 0) return '';
const steps = threadFlow.locations;
const lines: string[] = ['flowchart LR'];
const nodeIds: string[] = [];
for (let i = 0; i < steps.length; i++) {
const step = steps[i];
const loc = step.location?.physicalLocation;
const message = step.location?.message?.text ?? '(step)';
const uri = loc?.artifactLocation?.uri ?? 'unknown';
const line = loc?.region?.startLine ?? '?';
const fileName = uri.split('/').pop() ?? uri;
const nodeId = String.fromCharCode(65 + (i % 26)) + (i >= 26 ? String(Math.floor(i / 26)) : '');
nodeIds.push(nodeId);
const label = sanitizeMermaidLabel(message);
lines.push(` ${nodeId}["${label}<br/>${fileName}:${line}"]`);
}
// Add edges
for (let i = 0; i < nodeIds.length - 1; i++) {
lines.push(` ${nodeIds[i]} --> ${nodeIds[i + 1]}`);
}
// Style source (green) and sink (red)
if (nodeIds.length >= 2) {
lines.push(` style ${nodeIds[0]} fill:#d4edda`);
lines.push(` style ${nodeIds[nodeIds.length - 1]} fill:#f8d7da`);
}
return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Markdown report generation
// ---------------------------------------------------------------------------
/**
* Convert all results for a rule to a markdown report with Mermaid diagrams.
*
* Returns an empty string if the ruleId does not exist in the SARIF document.
*/
export function sarifRuleToMarkdown(sarif: SarifDocument, ruleId: string): string {
const extracted = extractRuleFromSarif(sarif, ruleId);
const run = extracted.runs[0];
const results = run.results ?? [];
const rules = run.tool.driver.rules ?? [];
if (results.length === 0 && rules.length === 0) return '';
const rule = rules[0];
const lines: string[] = [];
// Rule summary header
lines.push(`## ${ruleId}`);
lines.push('');
if (rule) {
const name = getRuleDisplayName(rule);
lines.push(`**Name**: ${name}`);
const props = rule.properties as Record<string, unknown> | undefined;
if (props) {
const parts: string[] = [];
if (props.kind) parts.push(`**Kind**: ${props.kind}`);
if (props.precision) parts.push(`**Precision**: ${props.precision}`);
if (props['security-severity']) parts.push(`**Security Severity**: ${props['security-severity']}`);
if (Array.isArray(props.tags) && props.tags.length > 0) {
parts.push(`**Tags**: ${(props.tags as string[]).join(', ')}`);
}
if (parts.length > 0) {
lines.push(parts.join(' | '));
}
}
lines.push(`**Results**: ${results.length}`);
lines.push('');
// Query help
if (rule.help?.markdown) {
lines.push('### Query Help');
lines.push('');
lines.push(rule.help.markdown);
lines.push('');
}
}
// Results table
if (results.length > 0) {
lines.push('### Results');
lines.push('');
lines.push('| # | File | Line | Message |');
lines.push('|---|------|------|---------|');
for (let i = 0; i < results.length; i++) {
const r = results[i];
const loc = r.locations?.[0]?.physicalLocation;
const uri = loc?.artifactLocation?.uri ?? '(unknown)';
const line = loc?.region?.startLine ?? '-';
const msg = r.message.text.replace(/([\\|])/g, '\\$1');
lines.push(`| ${i + 1} | ${uri} | ${line} | ${msg} |`);
}
lines.push('');
}
// Dataflow diagrams
const pathResults = results.filter(r => r.codeFlows && r.codeFlows.length > 0);
if (pathResults.length > 0 && rule) {
lines.push('### Dataflow Paths');
lines.push('');
for (let i = 0; i < pathResults.length; i++) {
const r = pathResults[i];
const loc = r.locations?.[0]?.physicalLocation;
const uri = loc?.artifactLocation?.uri ?? '(unknown)';
const line = loc?.region?.startLine ?? '?';
lines.push(`#### Path ${i + 1}: ${uri}:${line}`);
lines.push('');
const mermaid = sarifResultToMermaid(r, rule);
if (mermaid) {
lines.push('```mermaid');
lines.push(mermaid);
lines.push('```');
lines.push('');
}
}
}
return lines.join('\n');
}
// ---------------------------------------------------------------------------
// Rule listing and diffing
// ---------------------------------------------------------------------------
/**
* List all rules in a SARIF document with result counts and metadata.
*
* Returns a summary for each rule defined in the SARIF, including rules
* that have zero results (defined but not triggered).
*/
export function listSarifRules(sarif: SarifDocument): SarifRuleSummary[] {
const run = sarif.runs[0];
if (!run) return [];
const allRules = collectAllRules(run);
const results = run.results ?? [];
const toolName = run.tool.driver.name;
const toolVersion = run.tool.driver.version;
// Count results per ruleId
const countByRule = new Map<string, number>();
for (const r of results) {
countByRule.set(r.ruleId, (countByRule.get(r.ruleId) ?? 0) + 1);
}
// Build summaries from rule definitions
const summaries: SarifRuleSummary[] = [];
const seenRuleIds = new Set<string>();
for (const rule of allRules) {
seenRuleIds.add(rule.id);
const props = rule.properties as Record<string, unknown> | undefined;
summaries.push({
kind: props?.kind as string | undefined,
name: getRuleDisplayName(rule),
precision: props?.precision as string | undefined,
resultCount: countByRule.get(rule.id) ?? 0,
ruleId: rule.id,
severity: props?.['security-severity'] as string | undefined,
tags: Array.isArray(props?.tags) ? (props.tags as string[]) : undefined,
tool: toolName,
toolVersion,
});
}
// Include orphan ruleIds (results referencing rules not in definitions)
for (const [ruleId, count] of countByRule) {
if (!seenRuleIds.has(ruleId)) {
summaries.push({
resultCount: count,
ruleId,
tool: toolName,
toolVersion,
});
}
}
return summaries;
}
/**
* Diff two SARIF documents: compare rule sets and result counts.
*
* Useful for detecting behavioral changes across CodeQL versions,
* database updates, or query pack releases.
*/
export function diffSarifRules(sarifA: SarifDocument, sarifB: SarifDocument): SarifDiffResult {
const rulesA = listSarifRules(sarifA);
const rulesB = listSarifRules(sarifB);
const mapA = new Map(rulesA.map(r => [r.ruleId, r]));
const mapB = new Map(rulesB.map(r => [r.ruleId, r]));
const addedRules: SarifRuleSummary[] = [];
const removedRules: SarifRuleSummary[] = [];
const changedRules: ChangedRule[] = [];
const unchangedRules: SarifRuleSummary[] = [];
// Find removed and changed/unchanged rules
for (const [ruleId, ruleA] of mapA) {
const ruleB = mapB.get(ruleId);
if (!ruleB) {
removedRules.push(ruleA);
} else if (ruleA.resultCount !== ruleB.resultCount) {
changedRules.push({
countA: ruleA.resultCount,
countB: ruleB.resultCount,
delta: ruleB.resultCount - ruleA.resultCount,
ruleId,
});
} else {
unchangedRules.push(ruleA);
}
}
// Find added rules
for (const [ruleId, ruleB] of mapB) {
if (!mapA.has(ruleId)) {
addedRules.push(ruleB);
}
}
const runA = sarifA.runs[0];
const runB = sarifB.runs[0];
return {
addedRules,
changedRules,
removedRules,
summary: {
toolA: runA?.tool.driver.name,
toolB: runB?.tool.driver.name,
toolVersionA: runA?.tool.driver.version,
toolVersionB: runB?.tool.driver.version,
totalResultsA: rulesA.reduce((sum, r) => sum + r.resultCount, 0),
totalResultsB: rulesB.reduce((sum, r) => sum + r.resultCount, 0),
totalRulesA: rulesA.length,
totalRulesB: rulesB.length,
},
unchangedRules,
};
}
// ---------------------------------------------------------------------------
// Location overlap analysis
// ---------------------------------------------------------------------------
/**
* Compare two SARIF results by their partialFingerprints.
* Returns a match result if both have fingerprints with at least one shared key
* whose values are equal. Returns no match if fingerprints are absent.
*/
export function computeFingerprintOverlap(
resultA: SarifResult,
resultB: SarifResult,
): OverlapResult {
const fpA = resultA.partialFingerprints;
const fpB = resultB.partialFingerprints;
if (!fpA || !fpB || Object.keys(fpA).length === 0 || Object.keys(fpB).length === 0) {
return {
fingerprintMatch: false,
overlaps: false,
overlapMode: 'fingerprint',
sharedLocations: [],
};
}
const matchedFingerprints: Record<string, string> = {};
for (const key of Object.keys(fpA)) {
if (key in fpB && fpA[key] === fpB[key]) {
matchedFingerprints[key] = fpA[key];
}
}
const hasMatch = Object.keys(matchedFingerprints).length > 0;
return {
fingerprintMatch: hasMatch,
matchedFingerprints: hasMatch ? matchedFingerprints : undefined,
overlaps: hasMatch,
overlapMode: 'fingerprint',
sharedLocations: [],
};
}
/**
* Compute location overlap between two SARIF results.
*/
export function computeLocationOverlap(
resultA: SarifResult,
resultB: SarifResult,
mode: OverlapMode = 'sink',
): OverlapResult {
let locsA: NormalizedLocation[];
let locsB: NormalizedLocation[];
switch (mode) {
case 'fingerprint': {
const fpResult = computeFingerprintOverlap(resultA, resultB);
if (fpResult.fingerprintMatch) {
return fpResult;
}
// Fall back to full-path when fingerprints are absent or don't match
return computeLocationOverlap(resultA, resultB, 'full-path');
}
case 'sink':
locsA = extractPrimaryLocations(resultA);
locsB = extractPrimaryLocations(resultB);
break;
case 'source':
locsA = extractSourceLocations(resultA);
locsB = extractSourceLocations(resultB);
break;
case 'any-location':
locsA = extractAllLocations(resultA);
locsB = extractAllLocations(resultB);
break;
case 'full-path': {
const pathA = extractFullPathLocations(resultA);
const pathB = extractFullPathLocations(resultB);
const shared = findSharedLocations(pathA, pathB);
// Path similarity: proportion of shared steps vs total unique steps
const allKeysA = new Set(pathA.map(locationKey));
const allKeysB = new Set(pathB.map(locationKey));
const unionSize = new Set([...allKeysA, ...allKeysB]).size;
const intersectionSize = [...allKeysA].filter(k => allKeysB.has(k)).length;
const similarity = unionSize > 0 ? intersectionSize / unionSize : 0;
return {
overlaps: shared.length > 0,
overlapMode: mode,
pathSimilarity: Math.round(similarity * 1000) / 1000,
sharedLocations: shared,
};
}
default:
locsA = extractPrimaryLocations(resultA);
locsB = extractPrimaryLocations(resultB);
}
const shared = findSharedLocations(locsA, locsB);
return {
overlaps: shared.length > 0,
overlapMode: mode,
sharedLocations: shared,
};
}
/**
* Find all overlapping alerts between two sets of results (potentially different rules).
*/
export function findOverlappingAlerts(
resultsA: SarifResult[],
ruleA: SarifRule,
resultsB: SarifResult[],
ruleB: SarifRule,
mode: OverlapMode = 'sink',
): AlertOverlap[] {
const overlaps: AlertOverlap[] = [];
for (let i = 0; i < resultsA.length; i++) {
for (let j = 0; j < resultsB.length; j++) {
const overlapDetails = computeLocationOverlap(resultsA[i], resultsB[j], mode);
if (overlapDetails.overlaps) {
overlaps.push({
overlapDetails,
resultA: resultsA[i],
resultAIndex: i,
resultB: resultsB[j],
resultBIndex: j,
ruleIdA: ruleA.id,
ruleIdB: ruleB.id,
});
}
}
}
return overlaps;
}
// ---------------------------------------------------------------------------
// SARIF-to-git-diff correlation
// ---------------------------------------------------------------------------
/**
* Check whether a SARIF URI matches a diff file path.
*
* SARIF URIs may be absolute (`file:///…`) or relative (`src/db.js`),
* while git diff paths are always relative to the repo root (e.g. `src/db.js`).
* We normalize both and use suffix matching so that cross-environment
* comparisons work (e.g. CI vs local).
*/
function diffPathMatchesSarifUri(diffPath: string, sarifUri: string): boolean {
return urisMatch(diffPath, sarifUri);
}
/**
* Check whether a line number falls within any of a file's changed hunks.
*/
function lineInHunks(line: number, hunks: Array<{ startLine: number; lineCount: number }>): boolean {
for (const hunk of hunks) {
const hunkEnd = hunk.startLine + Math.max(hunk.lineCount - 1, 0);
if (line >= hunk.startLine && line <= hunkEnd) {
return true;
}
}
return false;
}
/**
* Partition SARIF results into "new" (touched by the diff) vs "pre-existing"
* based on file-level or line-level overlap with a set of changed files.
*
* This is a pure function — git operations are the caller's responsibility.
*
* @param sarif The SARIF document to classify.
* @param diffFiles Files changed in the git diff (with optional hunk info).
* @param refRange Git ref range string for metadata (e.g. "main..HEAD").
* @param granularity 'file' (default) matches any result in a changed file;
* 'line' additionally checks that the result's primary
* location line falls within a changed hunk.
*/
export function diffSarifByCommits(
sarif: SarifDocument,
diffFiles: DiffFileEntry[],
refRange: string,
granularity: DiffGranularity = 'file',
): SarifDiffByCommitsResult {
const results = sarif.runs[0]?.results ?? [];
const newResults: ClassifiedResult[] = [];
const preExistingResults: ClassifiedResult[] = [];
for (let i = 0; i < results.length; i++) {
const result = results[i];
const primaryLoc = result.locations?.[0]?.physicalLocation;
const uri = primaryLoc?.artifactLocation?.uri;
if (!uri) {
// No location info — classify as pre-existing (conservative)
preExistingResults.push({
file: '<unknown>',
resultIndex: i,
ruleId: result.ruleId,
});
continue;
}
const startLine = primaryLoc?.region?.startLine;
// Find matching diff file
const matchingDiff = diffFiles.find(df => diffPathMatchesSarifUri(df.path, uri));
let isNew = false;
if (matchingDiff) {
if (granularity === 'file') {
isNew = true;
} else if (startLine !== undefined && matchingDiff.hunks.length > 0) {
isNew = lineInHunks(startLine, matchingDiff.hunks);
} else if (matchingDiff.hunks.length === 0) {
// No hunk info available — treat as file-level match
isNew = true;
}
// else: line granularity requested but no startLine on the result → pre-existing
}
const classified: ClassifiedResult = {
file: matchingDiff ? matchingDiff.path : normalizeUri(uri),
line: startLine,
resultIndex: i,
ruleId: result.ruleId,
};
if (isNew) {
newResults.push(classified);
} else {
preExistingResults.push(classified);
}
}
return {
granularity,
newResults,
preExistingResults,
summary: {
diffFileCount: diffFiles.length,
refRange,
totalNew: newResults.length,
totalPreExisting: preExistingResults.length,
totalResults: results.length,
},
};
}