SARIF Results Format
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 10 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Lesson: Mastering the SARIF Results Format for CodeQL
Introduction: Why Standardizing Security Data Matters
In the world of software development and security, we often find ourselves dealing with a fragmented landscape of tools. Every static analysis security testing (SAST) tool, linter, and vulnerability scanner tends to output its findings in a proprietary format. When you are trying to build an automated pipeline that pulls data from CodeQL, sends alerts to a ticketing system, and displays trends in a dashboard, this lack of uniformity becomes a significant bottleneck. You end up writing custom "glue code" for every single tool you integrate.
This is where the Static Analysis Results Interchange Format (SARIF) comes into play. SARIF is an industry-standard JSON-based format designed to allow analysis tools to communicate their results in a consistent, machine-readable way. For CodeQL users, SARIF is the bridge between the raw power of semantic code analysis and the rest of your security ecosystem. Understanding SARIF is not just about reading JSON files; it is about mastering the data structure that allows your security team to automate remediation, track technical debt, and provide developers with actionable insights directly within their existing workflows.
By the end of this lesson, you will understand the architecture of a SARIF file, how to interpret CodeQL’s output through a SARIF lens, and how to manipulate these files to fit your specific organizational requirements. Whether you are building a custom vulnerability dashboard or simply trying to filter out noise from your CI/CD pipeline, the knowledge contained here will serve as your foundation.
Not read yet
The Anatomy of a SARIF File
At its core, a SARIF file is a structured JSON object. While a full SARIF specification is hundreds of pages long, CodeQL produces a specific subset of this format that is highly optimized for security findings. To understand how to work with these files, we must break down the hierarchy of the SARIF schema.
The Top-Level Structure
Every SARIF file begins with a runs array. A "run" represents a single execution of an analysis tool. Within each run, you will find information about the tool itself, the target files analyzed, and the actual findings (called "results").
version: The version of the SARIF schema being used (typically 2.1.0).runs: An array containing the actual analysis data.tool: Metadata about the tool, including the name, version, and rules definitions.results: The heart of the document, containing the actual security alerts found by CodeQL.
The results Array
The results property is where the most critical data resides. Each object within this array represents a single security issue. Key fields include:
ruleId: The identifier for the specific CodeQL query that triggered the alert (e.g.,cpp/sql-injection).message: A human-readable description of the finding, often including placeholders for specific code locations.locations: A physical reference to the file path, line number, and column where the issue exists.level: The severity of the finding, such aserror,warning, ornote.
Callout: SARIF vs. Raw JSON It is important to distinguish between CodeQL’s native database format and the SARIF output. The CodeQL database is a complex relational store optimized for high-performance querying. SARIF, by contrast, is a flat, serialized representation of the findings generated from that database. You cannot query a SARIF file with QL; you can only query the database. However, you can filter, parse, and transform the SARIF file using standard data processing tools like
jq, Python, or JavaScript.
Not read yet
Generating SARIF from CodeQL
Before we can manipulate SARIF data, we need to generate it correctly. When running CodeQL via the Command Line Interface (CLI), the output format is controlled by the --format flag.
The Standard Workflow
To generate a SARIF file from a CodeQL database, you use the codeql database analyze command. Here is the standard invocation:
codeql database analyze <database-path> <query-suite> \
--format=sarif-latest \
--output=results.sarif
Understanding the Flags
<database-path>: The path to your compiled CodeQL database.<query-suite>: The collection of queries you want to run (e.g.,javascript-security-extended.qls).--format=sarif-latest: This ensures the CLI uses the most recent version of the SARIF schema supported by your version of the tool.--output=results.sarif: The destination file for your report.
Tip: If you are working in a large repository, the resulting SARIF file can become massive, sometimes reaching hundreds of megabytes. If you only need to process specific results, consider using the
--sarif-categoryflag to tag your runs, which helps in merging multiple SARIF files later if you are running analysis in parallel across different modules.
Not read yet
Deep Dive: Parsing and Filtering SARIF Results
Once you have your results.sarif file, the real work begins. Because SARIF is standard JSON, you can use any language to process it. However, the command-line utility jq is the industry standard for quick inspection and filtering.
Example: Extracting All High-Severity Issues
Suppose you want to pull out only the alerts that CodeQL has classified as "error" level. You can use the following jq command:
cat results.sarif | jq '.runs[0].results[] | select(.level == "error")'
This command drills into the runs array, accesses the results array, and iterates through each result, checking if the level property is equal to "error".
Example: Identifying Unique Rule IDs
If you want to see which queries are finding the most issues, you might want a list of unique ruleId values present in the file:
cat results.sarif | jq -r '.runs[0].results[].ruleId' | sort | uniq -c
This is particularly useful for security triage. If a single rule is generating thousands of alerts, it is likely a candidate for a "false positive" review or a need for a custom query filter.
Not read yet
Integrating SARIF into CI/CD Pipelines
The primary goal of using SARIF is integration. Most modern CI platforms (like GitHub Actions, GitLab CI, or Jenkins) have built-in support for displaying SARIF files directly in the UI.
GitHub Actions Integration
If you are using GitHub Advanced Security, the CodeQL action automatically generates and uploads SARIF files. However, if you are running a custom analysis, you can manually upload your SARIF file using the upload-sarif action:
- name: Upload SARIF file
uses: github/codeql-action/upload-sarif@v2
with:
sarif_file: results.sarif
Best Practices for CI/CD Integration
- Fail-Fast Strategy: Do not fail your build on every issue. Use the SARIF severity levels to define a threshold. For example, only fail the pipeline if there are results with a
leveloferrorand aruleIdthat matches a critical vulnerability category. - Artifact Preservation: Always archive your SARIF files as build artifacts. If a developer asks why a pipeline failed three weeks ago, having the exact SARIF file that generated that failure is invaluable for debugging.
- Cross-Tool Merging: If you have multiple security tools (e.g., CodeQL for logic, Semgrep for style, Trivy for dependencies), use a tool like
sarif-multitoolto merge them into a single file before uploading to your dashboard. This provides a single pane of glass for your security team.
Warning: Do not manually edit SARIF files unless you are performing a programmatic transformation. The SARIF schema is strict, and a single missing comma or malformed URI reference can cause your security dashboard or CI platform to reject the entire file. Always validate your edited JSON against a SARIF schema validator.
Not read yet
Common Pitfalls and How to Avoid Them
Even with a standardized format, developers often run into recurring issues when working with SARIF. Here are the most common mistakes and how to avoid them.
1. The "Pathing" Problem
SARIF files contain URI references to the source files analyzed. If you run CodeQL on a CI runner where the workspace is located at /home/runner/work/repo, but your dashboard expects paths relative to the repository root, the links to the code will be broken.
- The Fix: Use the
--source-rootflag during the CodeQL analysis command. This forces the SARIF output to use relative paths, making the file portable across different environments.
2. Ignoring runAutomationDetails
Many teams forget to populate the runAutomationDetails field. This field is crucial for tracking which pipeline run produced the results. Without it, you cannot distinguish between a finding from a "main" branch build and a "feature" branch build.
- The Fix: Use the
--sarif-categoryflag in the CodeQL CLI. This automatically populates therunAutomationDetailsfield with a unique identifier for that specific analysis pass.
3. Excessive Noise (False Positives)
When you first turn on CodeQL, you might be overwhelmed by the number of findings in your SARIF file. A common mistake is to try to fix them all at once.
- The Fix: Use the SARIF
suppressionsobject. CodeQL supports in-code suppressions (e.g.,// lgtm [cpp/sql-injection]), which get reflected in the SARIF file. Encourage your developers to use these instead of just ignoring the output.
Not read yet
Advanced Manipulation: Transforming SARIF
Sometimes, you need to transform the SARIF output to meet the requirements of a legacy tool or a custom reporting engine. Python is excellent for this due to its native JSON handling.
Scripting Example: Summarizing Results by Severity
Here is a simple Python script to read a SARIF file and output a summary count of findings by severity level:
import json
def summarize_sarif(file_path):
with open(file_path, 'r') as f:
data = json.load(f)
summary = {"error": 0, "warning": 0, "note": 0}
for run in data.get('runs', []):
for result in run.get('results', []):
level = result.get('level', 'warning')
if level in summary:
summary[level] += 1
return summary
# Usage
print(summarize_sarif('results.sarif'))
This approach allows you to build custom compliance reports. For instance, if your organization requires that "no high-severity issues exist in production," you can wrap this script in a gate that checks the error count before allowing a deployment.
Not read yet
Comparison: SARIF vs. Other Formats
To appreciate why SARIF is the industry choice, it helps to compare it to the alternatives that historically dominated the security space.
| Feature | SARIF | CSV/Text Logs | Proprietary JSON |
|---|---|---|---|
| Machine Readable | Yes (Strict Schema) | No | Sometimes |
| Contextual Data | High (Full call stacks) | Low (Just line numbers) | Variable |
| Vendor Neutral | Yes (OASIS Standard) | N/A | No |
| Tool Interop | High | Low | Very Low |
| Extensibility | High (Property bags) | None | Low |
The "Property Bags" feature in SARIF is particularly powerful. It allows tools to add custom metadata to results without breaking the schema. For example, if you wanted to add a business_unit tag to a result, you can add a properties object to the SARIF result, and it will be preserved throughout the pipeline.
Best Practices Checklist
When implementing SARIF-based workflows, keep these industry-recommended practices in mind:
- Standardize on Version 2.1.0: While older versions exist, 2.1.0 is the most widely supported and stable version of the specification.
- Validate Before Upload: Before pushing a SARIF file to a production dashboard, run it through a validator to ensure it adheres to the JSON schema.
- Include Tool Metadata: Always ensure the
toolsection is fully populated. This helps security analysts understand which version of CodeQL generated the finding, which is critical for reproducing issues. - Automate Triage: Use the
ruleIdto route issues to the correct team. For example, findings related tojavascript/hardcoded-credentialsshould be routed to the DevOps team, whilejavascript/sql-injectionmight go to the application developers. - Context is King: Ensure that your CodeQL configuration is set to provide "full" results (including path information) so that developers can see the data flow that led to the vulnerability.
Not read yet
Common Questions and Answers
Q: Can I manually edit a SARIF file to fix a false positive?
A: While you can edit the JSON, it is highly discouraged. If you find a false positive, the correct approach is to either update the CodeQL query or add a suppression comment in the source code. Editing the SARIF file is a temporary fix that will be overwritten the next time the analysis runs.
Q: Why is my SARIF file missing results that I see in the CodeQL CLI output?
A: Check your level filters. Sometimes, the CLI output might show all findings, but the SARIF export might be configured to only include results above a certain severity. Additionally, verify that you are not using an old version of the SARIF schema that might not support newer CodeQL rule categories.
Q: How do I handle multiple languages in one SARIF file?
A: CodeQL supports multi-language analysis. When you run a query suite that includes multiple languages (e.g., cpp, python, javascript), the resulting SARIF file will contain results for all of them. The ruleId usually includes a prefix (e.g., cpp/, py/) which allows you to differentiate the language context.
Q: Is there a limit to how large a SARIF file can be?
A: There is no hard limit in the specification, but many platforms (like GitHub or GitLab) impose upload limits on artifacts. If your SARIF file is too large, consider running your analysis in smaller, language-specific batches and merging the results only when necessary.
Not read yet
Key Takeaways for SARIF Mastery
- Standardization is the Goal: SARIF is the lingua franca of security tools. By adopting it, you decouple your security analysis from your reporting and remediation infrastructure, allowing you to swap out tools without breaking your entire pipeline.
- Understand the Hierarchy: SARIF is not just a list of alerts; it is a structured document containing runs, tool metadata, and detailed result objects. Master the
resultsarray to control what your developers see. - Use the Right Tools: Don't parse SARIF by hand. Use command-line utilities like
jqfor quick tasks and robust libraries like Python'sjsonmodule for building automated reporting and triage pipelines. - Contextualize Your Data: Use flags like
--source-rootand--sarif-categoryto ensure your SARIF files are portable and traceable. A SARIF file without context is just a list of errors that no one knows how to fix. - Prioritize and Filter: Use the severity levels within SARIF to define your CI/CD gates. Do not overwhelm your developers with every single "note" or "warning." Focus on high-severity findings to build trust in your security program.
- Embrace Extensibility: Use the
propertiesfield (the "property bag") to add custom business context to your findings, such as priority, team ownership, or deadline information. - Maintainability Matters: Always treat your security pipeline code as production code. If your SARIF processing scripts break, your security visibility disappears. Keep your scripts simple, tested, and documented.
By mastering the SARIF format, you transition from being a passive consumer of CodeQL results to an active orchestrator of your application security program. The ability to manipulate, filter, and route these findings is what ultimately separates a successful security integration from a noisy, unmanaged one. Start small by automating a simple summary report, and scale to full-blown automated remediation as your team’s maturity grows.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
Spend your points to unlock exam-style practice questions
Spend points to unlock GH-500 exam-style practice questions.
Practice for GH-500