-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcodeqlService.ts
More file actions
1408 lines (1201 loc) · 41.7 KB
/
codeqlService.ts
File metadata and controls
1408 lines (1201 loc) · 41.7 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
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as vscode from "vscode";
import { GitHubService, RepositoryInfo } from "./githubService";
import { LoggerService } from "./loggerService";
import * as path from "path";
import * as fs from "fs";
import * as yaml from "js-yaml";
import { exec } from "child_process";
import { promisify } from "util";
import * as os from "os";
const execAsync = promisify(exec);
export interface FlowStep {
file: string;
startLine: number;
startColumn: number;
endLine: number;
endColumn: number;
message?: string;
stepIndex: number;
}
export interface ScanResult {
ruleId: string;
severity: string;
message: string;
language?: string; // Optional language field
location: {
file: string;
startLine: number;
startColumn: number;
endLine: number;
endColumn: number;
};
flowSteps?: FlowStep[]; // Data flow steps from source to sink
}
export class CodeQLService {
private githubService: GitHubService;
private logger: LoggerService;
private languages: { [key: string]: string[] } = {
javascript: ["javascript", "typescript", "js", "ts", "jsx", "tsx"],
python: ["python", "py"],
java: ["java"],
csharp: ["csharp", "c#", "cs"],
cpp: ["cpp", "c++", "c", "cc", "cxx"],
go: ["go", "golang"],
ruby: ["ruby", "rb"],
swift: ["swift"],
kotlin: ["kotlin", "kt"],
scala: ["scala"],
};
private resultsCallback?: (results: ScanResult[]) => void;
constructor(githubService: GitHubService) {
this.githubService = githubService;
this.logger = LoggerService.getInstance();
}
public setResultsCallback(callback: (results: ScanResult[]) => void): void {
this.resultsCallback = callback;
}
public async runScan(
progress: vscode.Progress<{ increment?: number; message?: string }>,
cancellationToken: vscode.CancellationToken
): Promise<ScanResult[]> {
this.logger.logServiceCall("CodeQLService", "runScan", "started");
const config = vscode.workspace.getConfiguration("codeql-scanner");
const useLocalScan = config.get<boolean>("useLocalScan", true);
this.logger.info(
"CodeQLService",
`Using ${useLocalScan ? "local" : "remote"} scan mode`
);
try {
let results;
if (useLocalScan) {
results = await this.runLocalScan(progress, cancellationToken);
} else {
results = await this.runRemoteScan(progress, cancellationToken);
}
this.logger.logServiceCall("CodeQLService", "runScan", "completed", {
resultCount: results.length,
});
return results;
} catch (error) {
this.logger.logServiceCall("CodeQLService", "runScan", "failed", error);
throw error;
}
}
private async runLocalScan(
progress: vscode.Progress<{ increment?: number; message?: string }>,
cancellationToken: vscode.CancellationToken
): Promise<ScanResult[]> {
progress.report({
increment: 5,
message: "Initializing local CodeQL scan...",
});
// Check if CodeQL CLI is available
await this.checkCodeQLCLI();
await this.getSupportedLanguages();
progress.report({ increment: 10, message: "Setting up directories..." });
// Setup directories
const codeqlDir = this.getCodeQLDirectory();
const workspaceFolder = this.getWorkspaceFolder();
const repoName = this.getRepositoryName();
const currentSHA = await this.getCurrentGitSHA();
progress.report({ increment: 15, message: "Detecting languages..." });
// Get languages and search paths from configuration
const config = vscode.workspace.getConfiguration("codeql-scanner");
var languages = config.get<string[]>("languages", []);
if (!languages || languages.length === 0) {
languages = this.mapLanguagesToCodeQL(
config.get<string[]>("github.languages", [])
);
this.logger.info(
"CodeQLService",
"Updating languages from GitHub repository"
);
config.update(
"languages",
languages,
vscode.ConfigurationTarget.Workspace
);
}
// Ensure languages are always mapped to CodeQL languages, even if manually configured
// This prevents issues where users might manually configure "typescript" instead of "javascript"
languages = this.mapLanguagesToCodeQL(languages);
this.logger.info(
"CodeQLService",
`Detected languages: [${languages.join(", ")}]`
);
const searchPaths = config.get<string[]>("searchPaths", ["src/", "lib/"]);
const results: ScanResult[] = [];
// Process each language
for (let i = 0; i < languages.length; i++) {
const language = languages[i];
const progressBase = 20 + (i / languages.length) * 60;
if (cancellationToken.isCancellationRequested) {
throw new Error("Operation cancelled");
}
// progress.report({
// increment: progressBase,
// message: `Checking ${language} support...`,
// });
// await this.installPack(`codeql/${language}-queries`);
progress.report({
increment: progressBase,
message: `Creating ${language} database...`,
});
// Create database for this language
const databasePath = await this.createCodeQLDatabase(
language,
searchPaths,
repoName,
workspaceFolder,
codeqlDir,
progress,
cancellationToken
);
progress.report({
increment: progressBase + 20,
message: `Analyzing ${language} database...`,
});
// Analyze database
const sarif = await this.analyzeCodeQLDatabase(
databasePath,
repoName,
language,
currentSHA,
codeqlDir,
progress,
cancellationToken
);
progress.report({
increment: progressBase + 35,
message: `Processing ${language} results...`,
});
// Parse SARIF results
const languageResults = this.parseSARIFResults(
sarif,
workspaceFolder,
language
);
results.push(...languageResults);
// Notify UI immediately with updated results
if (this.resultsCallback && languageResults.length > 0) {
this.resultsCallback([...results]); // Send a copy of all results so far
}
}
progress.report({ increment: 95, message: "Finalizing results..." });
return results;
}
private async runRemoteScan(
progress: vscode.Progress<{ increment?: number; message?: string }>,
cancellationToken: vscode.CancellationToken
): Promise<ScanResult[]> {
// Original GitHub Actions implementation
progress.report({
increment: 10,
message: "Getting repository information...",
});
const repoInfo = await this.githubService.getRepositoryInfo();
if (cancellationToken.isCancellationRequested) {
throw new Error("Operation cancelled");
}
progress.report({ increment: 30, message: "Triggering CodeQL scan..." });
await this.githubService.triggerCodeQLScan(repoInfo.owner, repoInfo.repo);
progress.report({ increment: 60, message: "Waiting for scan results..." });
// Wait a bit and then check for results
await this.waitForAnalysis(repoInfo, progress, cancellationToken);
progress.report({ increment: 90, message: "Fetching alerts..." });
const alerts = await this.githubService.getCodeQLAlerts(
repoInfo.owner,
repoInfo.repo
);
const results = this.convertAlertsToResults(alerts);
// Notify UI immediately when remote results are available
if (this.resultsCallback && results.length > 0) {
this.resultsCallback(results);
}
return results;
}
public async initRepository(
progress: vscode.Progress<{ increment?: number; message?: string }>,
cancellationToken: vscode.CancellationToken
): Promise<void> {
progress.report({
increment: 10,
message: "Getting repository information...",
});
const repoInfo = await this.githubService.getRepositoryInfo();
if (cancellationToken.isCancellationRequested) {
throw new Error("Operation cancelled");
}
progress.report({
increment: 30,
message: "Creating CodeQL configuration...",
});
await this.createCodeQLConfig(repoInfo);
progress.report({ increment: 60, message: "Creating GitHub workflow..." });
await this.createGitHubWorkflow(repoInfo);
progress.report({ increment: 90, message: "Finalizing setup..." });
}
public async getVersion(): Promise<string> {
try {
const config = vscode.workspace.getConfiguration("codeql-scanner");
const codeqlPath = config.get<string>("codeqlPath", "codeql");
const { stdout } = await execAsync(
`${codeqlPath} version -v --log-to-stderr --format=json`
);
const versionInfo = JSON.parse(stdout);
return versionInfo.version || "unknown";
} catch (error) {
this.logger.error("CodeQLService", "Error getting CodeQL version", error);
throw new Error(
"Failed to get CodeQL version. Please check your configuration."
);
}
}
/**
* List of supported languages by CodeQL CLI.
*
* Creates a map of supported languages with aliases.
*
* @returns
*/
public async getSupportedLanguages(): Promise<{ [key: string]: string[] }> {
this.logger.info(
"CodeQLService",
"Getting supported languages from CodeQL CLI"
);
try {
const config = vscode.workspace.getConfiguration("codeql-scanner");
const codeqlPath = config.get<string>("codeqlPath", "codeql");
const command = `${codeqlPath} resolve languages --format=betterjson`;
this.logger.info(
"CodeQLService",
`Running command to get supported languages: ${command}`
);
const { stdout } = await execAsync(command, {
timeout: 30000, // 30 seconds timeout
});
this.logger.info(
"CodeQLService",
"Successfully retrieved supported languages"
);
const languagesInfo = JSON.parse(stdout);
//
const extractors: { [key: string]: any } = languagesInfo.extractors || {};
this.logger.info(
"CodeQLService",
`Found ${Object.keys(extractors).length} language extractors`
);
for (const [lang, extractor] of Object.entries(extractors)) {
var name = lang.toLowerCase();
if (!this.languages[name]) {
this.languages[name] = [];
}
}
this.logger.info(
"CodeQLService",
`Supported languages: ${this.getLanguages().join(", ")}`
);
return this.languages;
} catch (error) {
this.logger.error(
"CodeQLService",
"Error getting supported languages",
error
);
throw new Error(
"Failed to get supported languages. Please check your configuration."
);
}
}
public getLanguages(): string[] {
// return Object.keys(this.languages).map((key) => this.languages[key]);
return Object.keys(this.languages);
}
/**
* Return a unique list of languages supported by CodeQL CLI
* @param languages Languages from GitHub repository
* @returns
*/
public mapLanguagesToCodeQL(languages: string[]): string[] {
const results: string[] = [];
const addedLanguages = new Set<string>();
for (const language of languages) {
const lang = language.toLowerCase();
// Direct match with CodeQL language
if (this.languages[lang] && !addedLanguages.has(lang)) {
results.push(lang);
addedLanguages.add(lang);
continue;
}
// Check if it's an alias for a CodeQL language
for (const [codeqlLang, aliases] of Object.entries(this.languages)) {
if (aliases.includes(lang) && !addedLanguages.has(codeqlLang)) {
results.push(codeqlLang);
addedLanguages.add(codeqlLang);
break;
}
}
}
return [...new Set(results)]; // Remove any duplicates just in case
}
public async getPacks(): Promise<string[]> {
this.logger.logServiceCall("CodeQLService", "getPacks", "started");
var packs: string[] = [];
try {
const config = vscode.workspace.getConfiguration("codeql-scanner");
const codeqlPath = config.get<string>("codeqlPath", "codeql");
this.logger.info(
"CodeQLService",
`Getting installed CodeQL packs using CLI at ${codeqlPath}`
);
const cmd = `${codeqlPath} resolve packs --format=json`;
this.logger.info(
"CodeQLService",
`Running command to get installed CodeQL packs: ${cmd}`
);
const { stdout } = await execAsync(cmd);
this.logger.info(
"CodeQLService",
"Successfully retrieved installed CodeQL packs"
);
const packsInfo = JSON.parse(stdout);
// Reverse steps
const steps = packsInfo.steps || [];
for (const step of steps.reverse()) {
for (const scans of step.scans || []) {
const found = scans.found || {};
// For each key, add the pack name to the list
for (const packName of Object.keys(found)) {
if (!packs.includes(packName)) {
packs.push(packName);
this.logger.debug(
"CodeQLService",
`Found CodeQL pack: ${packName}`
);
}
}
}
}
} catch (error) {
this.logger.error("CodeQLService", "Error getting CodeQL packs", error);
throw new Error(
"Failed to get CodeQL packs. Please check your configuration."
);
}
this.logger.info(
"CodeQLService",
`Found ${packs.length} installed CodeQL packs: ${packs.join(", ")}`
);
this.logger.logServiceCall("CodeQLService", "getPacks", "completed", {
packs: packs,
});
return packs;
}
public async runAnalysis(
progress: vscode.Progress<{ increment?: number; message?: string }>,
cancellationToken: vscode.CancellationToken
): Promise<void> {
progress.report({
increment: 10,
message: "Getting repository information...",
});
const repoInfo = await this.githubService.getRepositoryInfo();
if (cancellationToken.isCancellationRequested) {
throw new Error("Operation cancelled");
}
progress.report({ increment: 30, message: "Getting analysis history..." });
const analyses = await this.githubService.getCodeQLAnalyses(
repoInfo.owner,
repoInfo.repo
);
progress.report({
increment: 70,
message: "Processing analysis results...",
});
// Show analysis results in a new document
await this.showAnalysisResults(analyses);
}
private async waitForAnalysis(
repoInfo: RepositoryInfo,
progress: vscode.Progress<{ increment?: number; message?: string }>,
cancellationToken: vscode.CancellationToken,
maxWaitTime = 300000 // 5 minutes
): Promise<void> {
const startTime = Date.now();
while (Date.now() - startTime < maxWaitTime) {
if (cancellationToken.isCancellationRequested) {
throw new Error("Operation cancelled");
}
try {
const analyses = await this.githubService.getCodeQLAnalyses(
repoInfo.owner,
repoInfo.repo
);
const recentAnalysis = analyses[0];
if (recentAnalysis && recentAnalysis.status === "completed") {
return;
}
progress.report({
message: `Waiting for analysis (${
recentAnalysis?.status || "pending"
})...`,
});
} catch (error) {
// Continue waiting even if there's an error
this.logger.error(
"CodeQLService",
"Error checking analysis status",
error
);
}
// Wait 10 seconds before checking again
await new Promise((resolve) => setTimeout(resolve, 10000));
}
throw new Error("Analysis timeout - check GitHub Actions for status");
}
private convertAlertsToResults(alerts: any[]): ScanResult[] {
return alerts.map((alert) => {
// Extract flow steps if available from GitHub API
const flowSteps: FlowStep[] = [];
if (alert.instances && alert.instances.length > 0) {
const instance = alert.instances[0];
if (instance.flow && instance.flow.locations) {
instance.flow.locations.forEach(
(flowLocation: any, index: number) => {
if (flowLocation.location) {
flowSteps.push({
file: flowLocation.location.path,
startLine: flowLocation.location.start_line,
startColumn: flowLocation.location.start_column,
endLine: flowLocation.location.end_line,
endColumn: flowLocation.location.end_column,
message: flowLocation.message,
stepIndex: index,
});
}
}
);
}
}
return {
ruleId: alert.rule.id,
severity: alert.rule.severity,
message: alert.message.text,
location: {
file: alert.most_recent_instance.location.path,
startLine: alert.most_recent_instance.location.start_line,
startColumn: alert.most_recent_instance.location.start_column,
endLine: alert.most_recent_instance.location.end_line,
endColumn: alert.most_recent_instance.location.end_column,
},
flowSteps: flowSteps.length > 0 ? flowSteps : undefined,
};
});
}
private async createCodeQLConfig(repoInfo: RepositoryInfo): Promise<void> {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders || workspaceFolders.length === 0) {
throw new Error("No workspace folder found");
}
const config = vscode.workspace.getConfiguration("codeql-scanner");
const searchPaths = config.get<string[]>("searchPaths", ["src/", "lib/"]);
const suites = config.get<string[]>("suites", ["security-extended"]);
const codeqlConfig = {
name: "CodeQL Configuration",
"disable-default-path-filters": false,
paths: searchPaths,
"paths-ignore": [
"node_modules",
"dist",
"build",
"**/*.test.*",
"**/*.spec.*",
],
queries: suites.map((suite) => ({
uses: suite,
})),
};
const configPath = path.join(
workspaceFolders[0].uri.fsPath,
".github",
"codeql",
"codeql-config.yml"
);
// Create directory if it doesn't exist
const configDir = path.dirname(configPath);
if (!fs.existsSync(configDir)) {
fs.mkdirSync(configDir, { recursive: true });
}
// Write config file
const yamlContent = yaml.dump(codeqlConfig, { indent: 2 });
fs.writeFileSync(configPath, yamlContent);
vscode.window.showInformationMessage(
`CodeQL configuration created at ${configPath}`
);
}
private async createGitHubWorkflow(repoInfo: RepositoryInfo): Promise<void> {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders || workspaceFolders.length === 0) {
throw new Error("No workspace folder found");
}
const config = vscode.workspace.getConfiguration("codeql-scanner");
const languages = config.get<string[]>("languages", repoInfo.languages);
const workflow = {
name: "CodeQL Analysis",
on: {
push: {
branches: [repoInfo.defaultBranch],
},
pull_request: {
branches: [repoInfo.defaultBranch],
},
workflow_dispatch: {
inputs: {
languages: {
description: "Languages to analyze",
required: false,
default: languages.join(","),
},
},
},
},
jobs: {
analyze: {
name: "Analyze",
"runs-on": "ubuntu-latest",
permissions: {
actions: "read",
contents: "read",
"security-events": "write",
},
strategy: {
fail_fast: false,
matrix: {
language: languages,
},
},
steps: [
{
name: "Checkout repository",
uses: "actions/checkout@v3",
},
{
name: "Initialize CodeQL",
uses: "github/codeql-action/init@v2",
with: {
languages: "${{ matrix.language }}",
"config-file": "./.github/codeql/codeql-config.yml",
},
},
{
name: "Autobuild",
uses: "github/codeql-action/autobuild@v2",
},
{
name: "Perform CodeQL Analysis",
uses: "github/codeql-action/analyze@v2",
},
],
},
},
};
const workflowPath = path.join(
workspaceFolders[0].uri.fsPath,
".github",
"workflows",
"codeql-analysis.yml"
);
// Create directory if it doesn't exist
const workflowDir = path.dirname(workflowPath);
if (!fs.existsSync(workflowDir)) {
fs.mkdirSync(workflowDir, { recursive: true });
}
// Write workflow file
const yamlContent = yaml.dump(workflow, { indent: 2 });
fs.writeFileSync(workflowPath, yamlContent);
vscode.window.showInformationMessage(
`GitHub workflow created at ${workflowPath}`
);
}
private async showAnalysisResults(analyses: any[]): Promise<void> {
const document = await vscode.workspace.openTextDocument({
content: this.formatAnalysisResults(analyses),
language: "markdown",
});
await vscode.window.showTextDocument(document);
}
private formatAnalysisResults(analyses: any[]): string {
let content = "# CodeQL Analysis Results\n\n";
if (analyses.length === 0) {
content += "No analyses found.\n";
return content;
}
analyses.forEach((analysis, index) => {
content += `## Analysis ${index + 1}\n\n`;
content += `- **ID**: ${analysis.id}\n`;
content += `- **Reference**: ${analysis.ref}\n`;
content += `- **Status**: ${analysis.status}\n`;
content += `- **Created**: ${new Date(
analysis.createdAt
).toLocaleString()}\n`;
if (analysis.completedAt) {
content += `- **Completed**: ${new Date(
analysis.completedAt
).toLocaleString()}\n`;
}
if (analysis.resultsCount !== undefined) {
content += `- **Results**: ${analysis.resultsCount} alerts\n`;
}
content += `- **URL**: [View on GitHub](${analysis.url})\n\n`;
});
return content;
}
// Local CodeQL CLI methods
private async checkCodeQLCLI(): Promise<void> {
const config = vscode.workspace.getConfiguration("codeql-scanner");
const codeqlPath = config.get<string>("codeqlPath", "codeql");
try {
const version = await this.getVersion();
this.logger.info("CodeQLService", `CodeQL CLI version: ${version}`);
} catch (error) {
this.logger.error(
"CodeQLService",
`CodeQL CLI not found at '${codeqlPath}'`,
error
);
throw new Error(
`CodeQL CLI not found at '${codeqlPath}'. Please install CodeQL CLI and configure the path in settings.`
);
}
}
private getCodeQLDirectory(): string {
const homeDir = os.homedir();
const codeqlDir = path.join(homeDir, ".codeql");
// Create directories if they don't exist
const dbDir = path.join(codeqlDir, "databases");
const resultsDir = path.join(codeqlDir, "results");
if (!fs.existsSync(dbDir)) {
fs.mkdirSync(dbDir, { recursive: true });
}
if (!fs.existsSync(resultsDir)) {
fs.mkdirSync(resultsDir, { recursive: true });
}
return codeqlDir;
}
private getCodeQLDatabase(language: string): string {
const codeqlDir = this.getCodeQLDirectory();
const dbDir = path.join(
codeqlDir,
"databases",
this.getRepositoryName(),
language
);
if (!fs.existsSync(dbDir)) {
fs.mkdirSync(dbDir, { recursive: true });
}
return dbDir;
}
private getCodeQLConfig(): string {
const codeqlDir = this.getCodeQLDirectory();
const configPath = path.join(
codeqlDir,
this.getRepositoryName(),
"config.yml"
);
return configPath;
}
private getCodeQLResults(): string {
const codeqlDir = this.getCodeQLDirectory();
const resultsDir = path.join(codeqlDir, "results");
if (!fs.existsSync(resultsDir)) {
fs.mkdirSync(resultsDir, { recursive: true });
}
return resultsDir;
}
private getWorkspaceFolder(): string {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders || workspaceFolders.length === 0) {
throw new Error("No workspace folder found");
}
return workspaceFolders[0].uri.fsPath;
}
private getRepositoryName(): string {
const workspaceFolder = this.getWorkspaceFolder();
return path.basename(workspaceFolder);
}
private async getCurrentGitSHA(): Promise<string> {
try {
const workspaceFolder = this.getWorkspaceFolder();
const { stdout } = await execAsync("git rev-parse HEAD", {
cwd: workspaceFolder,
});
return stdout.trim().substring(0, 8); // Short SHA
} catch (error) {
return "unknown";
}
}
private async installPack(name: string): Promise<void> {
const config = vscode.workspace.getConfiguration("codeql-scanner");
const codeqlPath = config.get<string>("codeqlPath", "codeql");
this.logger.info(
"CodeQLService",
`Installing CodeQL pack: ${name} using CLI at ${codeqlPath}`
);
try {
const command = `${codeqlPath} pack download ${name}`;
this.logger.info("CodeQLService", `Installing pack: ${name}`);
const { stdout, stderr } = await execAsync(command, {
timeout: 30000, // 30 seconds timeout
});
this.logger.logCodeQLCLI(command, "completed", stdout);
if (stderr) {
this.logger.warn("CodeQLService", "Pack installation warnings", stderr);
}
} catch (error) {
this.logger.error(
"CodeQLService",
`Failed to install pack ${name}`,
error
);
throw new Error(`Failed to install pack ${name}: ${error}`);
}
}
private async createCodeQLDatabase(
language: string,
searchPaths: string[],
repoName: string,
workspaceFolder: string,
codeqlDir: string,
progress: vscode.Progress<{ increment?: number; message?: string }>,
cancellationToken: vscode.CancellationToken
): Promise<string> {
const config = vscode.workspace.getConfiguration("codeql-scanner");
const codeqlPath = config.get<string>("codeqlPath", "codeql");
const databasePath = this.getCodeQLDatabase(language);
let source = this.getWorkspaceFolder();
var command = `${codeqlPath} database create --overwrite -j 0 --language ${language} -s "${source}"`;
// Add BMN
if (language === "cpp" || language === "csharp" || language === "java") {
command += ` --build-mode=none`;
}
command += ` "${databasePath}"`;
this.logger.info("CodeQLService", `CodeQL Create Command: ${command}`);
try {
progress.report({ message: `Creating ${language} database...` });
const { stdout, stderr } = await execAsync(command, {
cwd: workspaceFolder,
timeout: 300000, // 5 minutes timeout
});
this.logger.logCodeQLCLI(command, "completed", stdout);
if (stderr) {
this.logger.warn("CodeQLService", "Database creation warnings", stderr);
}
return databasePath;
} catch (error) {
throw new Error(
`Failed to create CodeQL database for ${language}: ${error}`
);
}
}
private async analyzeCodeQLDatabase(
databasePath: string,
repoName: string,
language: string,
sha: string,
codeqlDir: string,
progress: vscode.Progress<{ increment?: number; message?: string }>,
cancellationToken: vscode.CancellationToken
): Promise<any> {
const config = vscode.workspace.getConfiguration("codeql-scanner");
const codeqlPath = config.get<string>("codeqlPath", "codeql");
const suites = config.get<Array<string>>("suites", ["default"]);
const threatModel = config
.get<string>("threatModel", "Remote")
.toLowerCase();
const outputPath = path.join(
codeqlDir,
"results",
`${repoName}-${language}-${sha}.sarif`
);
// Build the query suite argument
// var queries = `codeql/${language}-queries`;
const queries = await this.findQueryPack(language);
this.logger.info(
"CodeQLService",
`Using query pack: ${queries} for language: ${language}`
);
if (!queries) {
throw new Error(
`No query pack found for language: ${language}. Please ensure the pack is installed.`
);
}
const suite = suites[0];
this.logger.info("CodeQLService", `Using suite: ${suite} for analysis`);
if (
suite === "code-scanning" ||
suite === "security-extended" ||
suite === "security-and-quality"
) {
queries += `:codeql-suites/${language}-code-scanning.qls`;
}
var command = `${codeqlPath} database analyze -j 0 --output "${outputPath}" --format sarif-latest`;
if (threatModel !== "remote") {
command += ` --threat-model ${threatModel}`;
}
command += ` "${databasePath}" "${queries}"`;