-
Notifications
You must be signed in to change notification settings - Fork 329
/
codeql.ts
1407 lines (1338 loc) · 45 KB
/
codeql.ts
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 fs from "fs";
import * as path from "path";
import * as core from "@actions/core";
import * as toolrunner from "@actions/exec/lib/toolrunner";
import * as yaml from "js-yaml";
import { getOptionalInput, isAnalyzingDefaultBranch } from "./actions-util";
import * as api from "./api-client";
import type { Config } from "./config-utils";
import { EnvVar } from "./environment";
import {
CODEQL_VERSION_NEW_ANALYSIS_SUMMARY,
CodeQLDefaultVersionInfo,
Feature,
FeatureEnablement,
useCodeScanningConfigInCli,
} from "./feature-flags";
import { isTracedLanguage, Language } from "./languages";
import { Logger } from "./logging";
import * as setupCodeql from "./setup-codeql";
import * as util from "./util";
import { wrapError } from "./util";
type Options = Array<string | number | boolean>;
/**
* Extra command line options for the codeql commands.
*/
interface ExtraOptions {
"*"?: Options;
database?: {
"*"?: Options;
init?: Options;
"trace-command"?: Options;
analyze?: Options;
finalize?: Options;
};
resolve?: {
"*"?: Options;
extractor?: Options;
queries?: Options;
};
}
export class CommandInvocationError extends Error {
constructor(
cmd: string,
args: string[],
public exitCode: number,
public error: string,
public output: string,
) {
const prettyCommand = [cmd, ...args]
.map((x) => (x.includes(" ") ? `'${x}'` : x))
.join(" ");
super(
`Encountered a fatal error while running "${prettyCommand}". ` +
`Exit code was ${exitCode} and error was: ${error.trim()}`,
);
}
}
export interface CodeQL {
/**
* Get the path of the CodeQL executable.
*/
getPath(): string;
/**
* Get a string containing the semver version of the CodeQL executable.
*/
getVersion(): Promise<string>;
/**
* Print version information about CodeQL.
*/
printVersion(): Promise<void>;
/**
* Run 'codeql database init --db-cluster'.
*/
databaseInitCluster(
config: Config,
sourceRoot: string,
processName: string | undefined,
features: FeatureEnablement,
qlconfigFile: string | undefined,
logger: Logger,
): Promise<void>;
/**
* Runs the autobuilder for the given language.
*/
runAutobuild(language: Language): Promise<void>;
/**
* Extract code for a scanned language using 'codeql database trace-command'
* and running the language extractor.
*/
extractScannedLanguage(config: Config, language: Language): Promise<void>;
/**
* Finalize a database using 'codeql database finalize'.
*/
finalizeDatabase(
databasePath: string,
threadsFlag: string,
memoryFlag: string,
): Promise<void>;
/**
* Run 'codeql resolve languages'.
*/
resolveLanguages(): Promise<ResolveLanguagesOutput>;
/**
* Run 'codeql resolve languages' with '--format=betterjson'.
*/
betterResolveLanguages(): Promise<BetterResolveLanguagesOutput>;
/**
* Run 'codeql resolve queries'.
*/
resolveQueries(
queries: string[],
extraSearchPath: string | undefined,
): Promise<ResolveQueriesOutput>;
/**
* Run 'codeql resolve build-environment'
*/
resolveBuildEnvironment(
workingDir: string | undefined,
language: Language,
): Promise<ResolveBuildEnvironmentOutput>;
/**
* Run 'codeql pack download'.
*/
packDownload(
packs: string[],
qlconfigFile: string | undefined,
): Promise<PackDownloadOutput>;
/**
* Run 'codeql database cleanup'.
*/
databaseCleanup(databasePath: string, cleanupLevel: string): Promise<void>;
/**
* Run 'codeql database bundle'.
*/
databaseBundle(
databasePath: string,
outputFilePath: string,
dbName: string,
): Promise<void>;
/**
* Run 'codeql database run-queries'.
*
* @param optimizeForLastQueryRun Whether to apply additional optimization for
* the last database query run in the action.
* It is always safe to set it to false.
* It should be set to true only for the very
* last databaseRunQueries() call.
*/
databaseRunQueries(
databasePath: string,
extraSearchPath: string | undefined,
querySuitePath: string | undefined,
flags: string[],
optimizeForLastQueryRun: boolean,
features: FeatureEnablement,
): Promise<void>;
/**
* Run 'codeql database interpret-results'.
*/
databaseInterpretResults(
databasePath: string,
querySuitePaths: string[] | undefined,
sarifFile: string,
addSnippetsFlag: string,
threadsFlag: string,
verbosityFlag: string | undefined,
automationDetailsId: string | undefined,
config: Config,
features: FeatureEnablement,
logger: Logger,
): Promise<string>;
/**
* Run 'codeql database print-baseline'.
*/
databasePrintBaseline(databasePath: string): Promise<string>;
/**
* Run 'codeql database export-diagnostics'
*
* Note that the "--sarif-include-diagnostics" option is always used, as the command should
* only be run if the ExportDiagnosticsEnabled feature flag is on.
*/
databaseExportDiagnostics(
databasePath: string,
sarifFile: string,
automationDetailsId: string | undefined,
tempDir: string,
logger: Logger,
): Promise<void>;
/**
* Run 'codeql diagnostics export'.
*/
diagnosticsExport(
sarifFile: string,
automationDetailsId: string | undefined,
config: Config,
): Promise<void>;
/** Get the location of an extractor for the specified language. */
resolveExtractor(language: Language): Promise<string>;
}
export interface ResolveLanguagesOutput {
[language: string]: [string];
}
export interface BetterResolveLanguagesOutput {
extractors: {
[language: string]: [
{
extractor_root: string;
extractor_options?: any;
},
];
};
}
export interface ResolveQueriesOutput {
byLanguage: {
[language: string]: {
[queryPath: string]: {};
};
};
noDeclaredLanguage: {
[queryPath: string]: {};
};
multipleDeclaredLanguages: {
[queryPath: string]: {};
};
}
export interface ResolveBuildEnvironmentOutput {
configuration?: {
[language: string]: {
[key: string]: unknown;
};
};
}
export interface PackDownloadOutput {
packs: PackDownloadItem[];
}
interface PackDownloadItem {
name: string;
version: string;
packDir: string;
installResult: string;
}
/**
* Stores the CodeQL object, and is populated by `setupCodeQL` or `getCodeQL`.
* Can be overridden in tests using `setCodeQL`.
*/
let cachedCodeQL: CodeQL | undefined = undefined;
/**
* The oldest version of CodeQL that the Action will run with. This should be
* at least three minor versions behind the current version and must include the
* CLI versions shipped with each supported version of GHES.
*
* The version flags below can be used to conditionally enable certain features
* on versions newer than this.
*/
const CODEQL_MINIMUM_VERSION = "2.9.4";
/**
* This version will shortly become the oldest version of CodeQL that the Action will run with.
*/
const CODEQL_NEXT_MINIMUM_VERSION = "2.9.4";
/**
* Versions of CodeQL that version-flag certain functionality in the Action.
* For convenience, please keep these in descending order. Once a version
* flag is older than the oldest supported version above, it may be removed.
*/
const CODEQL_VERSION_LUA_TRACER_CONFIG = "2.10.0";
const CODEQL_VERSION_LUA_TRACING_GO_WINDOWS_FIXED = "2.10.4";
export const CODEQL_VERSION_GHES_PACK_DOWNLOAD = "2.10.4";
const CODEQL_VERSION_FILE_BASELINE_INFORMATION = "2.11.3";
/**
* Previous versions had the option already, but were missing the
* --extractor-options-verbosity that we need.
*/
export const CODEQL_VERSION_BETTER_RESOLVE_LANGUAGES = "2.10.3";
/**
* Versions 2.11.1+ of the CodeQL Bundle include a `security-experimental` built-in query suite for
* each language.
*/
export const CODEQL_VERSION_SECURITY_EXPERIMENTAL_SUITE = "2.12.1";
/**
* Versions 2.12.3+ of the CodeQL CLI support exporting configuration information from a code
* scanning config file to SARIF.
*/
export const CODEQL_VERSION_EXPORT_CODE_SCANNING_CONFIG = "2.12.3";
/**
* Versions 2.12.4+ of the CodeQL CLI support the `--qlconfig-file` flag in calls to `database init`.
*/
export const CODEQL_VERSION_INIT_WITH_QLCONFIG = "2.12.4";
/**
* Versions 2.12.4+ of the CodeQL CLI provide a better error message when `database finalize`
* determines that no code has been found.
*/
export const CODEQL_VERSION_BETTER_NO_CODE_ERROR_MESSAGE = "2.12.4";
/**
* Versions 2.13.4+ of the CodeQL CLI support the `resolve build-environment` command.
*/
export const CODEQL_VERSION_RESOLVE_ENVIRONMENT = "2.13.4";
/**
* Set up CodeQL CLI access.
*
* @param toolsInput
* @param apiDetails
* @param tempDir
* @param variant
* @param defaultCliVersion
* @param logger
* @param checkVersion Whether to check that CodeQL CLI meets the minimum
* version requirement. Must be set to true outside tests.
* @returns a { CodeQL, toolsVersion } object.
*/
export async function setupCodeQL(
toolsInput: string | undefined,
apiDetails: api.GitHubApiDetails,
tempDir: string,
variant: util.GitHubVariant,
defaultCliVersion: CodeQLDefaultVersionInfo,
logger: Logger,
checkVersion: boolean,
): Promise<{
codeql: CodeQL;
toolsDownloadDurationMs?: number;
toolsSource: setupCodeql.ToolsSource;
toolsVersion: string;
}> {
try {
const { codeqlFolder, toolsDownloadDurationMs, toolsSource, toolsVersion } =
await setupCodeql.setupCodeQLBundle(
toolsInput,
apiDetails,
tempDir,
variant,
defaultCliVersion,
logger,
);
let codeqlCmd = path.join(codeqlFolder, "codeql", "codeql");
if (process.platform === "win32") {
codeqlCmd += ".exe";
} else if (process.platform !== "linux" && process.platform !== "darwin") {
throw new Error(`Unsupported platform: ${process.platform}`);
}
cachedCodeQL = await getCodeQLForCmd(codeqlCmd, checkVersion);
return {
codeql: cachedCodeQL,
toolsDownloadDurationMs,
toolsSource,
toolsVersion,
};
} catch (e) {
throw new Error(
`Unable to download and extract CodeQL CLI: ${wrapError(e).message}`,
);
}
}
/**
* Use the CodeQL executable located at the given path.
*/
export async function getCodeQL(cmd: string): Promise<CodeQL> {
if (cachedCodeQL === undefined) {
cachedCodeQL = await getCodeQLForCmd(cmd, true);
}
return cachedCodeQL;
}
function resolveFunction<T>(
partialCodeql: Partial<CodeQL>,
methodName: string,
defaultImplementation?: T,
): T {
if (typeof partialCodeql[methodName] !== "function") {
if (defaultImplementation !== undefined) {
return defaultImplementation;
}
const dummyMethod = () => {
throw new Error(`CodeQL ${methodName} method not correctly defined`);
};
return dummyMethod as any;
}
return partialCodeql[methodName];
}
/**
* Set the functionality for CodeQL methods. Only for use in tests.
*
* Accepts a partial object and any undefined methods will be implemented
* to immediately throw an exception indicating which method is missing.
*/
export function setCodeQL(partialCodeql: Partial<CodeQL>): CodeQL {
cachedCodeQL = {
getPath: resolveFunction(partialCodeql, "getPath", () => "/tmp/dummy-path"),
getVersion: resolveFunction(
partialCodeql,
"getVersion",
() => new Promise((resolve) => resolve("1.0.0")),
),
printVersion: resolveFunction(partialCodeql, "printVersion"),
databaseInitCluster: resolveFunction(partialCodeql, "databaseInitCluster"),
runAutobuild: resolveFunction(partialCodeql, "runAutobuild"),
extractScannedLanguage: resolveFunction(
partialCodeql,
"extractScannedLanguage",
),
finalizeDatabase: resolveFunction(partialCodeql, "finalizeDatabase"),
resolveLanguages: resolveFunction(partialCodeql, "resolveLanguages"),
betterResolveLanguages: resolveFunction(
partialCodeql,
"betterResolveLanguages",
),
resolveQueries: resolveFunction(partialCodeql, "resolveQueries"),
resolveBuildEnvironment: resolveFunction(
partialCodeql,
"resolveBuildEnvironment",
),
packDownload: resolveFunction(partialCodeql, "packDownload"),
databaseCleanup: resolveFunction(partialCodeql, "databaseCleanup"),
databaseBundle: resolveFunction(partialCodeql, "databaseBundle"),
databaseRunQueries: resolveFunction(partialCodeql, "databaseRunQueries"),
databaseInterpretResults: resolveFunction(
partialCodeql,
"databaseInterpretResults",
),
databasePrintBaseline: resolveFunction(
partialCodeql,
"databasePrintBaseline",
),
databaseExportDiagnostics: resolveFunction(
partialCodeql,
"databaseExportDiagnostics",
),
diagnosticsExport: resolveFunction(partialCodeql, "diagnosticsExport"),
resolveExtractor: resolveFunction(partialCodeql, "resolveExtractor"),
};
return cachedCodeQL;
}
/**
* Get the cached CodeQL object. Should only be used from tests.
*
* TODO: Work out a good way for tests to get this from the test context
* instead of having to have this method.
*/
export function getCachedCodeQL(): CodeQL {
if (cachedCodeQL === undefined) {
// Should never happen as setCodeQL is called by testing-utils.setupTests
throw new Error("cachedCodeQL undefined");
}
return cachedCodeQL;
}
/**
* Get a real, newly created CodeQL instance for testing. The instance refers to
* a non-existent placeholder codeql command, so tests that use this function
* should also stub the toolrunner.ToolRunner constructor.
*/
export async function getCodeQLForTesting(
cmd = "codeql-for-testing",
): Promise<CodeQL> {
return getCodeQLForCmd(cmd, false);
}
/**
* Return a CodeQL object for CodeQL CLI access.
*
* @param cmd Path to CodeQL CLI
* @param checkVersion Whether to check that CodeQL CLI meets the minimum
* version requirement. Must be set to true outside tests.
* @returns A new CodeQL object
*/
export async function getCodeQLForCmd(
cmd: string,
checkVersion: boolean,
): Promise<CodeQL> {
const codeql: CodeQL = {
getPath() {
return cmd;
},
async getVersion() {
let result = util.getCachedCodeQlVersion();
if (result === undefined) {
result = (await runTool(cmd, ["version", "--format=terse"])).trim();
util.cacheCodeQlVersion(result);
}
return result;
},
async printVersion() {
await runTool(cmd, ["version", "--format=json"]);
},
async databaseInitCluster(
config: Config,
sourceRoot: string,
processName: string | undefined,
features: FeatureEnablement,
qlconfigFile: string | undefined,
logger: Logger,
) {
const extraArgs = config.languages.map(
(language) => `--language=${language}`,
);
if (config.languages.filter((l) => isTracedLanguage(l)).length > 0) {
extraArgs.push("--begin-tracing");
extraArgs.push(...(await getTrapCachingExtractorConfigArgs(config)));
extraArgs.push(`--trace-process-name=${processName}`);
if (
// There's a bug in Lua tracing for Go on Windows in versions earlier than
// `CODEQL_VERSION_LUA_TRACING_GO_WINDOWS_FIXED`, so don't use Lua tracing
// when tracing Go on Windows on these CodeQL versions.
(await util.codeQlVersionAbove(
this,
CODEQL_VERSION_LUA_TRACER_CONFIG,
)) &&
config.languages.includes(Language.go) &&
isTracedLanguage(Language.go) &&
process.platform === "win32" &&
!(await util.codeQlVersionAbove(
this,
CODEQL_VERSION_LUA_TRACING_GO_WINDOWS_FIXED,
))
) {
extraArgs.push("--no-internal-use-lua-tracing");
}
}
// A code scanning config file is only generated if the CliConfigFileEnabled feature flag is enabled.
const codeScanningConfigFile = await generateCodeScanningConfig(
codeql,
config,
features,
logger,
);
// Only pass external repository token if a config file is going to be parsed by the CLI.
let externalRepositoryToken: string | undefined;
if (codeScanningConfigFile) {
externalRepositoryToken = getOptionalInput("external-repository-token");
extraArgs.push(`--codescanning-config=${codeScanningConfigFile}`);
if (externalRepositoryToken) {
extraArgs.push("--external-repository-token-stdin");
}
}
if (
qlconfigFile !== undefined &&
(await util.codeQlVersionAbove(this, CODEQL_VERSION_INIT_WITH_QLCONFIG))
) {
extraArgs.push(`--qlconfig-file=${qlconfigFile}`);
}
await runTool(
cmd,
[
"database",
"init",
"--db-cluster",
config.dbLocation,
`--source-root=${sourceRoot}`,
...extraArgs,
...getExtraOptionsFromEnv(["database", "init"]),
],
{ stdin: externalRepositoryToken },
);
},
async runAutobuild(language: Language) {
const autobuildCmd = path.join(
await this.resolveExtractor(language),
"tools",
process.platform === "win32" ? "autobuild.cmd" : "autobuild.sh",
);
// Update JAVA_TOOL_OPTIONS to contain '-Dhttp.keepAlive=false'
// This is because of an issue with Azure pipelines timing out connections after 4 minutes
// and Maven not properly handling closed connections
// Otherwise long build processes will timeout when pulling down Java packages
// https://developercommunity.visualstudio.com/content/problem/292284/maven-hosted-agent-connection-timeout.html
const javaToolOptions = process.env["JAVA_TOOL_OPTIONS"] || "";
process.env["JAVA_TOOL_OPTIONS"] = [
...javaToolOptions.split(/\s+/),
"-Dhttp.keepAlive=false",
"-Dmaven.wagon.http.pool=false",
].join(" ");
// On macOS, System Integrity Protection (SIP) typically interferes with
// CodeQL build tracing of protected binaries.
// The usual workaround is to prefix `$CODEQL_RUNNER` to build commands:
// `$CODEQL_RUNNER` (not to be confused with the deprecated CodeQL Runner tool)
// points to a simple wrapper binary included with the CLI, and the extra layer of
// process indirection helps the tracer bypass SIP.
// The above SIP workaround is *not* needed here.
// At the `autobuild` step in the Actions workflow, we assume the `init` step
// has successfully run, and will have exported `DYLD_INSERT_LIBRARIES`
// into the environment of subsequent steps, to activate the tracer.
// When `DYLD_INSERT_LIBRARIES` is set in the environment for a step,
// the Actions runtime introduces its own workaround for SIP
// (https://github.com/actions/runner/pull/416).
await runTool(autobuildCmd);
},
async extractScannedLanguage(config: Config, language: Language) {
const databasePath = util.getCodeQLDatabasePath(config, language);
// Set trace command
const ext = process.platform === "win32" ? ".cmd" : ".sh";
const traceCommand = path.resolve(
await this.resolveExtractor(language),
"tools",
`autobuild${ext}`,
);
// Run trace command
await runTool(cmd, [
"database",
"trace-command",
...(await getTrapCachingExtractorConfigArgsForLang(config, language)),
...getExtraOptionsFromEnv(["database", "trace-command"]),
databasePath,
"--",
traceCommand,
]);
},
async finalizeDatabase(
databasePath: string,
threadsFlag: string,
memoryFlag: string,
) {
const args = [
"database",
"finalize",
"--finalize-dataset",
threadsFlag,
memoryFlag,
...getExtraOptionsFromEnv(["database", "finalize"]),
databasePath,
];
try {
await runTool(cmd, args);
} catch (e) {
if (
e instanceof CommandInvocationError &&
!(await util.codeQlVersionAbove(
this,
CODEQL_VERSION_BETTER_NO_CODE_ERROR_MESSAGE,
)) &&
isNoCodeFoundError(e)
) {
throw new util.UserError(
"No code found during the build. Please see: " +
"https://gh.io/troubleshooting-code-scanning/no-source-code-seen-during-build",
);
}
throw e;
}
},
async resolveLanguages() {
const codeqlArgs = [
"resolve",
"languages",
"--format=json",
...getExtraOptionsFromEnv(["resolve", "languages"]),
];
const output = await runTool(cmd, codeqlArgs);
try {
return JSON.parse(output);
} catch (e) {
throw new Error(
`Unexpected output from codeql resolve languages: ${e}`,
);
}
},
async betterResolveLanguages() {
const codeqlArgs = [
"resolve",
"languages",
"--format=betterjson",
"--extractor-options-verbosity=4",
...getExtraOptionsFromEnv(["resolve", "languages"]),
];
const output = await runTool(cmd, codeqlArgs);
try {
return JSON.parse(output);
} catch (e) {
throw new Error(
`Unexpected output from codeql resolve languages with --format=betterjson: ${e}`,
);
}
},
async resolveQueries(
queries: string[],
extraSearchPath: string | undefined,
) {
const codeqlArgs = [
"resolve",
"queries",
...queries,
"--format=bylanguage",
...getExtraOptionsFromEnv(["resolve", "queries"]),
];
if (extraSearchPath !== undefined) {
codeqlArgs.push("--additional-packs", extraSearchPath);
}
const output = await runTool(cmd, codeqlArgs);
try {
return JSON.parse(output);
} catch (e) {
throw new Error(`Unexpected output from codeql resolve queries: ${e}`);
}
},
async resolveBuildEnvironment(
workingDir: string | undefined,
language: Language,
) {
const codeqlArgs = [
"resolve",
"build-environment",
`--language=${language}`,
...getExtraOptionsFromEnv(["resolve", "build-environment"]),
];
if (workingDir !== undefined) {
codeqlArgs.push("--working-dir", workingDir);
}
const output = await runTool(cmd, codeqlArgs);
try {
return JSON.parse(output);
} catch (e) {
throw new Error(
`Unexpected output from codeql resolve build-environment: ${e} in\n${output}`,
);
}
},
async databaseRunQueries(
databasePath: string,
extraSearchPath: string | undefined,
querySuitePath: string | undefined,
flags: string[],
optimizeForLastQueryRun: boolean,
features: FeatureEnablement,
): Promise<void> {
const codeqlArgs = [
"database",
"run-queries",
...flags,
databasePath,
"--min-disk-free=1024", // Try to leave at least 1GB free
"-v",
...getExtraOptionsFromEnv(["database", "run-queries"]),
];
if (
optimizeForLastQueryRun &&
(await util.supportExpectDiscardedCache(this))
) {
codeqlArgs.push("--expect-discarded-cache");
}
if (extraSearchPath !== undefined) {
codeqlArgs.push("--additional-packs", extraSearchPath);
}
if (querySuitePath) {
codeqlArgs.push(querySuitePath);
}
if (
await features.getValue(
Feature.EvaluatorIntraLayerParallelismEnabled,
this,
)
) {
codeqlArgs.push("--intra-layer-parallelism");
}
await runTool(cmd, codeqlArgs);
},
async databaseInterpretResults(
databasePath: string,
querySuitePaths: string[] | undefined,
sarifFile: string,
addSnippetsFlag: string,
threadsFlag: string,
verbosityFlag: string,
automationDetailsId: string | undefined,
config: Config,
features: FeatureEnablement,
logger: Logger,
): Promise<string> {
const shouldExportDiagnostics = await features.getValue(
Feature.ExportDiagnosticsEnabled,
this,
);
// Update this to take into account the CodeQL version when we have a version with the fix.
const shouldWorkaroundInvalidNotifications = shouldExportDiagnostics;
const codeqlOutputFile = shouldWorkaroundInvalidNotifications
? path.join(config.tempDir, "codeql-intermediate-results.sarif")
: sarifFile;
const codeqlArgs = [
"database",
"interpret-results",
threadsFlag,
"--format=sarif-latest",
verbosityFlag,
`--output=${codeqlOutputFile}`,
addSnippetsFlag,
"--print-diagnostics-summary",
"--print-metrics-summary",
"--sarif-add-query-help",
"--sarif-group-rules-by-pack",
...(await getCodeScanningConfigExportArguments(config, this)),
...getExtraOptionsFromEnv(["database", "interpret-results"]),
];
if (automationDetailsId !== undefined) {
codeqlArgs.push("--sarif-category", automationDetailsId);
}
if (
await util.codeQlVersionAbove(
this,
CODEQL_VERSION_FILE_BASELINE_INFORMATION,
)
) {
codeqlArgs.push("--sarif-add-baseline-file-info");
}
if (shouldExportDiagnostics) {
codeqlArgs.push("--sarif-include-diagnostics");
} else if (await util.codeQlVersionAbove(this, "2.12.4")) {
codeqlArgs.push("--no-sarif-include-diagnostics");
}
if (await features.getValue(Feature.NewAnalysisSummaryEnabled, this)) {
codeqlArgs.push("--new-analysis-summary");
} else if (
await util.codeQlVersionAbove(this, CODEQL_VERSION_NEW_ANALYSIS_SUMMARY)
) {
codeqlArgs.push("--no-new-analysis-summary");
}
codeqlArgs.push(databasePath);
if (querySuitePaths) {
codeqlArgs.push(...querySuitePaths);
}
// Capture the stdout, which contains the analysis summary. Don't stream it to the Actions
// logs to avoid printing it twice.
const analysisSummary = await runTool(cmd, codeqlArgs, {
noStreamStdout: true,
});
if (shouldWorkaroundInvalidNotifications) {
util.fixInvalidNotificationsInFile(codeqlOutputFile, sarifFile, logger);
}
return analysisSummary;
},
async databasePrintBaseline(databasePath: string): Promise<string> {
const codeqlArgs = [
"database",
"print-baseline",
...getExtraOptionsFromEnv(["database", "print-baseline"]),
databasePath,
];
return await runTool(cmd, codeqlArgs);
},
/**
* Download specified packs into the package cache. If the specified
* package and version already exists (e.g., from a previous analysis run),
* then it is not downloaded again (unless the extra option `--force` is
* specified).
*
* If no version is specified, then the latest version is
* downloaded. The check to determine what the latest version is is done
* each time this package is requested.
*
* Optionally, a `qlconfigFile` is included. If used, then this file
* is used to determine which registry each pack is downloaded from.
*/
async packDownload(
packs: string[],
qlconfigFile: string | undefined,
): Promise<PackDownloadOutput> {
const qlconfigArg = qlconfigFile
? [`--qlconfig-file=${qlconfigFile}`]
: ([] as string[]);
const codeqlArgs = [
"pack",
"download",
...qlconfigArg,
"--format=json",
"--resolve-query-specs",
...getExtraOptionsFromEnv(["pack", "download"]),
...packs,
];
const output = await runTool(cmd, codeqlArgs);
try {
const parsedOutput: PackDownloadOutput = JSON.parse(output);
if (
Array.isArray(parsedOutput.packs) &&
// TODO PackDownloadOutput will not include the version if it is not specified
// in the input. The version is always the latest version available.
// It should be added to the output, but this requires a CLI change
parsedOutput.packs.every((p) => p.name /* && p.version */)
) {
return parsedOutput;
} else {
throw new Error("Unexpected output from pack download");
}
} catch (e) {
throw new Error(
`Attempted to download specified packs but got an error:\n${output}\n${e}`,
);
}
},
async databaseCleanup(
databasePath: string,
cleanupLevel: string,
): Promise<void> {
const codeqlArgs = [
"database",
"cleanup",
databasePath,
`--mode=${cleanupLevel}`,
...getExtraOptionsFromEnv(["database", "cleanup"]),
];
await runTool(cmd, codeqlArgs);
},
async databaseBundle(
databasePath: string,
outputFilePath: string,
databaseName: string,
): Promise<void> {
const args = [
"database",
"bundle",
databasePath,
`--output=${outputFilePath}`,
`--name=${databaseName}`,
...getExtraOptionsFromEnv(["database", "bundle"]),
];
await new toolrunner.ToolRunner(cmd, args).exec();
},
async databaseExportDiagnostics(
databasePath: string,
sarifFile: string,
automationDetailsId: string | undefined,
tempDir: string,
logger: Logger,
): Promise<void> {
// Update this to take into account the CodeQL version when we have a version with the fix.
const shouldWorkaroundInvalidNotifications = true;
const codeqlOutputFile = shouldWorkaroundInvalidNotifications
? path.join(tempDir, "codeql-intermediate-results.sarif")
: sarifFile;
const args = [
"database",
"export-diagnostics",
`${databasePath}`,
"--db-cluster", // Database is always a cluster for CodeQL versions that support diagnostics.
"--format=sarif-latest",
`--output=${codeqlOutputFile}`,
"--sarif-include-diagnostics", // ExportDiagnosticsEnabled is always true if this command is run.
"-vvv",
...getExtraOptionsFromEnv(["diagnostics", "export"]),
];
if (automationDetailsId !== undefined) {
args.push("--sarif-category", automationDetailsId);
}
await new toolrunner.ToolRunner(cmd, args).exec();
if (shouldWorkaroundInvalidNotifications) {
// Fix invalid notifications in the SARIF file output by CodeQL.
util.fixInvalidNotificationsInFile(codeqlOutputFile, sarifFile, logger);
}
},
async diagnosticsExport(
sarifFile: string,
automationDetailsId: string | undefined,
config: Config,
): Promise<void> {
const args = [
"diagnostics",
"export",
"--format=sarif-latest",
`--output=${sarifFile}`,