Code Pathfinder

by shivasurya (community) · Claude Desktop, Claude Code, OpenCode, macOS, Linux

MCP MCP Servers Open Source v2.1.1 · 25.04.2026 активный

Статический анализ кода для security-команд с межфайловым taint-анализом. Поиск уязвимостей, продвинутый структурный поиск, инсайты, поддержка MCP.

v2.1.1
25.04.2026 current

Установка
# Homebrew (рекомендуется)
brew install shivasurya/tap/pathfinder

# pip
pip install codepathfinder

# Docker
docker pull shivasurya/code-pathfinder:stable-latest
docker run --rm -v "$(pwd):/src" \
  shivasurya/code-pathfinder:stable-latest \
  scan --ruleset python/all --project /src

# Из исходного кода
git clone https://github.com/shivasurya/code-pathfinder
cd code-pathfinder/sast-engine
gradle buildGo
./build/go/pathfinder --help
показать оригинал переведено ИИ

Code Pathfinder - Open-source SAST with cross-file dataflow analysis

Open-source SAST engine that traces vulnerabilities across files and functions

Website · Docs · Rule Registry · MCP Server · Blog

Build GitHub Release Apache-2.0 License GitHub Stars Ask DeepWiki


Quick Start

Install:

brew install shivasurya/tap/pathfinder

Scan a Python project (rules download automatically):

pathfinder scan --ruleset python/all --project .

Scan Dockerfiles:

pathfinder scan --ruleset docker/all --project .

No config files, no API keys, no cloud accounts. Results in your terminal in seconds.


What is Code Pathfinder?

Code Pathfinder is an open-source static analysis engine that builds a graph of your codebase and traces how data flows through it. It parses source code into Abstract Syntax Trees, constructs call graphs across files, and runs taint analysis to find source-to-sink vulnerabilities that span multiple files and function boundaries.

v2.0 introduces cross-file dataflow analysis: trace user input from an HTTP handler in one file through helper functions and into a SQL query in another file. This is the kind of analysis that pattern-matching tools miss entirely.

Cross-File Taint Analysis

Most open-source SAST tools operate on single files. Code Pathfinder v2.0 tracks tainted data across file boundaries:

app.py:5    user_input = request.get("query")     ← Source: user-controlled input
  ↓ calls
db.py:12    cursor.execute(query)                  ← Sink: SQL execution

The engine builds a Variable Dependency Graph (VDG) per function, then connects them through inter-procedural taint transfer summaries. When user_input flows into a function parameter in another file, the taint propagates through the call graph to the sink.

How It Works

Source Code → Tree-sitter AST → Call Graph → Variable Dependency Graph → Taint Analysis → Findings
                                     ↓
                              Inter-procedural
                              Taint Summaries
                              (cross-file flows)
  1. Parse: Tree-sitter builds ASTs for Python, Dockerfiles, and Docker Compose files
  2. Index: Extract functions, call sites, parameters, and assignments into a queryable call graph
  3. Analyze: Build VDGs per function, resolve inter-procedural flows, run taint analysis
  4. Detect: Python-based security rules query the graph to find source-to-sink paths
  5. Report: Output findings as text, JSON, SARIF (GitHub Code Scanning), or CSV

190 Security Rules, Ready to Use

Rules download from CDN automatically. No need to clone the repo or manage rule files.

Language Bundles Rules Coverage
Python django, flask, aws_lambda, cryptography, jwt, lang, deserialization, pyramid 158 SQL injection, RCE, SSRF, path traversal, XSS, deserialization, crypto misuse, JWT vulnerabilities
Docker security, best-practice, performance 37 Root user, exposed secrets, image pinning, multi-stage builds, layer optimization
Docker Compose security, networking 10 Privileged mode, socket exposure, capability escalation, network isolation
# Scan with a specific bundle
pathfinder scan --ruleset python/django --project .

# Scan with multiple bundles
pathfinder scan --ruleset python/flask --ruleset python/jwt --project .

# Scan a single rule
pathfinder scan --ruleset python/PYTHON-DJANGO-SEC-001 --project .

# Scan all rules for a language
pathfinder scan --ruleset python/all --project .

Browse all rules with examples and test cases at the Rule Registry.

MCP Server for AI Coding Assistants

Code Pathfinder runs as an MCP server, giving Claude Code, Cursor, Cline, and other AI assistants access to call graphs, data flows, and security analysis. More context than LSP, focused on security and code structure.

pathfinder serve --project .

The MCP server exposes tools for querying the code graph: find callers/callees, trace data flows, search for patterns, and run security rules — all available to the AI assistant during code review or development.

Write Custom Rules

Security rules are Python scripts using the PathFinder SDK. Define sources, sinks, and sanitizers — the dataflow engine handles the analysis.

Here's a real rule from the repo (PYTHON-DJANGO-SEC-001) that detects SQL injection in Django:

from codepathfinder import calls, flows, QueryType
from codepathfinder.presets import PropagationPresets

class DBCursor(QueryType):
    fqns = ["sqlite3.Cursor", "psycopg2.extensions.cursor"]
    match_subclasses = True

