Generated banner for Sarif Parsing
Generated logo for Sarif Parsing

Sarif Parsing

Trail of BitsOfficialPublished by Trail of Bits

  • Skill
  • Tool integration
  • Software development
  • CC-BY-SA-4.0
  • Low risk
  • Has scripts

From the author

Parses and processes SARIF files from static analysis tools like CodeQL, Semgrep, or other scanners. Triggers on "parse sarif", "read scan results", "aggregate findings", "deduplicate alerts", or "process sarif output". Handles filtering, deduplication, format conversion, and CI/CD integration of SARIF data. Does NOT run scans — use the Semgrep or CodeQL skills for that.
— the description by Trail of Bits

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

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/trailofbits/sarif-parsing/download
  2. Unzip 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):

  1. kind other than "fail" (a pass/notApplicable record), so "none"

  2. result.level, when present

  3. the matched rule's defaultConfiguration.level, joining ruleIndex into runs[].tool.driver.rules[], or matching ruleId against rules[].id when the tool omits ruleIndex

  4. "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 CaseToolInstall / run
Quick CLI queriesjqbrew install jq / apt install jq
Python scripting (simple)pysarifuv run --with pysarif python script.py
Python scripting (advanced)sarif-toolsuv run --with sarif-tools python script.py
.NET applicationsSARIF SDKNuGet package
JavaScript/Node.jssarif-jsnpm package
Go applicationsgarifgo get github.com/chavacava/garif
ValidationSARIF Validatorsarifweb.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.sarif

Strategy 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.html

Strategy 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", 0
4. 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 result
5. 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 below
from 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 False

CI/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
    fi
Fail 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

  1. Validate first: Check SARIF structure before processing

  2. Resolve severity, never read result.level: it is optional, and CodeQL always omits it

  3. Handle optionals: Many fields are optional; use defensive access

  4. Normalize paths: Tools report paths differently; normalize early

  5. Fingerprint wisely: Combine multiple strategies for stable deduplication

  6. Stream large files: Use ijson or similar for 100MB+ files

  7. 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 from

  • Severity 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 from

  • normalize_path() - Handle tool-specific path formats

  • compute_fingerprint() - Rule, normalized path, line, and message

  • deduplicate() - 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.

Files

resources/sarif_helpers.py

"""
SARIF Parsing Helper Functions

Reusable utilities for working with SARIF files.
No external dependencies beyond standard library.
"""

import hashlib
import json
from collections import defaultdict
from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from urllib.parse import unquote

# What a result's severity is when neither the result nor its rule states one.
SARIF_DEFAULT_LEVEL = "warning"


@dataclass
class Finding:
    """Structured representation of a SARIF result."""

    rule_id: str
    level: str  # resolved by resolve_level(), not read from result.level
    message: str
    file_path: str | None = None
    start_line: int | None = None
    end_line: int | None = None
    start_column: int | None = None
    end_column: int | None = None
    fingerprint: str | None = None
    tool_name: str | None = None
    rule_name: str | None = None
    raw: dict = field(default_factory=dict, repr=False)


def load_sarif(path: str | Path) -> dict:
    """Load and parse a SARIF file."""
    with open(path) as f:
        return json.load(f)


def save_sarif(sarif: dict, path: str | Path, indent: int = 2) -> None:
    """Save SARIF data to file."""
    with open(path, "w") as f:
        json.dump(sarif, f, indent=indent)


def validate_version(sarif: dict) -> bool:
    """Check if SARIF version is 2.1.0."""
    return sarif.get("version") == "2.1.0"


def normalize_path(uri: str, base_path: str = "") -> str:
    """Normalize SARIF artifact URI to consistent path."""
    if not uri:
        return ""

    # Remove file:// prefix
    if uri.startswith("file://"):
        uri = uri[7:]

    # URL decode
    uri = unquote(uri)

    # Handle relative paths
    if base_path and not Path(uri).is_absolute():
        uri = str(Path(base_path) / uri)

    return str(Path(uri))


def safe_get(data: dict, *keys, default: Any = None) -> Any:
    """Safely navigate nested dict structure."""
    for key in keys:
        if isinstance(data, dict):
            data = data.get(key, {})
        elif isinstance(data, list) and isinstance(key, int):
            data = data[key] if 0 <= key < len(data) else {}
        else:
            return default
    return data if data != {} else default


def find_rule(result: dict, run: dict) -> dict | None:
    """Find the rule definition a result was produced by.

    Joins on `ruleIndex` first (the cheap, unambiguous key CodeQL populates) and falls
    back to matching `ruleId` against `runs[].tool.driver.rules[].id`, which is all
    Semgrep and most other tools give you.
    """
    rules = safe_get(run, "tool", "driver", "rules", default=[]) or []
    index = result.get("ruleIndex")
    if isinstance(index, int) and not isinstance(index, bool) and 0 <= index < len(rules):
        return rules[index]

    rule_id = result.get("ruleId")
    if rule_id:
        for rule in rules:
            if rule.get("id") == rule_id:
                return rule
    return None


def resolve_level(result: dict, run: dict) -> str:
    """Resolve a result's effective severity, per SARIF 2.1.0 section 3.27.10.

    `result.level` is optional, and CodeQL routinely omits it: severity lives on the
    rule as `defaultConfiguration.level`, and the result inherits it. Reading
    `result.level` directly therefore scores an entire CodeQL run as clean, which is
    why a severity gate written that way exits 0 on a repo full of errors.

    Resolution order:
      1. `kind` other than "fail" (a pass/informational/notApplicable record) is "none"
      2. `result.level` when present
      3. the matched rule's `defaultConfiguration.level`
      4. "warning", the SARIF default

    `invocations[].ruleConfigurationOverrides` can outrank the rule default; no tool in
    common use emits it, so this does not read it.
    """
    if (result.get("kind") or "fail") != "fail":
        return "none"

    level = result.get("level")
    if level:
        return level

    rule = find_rule(result, run)
    if rule:
        rule_level = safe_get(rule, "defaultConfiguration", "level")
        if rule_level:
            return rule_level

    return SARIF_DEFAULT_LEVEL


def extract_location(result: dict) -> tuple[str | None, int | None, int | None]:
    """Extract file path, start line, and end line from result."""
    loc = safe_get(result, "locations", 0, default={})
    phys = loc.get("physicalLocation", {})
    region = phys.get("region", {})

    file_path = safe_get(phys, "artifactLocation", "uri")
    start_line = region.get("startLine")
    end_line = region.get("endLine")

    return file_path, start_line, end_line


def iter_results(sarif: dict) -> Iterator[tuple[dict, dict]]:
    """Iterate over all results with their run context."""
    for run in sarif.get("runs", []):
        for result in run.get("results", []):
            yield result, run


def extract_findings(sarif: dict) -> list[Finding]:
    """Extract all findings as structured objects."""
    findings = []

    for result, run in iter_results(sarif):
        tool_name = safe_get(run, "tool", "driver", "name")
        file_path, start_line, end_line = extract_location(result)

        loc = safe_get(result, "locations", 0, default={})
        phys = loc.get("physicalLocation", {})
        region = phys.get("region", {})
        rule = find_rule(result, run)

        # Get fingerprint
        fp = None
        if result.get("partialFingerprints"):
            fp = next(iter(result["partialFingerprints"].values()), None)
        elif result.get("fingerprints"):
            fp = next(iter(result["fingerprints"].values()), None)

        findings.append(
            Finding(
                rule_id=result.get("ruleId", "unknown"),
                level=resolve_level(result, run),
                message=safe_get(result, "message", "text", default=""),
                file_path=file_path,
                start_line=start_line,
                end_line=end_line,
                start_column=region.get("startColumn"),
                end_column=region.get("endColumn"),
                fingerprint=fp,
                tool_name=tool_name,
                rule_name=rule.get("name") if rule else None,
                raw=result,
            )
        )

    return findings


def filter_by_level(findings: list[Finding], *levels: str) -> list[Finding]:
    """Filter findings by severity level(s)."""
    return [f for f in findings if f.level in levels]


def filter_by_file(findings: list[Finding], pattern: str) -> list[Finding]:
    """Filter findings by file path pattern (substring match)."""
    return [f for f in findings if f.file_path and pattern in f.file_path]


def filter_by_rule(findings: list[Finding], *rule_ids: str) -> list[Finding]:
    """Filter findings by rule ID(s)."""
    return [f for f in findings if f.rule_id in rule_ids]


def sort_by_severity(findings: list[Finding], reverse: bool = False) -> list[Finding]:
    """Sort findings by severity (error > warning > note > none)."""
    severity_order = {"error": 0, "warning": 1, "note": 2, "none": 3}
    return sorted(findings, key=lambda f: severity_order.get(f.level, 99), reverse=reverse)


def group_by_file(findings: list[Finding]) -> dict[str, list[Finding]]:
    """Group findings by file path."""
    grouped = defaultdict(list)
    for f in findings:
        key = f.file_path or "unknown"
        grouped[key].append(f)
    return dict(grouped)


def group_by_rule(findings: list[Finding]) -> dict[str, list[Finding]]:
    """Group findings by rule ID."""
    grouped = defaultdict(list)
    for f in findings:
        grouped[f.rule_id].append(f)
    return dict(grouped)


def count_by_level(findings: list[Finding]) -> dict[str, int]:
    """Count findings by severity level."""
    counts = defaultdict(int)
    for f in findings:
        counts[f.level] += 1
    return dict(counts)


def count_by_rule(findings: list[Finding]) -> dict[str, int]:
    """Count findings by rule ID."""
    counts = defaultdict(int)
    for f in findings:
        counts[f.rule_id] += 1
    return dict(counts)


def compute_fingerprint(result: dict, include_message: bool = True) -> str:
    """Compute stable fingerprint from result data.

    The whole normalized path goes into the hash, directory included. Hashing the
    basename alone gave `src/auth/login.py:42` and `src/admin/login.py:42` one
    fingerprint under the same rule, so `deduplicate()` and `diff_findings()` threw
    away the second finding and called the file fixed.

    The cost is that runs reporting different absolute prefixes for the same file
    (`/github/workspace/src/a.py` vs `/builds/proj/src/a.py`) no longer match. Make the
    URIs repo-relative before fingerprinting when comparing across environments; a
    collision that hides a finding is the worse failure.
    """
    components = [result.get("ruleId", "")]

    file_path, start_line, _ = extract_location(result)
    if file_path:
        # POSIX separators so a fingerprint computed on Windows matches one from CI.
        components.append(Path(normalize_path(file_path)).as_posix())
    if start_line:
        components.append(str(start_line))
    if include_message:
        msg = safe_get(result, "message", "text", default="")
        # First 50 chars of message for stability
        components.append(msg[:50])

    return hashlib.sha256("|".join(components).encode()).hexdigest()[:16]


def deduplicate(findings: list[Finding]) -> list[Finding]:
    """Remove duplicate findings based on fingerprints."""
    seen = set()
    unique = []

    for f in findings:
        key = f.fingerprint or compute_fingerprint(f.raw)
        if key not in seen:
            seen.add(key)
            unique.append(f)

    return unique


def merge_sarif_files(*paths: str | Path) -> dict:
    """Merge multiple SARIF files into one."""
    merged = {
        "version": "2.1.0",
        "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
        "runs": [],
    }

    for path in paths:
        sarif = load_sarif(path)
        merged["runs"].extend(sarif.get("runs", []))

    return merged


def diff_findings(
    baseline: list[Finding], current: list[Finding]
) -> tuple[list[Finding], list[Finding], list[Finding]]:
    """
    Compare two sets of findings.

    Returns:
        - new: findings in current but not baseline
        - fixed: findings in baseline but not current
        - unchanged: findings in both
    """
    baseline_fps = {f.fingerprint or compute_fingerprint(f.raw) for f in baseline}
    current_fps = {f.fingerprint or compute_fingerprint(f.raw) for f in current}

    new = [f for f in current if (f.fingerprint or compute_fingerprint(f.raw)) not in baseline_fps]
    fixed = [
        f for f in baseline if (f.fingerprint or compute_fingerprint(f.raw)) not in current_fps
    ]
    unchanged = [
        f for f in current if (f.fingerprint or compute_fingerprint(f.raw)) in baseline_fps
    ]

    return new, fixed, unchanged


def get_rules(sarif: dict) -> dict[str, dict]:
    """Extract rule definitions from SARIF file."""
    rules = {}
    for run in sarif.get("runs", []):
        for rule in safe_get(run, "tool", "driver", "rules", default=[]):
            rules[rule.get("id", "")] = rule
    return rules


def to_csv_rows(findings: list[Finding]) -> list[list[str]]:
    """Convert findings to CSV-ready rows."""
    rows = [["rule_id", "level", "file", "line", "message"]]
    for f in findings:
        rows.append(
            [
                f.rule_id,
                f.level,
                f.file_path or "",
                str(f.start_line or ""),
                f.message.replace("\n", " ")[:200],
            ]
        )
    return rows


def summary(findings: list[Finding]) -> dict:
    """Generate summary statistics for findings."""
    return {
        "total": len(findings),
        "by_level": count_by_level(findings),
        "by_rule": count_by_rule(findings),
        "files_affected": len(set(f.file_path for f in findings if f.file_path)),
        "rules_triggered": len(set(f.rule_id for f in findings)),
    }


# Example usage
if __name__ == "__main__":
    import sys

    if len(sys.argv) < 2:
        print("Usage: uv run --no-project sarif_helpers.py <sarif_file>")
        sys.exit(1)

    sarif = load_sarif(sys.argv[1])

    if not validate_version(sarif):
        print("Warning: SARIF version is not 2.1.0")

    findings = extract_findings(sarif)
    findings = sort_by_severity(findings)

    print("\nSummary:")
    stats = summary(findings)
    print(f"  Total findings: {stats['total']}")
    print(f"  Files affected: {stats['files_affected']}")
    print(f"  Rules triggered: {stats['rules_triggered']}")
    print("\nBy severity:")
    for level, count in stats["by_level"].items():
        print(f"  {level}: {count}")

    print("\nTop 5 rules:")
    for rule, count in sorted(stats["by_rule"].items(), key=lambda x: -x[1])[:5]:
        print(f"  {rule}: {count}")

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 or Trail of Bits.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download sarif-parsing.zip