### Install Trailmark from PyPI or Source Source: https://context7.com/trailofbits/trailmark/llms.txt Install Trailmark using pip for PyPI or sync all groups for source installation. Requires Python 3.12 or higher. ```bash uv pip install trailmark ``` ```bash uv sync --all-groups ``` -------------------------------- ### Installation Source: https://context7.com/trailofbits/trailmark/llms.txt Instructions for installing the Trailmark library using pip or from source. Requires Python 3.12 or higher. ```APIDOC ## Installation ```bash # Install from PyPI uv pip install trailmark # Or install from source uv sync --all-groups ``` Requires Python >= 3.12. ``` -------------------------------- ### Install Package and Dev Dependencies Source: https://github.com/trailofbits/trailmark/blob/main/README.md Install the project's package along with all development dependencies using `uv sync --all-groups`. ```bash # Install package and dev dependencies uv sync --all-groups ``` -------------------------------- ### Click Command (Python) Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Example of a command-line interface command using the Click library in Python. Requires the 'click' library to be installed. ```python import click @click.command() @click.argument("name") def greet(name): click.echo(f"Hello {name}") ``` -------------------------------- ### Install Trailmark Latest Release Source: https://github.com/trailofbits/trailmark/blob/main/README.md Installs the latest published release of Trailmark using uv pip. ```bash uv pip install trailmark ``` -------------------------------- ### TOML Entrypoint Configuration: Name Regex Rule Source: https://github.com/trailofbits/trailmark/blob/main/README.md Example TOML configuration for defining entrypoints based on a function name regex. This rule matches any function starting with `handle_`. ```toml [[entrypoint]] name_regex = "^handle_" kind = "api" trust = "untrusted_external" ``` -------------------------------- ### Koa Router Handler (JavaScript) Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Example of defining a GET route handler using Koa Router. Requires '@koa/router' to be installed. ```javascript const router = new Router(); router.get("/users", async ctx => { ... }); ``` -------------------------------- ### Get Trailmark Version Source: https://github.com/trailofbits/trailmark/blob/main/README.md Reports the installed version of Trailmark using the --version flag or the 'version' subcommand. ```bash trailmark --version # or: trailmark -V ``` ```bash trailmark version # subcommand form ``` -------------------------------- ### Trailmark CLI - Version Source: https://context7.com/trailofbits/trailmark/llms.txt Displays the installed version of the Trailmark CLI. ```bash trailmark --version trailmark version ``` -------------------------------- ### TOML Entrypoint Configuration: Single Node Source: https://github.com/trailofbits/trailmark/blob/main/README.md Example TOML configuration for defining a single entrypoint with its node ID, kind, trust level, asset value, and description. ```toml [[entrypoint]] node = "my_module:handle_request" kind = "api" trust = "untrusted_external" asset_value = "high" description = "HTTP POST /auth" ``` -------------------------------- ### Example Python Code Source: https://github.com/trailofbits/trailmark/blob/main/README.md This Python code defines an Authentication class with a verify method and a handler function for processing requests. ```python class Auth: def verify(self, token: str) -> bool: return self._check_sig(token) def _check_sig(self, token: str) -> bool: ... def handle_request(req: Request) -> Response: auth = Auth() if auth.verify(req.token): return process(req) return deny() ``` -------------------------------- ### TOML Entrypoint Configuration: File Glob Rule Source: https://github.com/trailofbits/trailmark/blob/main/README.md Example TOML configuration for defining entrypoints based on a file glob pattern. This rule marks all PHP files under `public_html/` as web-exposed. ```toml [[entrypoint]] file_glob = "public_html/**/*.php" kind = "user_input" trust = "untrusted_external" asset_value = "high" description = "Web-exposed PHP script" ``` -------------------------------- ### TOML Entrypoint Configuration: Parameter Type Rule Source: https://github.com/trailofbits/trailmark/blob/main/README.md Example TOML configuration for defining entrypoints based on parameter type. This rule identifies functions accepting a PSR-7 `ServerRequestInterface`. ```toml [[entrypoint]] param_type = "ServerRequestInterface" kind = "api" trust = "untrusted_external" asset_value = "high" description = "PSR-7 HTTP handler" ``` -------------------------------- ### Fastify GET Route (JavaScript) Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines a simple GET route handler for Fastify. The handler returns 'pong' for the '/ping' path. ```javascript fastify.get("/ping", async (request, reply) => "pong"); ``` -------------------------------- ### Django View Function and Class Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Example of a Django view function and a class-based view. For comprehensive detection, consider walking URL configurations. ```python # views.py def profile(request): ... class LoginView(APIView): def post(self, request): ... ``` -------------------------------- ### Example Mermaid Graph Source: https://github.com/trailofbits/trailmark/blob/main/README.md This Mermaid diagram visualizes the call graph generated from the example Python code, showing function calls and class containment. ```mermaid graph TD HR["handle_request"] -->|calls| AV["Auth.verify"] HR -->|calls| P["process"] HR -->|calls| D["deny"] AV -->|calls| CS["Auth._check_sig"] A["Auth"] -->|contains| AV A -->|contains| CS classDef fn fill:#007bff26,stroke:#007bff,color:#007bff classDef cls fill:#6f42c126,stroke:#6f42c1,color:#6f42c1 class HR,P,D fn class A,AV,CS cls ``` -------------------------------- ### Perform Type Checking Source: https://github.com/trailofbits/trailmark/blob/main/README.md Execute static type checking using the `ty` tool. Ensure `ty` is installed first. ```bash # Type check uv tool install ty && ty check ``` -------------------------------- ### Gin Router GET Request Handler Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines a GET route handler for a specific path using the Gin framework. Assumes `r` is a `gin.Engine` instance. ```go r := gin.Default() r.GET("/ping", pingHandler) ``` -------------------------------- ### NestJS Controller with Route Decorators Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines a NestJS controller with a GET route for fetching a user by ID. Requires the `@Controller` and `@Get` decorators. ```typescript @Controller("users") export class UsersController { @Get(":id") findOne(@Param("id") id: string) { ... } } ``` -------------------------------- ### Define Rocket Handler with GET Attribute Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines a handler function for GET requests in Rocket using a procedural macro. Path parameters are directly typed. ```rust #[get("/users/")] fn get_user(id: u32) -> String { ... } ``` -------------------------------- ### Run Preanalysis Passes and Get Findings Source: https://github.com/trailofbits/trailmark/blob/main/README.md Execute built-in audit-oriented preanalysis passes and retrieve identified findings using `preanalysis`, `findings`, and `subgraph_names`. ```python engine.preanalysis() engine.findings() engine.subgraph_names() ``` -------------------------------- ### Define Actix-web Handler with GET Attribute Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines an asynchronous handler function for GET requests in Actix-web using a procedural macro. The path parameter is extracted using web::Path. ```rust #[get("/users/{id}")] async fn get_user(path: web::Path) -> impl Responder { ... } ``` -------------------------------- ### Parse Code Files and Directories with Trailmark Source: https://github.com/trailofbits/trailmark/blob/main/README.md Use `parse_file` to get a raw CodeGraph for a single file or `parse_directory` to parse an entire project, optionally specifying the language or using auto-detection. ```python from trailmark.parse import parse_directory, parse_file graph = parse_file("path/to/file.py") graph = parse_directory("path/to/project", language="auto") ``` -------------------------------- ### Symfony Controller Route with Attributes Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines a GET route for listing products in a Symfony controller using PHP 8 attributes. Requires the `#[Route]` attribute. ```php #[Route('/products', methods: ['GET'])] public function list(): Response { ... } ``` -------------------------------- ### Inspect CodeUnit Data Model Source: https://context7.com/trailofbits/trailmark/llms.txt Example of how to inspect a CodeUnit object from the Trailmark graph, accessing its properties like ID, name, kind, location, complexity, parameters, return type, exceptions, and docstring. ```python from trailmark.models.nodes import NodeKind, CodeUnit, SourceLocation, Parameter, TypeRef, BranchInfo from trailmark.models.edges import EdgeKind, EdgeConfidence, CodeEdge from trailmark.models.annotations import AnnotationKind, Annotation, EntrypointKind, TrustLevel, AssetValue, EntrypointTag from trailmark.models.graph import CodeGraph # NodeKind enum values # FUNCTION, METHOD, CLASS, MODULE, STRUCT, INTERFACE, TRAIT, ENUM, NAMESPACE, CONTRACT, LIBRARY, TEMPLATE # EdgeKind enum values # CALLS, INHERITS, CONTAINS, IMPORTS, IMPLEMENTS # EdgeConfidence enum values # CERTAIN, INFERRED, UNCERTAIN # AnnotationKind enum values # ASSUMPTION, PRECONDITION, POSTCONDITION, INVARIANT, BLAST_RADIUS, PRIVILEGE_BOUNDARY, TAINT_PROPAGATION, FINDING, AUDIT_NOTE # EntrypointKind enum values # USER_INPUT, API, DATABASE, FILE_SYSTEM, THIRD_PARTY # TrustLevel enum values # UNTRUSTED_EXTERNAL, SEMI_TRUSTED_EXTERNAL, TRUSTED_INTERNAL # AssetValue enum values # HIGH, MEDIUM, LOW # Example: inspect a CodeUnit unit: CodeUnit = graph.nodes["my_module:my_function"] print(f"ID: {unit.id}") print(f"Name: {unit.name}") print(f"Kind: {unit.kind.value}") print(f"Location: {unit.location.file_path}:{unit.location.start_line}-{unit.location.end_line}") print(f"Complexity: {unit.cyclomatic_complexity}") print(f"Parameters: {[(p.name, p.type_ref) for p in unit.parameters]}") print(f"Return type: {unit.return_type}") print(f"Exceptions: {[e.name for e in unit.exception_types]}") print(f"Docstring: {unit.docstring}") ``` -------------------------------- ### Initialize QueryEngine from Directory Source: https://github.com/trailofbits/trailmark/blob/main/README.md Create a `QueryEngine` to analyze code within a directory. Supports single-language analysis, auto-detection across all languages, or specifying a comma-separated list of languages. ```python from trailmark.query.api import QueryEngine engine = QueryEngine.from_directory("path/to/project") engine = QueryEngine.from_directory("path/to/project", language="auto") engine = QueryEngine.from_directory("path/to/project", language="python,rust") ``` -------------------------------- ### QueryEngine.from_directory - Create a queryable engine from source directory Source: https://context7.com/trailofbits/trailmark/llms.txt Creates a queryable engine from a source directory. The engine automatically detects entrypoints and builds the graph index for fast traversal. ```APIDOC ## QueryEngine.from_directory - Create a queryable engine from source directory The QueryEngine provides a high-level API for querying code graphs. It automatically detects entrypoints and builds the graph index for fast traversal. ```python from trailmark.query.api import QueryEngine # Create engine with automatic entrypoint detection engine = QueryEngine.from_directory("./my_project", language="python") # Polyglot: auto-detect all languages engine = QueryEngine.from_directory("./my_project", language="auto") # Skip entrypoint detection if handling manually engine = QueryEngine.from_directory( "./my_project", language="python", detect_entrypoints_=False ) # Get graph summary summary = engine.summary() print(f"Total nodes: {summary['total_nodes']}") print(f"Functions: {summary['functions']}") print(f"Classes: {summary['classes']}") print(f"Call edges: {summary['call_edges']}") print(f"Entrypoints: {summary['entrypoints']}") print(f"Dependencies: {summary['dependencies']}") ``` ``` -------------------------------- ### Symfony GET Route Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines a GET route in Symfony using attributes or annotations. ```APIDOC ## GET /products ### Description Lists all products using a Symfony route. ### Method GET ### Endpoint /products ### Parameters (No specific parameters defined in the source for this endpoint) ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **Response** (Response) - The Symfony Response object containing the product list. #### Response Example (Example response structure not provided in source) ``` -------------------------------- ### Laravel GET Route Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines a GET route in Laravel for handling specific HTTP requests. ```APIDOC ## GET /users/{id} ### Description Retrieves a specific user by their ID using a Laravel route. ### Method GET ### Endpoint /users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user. ### Request Example (No request body for GET requests) ### Response #### Success Response (200) - **(structure depends on implementation)** - Details of the user. #### Response Example (Example response structure not provided in source) ``` -------------------------------- ### Create QueryEngine from Source Directory Source: https://context7.com/trailofbits/trailmark/llms.txt Create a QueryEngine from a source directory for high-level code graph querying. The engine automatically detects entrypoints and builds the graph index. Options include polyglot parsing and skipping entrypoint detection. ```python from trailmark.query.api import QueryEngine # Create engine with automatic entrypoint detection engine = QueryEngine.from_directory("./my_project", language="python") # Polyglot: auto-detect all languages engine = QueryEngine.from_directory("./my_project", language="auto") # Skip entrypoint detection if handling manually engine = QueryEngine.from_directory( "./my_project", language="python", detect_entrypoints_=False ) # Get graph summary summary = engine.summary() print(f"Total nodes: {summary['total_nodes']}") print(f"Functions: {summary['functions']}") print(f"Classes: {summary['classes']}") print(f"Call edges: {summary['call_edges']}") print(f"Entrypoints: {summary['entrypoints']}") print(f"Dependencies: {summary['dependencies']}") ``` -------------------------------- ### List Detected Entrypoints with JSON Output Source: https://github.com/trailofbits/trailmark/blob/main/README.md Display detected entrypoints in JSON format using the `--json` flag. ```bash trailmark entrypoints --json path/to/project ``` -------------------------------- ### Configure Entrypoints with TOML Source: https://context7.com/trailofbits/trailmark/llms.txt Define custom entrypoint detection rules using TOML. Supports matching by parameter type, function name regex, and file glob patterns. ```toml # Rule: match by parameter type [[entrypoint]] param_type = "ServerRequestInterface" kind = "api" trust = "untrusted_external" asset_value = "high" description = "PSR-7 HTTP handler" # Rule: match by function name regex [[entrypoint]] name_regex = "^handle_" kind = "api" trust = "untrusted_external" # Rule: combine conditions with AND [[entrypoint]] file_glob = "public/*.py" name_regex = "^handle_" kind = "api" trust = "untrusted_external" description = "Public Python handlers" ``` -------------------------------- ### Trailmark CLI - List Entrypoints Source: https://context7.com/trailofbits/trailmark/llms.txt Lists detected entrypoints in a project, with options for JSON output and language filtering. ```bash trailmark entrypoints ./my_project trailmark entrypoints --json ./my_project trailmark entrypoints --language rust ./my_project ``` -------------------------------- ### Running Development Checks with uv Source: https://github.com/trailofbits/trailmark/blob/main/AGENTS.md Commands to synchronize dependencies, check code style with Ruff, and format code. ```bash uv sync --all-groups ``` ```bash uv run ruff check src/ tests/ ``` ```bash uv run ruff format --check src/ tests/ ``` ```bash uv tool install ty && ty check ``` ```bash uv run pytest -q tests/ ``` -------------------------------- ### Deno.serve / Bun.serve Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Identifies HTTP servers created using Deno.serve or Bun.serve. ```APIDOC ## Deno.serve / Bun.serve HTTP Server ### Description Handles incoming HTTP requests for servers started with Deno.serve or Bun.serve. ### Method (Any HTTP method supported by Request) ### Endpoint (Localhost or configured host/port) ### Parameters #### Path Parameters - **req** (Request) - Required - The incoming request object. ### Request Example (Standard HTTP Request object) ### Response #### Success Response (200) - **Response** (Response) - The response to be sent back to the client. #### Response Example ```javascript new Response('Hello from Deno/Bun!', { status: 200 }) ``` ``` -------------------------------- ### Run Project Tests Source: https://github.com/trailofbits/trailmark/blob/main/CONTRIBUTING.md Execute the test suite using pytest. The -q flag provides a quieter output. ```bash pytest -q ``` -------------------------------- ### Run Tests Source: https://github.com/trailofbits/trailmark/blob/main/README.md Execute the project's test suite using pytest with the `-q` flag for quieter output. ```bash # Tests uv run pytest -q tests/ ``` -------------------------------- ### Laravel Route Definition Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines a GET route in Laravel for fetching a user by ID, mapping it to a specific controller method. Uses the Route facade. ```php Route::get('/users/{id}', [UserController::class, 'show']); ``` -------------------------------- ### Configure Custom Entrypoints Source: https://context7.com/trailofbits/trailmark/llms.txt Configures custom entrypoints for Trailmark analysis using a TOML file located at `.trailmark/entrypoints.toml` in the project root. Supports defining entrypoints by node ID or file glob, along with kind, trust level, asset value, and description. ```toml # Single-node entry by ID [[entrypoint]] node = "my_module:handle_request" kind = "api" # user_input | api | database | file_system | third_party trust = "untrusted_external" # untrusted_external | semi_trusted_external | trusted_internal asset_value = "high" # high | medium | low description = "HTTP POST /auth" # Rule: match by file glob [[entrypoint]] file_glob = "public_html/**/*.php" kind = "user_input" trust = "untrusted_external" asset_value = "high" description = "Web-exposed PHP script" ``` -------------------------------- ### C/C++ Main Function Signature Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Standard entry point for C/C++ programs. Supports different argument configurations for command-line arguments and environment variables. ```c int main(void) ``` ```c int main(int argc, char **argv) ``` ```c int main(int argc, char **argv, char **envp) ``` -------------------------------- ### aiohttp Route Definition Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines an HTTP GET route for an aiohttp web application using `web.RouteTableDef`. Ensure imports are checked to distinguish from Flask/FastAPI. ```python from aiohttp import web routes = web.RouteTableDef() @routes.get("/status") async def status(request): ... ``` -------------------------------- ### Analyze Project with Specific Languages Source: https://github.com/trailofbits/trailmark/blob/main/README.md Use the `analyze` command to scan a project. Specify languages with `--language` or use `auto` for automatic detection. Multiple languages can be comma-separated. ```bash trailmark analyze --language auto path/to/project ``` ```bash trailmark analyze --language python,rust,solidity path/to/project ``` -------------------------------- ### Get All Call Paths Between Nodes Source: https://github.com/trailofbits/trailmark/blob/main/README.md Retrieve all possible call paths connecting two specified nodes (functions) within the codebase using the `paths_between` method. ```python engine.paths_between("handle_request", "Auth._check_sig") ``` -------------------------------- ### Import and Query weAudit Findings Source: https://context7.com/trailofbits/trailmark/llms.txt Imports weAudit findings from a JSON file and then queries the augmented findings. Requires an initialized QueryEngine. ```python result = engine.augment_weaudit("./findings.json") print(f"weAudit augmentation:") print(f" Matched findings: {result['matched_findings']}") print(f" Unmatched findings: {result['unmatched_findings']}") findings = engine.findings() for f in findings: print(f"{f['id']}:") for finding in f['findings']: print(f" [{finding['kind']}] {finding['description']}") from trailmark.models.annotations import AnnotationKind audit_notes = engine.findings(kind=AnnotationKind.AUDIT_NOTE) ``` -------------------------------- ### Define Warp Filter Chain Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Combines path filtering with a GET request and maps the result to a handler function in Warp. This approach requires following filter chains. ```rust warp::path!("users" / u32).and(warp::get()).map(handler) ``` -------------------------------- ### Next.js App Router Route Handlers (TypeScript) Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Named export functions for HTTP methods (GET, POST, etc.) in Next.js App Router route handlers. ```typescript // app/api/users/route.ts export async function GET(request: Request) { ... } export async function POST(request: Request) { ... } ``` -------------------------------- ### Miden Assembly Program Entrypoint Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Detects the top-level `begin ... end` block in Miden Assembly, marking the program's entry point. ```APIDOC ## Miden Assembly Program Entrypoint ### Description Detects the top-level `begin ... end` block in Miden Assembly code, which defines the program's entry point. ### Method N/A (Pattern-based detection) ### Endpoint N/A ### Parameters N/A ### Request Example ```masm use.std::sys begin push.1 push.2 add # ... end ``` ### Response N/A ### Notes - **Scope:** module - **Kind:** `user_input` - **Trust:** `untrusted_external` - **Asset:** `high` - **Pattern:** File contains a top-level `^begin\s*$`. - **Source:** ``` -------------------------------- ### Go `main` function Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Identifies the entry point of a Go program, the `main` function in the `main` package. ```APIDOC ## Go `main` function ### Description Identifies the entry point of a Go program, the `main` function in the `main` package. ### Method N/A (Program entry point) ### Endpoint N/A (Program execution) ### Parameters N/A ### Request Example ```go package main func main() { // Program logic } ``` ### Response N/A (Program execution) ``` -------------------------------- ### List Detected Entrypoints Source: https://github.com/trailofbits/trailmark/blob/main/README.md List detected entrypoints (attack surface) for a project. This uses heuristic detection and can be overridden by `.trailmark/entrypoints.toml`. ```bash trailmark entrypoints path/to/project ``` -------------------------------- ### Analyze Project for Summary Statistics Source: https://github.com/trailofbits/trailmark/blob/main/README.md Generate summary statistics for a project using the `analyze --summary` command. ```bash trailmark analyze --summary path/to/project ``` -------------------------------- ### Next.js App Router Route Handlers Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Identifies API routes defined using named exports (GET, POST, etc.) in `app/**/route.{ts,js}` files within Next.js applications. ```APIDOC ## Next.js (App Router) ### Description Detects API routes defined in Next.js applications using the App Router. These are typically found in `app/**/route.{ts,js}` files and export functions named after HTTP verbs (e.g., `GET`, `POST`). ### Method GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS ### Endpoint `/path` (e.g., `/api/users`, `/items/:id`) ### Parameters N/A ### Request Example ```ts // app/api/users/route.ts export async function GET(request: Request) { // Fetch users return new Response(JSON.stringify({ users: [] }), { status: 200 }); } export async function POST(request: Request) { // Create user const userData = await request.json(); return new Response(JSON.stringify({ success: true, data: userData }), { status: 201 }); } ``` ### Response N/A ``` -------------------------------- ### Trailmark File Layout Source: https://github.com/trailofbits/trailmark/blob/main/AGENTS.md Shows the directory structure of the Trailmark project, highlighting key modules. ```text src/trailmark/ models/ # Data classes: CodeUnit, CodeEdge, Annotation, CodeGraph graph.py # CodeGraph with add_annotation, clear_annotations, merge nodes.py # CodeUnit, Parameter, TypeRef, BranchInfo edges.py # CodeEdge, EdgeKind, EdgeConfidence annotations.py # Annotation, AnnotationKind, EntrypointTag parsers/ # Language-specific tree-sitter parsers base.py # BaseParser protocol _common.py # Shared parser utilities python/ # One subpackage per language javascript/ ... analysis/ # Higher-level passes: entrypoints, diff, augment, preanalysis storage/ graph_store.py # GraphStore: rustworkx-backed indexed storage query/ api.py # QueryEngine: high-level facade cli.py # CLI entry point tests/ # pytest test suite ``` -------------------------------- ### Trailmark CLI - Augment with Findings Source: https://context7.com/trailofbits/trailmark/llms.txt Augments project analysis with findings from SARIF or weAudit files. Multiple SARIF files can be provided. ```bash trailmark augment --sarif results.sarif ./my_project trailmark augment --weaudit findings.json ./my_project trailmark augment --sarif a.sarif --sarif b.sarif --json ./my_project ``` -------------------------------- ### Rust `main` function Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Detects the main entry point of a Rust program, potentially decorated with runtime attributes like `#[tokio::main]`. ```APIDOC ## Rust `main` function ### Description Detects the main entry point of a Rust program, potentially decorated with runtime attributes like `#[tokio::main]`. ### Method N/A (Program entry point) ### Endpoint N/A (Program execution) ### Parameters N/A ### Request Example ```rust #[tokio::main] async fn main() { // Program logic println!("Hello, Rust!"); } ``` ### Response N/A (Program execution) ``` -------------------------------- ### Trailmark CLI - Analyze Project Source: https://context7.com/trailofbits/trailmark/llms.txt Analyzes a specified project directory. Supports specifying languages and outputting summary statistics or complexity hotspots. ```bash trailmark analyze ./my_project trailmark analyze --language rust ./my_project trailmark analyze --language auto ./my_project trailmark analyze --language python,rust,solidity ./my_project trailmark analyze --summary ./my_project trailmark analyze --complexity 10 ./my_project ``` -------------------------------- ### Analyze Project for Complexity Hotspots Source: https://github.com/trailofbits/trailmark/blob/main/README.md Identify complexity hotspots in a project by setting a threshold with the `analyze --complexity` command. A threshold of 10 is shown. ```bash trailmark analyze --complexity 10 path/to/project ``` -------------------------------- ### Analyze Rust Project Source: https://github.com/trailofbits/trailmark/blob/main/README.md Performs a full JSON graph analysis of a Rust project, specifying the language as rust. ```bash trailmark analyze --language rust path/to/project ``` -------------------------------- ### Run Lint and Format Checks Source: https://github.com/trailofbits/trailmark/blob/main/CONTRIBUTING.md Execute Ruff for linting and formatting checks on the src/ and tests/ directories. Use --fix to automatically correct issues. ```bash uv run ruff check --fix src/ tests/ ``` ```bash uv run ruff format src/ tests/ ``` -------------------------------- ### Haskell Entrypoints Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Detects top-level 'main' functions in Haskell, which serve as the program's entry point. ```APIDOC ## Haskell Entrypoints ### Description Detects top-level `main :: IO ()` bindings in Haskell code, which are the primary entry points for execution. ### Method N/A (Pattern-based detection) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Notes - **Scope:** function - **Kind:** `user_input` - **Trust:** `untrusted_external` - **Asset:** `high` - **Pattern:** `^main\s*::` or `^main\s*=`. - **Source:** ``` -------------------------------- ### Find Entrypoint Paths to a Target Source: https://context7.com/trailofbits/trailmark/llms.txt Use `entrypoint_paths_to` to find all call paths from any detected entrypoint to a specific function. This helps answer 'how can an attacker reach this sink?' and can be limited by `max_depth`. Returns an empty list if the target is unreachable. ```python from trailmark.query.api import QueryEngine engine = QueryEngine.from_directory("./my_project") paths = engine.entrypoint_paths_to("database.execute_raw_sql", max_depth=20) print(f"Found {len(paths)} entrypoint path(s) to execute_raw_sql") for path in paths: entrypoint = path[0] print(f"From {entrypoint}: {" -> ".join(path)}") paths = engine.entrypoint_paths_to("internal_helper") print(paths) # [] ``` -------------------------------- ### Trailmark CLI Usage Source: https://github.com/trailofbits/trailmark/blob/main/README.md Command-line interface commands for analyzing projects and reporting versions. ```APIDOC ## Trailmark CLI Commands ### Version Reporting **Description**: Reports the installed version of Trailmark. **Method**: N/A (CLI command) **Endpoint**: N/A **Commands**: - `trailmark --version` - `trailmark -V` - `trailmark version` ### Project Analysis **Description**: Analyzes a given project path to generate a code graph. **Method**: N/A (CLI command) **Endpoint**: N/A **Usage**: - `trailmark analyze path/to/project` (Analyzes Python projects by default) - `trailmark analyze --language rust path/to/project` (Analyzes Rust projects) - `trailmark analyze --language javascript path/to/project` (Analyzes JavaScript projects) **Polyglot Analysis**: - Trailmark can auto-detect and merge analysis results from multiple supported languages found within a project. ``` -------------------------------- ### List Detected Entrypoints for Attack Surface Analysis Source: https://context7.com/trailofbits/trailmark/llms.txt The `attack_surface` function lists all detected entrypoints, including their trust levels, kinds, and asset values. This is crucial for attack surface analysis. ```python from trailmark.query.api import QueryEngine engine = QueryEngine.from_directory("./my_project") surface = engine.attack_surface() print(f"Attack surface: {len(surface)} entrypoint(s)") for ep in surface: print(f" {ep['node_id']}") print(f" Kind: {ep['kind']}") # user_input, api, database, file_system, third_party print(f" Trust: {ep['trust_level']}") # untrusted_external, semi_trusted_external, trusted_internal print(f" Asset: {ep['asset_value']}") # high, medium, low if ep['description']: print(f" Description: {ep['description']}") ``` -------------------------------- ### Miden Assembly Program Entrypoint Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines the program's entrypoint in Miden Assembly. Requires the 'use.std::sys' import for system functionalities. ```masm use.std::sys begin push.1 push.2 add # ... end ``` -------------------------------- ### Cairo Contract Entrypoints Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines external, view, l1_handler, and constructor entrypoints for a Cairo smart contract using StarkNet attributes. These attributes mark functions as callable from outside or for specific contract interactions. ```cairo #[starknet::contract] mod MyContract { #[external(v0)] fn transfer(ref self: ContractState, to: ContractAddress, amount: u256) { ... } #[constructor] fn constructor(ref self: ContractState) { ... } } ``` -------------------------------- ### Synchronize Project Dependencies Source: https://github.com/trailofbits/trailmark/blob/main/CONTRIBUTING.md Use uv to synchronize all project dependency groups. Ensure Python version is >= 3.13. ```bash uv sync --all-groups ``` -------------------------------- ### Trailmark Architecture Diagram Source: https://github.com/trailofbits/trailmark/blob/main/AGENTS.md Illustrates the data flow from code parsing to query execution. ```text CodeGraph (data) -> GraphStore (indexed storage) -> QueryEngine (facade) ``` -------------------------------- ### Go Web Framework Routers (gin, chi, echo) Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Identifies API endpoints defined using popular Go web frameworks like Gin, Chi, and Echo. ```APIDOC ## Go Web Framework Routers (gin, chi, echo) ### Description Identifies API endpoints defined using popular Go web frameworks like Gin, Chi, and Echo. ### Method - `GET` - `POST` - `PUT` - `DELETE` - `PATCH` - `HEAD` - `OPTIONS` - `Any` (for Gin) ### Endpoint Defined using methods like `r.GET("/path", handler)`, `r.POST(...)`, etc., where `r` is the router instance. ### Parameters - **Path**: The URL path for the route. - **Handler**: The function to execute for the route. ### Request Example ```go package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run(":8080") } ``` ### Response - **Success Response**: Varies based on the handler implementation. ### Response Example ```json { "message": "pong" } ``` ``` -------------------------------- ### Perform Mutation Testing Source: https://github.com/trailofbits/trailmark/blob/main/README.md Run mutation tests using `mutmut`. On macOS, set the `OBJC_DISABLE_INITIALIZE_FORK_SAFETY` environment variable to prevent potential segfaults. ```bash # Mutation testing (on macOS, set this env var to avoid rustworkx fork segfaults) OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES uv run mutmut run ``` -------------------------------- ### Sidekiq Worker Implementation Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Implements a background job using Sidekiq. The `perform` method serves as the entry point for the job's execution. ```ruby class SendEmailJob include Sidekiq::Job def perform(user_id, subject) ... end end ``` -------------------------------- ### Rust Main Function with Async Runtime Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md The entry point for a Rust program, often annotated to use an asynchronous runtime like Tokio, async-std, or Actix. ```rust #[tokio::main] async fn main() { // ... } ``` -------------------------------- ### Find Attack-Surface Paths Source: https://github.com/trailofbits/trailmark/blob/main/README.md Identify potential attack paths by finding all paths from detected entrypoints to a specific sink function using `entrypoint_paths_to`. ```python engine.entrypoint_paths_to("Auth._check_sig") ``` -------------------------------- ### Augment Graph with Multiple SARIF Files and JSON Output Source: https://github.com/trailofbits/trailmark/blob/main/README.md Combine multiple SARIF files for augmentation and output the result in JSON format using `--sarif` and `--json` flags. ```bash trailmark augment --sarif a.sarif --sarif b.sarif --json path/to/project ``` -------------------------------- ### Analyze JavaScript Project Source: https://github.com/trailofbits/trailmark/blob/main/README.md Performs a full JSON graph analysis of a JavaScript project, specifying the language as javascript. ```bash trailmark analyze --language javascript path/to/project ``` -------------------------------- ### Trailmark CLI - Structural Diff Source: https://context7.com/trailofbits/trailmark/llms.txt Performs a structural diff between two project versions, with options for JSON output, comparing Git references, and language filtering. ```bash trailmark diff ./before ./after trailmark diff --json ./before ./after trailmark diff --repo . main HEAD # Compare git refs trailmark diff --language auto ./v1 ./v2 ``` -------------------------------- ### Run Mutation Testing Source: https://github.com/trailofbits/trailmark/blob/main/CONTRIBUTING.md Execute mutmut to run mutation tests, which verifies the quality of the test suite by generating and testing code mutations. ```bash uv run mutmut run ``` ```bash uv run mutmut results ``` -------------------------------- ### Perform Type Checking Source: https://github.com/trailofbits/trailmark/blob/main/CONTRIBUTING.md Run the type checker using uv to ensure code adheres to type annotations. ```bash uv run ty check ``` -------------------------------- ### Go gRPC Server Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Detects gRPC server implementations in Go by checking for struct embedding of `pb.UnimplementedServer` and implementation of RPC methods. ```APIDOC ## Go gRPC Server ### Description Detects gRPC server implementations in Go by checking for struct embedding of `pb.UnimplementedServer` and implementation of RPC methods. ### Method RPC methods defined in the proto file. ### Endpoint N/A (gRPC services are accessed via RPC calls) ### Parameters - **Request**: gRPC request message defined in the proto file. - **Response**: gRPC response message defined in the proto file. ### Request Example ```go package main import ( "context" "google.golang.org/grpc" "pb" ) type server struct { pb.UnimplementedYourServiceServer } func (s *server) YourRpcMethod(ctx context.Context, req *pb.YourRequest) (*pb.YourResponse, error) { // Implement RPC logic return &pb.YourResponse{}, nil } func main() { lis, err := net.Listen("tcp", ":50051") if err != nil { log.Fatalf("failed to listen: %v", err) } s := grpc.NewServer() pb.RegisterYourServiceServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) } } ``` ### Response - **Success Response**: gRPC response message defined in the proto file. ### Response Example ```protobuf // Example response message structure from proto file message YourResponse { string result = 1; } ``` ``` -------------------------------- ### Rack Middleware Component Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Represents a Rack middleware component. The `call(env)` method is the entry point for processing requests in a Rack application. ```ruby class MyMiddleware def initialize(app) @app = app end def call(env) # Process request status, headers, body = @app.call(env) # Process response [status, headers, body] end end ``` -------------------------------- ### Yesod Routing and Handlers Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Recognizes API resources declared via Yesod's `parseRoutes` and corresponding handlers. ```APIDOC ## Yesod Routing and Handlers ### Description Identifies API resources declared using Yesod's `parseRoutes` QuasiQuote. Handlers for these resources follow a naming convention, such as `getR`, `postR`, etc. ### Method N/A (Pattern-based detection) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Notes - **Scope:** function - **Kind:** `api` - **Trust:** `untrusted_external` - **Asset:** `high` - **Pattern:** Functions named `(get|post|put|delete|patch)\w+R\b` within a Yesod application. - **Source:** ``` -------------------------------- ### Analyze Python Project Source: https://github.com/trailofbits/trailmark/blob/main/README.md Performs a full JSON graph analysis of a Python project located at path/to/project. ```bash trailmark analyze path/to/project ``` -------------------------------- ### Fastify Route Handlers (JavaScript/TypeScript) Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Detects API routes defined in Fastify applications using `fastify.get`, `fastify.post`, or `fastify.route`. ```APIDOC ## Fastify ### Description Detects API routes in Fastify applications. Handlers are defined using methods like `fastify.get`, `fastify.post`, or the more structured `fastify.route` configuration. ### Method GET, POST, PUT, DELETE, etc. ### Endpoint `/path` (e.g., `/ping`, `/api/v1/data`) ### Parameters N/A ### Request Example ```js const fastify = require('fastify')({ logger: true }); fastify.get('/ping', async (request, reply) => { return 'pong'; }); fastify.route({ method: 'POST', url: '/submit', handler: async (request, reply) => { // Submission logic reply.send({ success: true }); } }); ``` ### Response N/A ``` -------------------------------- ### Augment Graph with WeAudit Findings Source: https://github.com/trailofbits/trailmark/blob/main/README.md Augment the code graph with findings from WeAudit. The `--weaudit` flag can be repeated for multiple files. Use `--json` to print the augmented graph. ```bash trailmark augment --weaudit findings.json path/to/project ``` -------------------------------- ### Script Entrypoints (`if __name__ == "__main__:") Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Identifies functions called directly from the `if __name__ == "__main__:"` block in Python scripts. ```APIDOC ## `if __name__ == "__main__:"` block ### Description Identifies functions called from within an `if __name__ == "__main__:"` block, marking them as script entrypoints. ### Method N/A (Script execution) ### Endpoint N/A ### Parameters N/A ### Request Example ```python def main_function(): print("Running main function") if __name__ == "__main__": main_function() ``` ### Response N/A ``` -------------------------------- ### QueryEngine API Source: https://github.com/trailofbits/trailmark/blob/main/README.md The QueryEngine provides a high-level API for interacting with the indexed code graph. ```APIDOC ## QueryEngine Methods ### `callers_of(name)` **Description**: Retrieves the direct callers of a named target. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `callees_of(name)` **Description**: Retrieves the direct callees of a named source. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `ancestors_of(name)` **Description**: Retrieves all functions that can transitively reach the target (upward slice). **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `reachable_from(name)` **Description**: Retrieves all functions transitively reachable from the source. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `paths_between(src, dst)` **Description**: Finds all simple call paths between two nodes. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `entrypoint_paths_to(name)` **Description**: Retrieves paths from any detected entrypoint to the target. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `attack_surface()` **Description**: Identifies entrypoints tagged with trust level and asset value. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `complexity_hotspots(n)` **Description**: Finds functions with cyclomatic complexity greater than or equal to `n`. **Method**: N/A (Method of a Python object) **Parameters**: #### Query Parameters - **n** (integer) - Required - The minimum cyclomatic complexity threshold. **Endpoint**: N/A ### `functions_that_raise(exc)` **Description**: Retrieves functions whose parser-detected exception list includes `exc`. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `annotate(name, kind, description, source)` **Description**: Adds a semantic annotation to a node. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `annotations_of(name, kind=None)` **Description**: Retrieves annotations for a node, optionally filtered by `kind`. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `nodes_with_annotation(kind)` **Description**: Retrieves all nodes tagged with the given annotation `kind`. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `clear_annotations(name, kind=None)` **Description**: Removes annotations from a node, optionally filtered by `kind`. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `diff_against(other)` **Description**: Computes the structural difference of this engine's graph against another. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `preanalysis()` **Description**: Runs the built-in pre-analysis passes and stores annotations/subgraphs. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `augment_sarif(path)` **Description**: Merges SARIF findings into the graph. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `augment_weaudit(path)` **Description**: Merges weAudit findings into the graph. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `findings(kind=None)` **Description**: Returns nodes carrying finding-style annotations, optionally filtered by `kind`. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `subgraph(name)` **Description**: Returns the nodes within a named subgraph. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `subgraph_names()` **Description**: Lists all named subgraphs currently present in the graph. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `summary()` **Description**: Provides a summary of the graph, including node and edge counts, and dependencies. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ### `to_json()` **Description**: Exports the full graph as a JSON object. **Method**: N/A (Method of a Python object) **Endpoint**: N/A ``` -------------------------------- ### Lint and Format Code Source: https://github.com/trailofbits/trailmark/blob/main/README.md Run linting and formatting checks using Ruff. The `--fix` flag attempts to automatically correct issues. ```bash # Lint and format uv run ruff check --fix uv run ruff format ``` -------------------------------- ### ASP.NET Core Minimal API Endpoint Source: https://github.com/trailofbits/trailmark/blob/main/docs/entrypoint-patterns.md Defines a minimal API endpoint in ASP.NET Core using `WebApplication`. This approach is suitable for simpler APIs and microservices. ```csharp var app = WebApplication.Create(); app.MapGet("/hello", () => "Hello World!"); ``` -------------------------------- ### Diff Codebase Snapshots Source: https://github.com/trailofbits/trailmark/blob/main/README.md Compare the current codebase analysis against a previous snapshot using `diff_against`. The result includes summaries of changes to nodes, edges, and entrypoints. ```python before = QueryEngine.from_directory("before/") diff = engine.diff_against(before) # diff contains: summary_delta, nodes {added/removed/modified}, # edges {added/removed}, entrypoints {added/removed/modified} ```