Sarif Parsing
Trail of BitsOfficialPublished by Trail of Bits
- Skill
- Tool integration
- Software development
- CC-BY-SA-4.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a comprehensive framework for working with the SARIF 2.1.0 standard. It focuses on the programmatic processing of static analysis output, offering strategies for severity resolution, deduplication, and CI/CD integration. It emphasizes the importance of correctly resolving severity levels—which may be defined on rules rather than individual results—and provides robust patterns for path normalization and fingerprinting to ensure consistent tracking of vulnerabilities across different scanning environments.
What it does
- Parses and interprets SARIF 2.1.0 files from various static analysis tools.
- Resolves severity levels by correctly traversing SARIF rule definitions.
- Provides patterns for deduplicating findings across multiple scan runs.
- Offers CLI and Python-based approaches for filtering and extracting actionable data.
- Facilitates CI/CD pipeline integration for automated security gating.
- Includes utilities for path normalization and stable fingerprinting.
When to use it
- When you need to aggregate or filter findings from multiple security scanners.
- When building custom CI/CD gates based on static analysis results.
- When you need to convert SARIF output into custom reports or formats.
- When troubleshooting inconsistent severity reporting or duplicate alerts.
- When performing regression analysis between baseline and current scan results.
Advantages
- Standardized approach to severity resolution across different tool outputs.
- Reduces false positives through robust deduplication and fingerprinting logic.
- Provides ready-to-use patterns for common tasks like path normalization.
- Supports both quick CLI exploration and complex programmatic analysis.
- Includes defensive coding practices for handling optional SARIF fields.
Usage examples
- “Parse this SARIF file and list all unique rule IDs that triggered an error.”
- The agent uses the provided jq query logic to resolve severity levels and output a unique list of rule IDs associated with 'error' level findings.
- “How do I aggregate results from two different security tools into one report?”
- The agent provides a Python script using the aggregation pattern to merge multiple SARIF files while maintaining the correct structure.
- “Why are my high-severity alerts not failing the build in CI?”
- The agent explains that severity is often defined on the rule rather than the result, providing a corrected CI/CD script to properly resolve and gate on those levels.
- “How can I deduplicate findings across two different scan runs?”
- The agent demonstrates how to use fingerprinting strategies to compare results and filter out duplicates based on content rather than volatile file paths.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/trailofbits/sarif-parsing/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip sarif-parsing.zip -d .agents/skills
Documentation by Trail of Bits
SARIF Parsing Best Practices
You are a SARIF parsing expert. Your role is to help users effectively read, analyze, and process SARIF files from static analysis tools.
When to Use
Use this skill when:
Reading or interpreting static analysis scan results in SARIF format
Aggregating findings from multiple security tools
Deduplicating or filtering security alerts
Extracting specific vulnerabilities from SARIF files
Integrating SARIF data into CI/CD pipelines
Converting SARIF output to other formats
When NOT to Use
Do NOT use this skill for:
Running static analysis scans (use CodeQL or Semgrep skills instead)
Writing CodeQL or Semgrep rules (use their respective skills)
Analyzing source code directly (SARIF is for processing existing scan results)
Triaging findings without SARIF input (use variant-analysis or audit skills)
SARIF Structure Overview
SARIF 2.1.0 is the current OASIS standard. Every SARIF file has this hierarchical structure:
sarifLog
├── version: "2.1.0"
├── $schema: (optional, enables IDE validation)
└── runs[] (array of analysis runs)
├── tool
│ ├── driver
│ │ ├── name (required)
│ │ ├── version
│ │ └── rules[] (rule definitions)
│ └── extensions[] (plugins)
├── results[] (findings)
│ ├── ruleId
│ ├── ruleIndex (index into tool.driver.rules[])
│ ├── level (OPTIONAL, inherited from the rule when absent)
│ ├── message.text
│ ├── locations[]
│ │ └── physicalLocation
│ │ ├── artifactLocation.uri
│ │ └── region (startLine, startColumn, etc.)
│ ├── fingerprints{}
│ └── partialFingerprints{}
└── artifacts[] (scanned files metadata)Severity Is Not Always on the Result
result.level is optional. CodeQL omits it on every result and records severity on the
rule as defaultConfiguration.level, which the result inherits. Read result.level
directly and a CodeQL run scores as clean however many errors it found, which is how a
severity gate ends up exiting 0 on a failing repo.
Resolve severity in this order (SARIF 2.1.0 section 3.27.10):
kindother than"fail"(a pass/notApplicable record), so"none"result.level, when presentthe matched rule's
defaultConfiguration.level, joiningruleIndexintoruns[].tool.driver.rules[], or matchingruleIdagainstrules[].idwhen the tool omitsruleIndex"warning", the SARIF default
Every severity query in this skill starts from that resolution. In jq it is the
LEVEL_FN definition in {baseDir}/resources/jq-queries.md;
in Python it is resolve_level(result, run) in
{baseDir}/resources/sarif_helpers.py.
Why Fingerprinting Matters
Without stable fingerprints, you can't track findings across runs:
Baseline comparison: "Is this a new finding or did we see it before?"
Regression detection: "Did this PR introduce new vulnerabilities?"
Suppression: "Ignore this known false positive in future runs"
Tools report different paths (/path/to/project/ vs /github/workspace/), so path-based matching fails. Fingerprints hash the content (code snippet, rule ID, relative location) to create stable identifiers regardless of environment.
Tool Selection Guide
| Use Case | Tool | Install / run |
|---|---|---|
| Quick CLI queries | jq | brew install jq / apt install jq |
| Python scripting (simple) | pysarif | uv run --with pysarif python script.py |
| Python scripting (advanced) | sarif-tools | uv run --with sarif-tools python script.py |
| .NET applications | SARIF SDK | NuGet package |
| JavaScript/Node.js | sarif-js | npm package |
| Go applications | garif | go get github.com/chavacava/garif |
| Validation | SARIF Validator | sarifweb.azurewebsites.net |
Strategy 1: Quick Analysis with jq
For rapid exploration and one-off queries:
# Pretty print the file
jq '.' results.sarif
# Count total findings
jq '[.runs[].results[]] | length' results.sarif
# List all rule IDs triggered
jq '[.runs[].results[].ruleId] | unique' results.sarif
# Severity resolution, needed by every query below that filters on level.
# See resources/jq-queries.md for the annotated version.
LEVEL_FN='
def rule($run):
. as $r
| ($run.tool.driver.rules // []) as $rules
| (if ($r.ruleIndex | type) == "number" and $r.ruleIndex >= 0
then $rules[$r.ruleIndex] else null end)
// first($rules[] | select(.id == $r.ruleId))
// null;
def level($run):
. as $r
| if ($r.kind // "fail") != "fail" then "none"
else ($r.level // rule($run).defaultConfiguration.level // "warning") end;
'
# Extract errors only
jq "$LEVEL_FN"'.runs[] as $run | $run.results[] | select(level($run) == "error")' results.sarif
# Get findings with file locations
jq '.runs[].results[] | {
rule: .ruleId,
message: .message.text,
file: .locations[0].physicalLocation.artifactLocation.uri,
line: .locations[0].physicalLocation.region.startLine
}' results.sarif
# Filter by severity and get count per rule
jq "$LEVEL_FN"'[.runs[] as $run | $run.results[] | select(level($run) == "error")] | group_by(.ruleId) | map({rule: .[0].ruleId, count: length})' results.sarif
# Extract findings for a specific file
jq --arg file "src/auth.py" '.runs[].results[] | select(.locations[].physicalLocation.artifactLocation.uri | contains($file))' results.sarifStrategy 2: Python with pysarif
For programmatic access with full object model:
from pysarif import load_from_file, save_to_file
# Load SARIF file
sarif = load_from_file("results.sarif")
# Iterate through runs and results
for run in sarif.runs:
tool_name = run.tool.driver.name
print(f"Tool: {tool_name}")
for result in run.results:
# pysarif fills a missing result.level with "warning", so .level here is NOT the
# rule-inherited severity: a CodeQL error (no level on the result, severity on the
# rule) reads as "warning". Gate severity with Strategy 1's level() or with
# resolve_level() in resources/sarif_helpers.py, which resolve it from the rule.
print(f" {result.rule_id}: {result.message.text}")
if result.locations:
loc = result.locations[0].physical_location
if loc and loc.artifact_location:
print(f" File: {loc.artifact_location.uri}")
if loc.region:
print(f" Line: {loc.region.start_line}")
# Save modified SARIF
save_to_file(sarif, "modified.sarif")Strategy 3: Python with sarif-tools
For aggregation, reporting, and CI/CD integration:
from sarif import loader
# Load single file
sarif_data = loader.load_sarif_file("results.sarif")
# Or load multiple files
sarif_set = loader.load_sarif_files(["tool1.sarif", "tool2.sarif"])
# Get summary report
report = sarif_data.get_report()
# Get histogram by severity
errors = report.get_issue_type_histogram_for_severity("error")
warnings = report.get_issue_type_histogram_for_severity("warning")
# Filter by severity. sarif-tools hands back raw result dicts, and a result's level may
# live on its rule, so resolve it against the run instead of reading r["level"].
from sarif_helpers import extract_findings, filter_by_level, load_sarif
high_severity = filter_by_level(extract_findings(load_sarif("results.sarif")), "error")sarif-tools CLI commands:
# Summary of findings
sarif summary results.sarif
# List all results with details
sarif ls results.sarif
# Get results by severity
sarif ls --level error results.sarif
# Diff two SARIF files (find new/fixed issues)
sarif diff baseline.sarif current.sarif
# Convert to other formats
sarif csv results.sarif > results.csv
sarif html results.sarif > report.htmlStrategy 4: Aggregating Multiple SARIF Files
When combining results from multiple tools:
import json
from sarif_helpers import deduplicate, extract_findings
def aggregate_sarif_files(sarif_paths: list[str]) -> dict:
"""Combine multiple SARIF files into one."""
aggregated = {
"version": "2.1.0",
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"runs": []
}
for path in sarif_paths:
with open(path) as f:
sarif = json.load(f)
aggregated["runs"].extend(sarif.get("runs", []))
return aggregated
unique = deduplicate(extract_findings(aggregate_sarif_files(["tool1.sarif", "tool2.sarif"])))deduplicate() prefers whatever fingerprints or partialFingerprints the tool supplied
and falls back to hashing rule ID, the whole normalized path, line, and message. Keep the
directory in that key: the same rule at the same line in auth/login.py and
admin/login.py is two findings, and a basename-only key throws one of them away.
Strategy 5: Extracting Actionable Data
resources/sarif_helpers.py covers this with the standard library alone.
extract_findings() returns Finding objects whose severity is already resolved, and
filter_by_level(), sort_by_severity(), deduplicate() and diff_findings() consume
those:
from sarif_helpers import extract_findings, filter_by_level, load_sarif, sort_by_severity
findings = sort_by_severity(extract_findings(load_sarif("results.sarif")))
for f in filter_by_level(findings, "error"):
print(f"{f.file_path}:{f.start_line} [{f.level}] {f.rule_id}: {f.message}")Writing your own extractor, severity is the part that goes wrong silently:
def resolve_level(result: dict, run: dict) -> str:
"""Severity of a result: its own level, else its rule's default, else "warning"."""
if result.get("kind", "fail") != "fail":
return "none"
if result.get("level"):
return result["level"]
rules = run.get("tool", {}).get("driver", {}).get("rules", [])
index = result.get("ruleIndex")
rule = rules[index] if isinstance(index, int) and 0 <= index < len(rules) else next(
(r for r in rules if r.get("id") == result.get("ruleId")), {}
)
return rule.get("defaultConfiguration", {}).get("level") or "warning"Results carry ruleIndex on some tools and only ruleId on others, so a resolver that
joins one way alone silently returns the default for every result the other kind of tool
produces.
Common Pitfalls and Solutions
1. Path Normalization Issues
Different tools report paths differently (absolute, relative, URI-encoded), so
file:///src/a%20b.py and src/a b.py can be the same file. Strip the file:// scheme,
percent-decode, resolve against a base path, and normalize separators before comparing or
hashing anything: normalize_path() in resources/sarif_helpers.py does all four.
2. Fingerprint Mismatch Across Runs
Fingerprints may not match if:
File paths differ between environments
Tool versions changed fingerprinting algorithm
Code was reformatted (changing line numbers)
Solution: Use multiple fingerprint strategies:
def compute_stable_fingerprint(result: dict, file_content: str = None) -> str:
"""Compute environment-independent fingerprint."""
import hashlib
components = [
result.get("ruleId", ""),
result.get("message", {}).get("text", "")[:100], # First 100 chars
]
# Add code snippet if available
if file_content and result.get("locations"):
region = result["locations"][0].get("physicalLocation", {}).get("region", {})
if region.get("startLine"):
lines = file_content.split("\n")
line_idx = region["startLine"] - 1
if 0 <= line_idx < len(lines):
# Normalize whitespace
components.append(lines[line_idx].strip())
return hashlib.sha256("".join(components).encode()).hexdigest()[:16]3. Missing or Incomplete Data
SARIF allows many optional fields. Always use defensive access:
def safe_get_location(result: dict) -> tuple[str, int]:
"""Safely extract file and line from result."""
try:
loc = result.get("locations", [{}])[0]
phys = loc.get("physicalLocation", {})
file_path = phys.get("artifactLocation", {}).get("uri", "unknown")
line = phys.get("region", {}).get("startLine", 0)
return file_path, line
except (IndexError, KeyError, TypeError):
return "unknown", 04. Large File Performance
For very large SARIF files (100MB+):
import ijson # run via: uv run --with ijson
def stream_results(sarif_path: str):
"""Stream results without loading entire file."""
with open(sarif_path, "rb") as f:
# Stream through results arrays
for result in ijson.items(f, "runs.item.results.item"):
yield result5. Schema Validation
Validate before processing to catch malformed files:
# Using ajv-cli
npm install -g ajv-cli
ajv validate -s sarif-schema-2.1.0.json -d results.sarif
# Using Python jsonschema
uv run --with jsonschema python your_script.py # e.g. the function belowfrom jsonschema import validate, ValidationError
import json
def validate_sarif(sarif_path: str, schema_path: str) -> bool:
"""Validate SARIF file against schema."""
with open(sarif_path) as f:
sarif = json.load(f)
with open(schema_path) as f:
schema = json.load(f)
try:
validate(sarif, schema)
return True
except ValidationError as e:
print(f"Validation error: {e.message}")
return FalseCI/CD Integration Patterns
GitHub Actions
- name: Upload SARIF
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: results.sarif
- name: Check for high severity
run: |
# select(.level == "error") counts zero on CodeQL output, which records severity on
# the rule instead. Resolve the level or the gate passes on a repo full of errors.
HIGH_COUNT=$(jq '
def rule($run):
. as $r
| ($run.tool.driver.rules // []) as $rules
| (if ($r.ruleIndex | type) == "number" and $r.ruleIndex >= 0
then $rules[$r.ruleIndex] else null end)
// first($rules[] | select(.id == $r.ruleId))
// null;
def level($run):
. as $r
| if ($r.kind // "fail") != "fail" then "none"
else ($r.level // rule($run).defaultConfiguration.level // "warning") end;
[.runs[] as $run | $run.results[] | select(level($run) == "error")] | length
' results.sarif)
if [ "$HIGH_COUNT" -gt 0 ]; then
echo "Found $HIGH_COUNT high severity issues"
exit 1
fiFail on New Issues
from sarif import loader
def check_for_regressions(baseline: str, current: str) -> int:
"""Return count of new issues not in baseline."""
baseline_data = loader.load_sarif_file(baseline)
current_data = loader.load_sarif_file(current)
baseline_fps = {get_fingerprint(r) for r in baseline_data.get_results()}
new_issues = [r for r in current_data.get_results()
if get_fingerprint(r) not in baseline_fps]
return len(new_issues)Key Principles
Validate first: Check SARIF structure before processing
Resolve severity, never read
result.level: it is optional, and CodeQL always omits itHandle optionals: Many fields are optional; use defensive access
Normalize paths: Tools report paths differently; normalize early
Fingerprint wisely: Combine multiple strategies for stable deduplication
Stream large files: Use ijson or similar for 100MB+ files
Aggregate thoughtfully: Preserve tool metadata when combining files
Skill Resources
For ready-to-use query templates, see {baseDir}/resources/jq-queries.md:
40+ jq queries for common SARIF operations
LEVEL_FN- the severity resolution every filtering query starts fromSeverity filtering, rule extraction, aggregation patterns
For Python utilities, see {baseDir}/resources/sarif_helpers.py:
resolve_level()- Severity from the result or the rule it inherits fromnormalize_path()- Handle tool-specific path formatscompute_fingerprint()- Rule, normalized path, line, and messagededuplicate()- Remove duplicates across runs
Two SARIF fixtures live in {baseDir}/resources/fixtures, one with severity on the rules only and one with severity on the results. Each contains exactly one error, so a gate can be checked against a known answer before it is trusted.
Reference Links
Files
- ATTRIBUTION.mdAdded by AutoGineer935 B
- LICENSELicence file added by AutoGineer19.7 KiB
- SKILL.md17.5 KiB
- agents/openai.yaml231 B
- assets/trail-of-bits-mark.svg3.0 KiB
- resources/fixtures/codeql-no-level.sarif2.2 KiB
- resources/fixtures/levels-on-results.sarif1.7 KiB
- resources/jq-queries.md7.7 KiB
- resources/sarif_helpers.pyScript12.7 KiB
- resources/test_sarif_helpers.pyScript13.7 KiB
resources/test_sarif_helpers.py
# /// script
# requires-python = ">=3.11"
# dependencies = ["pytest>=8"]
# ///
"""Tests for sarif_helpers.py, with the weight on severity resolution.
`result.level` is optional in SARIF 2.1.0, and CodeQL never emits it: severity lives on
the rule as `defaultConfiguration.level` and the result inherits it. Every helper here
used to read `result.level` directly, so `filter_by_level(findings, "error")` returned
nothing for a CodeQL run and the documented CI gate exited 0 on a repo full of errors.
fixtures/codeql-no-level.sarif is that shape, and test_naive_level_read_finds_nothing
pins it: if someone "fixes" the fixture by adding levels to its results, that test fails
rather than the suite quietly losing the only case it exists to cover.
fixtures/levels-on-results.sarif is the ordinary shape, and it is here so a resolver
cannot pass by ignoring `result.level` altogether.
The jq tests run the documented commands themselves, extracted from the markdown. A
severity gate that is correct in sarif_helpers.py and wrong in the docs is still a
severity gate that passes on a failing repo.
"""
from __future__ import annotations
import json
import re
import shutil
import subprocess
from pathlib import Path
import pytest
from sarif_helpers import (
compute_fingerprint,
deduplicate,
extract_findings,
filter_by_level,
find_rule,
load_sarif,
resolve_level,
)
RESOURCES = Path(__file__).resolve().parent
SKILL = RESOURCES.parent / "SKILL.md"
JQ_QUERIES = RESOURCES / "jq-queries.md"
NO_LEVEL = RESOURCES / "fixtures/codeql-no-level.sarif"
WITH_LEVEL = RESOURCES / "fixtures/levels-on-results.sarif"
# The gate every CI pipeline built from this skill runs, in its jq form.
ERROR_GATE = '[.runs[] as $run | $run.results[] | select(level($run) == "error")] | length'
NAIVE_GATE = '[.runs[].results[] | select(.level == "error")] | length'
FENCE = re.compile(r"^```[a-z]*\n(.*?)^```", re.MULTILINE | re.DOTALL)
LEVEL_FN = re.compile(r"LEVEL_FN='\n(.*?)'\n", re.DOTALL)
# The GitHub Actions gate, which inlines its own copy of the resolver.
CI_GATE = re.compile(r"HIGH_COUNT=\$\(jq '\n(.*?)\n\s*' results\.sarif\)", re.DOTALL)
def results_of(sarif: dict) -> list[dict]:
return [r for run in sarif["runs"] for r in run["results"]]
def jq(program: str, path: Path) -> str:
"""Run jq, failing rather than skipping when it is missing.
A skip reads as a clean run while the only check that can catch a broken documented
gate did not execute. jq is this skill's primary tool and CI installs it.
"""
if not shutil.which("jq"):
raise AssertionError(
"jq is not installed, so the documented severity gate went unverified. "
"Install it (brew install jq); this suite must not pass without it."
)
out = subprocess.run(["jq", program, str(path)], capture_output=True, text=True, check=True)
return out.stdout.strip()
def documented_level_fn(path: Path) -> str:
"""The LEVEL_FN jq definition as the docs publish it."""
match = LEVEL_FN.search(path.read_text())
assert match, f"{path.name} no longer defines LEVEL_FN; the jq tests below test nothing"
return match.group(1)
# --- the fixtures themselves, so the suite cannot go vacuous ------------------------
def test_codeql_fixture_omits_every_result_level():
"""The bug only exists on results with no level of their own."""
results = results_of(load_sarif(NO_LEVEL))
assert results, "fixture has no results"
assert all("level" not in r for r in results)
rules = load_sarif(NO_LEVEL)["runs"][0]["tool"]["driver"]["rules"]
assert any(r.get("defaultConfiguration", {}).get("level") == "error" for r in rules)
def test_codeql_fixture_covers_both_join_directions():
"""One result joins by ruleIndex, another only by ruleId."""
results = results_of(load_sarif(NO_LEVEL))
assert any("ruleIndex" in r for r in results)
assert any("ruleIndex" not in r for r in results)
def test_naive_level_read_finds_nothing_on_codeql_output():
"""The bug, stated: reading result.level scores a CodeQL run as clean."""
results = results_of(load_sarif(NO_LEVEL))
assert [r for r in results if r.get("level") == "error"] == []
assert len(filter_by_level(extract_findings(load_sarif(NO_LEVEL)), "error")) == 1
# --- resolution ---------------------------------------------------------------------
def test_severity_inherited_from_rule_defaults():
levels = {f.rule_id: f.level for f in extract_findings(load_sarif(NO_LEVEL))}
assert levels == {
"py/sql-injection": "error", # defaultConfiguration.level, via ruleIndex
"py/clear-text-logging-sensitive-data": "warning", # via ruleId, no ruleIndex
"py/unused-import": "warning", # rule has no defaultConfiguration at all
}
def test_result_level_outranks_rule_default():
"""Both fixtures hold exactly one error; a resolver that ignored result.level would
report zero here, which is how you notice the fix was an inversion."""
findings = extract_findings(load_sarif(WITH_LEVEL))
assert {f.rule_id: f.level for f in findings} == {
"python.lang.security.audit.dangerous-subprocess-use": "error",
"python.django.security.audit.avoid-mark-safe": "warning",
}
rules = load_sarif(WITH_LEVEL)["runs"][0]["tool"]["driver"]["rules"]
assert all(r["defaultConfiguration"]["level"] == "warning" for r in rules)
assert len(filter_by_level(findings, "error")) == 1
@pytest.mark.parametrize("kind", ["pass", "notApplicable", "informational"])
def test_kind_other_than_fail_is_none(kind):
"""A passing compliance check must not inherit its rule's error level."""
run = {"tool": {"driver": {"rules": [{"id": "r", "defaultConfiguration": {"level": "error"}}]}}}
assert resolve_level({"ruleId": "r", "kind": kind}, run) == "none"
assert resolve_level({"ruleId": "r", "kind": "fail"}, run) == "error"
@pytest.mark.parametrize("kind", [None, "fail"])
def test_null_or_fail_kind_resolves_from_the_rule(kind):
"""SARIF's `kind` defaults to "fail", and the jq gate coalesces null with `// "fail"`.
`.get("kind", "fail")` would instead read an explicit null and hide the error as
"none", so the resolver must coalesce null to "fail" to agree with the jq gate."""
run = {"tool": {"driver": {"rules": [{"id": "r", "defaultConfiguration": {"level": "error"}}]}}}
assert resolve_level({"ruleId": "r", "kind": kind}, run) == "error"
def test_unmatched_rule_falls_back_to_sarif_default():
run = {"tool": {"driver": {"name": "tool-with-no-rule-metadata"}}}
assert resolve_level({"ruleId": "r"}, run) == "warning"
assert find_rule({"ruleId": "r"}, run) is None
@pytest.mark.parametrize("index", [9, -1])
def test_rule_index_outside_the_array_falls_back_to_rule_id(index):
"""-1 is SARIF's "no rule", and it is the dangerous one: `$rules[-1]` in jq is the
last rule, so an unguarded index labels the result with that rule's severity."""
run = {
"tool": {
"driver": {
"rules": [
{"id": "r", "defaultConfiguration": {"level": "note"}},
{"id": "last", "defaultConfiguration": {"level": "error"}},
]
}
}
}
assert resolve_level({"ruleId": "r", "ruleIndex": index}, run) == "note"
# --- the documented jq gate ---------------------------------------------------------
def test_documented_jq_gate_reports_errors_from_rule_defaults():
"""Before and after, against the same bytes: the naive gate misses the error the
documented one finds, and neither over-reports on ordinary SARIF."""
level_fn = documented_level_fn(JQ_QUERIES)
assert jq(NAIVE_GATE, NO_LEVEL) == "0"
assert jq(level_fn + ERROR_GATE, NO_LEVEL) == "1"
assert jq(NAIVE_GATE, WITH_LEVEL) == "1"
assert jq(level_fn + ERROR_GATE, WITH_LEVEL) == "1"
def test_jq_and_python_resolution_agree():
level_fn = documented_level_fn(JQ_QUERIES)
program = level_fn + r'[.runs[] as $run | $run.results[] | level($run)] | join(",")'
for fixture in (NO_LEVEL, WITH_LEVEL):
from_jq = json.loads(jq(program, fixture)).split(",")
assert from_jq == [f.level for f in extract_findings(load_sarif(fixture))]
def test_skill_and_reference_publish_the_same_resolution():
assert documented_level_fn(SKILL) == documented_level_fn(JQ_QUERIES)
def test_the_github_actions_gate_runs_and_counts_the_inherited_error():
"""The gate from issue #262, run as published. It inlines its own copy of the
resolver because a workflow step has no shell variable to paste into, so comparing
the LEVEL_FN blocks does not cover it."""
match = CI_GATE.search(SKILL.read_text())
assert match, "the GitHub Actions gate is no longer where this test reads it"
program = match.group(1)
assert jq(program, NO_LEVEL) == "1"
assert jq(program, WITH_LEVEL) == "1"
def test_documented_jq_does_not_read_the_last_rule_for_rule_index_minus_one(tmp_path):
"""`$rules[-1]` is the last element in jq, so the documented guard has to reject it."""
sarif = {
"version": "2.1.0",
"runs": [
{
"tool": {
"driver": {
"name": "t",
"rules": [
{"id": "r", "defaultConfiguration": {"level": "note"}},
{"id": "last", "defaultConfiguration": {"level": "error"}},
],
}
},
"results": [{"ruleId": "r", "ruleIndex": -1, "message": {"text": "m"}}],
}
],
}
path = tmp_path / "minus-one.sarif"
path.write_text(json.dumps(sarif))
program = documented_level_fn(JQ_QUERIES) + ".runs[] as $run | $run.results[] | level($run)"
assert json.loads(jq(program, path)) == "note"
assert jq(documented_level_fn(JQ_QUERIES) + ERROR_GATE, path) == "0"
def unresolved_severity(markdown: str) -> tuple[list[str], int]:
"""Documented jq lines that read a result's `.level` without resolving it, and the
number of jq blocks scanned.
Line by line, not block by block: one query reverted to `select(.level == "error")`
hides inside a block whose other queries still resolve, which is how five of these
survived review the first time.
`.defaultConfiguration.level` is the rule's own field, read on purpose by the queries
that list rule metadata, and `$r.level` is the resolver's own first branch.
"""
offenders, blocks = [], 0
for block in FENCE.findall(markdown):
if "jq " not in block:
continue
blocks += 1
for raw in block.splitlines():
line = raw.strip()
if line.startswith("#"):
continue
for benign in ("defaultConfiguration.level", "$r.level"):
line = line.replace(benign, "")
if ".level" in line and "level($run)" not in line:
offenders.append(raw.strip())
return offenders, blocks
def test_no_documented_jq_command_filters_on_bare_result_level():
"""No unresolved read anywhere, and the resolved queries did not vanish either.
A doc with every severity query deleted would satisfy the first assertion, so the
second one counts the resolutions that must still be there.
"""
scanned, resolutions = 0, 0
for doc in (SKILL, JQ_QUERIES):
text = doc.read_text()
offenders, blocks = unresolved_severity(text)
assert offenders == [], f"{doc.name}: unresolved severity in {offenders}"
scanned += blocks
resolutions += text.count("level($run)")
assert scanned >= 10, f"only {scanned} jq blocks found; block discovery is broken"
assert resolutions >= 15, f"only {resolutions} resolved queries left in the docs"
def test_the_severity_guard_still_detects_a_regression():
"""The guard above reports nothing by design, so prove it can still report."""
regressed = """```bash
# select(.level == "error") is what this used to say
jq '.runs[].results[] | select(.level == "error")' results.sarif
jq '.runs[].tool.driver.rules[] | {id: .id, level: .defaultConfiguration.level}' results.sarif
jq "$LEVEL_FN"'.runs[] as $run | $run.results[] | select(level($run) == "error")' out.sarif
```
"""
offenders, blocks = unresolved_severity(regressed)
assert blocks == 1
assert offenders == ["""jq '.runs[].results[] | select(.level == "error")' results.sarif"""]
# --- fingerprints -------------------------------------------------------------------
def result_at(uri: str) -> dict:
return {
"ruleId": "py/sql-injection",
"message": {"text": "This query depends on a user-provided value."},
"locations": [
{"physicalLocation": {"artifactLocation": {"uri": uri}, "region": {"startLine": 42}}}
],
}
def test_fingerprint_separates_identical_findings_in_different_directories():
"""Hashing the basename alone made these one finding, so the second was discarded."""
assert compute_fingerprint(result_at("app/auth/login.py")) != compute_fingerprint(
result_at("app/admin/login.py")
)
def test_deduplicate_keeps_a_finding_from_each_directory():
sarif = {
"version": "2.1.0",
"runs": [
{
"tool": {"driver": {"name": "CodeQL"}},
"results": [result_at("app/auth/login.py"), result_at("app/admin/login.py")],
}
],
}
assert len(deduplicate(extract_findings(sarif))) == 2
def test_fingerprint_ignores_uri_scheme_and_percent_encoding():
assert compute_fingerprint(result_at("file:///src/a%20b.py")) == compute_fingerprint(
result_at("/src/a b.py")
)
def test_fingerprint_still_matches_the_same_finding_twice():
assert compute_fingerprint(result_at("app/auth/login.py")) == compute_fingerprint(
result_at("app/auth/login.py")
)
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Needs Python, Needs Node.js
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Trail of Bits
- Publisher
- Trail of Bits (Official)
- Source
- trailofbits/skills · plugins/static-analysis/skills/sarif-parsing · commit e4dd0bb
- Licence
- Creative Commons Attribution-ShareAlike 4.0 International (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Trail of Bits.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download sarif-parsing.zip