@python_rule(
    id="PYTHON-DJANGO-SEC-001",
    name="Django SQL Injection via cursor.execute()",
    severity="CRITICAL",
    cwe="CWE-89",
)
def detect_django_cursor_sqli():
    return flows(
        from_sources=[
            calls("request.GET.get"),
            calls("request.POST.get"),
        ],
        to_sinks=[
            DBCursor.method("execute").tracks(0),
            calls("cursor.execute"),
        ],
        sanitized_by=[calls("escape"), calls("escape_string")],
        propagates_through=PropagationPresets.standard(),
        scope="global",  # cross-file taint analysis
    )
# Run your custom rules
pathfinder scan --rules ./my_rules/ --project .

Исследуйте все 190 правил в директории ... или просмотрите [правила ... Узнайте подробнее о [написании правил ... и [анализе потока данных ... чтобы написать свои собственные.

Узнайте больше о [написании правил ... и [анализе потока данных ....

Установка

Homebrew (Рекомендуется)

brew install shivasurya/tap/pathfinder

pip

Устанавливает двоичный файл CLI и Python SDK для написания правил.

pip install codepathfinder

Docker

docker pull shivasurya/code-pathfinder:stable-latest

docker run --rm -v "$(pwd):/src" \
  shivasurya/code-pathfinder:stable-latest \
  scan --ruleset python/all --project /src

Предварительно собранные бинарные файлы

Скачайте с [GitHub ... для Linux (amd64, arm64), macOS (Intel, Apple Silicon) и Windows (x64).

Из исходников

git clone https://github.com/shivasurya/code-pathfinder
cd code-pathfinder/sast-engine
gradle buildGo
./build/go/pathfinder --help

Использование

# Scan with text output (default)
pathfinder scan --ruleset python/all --project .

# JSON output
pathfinder scan --ruleset python/all --project . --output json --output-file results.json

# SARIF output (GitHub Code Scanning)
pathfinder scan --ruleset python/all --project . --output sarif --output-file results.sarif

# CSV output
pathfinder scan --ruleset python/all --project . --output csv --output-file results.csv

# Fail CI on critical/high findings
pathfinder scan --ruleset python/all --project . --fail-on=critical,high

# MCP server mode
pathfinder serve --project .

# Verbose output with statistics
pathfinder scan --ruleset python/all --project . --verbose

GitHub Action

name: Code Pathfinder Security SAST Scan

on:
  pull_request:

permissions:
  security-events: write
  contents: read
  pull-requests: write

jobs:
  security-scan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Run Security Scan
        uses: shivasurya/code-pathfinder@v2.1.1
        with:
          ruleset: python/all, docker/all, docker-compose/all
          verbose: true
          pr-comment: ${{ github.event_name == 'pull_request' }}
          pr-inline: ${{ github.event_name == 'pull_request' }}
          github-token: ${{ secrets.GITHUB_TOKEN }}

      - name: Upload SARIF
        uses: github/codeql-action/upload-sarif@v4
        if: always()
        with:
          sarif_file: pathfinder-results.sarif

Посмотрите полный пример: ...

Входные параметры Action

Вход Описание По умолчанию
rules Путь к локальным Python-файлам правил или директории -
ruleset Удалённые наборы правил, разделённые запятыми (например, python/all, docker/security) -
project Путь к исходному коду .
output Формат вывода: sarif, json или csv sarif
output-file Путь к файлу вывода pathfinder-results.sarif
fail-on Ошибка при уровнях серьезности (например, critical,high) -
verbose Включить подробный вывод false
debug Включить отладочную диагностику с временными метками false
skip-tests Пропустить тестовые файлы true
refresh-rules Принудительно обновить кэшированные наборы правил false
disable-metrics Отключить анонимную метрику использования false
python-version Версия Python для использования 3.12
pr-comment Опубликовать сводный комментарий в pull request false
pr-inline Опубликовать инлайн-комментарии рецензента для критических/высоких находок false
github-token Токен GitHub (требуется, когда включён pr-comment или pr-inline) -
no-diff Отключить сканирование с учётом изменений (сканировать все файлы) false

Требуется либо rules, либо ruleset.

Поддерживаемые языки

Язык Анализ Статус
Python Кросс-файловый анализ потока данных, анализ загрязнения, графы вызовов Стабильно
Dockerfile Анализ инструкций, шаблоны безопасности Стабильно
Docker Compose Анализ конфигурации, шаблоны безопасности Стабильно
Go AST-анализ, графы вызовов Скоро

Вклад

Вклад приветствуется. Прочитайте [Contributing ... для инструкций по настройке, запуску тестов локально и процесса PR.

Публикация объявления в продукте

Объявления в продукте (мастер-классы, блог-посты, уведомления о безопасности) управляются через release/latest.json. Добавьте запись в announcements[], откройте PR, и после слияния с main workflow публикации загрузит манифест на CDN примерно за 60 секунд. Смотрите технический спецификатор version-update-check для схемы и version_range семантики.

Все участники должны подписать [Contributor License Agreement ... прежде чем любой pull request может быть объединён.

  • [Сообщите об ошибках или запросите ...
  • [Задайте вопросы или начните ...
  • [Напишите о безопасности ...

Лицензия

...

Войдите, чтобы оставить комментарий