Skip to content

Skip validating SARIF produced by CodeQL #2894

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 14, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Skip validating SARIF produced by CodeQL
  • Loading branch information
henrymercer committed May 14, 2025
commit 2f70a988e76f219f826110e1c12b79733d647084
6 changes: 2 additions & 4 deletions lib/analyze.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/analyze.js.map

Large diffs are not rendered by default.

47 changes: 28 additions & 19 deletions lib/upload-lib.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/upload-lib.js.map

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions lib/upload-lib.test.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/upload-lib.test.js.map

Large diffs are not rendered by default.

9 changes: 2 additions & 7 deletions src/analyze.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import { getRepositoryNwoFromEnv } from "./repository";
import { DatabaseCreationTimings, EventReport } from "./status-report";
import { ToolsFeature } from "./tools-features";
import { endTracingForCluster } from "./tracer-config";
import { validateSarifFileSchema } from "./upload-lib";
import * as util from "./util";
import { BuildMode } from "./util";

Expand Down Expand Up @@ -630,7 +629,7 @@ export async function runQueries(
logger.info(analysisSummary);

if (await features.getValue(Feature.QaTelemetryEnabled)) {
const perQueryAlertCounts = getPerQueryAlertCounts(sarifFile, logger);
const perQueryAlertCounts = getPerQueryAlertCounts(sarifFile);

const perQueryAlertCountEventReport: EventReport = {
event: "codeql database interpret-results",
Expand Down Expand Up @@ -682,11 +681,7 @@ export async function runQueries(
}

/** Get an object with all queries and their counts parsed from a SARIF file path. */
function getPerQueryAlertCounts(
sarifPath: string,
log: Logger,
): Record<string, number> {
validateSarifFileSchema(sarifPath, log);
function getPerQueryAlertCounts(sarifPath: string): Record<string, number> {
const sarifObject = JSON.parse(
fs.readFileSync(sarifPath, "utf8"),
) as util.SarifFile;
Expand Down
18 changes: 15 additions & 3 deletions src/upload-lib.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,22 @@ test.beforeEach(() => {
test("validateSarifFileSchema - valid", (t) => {
const inputFile = `${__dirname}/../src/testdata/valid-sarif.sarif`;
t.notThrows(() =>
uploadLib.validateSarifFileSchema(inputFile, getRunnerLogger(true)),
uploadLib.validateSarifFileSchema(
uploadLib.readSarifFile(inputFile),
inputFile,
getRunnerLogger(true),
),
);
});

test("validateSarifFileSchema - invalid", (t) => {
const inputFile = `${__dirname}/../src/testdata/invalid-sarif.sarif`;
t.throws(() =>
uploadLib.validateSarifFileSchema(inputFile, getRunnerLogger(true)),
uploadLib.validateSarifFileSchema(
uploadLib.readSarifFile(inputFile),
inputFile,
getRunnerLogger(true),
),
);
});

Expand Down Expand Up @@ -314,7 +322,11 @@ test("accept results with invalid artifactLocation.uri value", (t) => {
} as Logger;

const sarifFile = `${__dirname}/../src/testdata/with-invalid-uri.sarif`;
uploadLib.validateSarifFileSchema(sarifFile, mockLogger);
uploadLib.validateSarifFileSchema(
uploadLib.readSarifFile(sarifFile),
sarifFile,
mockLogger,
);

t.deepEqual(loggedMessages.length, 3);
t.deepEqual(
Expand Down
68 changes: 44 additions & 24 deletions src/upload-lib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,18 +434,35 @@ function countResultsInSarif(sarif: string): number {
return numResults;
}

// Validates that the given file path refers to a valid SARIF file.
// Throws an error if the file is invalid.
export function validateSarifFileSchema(sarifFilePath: string, logger: Logger) {
logger.info(`Validating ${sarifFilePath}`);
let sarif;
export function readSarifFile(sarifFilePath: string): SarifFile {
try {
sarif = JSON.parse(fs.readFileSync(sarifFilePath, "utf8")) as SarifFile;
return JSON.parse(fs.readFileSync(sarifFilePath, "utf8")) as SarifFile;
} catch (e) {
throw new InvalidSarifUploadError(
`Invalid SARIF. JSON syntax error: ${getErrorMessage(e)}`,
);
}
}

// Validates that the given file path refers to a valid SARIF file.
// Throws an error if the file is invalid.
export function validateSarifFileSchema(
sarif: SarifFile,
sarifFilePath: string,
logger: Logger,
) {
if (
areAllRunsProducedByCodeQL([sarif]) &&
// We want to validate CodeQL SARIF in testing environments.
!util.getTestingEnvironment()
) {
logger.debug(
`Skipping SARIF schema validation for ${sarifFilePath} as all runs are produced by CodeQL.`,
);
return;
}

logger.info(`Validating ${sarifFilePath}`);
// eslint-disable-next-line @typescript-eslint/no-require-imports
const schema = require("../src/sarif-schema-2.1.0.json") as jsonschema.Schema;

Expand Down Expand Up @@ -551,41 +568,44 @@ export function buildPayload(
}

/**
* Uploads a single SARIF file or a directory of SARIF files depending on what `sarifPath` refers
* Uploads a single SARIF file or a directory of SARIF files depending on what `inputSarifPath` refers
* to.
*/
export async function uploadFiles(
sarifPath: string,
inputSarifPath: string,
checkoutPath: string,
category: string | undefined,
features: FeatureEnablement,
logger: Logger,
): Promise<UploadResult> {
const sarifFiles = getSarifFilePaths(sarifPath);
const sarifPaths = getSarifFilePaths(inputSarifPath);

logger.startGroup("Uploading results");
logger.info(`Processing sarif files: ${JSON.stringify(sarifFiles)}`);
logger.info(`Processing sarif files: ${JSON.stringify(sarifPaths)}`);

const gitHubVersion = await getGitHubVersion();

try {
let sarif: SarifFile;

if (sarifPaths.length > 1) {
// Validate that the files we were asked to upload are all valid SARIF files
for (const file of sarifFiles) {
validateSarifFileSchema(file, logger);
}
} catch (e) {
if (e instanceof SyntaxError) {
throw new InvalidSarifUploadError(e.message);
for (const sarifPath of sarifPaths) {
const parsedSarif = readSarifFile(sarifPath);
validateSarifFileSchema(parsedSarif, sarifPath, logger);
}
throw e;

sarif = await combineSarifFilesUsingCLI(
sarifPaths,
gitHubVersion,
features,
logger,
);
} else {
const sarifPath = sarifPaths[0];
sarif = readSarifFile(sarifPath);
validateSarifFileSchema(sarif, sarifPath, logger);
}

let sarif = await combineSarifFilesUsingCLI(
sarifFiles,
gitHubVersion,
features,
logger,
);
sarif = filterAlertsByDiffRange(logger, sarif);
sarif = await fingerprints.addFingerprints(sarif, checkoutPath, logger);

Expand Down
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy