Generated banner for Codeql
Generated logo for Codeql

Codeql

Trail of BitsOfficialPublished by Trail of Bits

  • Skill
  • Workflow
  • Security
  • CC-BY-SA-4.0
  • Low risk
  • Has scripts

From the author

Scans a codebase for security vulnerabilities using CodeQL's interprocedural data flow and taint tracking analysis. Triggers on "run codeql", "codeql scan", "build codeql database", "SAST scan", "taint analysis", "dataflow analysis", or "find vulnerabilities in this repo". Covers Python, JavaScript/TypeScript, Go, Java/Kotlin, C/C++, C#, Ruby, and Swift. Supports "run all" (security-and-quality + security-experimental) and "important only" (high-precision) scan modes, and creates data extension models for project-specific sources and sinks. For fast single-file pattern matching, or when no build is available for a compiled language, use the semgrep skill; to parse SARIF that already exists rather than produce it, use the sarif-parsing skill.
— 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 structured, multi-phase workflow for performing static application security testing (SAST) using CodeQL. It manages the entire lifecycle of a security scan, including database construction, data extension modeling for custom project APIs, and execution of high-precision or comprehensive query suites. The skill enforces rigorous quality gates, such as database validation and explicit suite verification, to ensure that findings are accurate and that the absence of findings is a result of secure code rather than extraction or configuration errors.

What it does

  • Builds CodeQL databases for multiple languages including Python, JS/TS, Go, Java, C/C++, C#, Ruby, and Swift.
  • Automates the creation and application of data extension models to cover project-specific sources and sinks.
  • Executes security scans using either high-precision or comprehensive query suites.
  • Validates database quality and query suite resolution to prevent silent analysis failures.
  • Generates and manages SARIF-formatted security reports within a structured output directory.
  • Provides a robust fallback mechanism for build failures, including dependency installation and environment-specific workarounds.

When to use it

  • When you need to perform deep, interprocedural security analysis on a codebase.
  • When you want to identify vulnerabilities that require taint tracking across complex application logic.
  • When you need to audit custom frameworks or APIs that standard scanners might miss.
  • When you require a repeatable, documented security scan process with verified results.

Advantages

  • Reduces false negatives by enforcing data extension modeling for custom code.
  • Ensures analysis reliability through mandatory database quality checks.
  • Prevents configuration drift by using explicit query suite references.
  • Provides clear audit trails for security findings and scan configurations.

Usage examples

“run codeql scan on this repository”
The agent will discover the codebase language, build a CodeQL database, apply necessary data extensions, run the security analysis, and output a SARIF report.
“find vulnerabilities in this repo”
The agent will initiate the full CodeQL pipeline, including database discovery, quality assessment, and vulnerability analysis.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/trailofbits/codeql/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip codeql.zip -d .agents/skills

Documentation by Trail of Bits

CodeQL Analysis

Supported languages: Python, JavaScript/TypeScript, Go, Java/Kotlin, C/C++, C#, Ruby, Swift.

Skill resources: Reference files and templates are located at {baseDir}/references/ and {baseDir}/workflows/.

Essential Principles

  1. Database quality is non-negotiable. A database that builds is not automatically good — a cached build extracts nothing while reporting success.

  2. Data extensions catch what CodeQL misses. Django, Spring, and Express projects still wrap database calls, request parsing, and shell execution in project-specific APIs that no shipped model covers.

  3. Explicit suite references prevent silent query dropping. Never pass pack names to codeql database analyze — each pack's defaultSuiteFile applies hidden filters that can produce zero results. Always generate a .qls.

  4. Zero findings needs investigation, not celebration. It can mean poor extraction, missing models, the wrong packs, or suite filtering. Run {baseDir}/scripts/check_db_quality.py after the build, confirm {baseDir}/scripts/verify_query_suite.py exited zero for the suite in use — the generation scripts run it, so invoke it by hand only for a reused or hand-edited suite — and say in the report that both passed.

  5. macOS Apple Silicon requires workarounds for compiled languages. Exit code 137 is an arm64e/arm64 mismatch, not a build failure. Try Homebrew arm64 tools or Rosetta before falling back to build-mode=none.

  6. Follow workflows step by step. Each phase gates the next; skipping quality assessment or data extensions leaves the gap invisible in the results.

Each Bash call is a fresh shell

Nothing carries across a Bash call: not variables, not arrays, not functions sourced from build_log.sh. Every block below that uses a value must re-establish it in the same block. The workflows point back here rather than repeating it; what they do state is the specific damage at that site, because each one fails differently and silently:

  • a lost function makes run_logged exit 127, which the build ladder reads as a failed method and walks down to --build-mode=none, never having invoked CodeQL

  • a lost array expands to nothing, so every --threat-model and --model-packs the user chose is dropped while the final report still lists them as used

  • a lost scalar under set -u aborts the block with unbound variable

Output Directory

All generated files (database, build logs, diagnostics, extensions, results) are stored in a single output directory.

  • If the user specifies an output directory in their prompt, use it as OUTPUT_DIR.

  • If not specified, default to ./static_analysis_codeql_1. If that already exists, increment to _2, _3, etc.

In both cases, always create the directory with mkdir -p before writing any files.

Set USER_SPECIFIED_DIR to the literal path from the user's prompt before running this, or leave it unset to auto-increment. Nothing else assigns it.

# Resolve output directory
USER_SPECIFIED_DIR="${USER_SPECIFIED_DIR:-}"   # substitute the user's path here, if any
if [ -n "$USER_SPECIFIED_DIR" ]; then
  OUTPUT_DIR="$USER_SPECIFIED_DIR"
else
  BASE="static_analysis_codeql"
  N=1
  while [ -e "${BASE}_${N}" ]; do
    N=$((N + 1))
  done
  OUTPUT_DIR="${BASE}_${N}"
fi
mkdir -p "$OUTPUT_DIR"

The output directory is resolved once at the start before any workflow executes. All workflows receive $OUTPUT_DIR and store their artifacts there:

$OUTPUT_DIR/
├── rulesets.txt                 # Selected query packs (logged after Step 3)
├── codeql.db/                   # CodeQL database (dir containing codeql-database.yml)
├── build.log                    # Build log
├── codeql-config.yml            # Exclusion config (interpreted languages)
├── diagnostics/                 # Diagnostic queries and CSVs
├── extensions/                  # Data extension YAMLs
├── raw/                         # Unfiltered analysis output
│   ├── results.sarif
│   └── run-all.qls | important-only.qls
└── results/                     # Final results (filtered for important-only, copied for run-all)
    └── results.sarif
Database Discovery

A CodeQL database is identified by the presence of a codeql-database.yml marker file inside its directory. When searching for existing databases, always collect all matches — there may be multiple databases from previous runs or for different languages.

Discovery command. find_databases.sh prints one database path per line, filtering out the marker files a failed build leaves behind. Build the array in the same block that selects from it — each Bash call is a fresh shell, so an array built here is empty by the next call, and the run concludes there is no database:

# Command substitution, not `done < <(...)`: a process substitution discards the script's
# exit status, so "codeql is not on this shell's PATH" (exit 2) would arrive as an empty
# list and route to "build a new database" with three good ones sitting on disk.
if ! DB_LIST=$("{baseDir}/scripts/find_databases.sh" "${OUTPUT_DIR:-.}" .); then
  echo "ERROR: database discovery failed — see the message above" >&2
  exit 1
fi

FOUND_DBS=()
while IFS= read -r db; do
  [ -n "$db" ] || continue
  FOUND_DBS+=("$db")
done <<<"$DB_LIST"

echo "Found ${#FOUND_DBS[@]} existing database(s)"

# The metadata the selection prompt needs, collected here rather than in a block of its
# own: FOUND_DBS is gone by the next Bash call, and a loop over an array that no longer
# exists prints nothing and reports success.
for db in "${FOUND_DBS[@]}"; do
  CODEQL_LANG=$(codeql resolve database --format=json -- "$db" 2>/dev/null | jq -r '.languages[0]')
  CREATED=$(grep '^creationMetadata:' -A5 "$db/codeql-database.yml" 2>/dev/null | grep 'creationTime' | awk '{print $2}')
  echo "$db — language: $CODEQL_LANG, created: $CREATED"
done

Never assume a database is named codeql.db — discover it by its marker file.

When multiple databases are found: use AskUserQuestion to let the user select which database to use, or to build a new one, from the language and creation time printed above. AskUserQuestion takes at most four options, so with more databases than that, offer the three most recent plus "Build a new database" and list the rest in the prompt text. Skip AskUserQuestion if the user explicitly stated which database to use or to build a new one in their prompt.

Quick Start

For the common case ("scan this codebase for vulnerabilities"):

# Verify CodeQL is installed. Stop here if it is not — every later command fails with
# a less informative error, and the run wastes a build cycle before saying why.
if ! command -v codeql >/dev/null 2>&1; then
  echo "ERROR: codeql not found on PATH. Install it with one of:" >&2
  echo "  gh extension install github/gh-codeql   # then: gh codeql install-stub" >&2
  echo "  brew install --cask codeql" >&2
  echo "  https://github.com/github/codeql-action/releases  (codeql-bundle)" >&2
  exit 1
fi

# jq parses `codeql resolve database --format=json` in the very next step. Without it
# CODEQL_LANG comes back empty and the run continues against the wrong language.
if ! command -v jq >/dev/null 2>&1; then
  echo "ERROR: jq not found on PATH (brew install jq / apt install jq)" >&2
  exit 1
fi

# uv runs both guard scripts and both suite generators. Check it here rather than at
# suite generation, which is after the build — otherwise a machine without uv spends
# the whole build before failing.
if ! command -v uv >/dev/null 2>&1; then
  echo "ERROR: uv not found on PATH (https://docs.astral.sh/uv/getting-started/)" >&2
  exit 1
fi

codeql --version

Then resolve OUTPUT_DIR using the block in Output Directory above — it honours a user-specified directory, which a bare auto-increment does not.

Then execute the full pipeline: build database → create data extensions → run analysis using the workflows below.

Rationalizations to Reject

These shortcuts lead to missed findings. Do not accept them:

  • "security-extended is enough" - It is the baseline. Always check if Trail of Bits packs and Community Packs are available for the language. They catch categories security-extended misses entirely.

  • "security-and-quality is the broadest suite" - security-and-quality excludes all experimental/ query paths. For run-all mode, import both security-and-quality and security-experimental. The delta is 1–52 queries depending on the language.

  • "The database built, so it's good" - A database that builds does not mean it extracted well. Always run quality assessment and check file counts against expected source files.

  • "Data extensions aren't needed for standard frameworks" - Even Django/Spring apps have custom wrappers that CodeQL does not model. Skipping extensions means missing vulnerabilities.

  • "build-mode=none is fine for compiled languages" - It produces severely incomplete analysis. Only use as an absolute last resort. On macOS, try the arm64 toolchain workaround or Rosetta first.

  • "The build fails on macOS, just use build-mode=none" - Exit code 137 is caused by arm64e/arm64 mismatch, not a fundamental build failure. See macos-arm64e-workaround.md.

  • "No findings means the code is secure" - Run check_db_quality.py and verify_query_suite.py and report that they passed. Without them, zero findings and a database that extracted nothing are the same output.

  • "I'll just run the default suite" / "I'll just pass the pack names directly" - Each pack's defaultSuiteFile applies hidden filters and can produce zero results. Always use an explicit suite reference.

  • "I'll put files in the current directory" - All generated files must go in $OUTPUT_DIR. Scattering files in the working directory makes cleanup impossible and risks overwriting previous runs.

  • "Just use the first database I find" - Multiple databases may exist for different languages or from previous runs. When more than one is found, present all options to the user. Only skip the prompt when the user already specified which database to use.

  • "The user said 'scan', that means they want me to pick a database" - "Scan" is not database selection. If multiple databases exist and the user didn't name one, ask.


Workflow Selection

This skill has three workflows. Once a workflow is selected, execute it step by step without skipping phases.

These runs are long. A database build has four fallback methods, so use the task tools to track progress. Decide which steps are worth tracking based on the run.

WorkflowPurpose
build-databaseCreate CodeQL database using build methods in sequence
create-data-extensionsDetect or generate data extension models for project APIs
run-analysisSelect rulesets, execute queries, process results
Building unattended

This plugin ships /static-analysis:codeql-build, which runs the build-database steps end to end: detect the language and toolchain, walk the method ladder applying fixes from build-fixes.md between rungs, and enforce the quality gate.

/static-analysis:codeql-build {"target": "/abs/path", "lang": "cpp"}

It asks nothing. Every method failing, and a database that built but sits below the quality threshold, come back as statuses — no-method-succeeded and built-below-threshold — for you to act on here, because whether the remaining extractor errors are confined to code nobody needs analysed is a judgement call the run cannot make.

Use it when the build is the long, uncertain part and you want it driven to a conclusion. Work build-database.md by hand when you want a say in which method is tried, or when a build failure needs interpreting as it happens.

Auto-Detection Logic

If user explicitly specifies what to do (e.g., "build a database", "run analysis on ./my-db"), execute that workflow directly. Do NOT call AskUserQuestion for database selection if the user's prompt already makes their intent clear — e.g., "build a new database", "analyze the codeql database in static_analysis_codeql_2", "run a full scan from scratch".

Default pipeline for "test", "scan", "analyze", or similar: Discover existing databases using the command in Database Discovery above, then decide.

ConditionAction
No databases foundResolve new $OUTPUT_DIR, execute build → extensions → analysis (full pipeline)
One database foundUse AskUserQuestion: reuse it or build new?
Multiple databases foundUse AskUserQuestion, capped at four options — see Database Discovery
User explicitly stated intentSkip AskUserQuestion, act on their instructions directly
Database Selection Prompt

When existing databases are found and the user did not explicitly specify which to use, present them via AskUserQuestion under the header "Existing CodeQL Databases". Label each option with the path, language, and creation time collected above — ./static_analysis_codeql_1/codeql.db (language: python, created: 2026-02-24) — and make the last option "Build a new database".

After selection:

  • If user picks an existing database: Set $OUTPUT_DIR to its parent directory (or the directory containing it), set $DB_NAME to the selected path, then proceed to extensions → analysis.

  • If user picks "Build new": Resolve a new $OUTPUT_DIR, execute build → extensions → analysis.

General Decision Prompt

If neither the database nor the workflow is clear from the prompt, offer the four workflows via AskUserQuestion — full scan (recommended), build database, create data extensions, run analysis — naming any databases found and the resolved $OUTPUT_DIR.


Reference Index

FileContent
Scripts
scripts/verify_query_suite.pyFails a suite that resolves to zero queries. The generation scripts run it; invoke by hand only for a reused or hand-edited suite
scripts/check_db_quality.pyFails a database with no analysable source. Run after every build
scripts/build_log.shlog_step/run_logged helpers; source before any build step
scripts/find_databases.shPrints every database that codeql resolve database accepts, one per line. Build your array from it in the block that reads it
scripts/generate_suite.shWrites the run-all or important-only .qls and verifies it resolves to a non-zero query count
References — the three workflows are listed under Workflow Selection
references/macos-arm64e-workaround.mdApple Silicon build tracing workarounds
references/build-fixes.mdBuild failure fix catalog
references/quality-assessment.mdDatabase quality metrics and improvements
references/extension-yaml-format.mdData extension YAML column definitions and examples
references/sarif-processing.mdjq commands for SARIF output processing
references/diagnostic-query-templates.mdQL queries for source/sink enumeration
references/important-only-suite.mdImportant-only suite template and generation
references/run-all-suite.mdRun-all suite template
references/ruleset-catalog.mdAvailable query packs by language
references/threat-models.mdThreat model configuration
references/language-details.mdLanguage-specific build and extraction details
references/performance-tuning.mdMemory, threading, and timeout configuration

Success Criteria

A complete CodeQL analysis run should satisfy:

  • [ ] Output directory resolved (user-specified or auto-incremented default)

  • [ ] All generated files stored inside $OUTPUT_DIR

  • [ ] Database built (discovered via codeql-database.yml marker) and {baseDir}/scripts/check_db_quality.py exited zero

  • [ ] Data extensions evaluated — either created in $OUTPUT_DIR/extensions/ or explicitly skipped with justification

  • [ ] Analysis run with explicit suite reference (not default pack suite), and {baseDir}/scripts/verify_query_suite.py exited zero for it

  • [ ] All installed query packs (official + Trail of Bits + Community) used or explicitly excluded

  • [ ] Selected query packs logged to $OUTPUT_DIR/rulesets.txt

  • [ ] Unfiltered results preserved in $OUTPUT_DIR/raw/results.sarif

  • [ ] Final results in $OUTPUT_DIR/results/results.sarif (filtered for important-only, copied for run-all)

  • [ ] Zero-finding results investigated (database quality, model coverage, suite selection)

  • [ ] Build log preserved at $OUTPUT_DIR/build.log with all commands, fixes, and quality assessments

Files

scripts/test_shell_blocks.py

"""Lint the shell that lives inside this skill's markdown.

`make shell` covers `*.sh` files; this skill ships none, so nothing checked its
commands. That gap hid one bug class in nine places: a pipeline's exit status used as
a success test, which without `pipefail` belongs to the formatter, not the command.
"""

from __future__ import annotations

import re
import subprocess
from pathlib import Path

import pytest

SKILL_ROOT = Path(__file__).resolve().parent.parent
BASH_BLOCK = re.compile(r"^```bash\n(.*?)^```", re.MULTILINE | re.DOTALL)

# Defined in build_log.sh alongside `set -o pipefail`, so it preserves exit status by
# construction; callers need not repeat the setting.
SAFE_PIPE_WRAPPER = "run_logged"

# A single `|`. `if [ -f a ] || [ -f b ]` is a logical or, not a pipeline, and matching it
# made two blocks look like offenders that the whole-block exemption then waved through.
PIPE = r"(?<!\|)\|(?!\|)"
PIPED_TO_TEE = re.compile(PIPE + r"\s*tee\b")
PIPELINE_IN_CONDITION = re.compile(r"if\s+!?\s*[^|]*" + PIPE)
# The line itself runs under the wrapper, wherever it sits in the block.
WRAPPED = re.compile(r"^(if\s+!?\s*)?" + SAFE_PIPE_WRAPPER + r"\b")
# Sourcing the helpers sets pipefail for the rest of the block, exactly as writing it out
# would. Matching the bare token `run_logged` anywhere in the block did not mean that.
SOURCES_LOG_HELPERS = re.compile(r"^\s*(\.|source)\s+.*build_log\.sh")


def _status_consuming_pipelines(source: str) -> list[str]:
    """Lines whose pipeline *exit status* is consumed.

    `VAR=$(cmd | wc -l)` consumes output and is fine. `cmd | tee "$LOG"` as a statement,
    or a pipeline inside an `if`, decides what happens next.
    """
    found: list[str] = []
    for raw in source.splitlines():
        stripped = raw.strip()
        if stripped.startswith("#"):
            continue
        # Output capture — status is not what is being used.
        if re.search(r"(\$\(|`|=\s*\$\()", stripped) and not stripped.startswith("if "):
            continue
        if PIPED_TO_TEE.search(stripped) or PIPELINE_IN_CONDITION.match(stripped):
            found.append(stripped)
    return found


def _sets_pipefail(source: str) -> bool:
    """pipefail is block-scoped, so set it directly or inherit it by sourcing the helpers."""
    return (
        "set -o pipefail" in source
        or "set -euo pipefail" in source
        or any(SOURCES_LOG_HELPERS.match(raw) for raw in source.splitlines())
    )


def _unpreserved_pipelines(source: str) -> list[str]:
    """Status-consuming pipelines in `source` that read the formatter's status instead.

    The wrapper exemption is applied per line. Applied per block — "does `run_logged`
    appear anywhere in this source" — a bare `cmd | tee "$LOG_FILE"` added later to a
    block that already used the wrapper elsewhere passed silently, which is the exact
    regression this check exists to catch.
    """
    if _sets_pipefail(source):
        return []
    return [line for line in _status_consuming_pipelines(source) if not WRAPPED.match(line)]


def _markdown_files() -> list[Path]:
    return sorted(p for p in SKILL_ROOT.rglob("*.md") if ".pytest_cache" not in p.parts)


def _blocks() -> list[tuple[Path, int, str]]:
    """Every bash block in the skill, as (file, line number, source)."""
    found: list[tuple[Path, int, str]] = []
    for path in _markdown_files():
        text = path.read_text(encoding="utf-8")
        for match in BASH_BLOCK.finditer(text):
            line = text.count("\n", 0, match.start()) + 1
            found.append((path, line, match.group(1)))
    return found


ALL_BLOCKS = _blocks()


def _ident(path: Path, line: int) -> str:
    return f"{path.relative_to(SKILL_ROOT)}:{line}"


def test_extraction_found_blocks() -> None:
    """Guard the guard: a broken regex would turn every test below into a no-op."""
    assert len(ALL_BLOCKS) >= 20, (
        f"only {len(ALL_BLOCKS)} bash blocks extracted from {SKILL_ROOT} — the extractor "
        f"is broken, not the skill"
    )


def test_every_block_is_syntactically_valid() -> None:
    """Every block must parse. Catches unterminated heredocs and quoting errors."""
    offenders = []
    for path, line, source in ALL_BLOCKS:
        # <BUILD_CMD>, <mode> etc. are documentation, not shell — neutralise before parsing.
        cleaned = re.sub(r"<[A-Za-z0-9_ .-]+>", "PLACEHOLDER", source)
        result = subprocess.run(["bash", "-n"], input=cleaned, capture_output=True, text=True)
        if result.returncode != 0:
            offenders.append(f"{_ident(path, line)}: {result.stderr.strip()}")

    assert not offenders, "a block is not valid bash:\n  " + "\n  ".join(offenders)


def test_no_block_consumes_an_unpreserved_pipeline_status() -> None:
    """A pipeline whose *exit status* is consumed must preserve the real one.

    Without pipefail that status is the formatter's, which is always 0. No block ships a
    bare pipeline today — every one goes through `run_logged` — so this is a tripwire for
    new markdown, and it scans every block in one test rather than parametrizing over all
    of them to skip the ones with no pipeline. What proves the detector still fires is
    `test_detector_flags_unsafe_pipelines` below.
    """
    offenders = [
        f"{_ident(path, line)}: {offender}"
        for path, line, source in ALL_BLOCKS
        for offender in _unpreserved_pipelines(source)
    ]
    assert not offenders, (
        f"a block decides control flow on a pipeline's exit status without "
        f"`set -o pipefail` or {SAFE_PIPE_WRAPPER}, so it reads the formatter's status "
        f"(always 0) rather than the command's:\n  " + "\n  ".join(offenders)
    )


# The detector matches no block in the skill today, so these fixtures are the only thing
# that would notice it silently breaking. Kept as tables inside two tests rather than
# parametrized: seven pytest cases for one detector was more ceremony than it earns.
_BARE_TEE = 'codeql database analyze "$DB_NAME" suite.qls 2>&1 | tee -a "$LOG_FILE"'

MUST_FLAG = (
    ('codeql database create "$DB_NAME" --language=cpp 2>&1 | tee -a "$LOG_FILE"', None),
    ('if codeql resolve queries "$SUITE_FILE" | grep -q "\\.ql"; then echo ok; fi', None),
    # The regression the per-line exemption exists for: under the old whole-block test
    # `run_logged` appearing anywhere waved through every pipeline in the block.
    (f'run_logged codeql database create "$DB_NAME" --language=cpp\n{_BARE_TEE}\n', [_BARE_TEE]),
)

MUST_PASS = (
    # Output capture: the pipeline's status is never read.
    'COUNT=$(codeql resolve queries "$SUITE_FILE" | wc -l)',
    # Logical or, not a pipeline.
    "if [ -f setup.py ] || [ -f pyproject.toml ]; then echo python; fi",
    # The wrapper sets pipefail itself.
    'run_logged codeql database create "$DB_NAME" --language=cpp',
    # `. build_log.sh` runs `set -o pipefail`, so the rest of the block is genuinely safe.
    f'. "{{baseDir}}/scripts/build_log.sh"\n{_BARE_TEE}\n',
)


def test_detector_flags_unsafe_pipelines() -> None:
    """Guard the guard: with no offending block left in the skill, nothing else would
    notice if this detector stopped matching."""
    for source, expected in MUST_FLAG:
        assert _unpreserved_pipelines(source) == (expected or [source]), (
            f"the detector stopped flagging:\n  {source}"
        )


def test_detector_passes_safe_pipelines() -> None:
    """False positives get silenced, and a silenced check catches nothing."""
    for source in MUST_PASS:
        assert _unpreserved_pipelines(source) == [], (
            f"the detector now fires on safe shell, which is how it gets disabled:\n  {source}"
        )


# Everything build_log.sh defines. Used in a block that never sourced the file, a helper is
# 127 and LOG_FILE is an append to "".
LOG_HELPERS = ("run_logged", "log_step", "log_cmd", "log_result", "LOG_FILE")
USES_LOG_HELPER = re.compile(r"\b(" + "|".join(LOG_HELPERS) + r")\b")


def _unsourced_helper_uses(source: str) -> list[str]:
    """Lines that use a build_log.sh helper in a block that never sources build_log.sh."""
    if any(SOURCES_LOG_HELPERS.match(raw) for raw in source.splitlines()):
        return []
    lines = (raw.strip() for raw in source.splitlines())
    return [line for line in lines if not line.startswith("#") and USES_LOG_HELPER.search(line)]


def test_helper_uses_are_sourced_in_the_same_block() -> None:
    """A helper is a function, and a function does not survive into the next Bash call.

    Same rule as the array check below, higher cost: 127 is a non-zero status, so the ladder
    in build-database.md records the method as failed and walks to the next one. Method 2m-a
    was the case that motivated this: the first rung an affected Mac lands on called
    `log_step` without sourcing the helpers.
    """
    offenders = [
        f"{_ident(path, line)}: {offender}"
        for path, line, source in ALL_BLOCKS
        for offender in _unsourced_helper_uses(source)
    ]
    assert not offenders, (
        "a block uses a build_log.sh helper without sourcing it. Each block is a separate "
        "Bash call, so the helper is undefined there and the line exits 127. Add `. "
        '"{baseDir}/scripts/build_log.sh" || exit 1` to the block:\n  ' + "\n  ".join(offenders)
    )


HELPERS_MUST_FLAG = (
    'log_step "METHOD 2m-a: macOS arm64 Homebrew compiler"',
    'run_logged codeql database create "$DB_NAME" --language=cpp',
    # Not a function, but build_log.sh is what defaults it. Unsourced, this appends to "".
    'echo "=== Build Complete ===" >> "$LOG_FILE"',
)

HELPERS_MUST_PASS = (
    '. "{baseDir}/scripts/build_log.sh" || exit 1\nlog_step "building"',
    "source {baseDir}/scripts/build_log.sh\nrun_logged make",
    # A comment about the helpers, not a call. Blocks carry those.
    "# run_logged returns the build's exit status. Check it before moving on.",
)


def test_detector_flags_unsourced_helpers() -> None:
    """Guard the guard: no block violates the rule now, so nothing else would notice this
    detector going quiet."""
    for source in HELPERS_MUST_FLAG:
        assert _unsourced_helper_uses(source) == [source], (
            f"the detector stopped flagging:\n  {source}"
        )


def test_detector_passes_sourced_helpers() -> None:
    """False positives get silenced, and a silenced check catches nothing."""
    for source in HELPERS_MUST_PASS:
        assert _unsourced_helper_uses(source) == [], (
            f"the detector now fires on a block that sources the helpers, which is how it "
            f"gets disabled:\n  {source}"
        )


def test_the_sourcing_rule_has_something_to_check() -> None:
    """Guard the guard: if the token list or the block extractor broke, every block would
    look helper-free and the check above would inspect nothing."""
    users = [
        _ident(path, line)
        for path, line, source in ALL_BLOCKS
        if any(USES_LOG_HELPER.search(raw) for raw in source.splitlines())
    ]
    assert len(users) >= 10, (
        f"only {len(users)} blocks use a build_log.sh helper across {len(ALL_BLOCKS)} blocks "
        f"in {SKILL_ROOT} — the detector is broken, not the skill"
    )


# `codeql database finalize` after a failed `trace-command` writes a database that resolves
# and holds nothing, so the build method reports success. Something has to gate it: a test on
# the same line, or an enclosing `if` the step already set, which shows as indentation.
FINALIZE = "codeql database finalize"
GATED_ON_THE_LINE = re.compile(r"^(if|elif)\s+!|&&")


def _ungated_finalizes(source: str) -> list[str]:
    """`codeql database finalize` calls that run whatever the step before them returned."""
    found: list[str] = []
    for raw in source.splitlines():
        stripped = raw.strip()
        if FINALIZE not in stripped or stripped.startswith("#"):
            continue
        # Indented means it sits inside an enclosing block; 2m-a's is under `if $TRACE_OK`.
        if raw != stripped or GATED_ON_THE_LINE.search(stripped):
            continue
        found.append(stripped)
    return found


def test_finalize_is_gated_on_the_step_before_it() -> None:
    """A build method that finalizes a database it failed to populate reports success.

    `build_log.sh` deliberately omits `set -e` so the ladder survives a failed method, which
    leaves each block responsible for its own sequencing. Method 3 in build-database.md ran
    four `run_logged` calls in a row, so a `trace-command` that failed on build step 2 still
    reached `finalize`, and `codeql resolve database` then succeeded.
    """
    offenders = [
        f"{_ident(path, line)}: {offender}"
        for path, line, source in ALL_BLOCKS
        for offender in _ungated_finalizes(source)
    ]
    assert not offenders, (
        "a block finalizes a database without checking that the step before it succeeded, so "
        "a failed trace-command still produces a database that resolves and holds nothing:\n  "
        + "\n  ".join(offenders)
    )


FINALIZE_MUST_FLAG = (
    'run_logged codeql database finalize "$DB_NAME"',
    'codeql database finalize "$DB_NAME"',
)

FINALIZE_MUST_PASS = (
    'elif ! run_logged codeql database finalize "$DB_NAME"; then',
    'if ! run_logged codeql database finalize "$DB_NAME"; then',
    # 2m-a's shape: the trace loop sets TRACE_OK, and the finalize sits inside that test.
    'if $TRACE_OK; then\n  run_logged codeql database finalize "$DB_NAME"\nfi',
)


def test_detector_flags_ungated_finalize() -> None:
    """Guard the guard: two call sites, both gated now, so nothing else would notice this
    detector going quiet."""
    for source in FINALIZE_MUST_FLAG:
        assert _ungated_finalizes(source) == [source], f"the detector stopped flagging:\n  {source}"


def test_detector_passes_gated_finalize() -> None:
    """False positives get silenced, and a silenced check catches nothing."""
    for source in FINALIZE_MUST_PASS:
        assert _ungated_finalizes(source) == [], (
            f"the detector now fires on a gated finalize, which is how it gets disabled:\n"
            f"  {source}"
        )


def test_the_finalize_rule_has_something_to_check() -> None:
    """Guard the guard: no `finalize` anywhere means the check above inspects nothing."""
    sites = [_ident(path, line) for path, line, source in ALL_BLOCKS if FINALIZE in source]
    assert len(sites) >= 2, (
        f"only {len(sites)} `{FINALIZE}` call sites found across {len(ALL_BLOCKS)} blocks in "
        f"{SKILL_ROOT} — the detector is broken, not the skill"
    )


def test_exit_status_is_not_captured_after_a_pipe() -> None:
    """`EXIT_CODE=$?` after a pipeline captures the wrong process.

    This is how the arm64e exit-137 check was neutered.
    """
    offenders = []
    for path, line, source in ALL_BLOCKS:
        if "set -o pipefail" in source or "set -euo pipefail" in source:
            continue
        lines = source.splitlines()
        for index, raw in enumerate(lines[:-1]):
            if raw.strip().startswith("#") or "|" not in raw:
                continue
            if re.search(r"\|\s*(tee|wc|head|tail)\b", raw) and re.match(
                r"\s*\w+=\$\?", lines[index + 1]
            ):
                offenders.append(
                    f"{_ident(path, line)}: {raw.strip()} / {lines[index + 1].strip()}"
                )

    assert not offenders, (
        "a block captures $? straight after a pipe without pipefail, so it records the "
        "formatter's status rather than the command's:\n  " + "\n  ".join(offenders)
    )


def test_no_unquoted_command_string_expansion() -> None:
    """`CMD="a b c"` then `$CMD` word-splits on any path containing a space."""
    offenders = [
        f"{_ident(path, line)}: {raw.strip()}"
        for path, line, source in ALL_BLOCKS
        for raw in source.splitlines()
        if re.match(r"\s*\$(CMD|BUILD_CMD)\b", raw) and not raw.strip().startswith("#")
    ]
    assert not offenders, (
        "a block runs a command built as a string, unquoted. Pass argv as a list (see "
        "run_logged) so paths with spaces survive:\n  " + "\n  ".join(offenders)
    )


# Variables that hold a filesystem path. An unquoted expansion of any of these splits on
# a space, so `$OUTPUT_DIR` under "~/My Scans" silently targets the wrong path.
PATH_VARS = (
    "DB_NAME",
    "OUTPUT_DIR",
    "SUITE_FILE",
    "RAW_DIR",
    "RESULTS_DIR",
    "LOG_FILE",
    "DIAG_DIR",
)
UNQUOTED_PATH_VAR = re.compile(r"\$\{?(" + "|".join(PATH_VARS) + r")\}?(?![\w\"])")


def _outside_heredoc(source: str):
    """Yield (line, is_shell) — heredoc bodies are literal text, not shell."""
    terminator: str | None = None
    for raw in source.splitlines():
        if terminator is not None:
            if raw.strip() == terminator:
                terminator = None
            yield raw, False
            continue
        opener = re.search(r"<<-?\s*'?([A-Za-z_][A-Za-z0-9_]*)'?", raw)
        yield raw, True
        if opener:
            terminator = opener.group(1)


def test_path_variables_are_quoted() -> None:
    """Every path variable must be quoted at the point of use.

    The narrower CMD/BUILD_CMD check above missed the production command:
    `codeql database analyze $DB_NAME` sits in run-analysis Step 4 and breaks on any
    output directory containing a space.
    """
    offenders = []
    for path, line, source in ALL_BLOCKS:
        for raw, is_shell in _outside_heredoc(source):
            stripped = raw.strip()
            if not is_shell or stripped.startswith("#"):
                continue
            for match in UNQUOTED_PATH_VAR.finditer(raw):
                # Inside double quotes is fine; count quotes before the match to tell.
                if raw[: match.start()].count('"') % 2 == 1:
                    continue
                offenders.append(f"{_ident(path, line)}: {stripped}")
                break

    assert not offenders, (
        "a block expands a path variable unquoted, so it word-splits on any path "
        "containing a space:\n  " + "\n  ".join(offenders)
    )


ARRAY_ASSIGN = re.compile(r"^\s*([A-Z_][A-Z0-9_]*)=\(")

# Array names assigned anywhere in the skill's bash blocks.
ARRAY_NAMES = frozenset(
    m.group(1)
    for _, _, blk in ALL_BLOCKS
    for raw in blk.splitlines()
    if (m := ARRAY_ASSIGN.match(raw))
)


def test_array_names_were_found() -> None:
    """Guard the guard: with no names collected, the scan below inspects nothing and
    passes. A skip here would report that as success."""
    assert ARRAY_NAMES, (
        f"no `NAME=()` assignment found in any of the {len(ALL_BLOCKS)} blocks in "
        f"{SKILL_ROOT} — the collector is broken, not the skill"
    )


def test_arrays_are_expanded_with_subscript() -> None:
    """`$ARR` on an array yields only element 0, silently.

    SKILL.md built FOUND_DBS as an array, counted it with ${#FOUND_DBS[@]}, then looped
    with `for db in $FOUND_DBS` — so multi-database discovery always offered exactly one
    database, contradicting three other sections of the same file.

    Keyed on assignment rather than a name list, so a new array is covered on the day it
    is written. Names are collected across every block and checked against every block, so
    a bad expansion is caught wherever it sits relative to the assignment.
    """
    offenders = []
    for path, line, source in ALL_BLOCKS:
        for raw in source.splitlines():
            stripped = raw.strip()
            if stripped.startswith("#"):
                continue
            for name in ARRAY_NAMES:
                # Bare $NAME or ${NAME}: no [@], [*], or [n] subscript, and not ${#NAME[@]}.
                if re.search(rf"(?<!#)\$\{{?{name}\}}?(?!\[|\w)", raw):
                    offenders.append(f"{_ident(path, line)}: {stripped}")
                    break

    assert not offenders, (
        "an array is expanded without a subscript, which yields only its first element. "
        'Use "${NAME[@]}":\n  ' + "\n  ".join(offenders)
    )


# A subscripted read: "${NAME[@]}", ${#NAME[@]}, ${NAME[0]}. Bare $NAME is the other bug,
# caught by the test above.
def _subscripted_reads(source: str, name: str) -> bool:
    return bool(re.search(rf"\$\{{#?{name}\[", source))


def _assigns(source: str, name: str) -> bool:
    return any((m := ARRAY_ASSIGN.match(raw)) and m.group(1) == name for raw in source.splitlines())


def test_arrays_are_consumed_in_the_block_that_builds_them() -> None:
    """An array does not survive into the next Bash call, so neither half works alone.

    Each fenced block is its own Bash invocation. SKILL.md built FOUND_DBS in the Database
    Discovery block and looped over it in the next one to print each database's language
    and creation time: the loop iterated zero times and printed nothing, and the selection
    prompt it feeds had no metadata to offer — one paragraph after the text stating the
    rule. Nothing caught it, because both halves are correct read on their own.

    Scoped to arrays because that is the case where the failure is silent: an unset array
    expands to nothing and the loop simply does not run. An unset scalar usually surfaces
    as a command that fails.
    """
    offenders = []
    for path, line, source in ALL_BLOCKS:
        for name in ARRAY_NAMES:
            if _subscripted_reads(source, name) and not _assigns(source, name):
                offenders.append(f"{_ident(path, line)}: reads ${{{name}[@]}}, never builds it")

    assert not offenders, (
        "a block reads an array it does not build. Each block is a separate Bash call, so "
        "the array is empty there and the loop over it silently does nothing — build it in "
        "the same block that reads it:\n  " + "\n  ".join(offenders)
    )


def test_the_same_block_rule_has_something_to_check() -> None:
    """Guard the guard: with no subscripted read anywhere, the check above inspects nothing.

    Also pins the detector itself, since no block in the skill violates the rule today and
    a detector that stopped matching would look identical to a clean skill.
    """
    reads = [
        (path, line, name)
        for path, line, source in ALL_BLOCKS
        for name in ARRAY_NAMES
        if _subscripted_reads(source, name)
    ]
    assert len(reads) >= 2, (
        f"only {len(reads)} subscripted array reads found across {len(ALL_BLOCKS)} blocks — "
        f"the detector is broken, not the skill"
    )
    split = 'FOUND_DBS=()\nFOUND_DBS+=("$db")\n'
    assert _subscripted_reads('for db in "${FOUND_DBS[@]}"; do :; done', "FOUND_DBS")
    assert not _assigns('for db in "${FOUND_DBS[@]}"; do :; done', "FOUND_DBS")
    assert _assigns(split, "FOUND_DBS"), "an append must not be mistaken for the declaration"


# find_databases.sh exits 2 when codeql is missing from the calling shell's PATH, precisely
# so that state cannot be mistaken for "this project has no databases". `done < <(script)`
# throws the status away: the loop's status is the loop's, and the substitution's is
# unobservable. Command substitution keeps it, so the caller can tell the two apart.
DISCOVERY_SCRIPT = "find_databases.sh"
PROCESS_SUBSTITUTION = re.compile(r"<\s*<\(")


def _discovery_without_status(source: str) -> list[str]:
    """Lines that run the discovery script through a process substitution."""
    offenders = []
    for raw in source.splitlines():
        stripped = raw.strip()
        if stripped.startswith("#") or DISCOVERY_SCRIPT not in stripped:
            continue
        if PROCESS_SUBSTITUTION.search(stripped):
            offenders.append(stripped)
    return offenders


def test_discovery_exit_status_is_observed() -> None:
    """All three callers read discovery through a process substitution and dropped its status.

    Failure scenario: codeql is not on this Bash call's PATH — a fresh shell each block, so
    the preflight that checked it ran in a different one. The script prints its ERROR to
    stderr and exits 2, the array comes back empty, and the caller reports "No CodeQL
    database found" while three good databases sit on disk. The user is then walked through
    a full rebuild that fails for the same reason at the same place.
    """
    offenders = [
        f"{_ident(path, line)}: {offender}"
        for path, line, source in ALL_BLOCKS
        for offender in _discovery_without_status(source)
    ]
    assert not offenders, (
        "a block reads find_databases.sh through a process substitution, whose exit status "
        "is unobservable, so exit 2 (no codeql on PATH) reads as an empty result. Use "
        '`if ! DB_LIST=$("{baseDir}/scripts/find_databases.sh" …); then … fi` and loop over '
        '`<<<"$DB_LIST"`:\n  ' + "\n  ".join(offenders)
    )


DISCOVERY_MUST_FLAG = (
    'done < <("{baseDir}/scripts/find_databases.sh" "${OUTPUT_DIR:-.}" .)',
    "done < <(find_databases.sh)",
    # Spacing between the redirect and the substitution is the caller's habit, not a signal.
    'done <  <("{baseDir}/scripts/find_databases.sh" .)',
)

DISCOVERY_MUST_PASS = (
    'if ! DB_LIST=$("{baseDir}/scripts/find_databases.sh" "${OUTPUT_DIR:-.}" .); then',
    'done <<<"$DB_LIST"',
    # Prose about the script, which the blocks carry above every call site.
    "# Command substitution, not `done < <(...)`: find_databases.sh exits 2 when codeql is "
    "missing.",
)


def test_detector_flags_discovery_process_substitution() -> None:
    """Guard the guard: no block violates the rule now, so nothing else would notice this
    detector going quiet."""
    for source in DISCOVERY_MUST_FLAG:
        assert _discovery_without_status(source) == [source], (
            f"the detector stopped flagging:\n  {source}"
        )


def test_detector_passes_status_checked_discovery() -> None:
    """False positives get silenced, and a silenced check catches nothing."""
    for source in DISCOVERY_MUST_PASS:
        assert _discovery_without_status(source) == [], (
            f"the detector now fires on a caller that does check the status, which is how it "
            f"gets disabled:\n  {source}"
        )


def test_the_discovery_rule_has_something_to_check() -> None:
    """Guard the guard: if the block extractor or the script name broke, every block would
    look discovery-free and the check above would inspect nothing."""
    callers = [
        _ident(path, line)
        for path, line, source in ALL_BLOCKS
        if any(
            DISCOVERY_SCRIPT in raw and not raw.strip().startswith("#")
            for raw in source.splitlines()
        )
    ]
    assert len(callers) >= 3, (
        f"only {len(callers)} blocks call {DISCOVERY_SCRIPT} across {len(ALL_BLOCKS)} blocks "
        f"in {SKILL_ROOT} — SKILL.md, run-analysis.md and create-data-extensions.md each do, "
        f"so the detector is broken, not the skill"
    )


# Bodies of `python3 -c '…'`, either quote style, on one line or many. Requiring a newline
# after the opening quote missed the two one-liners in create-data-extensions.md, and a
# missed block reports `skip` — indistinguishable from a block with no Python in it.
EMBEDDED_PYTHON = re.compile(r"""python3 -c (['"])(.*?)\1""", re.DOTALL)


def _embedded_python(source: str) -> list[str]:
    return [match.group(2) for match in EMBEDDED_PYTHON.finditer(source)]


def _embedded_python_bodies() -> list[tuple[str, str]]:
    """Every `python3 -c` body in the skill, as (where it came from, the source)."""
    return [
        (f"{_ident(path, line)}#{index}", body)
        for path, line, source in ALL_BLOCKS
        for index, body in enumerate(_embedded_python(source))
    ]


ALL_EMBEDDED_PYTHON = _embedded_python_bodies()


def test_embedded_python_extraction_still_matches() -> None:
    """Guard the guard: a regex that matched nothing would leave the compile check below
    running against an empty parameter set, which passes without inspecting anything.

    Two bodies today, both in create-data-extensions.md. Was three until
    quality-assessment.md stopped parsing baseline-info.json inline — check_db_quality.py
    reports baseline_loc, so the block was computing it twice.
    """
    assert len(ALL_EMBEDDED_PYTHON) >= 2, (
        f"only {len(ALL_EMBEDDED_PYTHON)} embedded python bodies extracted from "
        f"{SKILL_ROOT} — the extractor is broken, not the skill"
    )


@pytest.mark.parametrize(
    "snippet",
    (
        # create-data-extensions.md counts SARIF results this way.
        "BASELINE=$(python3 -c \"import json; print(len(json.load(open('x.sarif'))))\")",
        # The argv form, which the extractor must handle even though no doc uses it today.
        "LOC=$(python3 -c '\nimport json, sys\nprint(json.load(open(sys.argv[1])))\n' \"$DB\")",
    ),
)
def test_both_quote_styles_are_extracted(snippet: str) -> None:
    """Either form is real shell in this skill, and both must reach the compiler below."""
    assert _embedded_python(snippet)


@pytest.mark.parametrize(
    ("origin", "body"),
    ALL_EMBEDDED_PYTHON,
    ids=[origin for origin, _ in ALL_EMBEDDED_PYTHON],
)
def test_embedded_python_compiles(origin: str, body: str) -> None:
    """Python inside a bash block must parse.

    Quoting the shell string correctly and quoting the Python correctly are separate
    problems, and fixing one can break the other: moving a script from a double- to a
    single-quoted shell string leaves `\\"` escapes behind that are then literal
    backslashes to Python.
    """
    try:
        compile(body, "<embedded>", "exec")
    except SyntaxError as error:
        pytest.fail(f"{origin} embeds Python that does not parse: {error}\n{body}")

Requirements and compatibility

Written for: Claude Code

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, Names Claude Code tools, Needs Python

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/codeql · 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 codeql.zip