argus

command module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 29, 2026 License: MIT Imports: 10 Imported by: 0

README ยถ

Argus: Production-Grade Go & PostgreSQL 18 Static Analyzer

Go Reference PostgreSQL 18 Ready Wiki Documentation

Argus is an advanced compile-time static analyzer and pre-commit database safety linter for Go applications and PostgreSQL migrations. Built on top of the official Go analysis framework (go/analysis) and PostgreSQL's native C query parser (libpg_query via pg_query_go), Argus bridges the gap between Go application code and PostgreSQL engine internals.

It enforces 30 production-grade database invariants, eliminating SQL injections, N+1 query latency collapses, connection pool starvation, cross-tenant data leaks, and catastrophic production table locking during zero-downtime schema migrations. Complete specifications and remediation examples are available in the official Argus Wiki.


Why Argus?

Traditional linters only inspect Go syntax, while schema linters only look at migration syntax in isolation. Argus combines both worlds:

  1. Dual-Engine Precision: Analyzes Go AST control-flow, scopes, and taint tracking alongside native PostgreSQL C-parser SQL AST (SelectStmt, FromClause, IndexStmt, etc.).
  2. PostgreSQL 18.x Internals Awareness: Understands MVCC, transaction_timeout GUC, table lock modes (SHARE vs SHARE UPDATE EXCLUSIVE), and partition pruning.
  3. Zero False-Positive Target: Built-in heuristics for idiomatic Go and pgx/v5 constructs (e.g., COUNT(*), pgx.CollectRows, keyset pagination).
  4. Dual Execution Modes: Runs seamlessly as a standard go vet tool or as a standalone CLI for CI/CD pipelines.

Quickstart

Installation
Linux & macOS (One-Line Installer)
curl -fsSL https://raw.githubusercontent.com/will2469/argus/main/install.sh | bash
Windows (PowerShell)
irm https://raw.githubusercontent.com/will2469/argus/main/install.ps1 | iex
Via Go Toolchain
go install github.com/will2469/argus/cmd/argus@latest

Or download pre-compiled binaries directly from GitHub Releases.

Basic Usage
# 1. Run static analysis across current directory and migrations
argus --dirs=. --migrations=migrations

# 2. Generate a comprehensive markdown audit report
argus --output=argus-report.md

# 3. Integrate directly into go vet
go vet -vettool=$(which argus) ./...

# 4. Self-update to the latest release
argus update # or: argus --update, argus -u

# 5. Uninstall Argus from system
argus uninstall # or: argus --uninstall

๐Ÿค– AI Agent Integration (MCP)

Argus ships with a built-in Model Context Protocol (MCP) server. AI coding agents like Cursor, Claude Desktop, VS Code Copilot, and Antigravity can automatically invoke Argus to audit database queries in real-time โ€” no manual tagging required.

Setup โ€” Add to your AI editor's MCP configuration:

{
  "mcpServers": {
    "argus": {
      "command": "argus",
      "args": ["mcp"]
    }
  }
}

Exposed Tools:

Tool Description
argus_scan Full audit of Go source files and SQL migrations against all 30 rules
argus_check_migration Instant safety check for raw SQL DDL/DML snippets
argus_explain_rule Retrieve documentation and fix patterns for any rule (A01โ€“A30)
argus_report_issue Two-phase Human-in-the-Loop (HITL) reporter for false positives & feedback

๐Ÿ’ก The argus_scan tool description instructs AI models to automatically invoke it after writing or modifying database queries โ€” no .cursorrules or prompt engineering needed.

๐Ÿ”’ Enterprise Privacy & Telemetry Kill-Switch

For corporate, banking, or air-gapped environments where outbound issue reporting must be unconditionally disabled, set telemetry: false in .argus.yaml or export ARGUS_TELEMETRY=false:

# .argus.yaml
version: "1"
options:
  telemetry: false # Blocks all outbound issue submission
export ARGUS_TELEMETRY=false

๐Ÿ“– Detailed Guide: Read the full Argus MCP Server Specification & Architecture Wiki for HITL protocols, trust-mode security advisories, and client setup guides.


The 30 Argus Rules Matrix

๐Ÿ“– Full Documentation: Every rule is thoroughly documented in the Argus Wiki. Click on any rule code or identifier below to open its dedicated specification, failure modes, and code fix examples.

Rule Identifier Severity Category Description
A01 UNSAFE_SQL_CONCATENATION CRITICAL Security (CWE-89) Forbids raw string concatenation in queries; mandates $1, $2 bind parameters.
A02 MISSING_DEFER_CLOSE HIGH Reliability Mandates defer rows.Close() immediately after query execution to prevent pool leaks.
A03 UNBOUNDED_CONTEXT HIGH Resilience Prohibits raw context.Background() or context.TODO() in query calls.
A04 UNSAFE_ORDER_BY HIGH Security (CWE-89) Dynamic ORDER BY / GROUP BY must be validated against compile-time static allowlists.
A05 AUDIT_LOG_IMMUTABILITY CRITICAL Compliance Prohibits UPDATE, DELETE, TRUNCATE, or MERGE on append-only audit ledger tables.
A06 RUNTIME_DDL CRITICAL Security Blocks DDL execution in application runtime code; runtime roles must be DML-only.
A07 ERROR_LEAK HIGH Privacy (CWE-200) Forbids leaking raw database error messages or PII details to external clients.
A08 TX_EXTERNAL_IO HIGH Performance Forbids blocking network/disk I/O (HTTP, gRPC, disk) inside active database transactions.
A09 ADVISORY_LOCK HIGH Concurrency Mandates transaction-level advisory locks; forbids session locks in pooled connections.
A10 ISOLATION_LEVEL HIGH Integrity Critical financial/inventory mutations must declare explicit Serializable or FOR UPDATE.
A11 DESTRUCTIVE_MIGRATION CRITICAL Zero-Downtime Prohibits destructive DDL (DROP COLUMN, RENAME) in single releases without expand-contract.
A12 TIMEOUT_CONFIG HIGH Availability Mandates 4-tier timeout settings (statement_timeout, lock_timeout, idle timeouts).
A13 MISSING_DOWN_MIGRATION HIGH Rollback Safety Every .up.sql migration must have a non-empty, deterministic symmetric .down.sql.
A14 FORBIDDEN_SELECT_STAR HIGH Performance Prohibits wildcard SELECT *; mandates explicit column projection to avoid TOAST bloat.
A15 FORBIDDEN_DDL_APP_ROLE_GRANT CRITICAL Security (CWE-250) Prohibits granting DDL/ALL privileges or table ownership to application runtime roles.
A16 MAX_CONNS_CONFIG HIGH Scalability Enforces mathematically bounded MaxConns on connection pools to prevent process thrashing.
A17 FORBIDDEN_QUERY_IN_LOOP HIGH Performance Eliminates N+1 query patterns inside loops in favor of WHERE id = ANY($1) or pgx.Batch.
A18 MISSING_ROWS_ERR_CHECK HIGH Integrity (CWE-391) Mandates rows.Err() check after rows.Next() loops to catch silent network truncations.
A19 UNBOUNDED_QUERY_LIMIT HIGH Resilience (CWE-400) Queries on high-cardinality tables must have an explicit LIMIT or keyset pagination.
A20 PARAM_LIMIT_65535 HIGH Protocol Limits Prevents exceeding PostgreSQL's 65,535 wire parameter ceiling; recommends pgx.CopyFrom.
A21 UNBOUNDED_ROW_LOCK_BLOCKING HIGH Concurrency Queue queries (SELECT ... FOR UPDATE) must use SKIP LOCKED or NOWAIT.
A22 SERIALIZATION_FAILURE_RETRY HIGH Fault Tolerance Serializable transactions must be wrapped in automated retry loops catching SQLSTATE 40001.
A23 TRANSACTION_TIMEOUT_CONFIG HIGH Modern PG17/18 Enforces transaction_timeout cap on connection pools to prevent XID horizon freezing.
A24 TENANT_ISOLATION_LEAK CRITICAL Multi-Tenancy Mandates explicit tenant predicates (WHERE tenant_id = $1) or verified RLS context.
A25 EXPENSIVE_CPU_IN_TRANSACTION HIGH Performance Prohibits CPU-heavy tasks (bcrypt, argon2, RSA keygen, PDF rendering) inside transactions.
A26 LIKE_WILDCARD_INJECTION HIGH Security (CWE-89) Mandates escaping wildcard characters (\, %, _) on user input bound to LIKE/ILIKE.
A27 NON_CONCURRENT_INDEX_CREATION CRITICAL Zero-Downtime Indexes on existing tables must use CREATE INDEX CONCURRENTLY to avoid write lockouts.
A28 TABLE_LOCKING_CONSTRAINT_ADDITION CRITICAL Zero-Downtime FK and CHECK constraints must use 2-phase NOT VALID followed by VALIDATE CONSTRAINT.
A29 UNINDEXED_FOREIGN_KEY HIGH Performance Every foreign key on child tables must have a supporting B-tree index (anti-table scan).
A30 TIMESTAMP_WITHOUT_TIMEZONE CRITICAL Temporal Hygiene Prohibits bare TIMESTAMP; mandates TIMESTAMPTZ (UTC-normalized) for temporal determinism.

Suppressing Findings (Ignore Directives)

When a rule violation is deliberate and reviewed, suppress it with an inline directive:

// In Go code:
// argus:ignore ARGUS-A14 export worker requires full row dump
rows, err := pool.Query(ctx, "SELECT * FROM historical_archive")
-- In SQL migrations:
-- argus:ignore ARGUS-A29 static dictionary table with under 50 rows never deleted
status_code VARCHAR(20) REFERENCES ref_status(code)

Directives require an explanatory reason of at least two words.


Configuration (.argus.yaml)

Initialize a .argus.yaml file in your repository root to configure project-specific settings:

version: "1"

rules:
  ARGUS-A14:
    enabled: true
  ARGUS-A16:
    enabled: true
    max_conns_limit: 50
  ARGUS-A19:
    enabled: true
    default_max_limit: 1000
    high_growth_tables:
      - "orders"
      - "audit_logs"
  ARGUS-A24:
    enabled: true
    tenant_column: "tenant_id"
    tenant_tables:
      - "customers"
      - "invoices"

GitHub Actions CI Integration

name: Database Safety Audit
on: [push, pull_request]

jobs:
  argus:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-go@v5
        with:
          go-version: "1.24"
      - name: Install Argus
        run: go install github.com/will2469/argus/cmd/argus@latest
      - name: Audit Go Packages & Migrations
        run: argus --no-report --dirs=. --migrations=migrations

License

Argus is open-source software licensed under the MIT License.

Documentation ยถ

Overview ยถ

Package main provides the dual-mode CLI and vettool entry point for Argus Checker.

Directories ยถ

Path Synopsis
cmd
argus command
Package main provides the dual-mode CLI and vettool entry point for Argus Checker.
Package main provides the dual-mode CLI and vettool entry point for Argus Checker.
Package rules provides the central registry of all active Argus analyzers.
Package rules provides the central registry of all active Argus analyzers.
a01_sql_concat
Package a01_sql_concat prohibits dynamic SQL concatenation and string formatting in favor of compile-time string constants with parameterized placeholders ($1, $2, ...).
Package a01_sql_concat prohibits dynamic SQL concatenation and string formatting in favor of compile-time string constants with parameterized placeholders ($1, $2, ...).
a02_unclosed_rows
Package a02_unclosed_rows enforces that every pgx.Rows produced by Query() is safely closed via defer rows.Close() or consumed by an auto-closing helper.
Package a02_unclosed_rows enforces that every pgx.Rows produced by Query() is safely closed via defer rows.Close() or consumed by an auto-closing helper.
a03_context
Package a03_context detects database operations executed with raw unbounded contexts such as context.Background() or context.TODO(), enforcing request deadlines or timeouts.
Package a03_context detects database operations executed with raw unbounded contexts such as context.Background() or context.TODO(), enforcing request deadlines or timeouts.
a04_orderby
Package a04_orderby detects unsafe dynamic ORDER BY clauses and enforces that sort columns and directions originate from closed-set allowlist maps or switch-case branches.
Package a04_orderby detects unsafe dynamic ORDER BY clauses and enforces that sort columns and directions originate from closed-set allowlist maps or switch-case branches.
a05_audit_immutability
Package a05_audit_immutability enforces that audit log tables remain append-only by forbidding UPDATE, DELETE, TRUNCATE, MERGE, and DROP operations.
Package a05_audit_immutability enforces that audit log tables remain append-only by forbidding UPDATE, DELETE, TRUNCATE, MERGE, and DROP operations.
a06_runtime_ddl
Package a06_runtime_ddl prohibits executing DDL statements in Go application runtime code.
Package a06_runtime_ddl prohibits executing DDL statements in Go application runtime code.
a07_error_leak
Package a07_error_leak prohibits exposing raw database driver errors, pgconn.PgError fields (Detail, Hint, Where), or raw err.Error() strings into API responses.
Package a07_error_leak prohibits exposing raw database driver errors, pgconn.PgError fields (Detail, Hint, Where), or raw err.Error() strings into API responses.
a08_tx_io
Package a08_tx_io enforces that open database transactions do not enclose blocking external I/O operations (HTTP, network, disk, sleep, command execution).
Package a08_tx_io enforces that open database transactions do not enclose blocking external I/O operations (HTTP, network, disk, sleep, command execution).
a09_advisory_lock
Package a09_advisory_lock ensures safe PostgreSQL advisory lock usage by prohibiting session-level locks on connection pools and forbidding hardcoded integer magic numbers.
Package a09_advisory_lock ensures safe PostgreSQL advisory lock usage by prohibiting session-level locks on connection pools and forbidding hardcoded integer magic numbers.
a10_isolation_level
Package a10_isolation_level enforces that transactions modifying critical tables (saldo, kuota, nomor_urut, rekening) do not rely on default ReadCommitted isolation.
Package a10_isolation_level enforces that transactions modifying critical tables (saldo, kuota, nomor_urut, rekening) do not rely on default ReadCommitted isolation.
a11_destructive_migration
Package a11_destructive_migration enforces that .up.sql schema migrations do not execute destructive DDL operations that break zero-downtime rolling deployments.
Package a11_destructive_migration enforces that .up.sql schema migrations do not execute destructive DDL operations that break zero-downtime rolling deployments.
a12_timeout_config
Package a12_timeout_config enforces explicit server-side and client-side timeout configurations (statement_timeout, lock_timeout, idle_in_transaction, MaxConnIdleTime, MaxConnLifetime) on pgxpool initialization.
Package a12_timeout_config enforces explicit server-side and client-side timeout configurations (statement_timeout, lock_timeout, idle_in_transaction, MaxConnIdleTime, MaxConnLifetime) on pgxpool initialization.
a13_missing_down_migration
Package a13_missing_down_migration ensures every .up.sql migration has a valid, non-empty corresponding .down.sql rollback migration.
Package a13_missing_down_migration ensures every .up.sql migration has a valid, non-empty corresponding .down.sql rollback migration.
a14_select_star
Package a14_select_star detects and forbids wildcard column selection (SELECT * and alias.*) in application database queries to prevent TOAST table bloat, buffer cache pollution, and PII leaks (CWE-200).
Package a14_select_star detects and forbids wildcard column selection (SELECT * and alias.*) in application database queries to prevent TOAST table bloat, buffer cache pollution, and PII leaks (CWE-200).
a15_ddl_grant
Package a15_ddl_grant forbids granting DDL permissions or table ownership to runtime application roles in migration scripts.
Package a15_ddl_grant forbids granting DDL permissions or table ownership to runtime application roles in migration scripts.
a16_max_conns
Package a16_max_conns enforces explicit, bounded MaxConns configuration on pgxpool to prevent Linux kernel process thrashing, memory exhaustion, and connection starvation.
Package a16_max_conns enforces explicit, bounded MaxConns configuration on pgxpool to prevent Linux kernel process thrashing, memory exhaustion, and connection starvation.
a17_nplusone
Package a17_nplusone detects and eliminates N+1 database query patterns inside loops in favor of set-based (ANY($1)) or batch operations.
Package a17_nplusone detects and eliminates N+1 database query patterns inside loops in favor of set-based (ANY($1)) or batch operations.
a18_rows_err
Package a18_rows_err enforces mandatory rows.Err() checks immediately after database cursor loops (for rows.Next()) to prevent silent dataset truncation.
Package a18_rows_err enforces mandatory rows.Err() checks immediately after database cursor loops (for rows.Next()) to prevent silent dataset truncation.
a19_unbounded_limit
Package a19_unbounded_limit detects and flags queries without LIMIT clauses on high-cardinality tables to prevent buffer cache pollution and Go runtime OOM crashes (CWE-400).
Package a19_unbounded_limit detects and flags queries without LIMIT clauses on high-cardinality tables to prevent buffer cache pollution and Go runtime OOM crashes (CWE-400).
a20_param_limit
Package a20_param_limit enforces PostgreSQL 65,535 wire protocol parameter bounds on dynamic multi-row and IN clause statements, promoting pgx.CopyFrom and ANY($1).
Package a20_param_limit enforces PostgreSQL 65,535 wire protocol parameter bounds on dynamic multi-row and IN clause statements, promoting pgx.CopyFrom and ANY($1).
a21_row_lock
Package a21_row_lock enforces non-blocking directives (SKIP LOCKED / NOWAIT) on multi-row and task queue row locks to prevent lock convoys and serialization bottlenecks.
Package a21_row_lock enforces non-blocking directives (SKIP LOCKED / NOWAIT) on multi-row and task queue row locks to prevent lock convoys and serialization bottlenecks.
a22_serializable_retry
Package a22_serializable_retry enforces automatic retry loops on Serializable and RepeatableRead transactions to prevent unhandled 500 serialization abort errors (SQLSTATE 40001, 40P01).
Package a22_serializable_retry enforces automatic retry loops on Serializable and RepeatableRead transactions to prevent unhandled 500 serialization abort errors (SQLSTATE 40001, 40P01).
a23_tx_timeout
Package a23_tx_timeout enforces explicit transaction_timeout GUC parameter on pgxpool configuration for PostgreSQL 17/18+ targets to prevent XID horizon freezing and dead tuple bloat.
Package a23_tx_timeout enforces explicit transaction_timeout GUC parameter on pgxpool configuration for PostgreSQL 17/18+ targets to prevent XID horizon freezing and dead tuple bloat.
a24_tenant_leak
Package a24_tenant_leak enforces explicit tenant isolation predicates (WHERE tenant_id = $1) or verified RLS session context on multi-tenant tables to prevent cross-tenant data leaks (CWE-284, BOLA).
Package a24_tenant_leak enforces explicit tenant isolation predicates (WHERE tenant_id = $1) or verified RLS session context on multi-tenant tables to prevent cross-tenant data leaks (CWE-284, BOLA).
a25_expensive_cpu
Package a25_expensive_cpu enforces that active database transactions do not enclose CPU-expensive operations (password hashing, key derivation, asymmetric keygen, subprocess exec) to prevent connection pool exhaustion and lock duration inflation (CWE-400, CWE-662).
Package a25_expensive_cpu enforces that active database transactions do not enclose CPU-expensive operations (password hashing, key derivation, asymmetric keygen, subprocess exec) to prevent connection pool exhaustion and lock duration inflation (CWE-400, CWE-662).
a26_like_sanitize
Package a26_like_sanitize enforces wildcard sanitization on user input bound to SQL LIKE/ILIKE clauses.
Package a26_like_sanitize enforces wildcard sanitization on user input bound to SQL LIKE/ILIKE clauses.
a27_concurrent_index
Package a27_concurrent_index enforces that creating indexes on existing tables in migration scripts must use the CREATE INDEX CONCURRENTLY syntax.
Package a27_concurrent_index enforces that creating indexes on existing tables in migration scripts must use the CREATE INDEX CONCURRENTLY syntax.
a28_constraint_lock
Package a28_constraint_lock enforces 2-phase zero-downtime constraint additions (NOT VALID followed by VALIDATE CONSTRAINT) on existing tables in migrations.
Package a28_constraint_lock enforces 2-phase zero-downtime constraint additions (NOT VALID followed by VALIDATE CONSTRAINT) on existing tables in migrations.
a29_unindexed_fk
Package a29_unindexed_fk enforces that foreign key columns on child tables have supporting B-tree indexes where the FK column is the leading column.
Package a29_unindexed_fk enforces that foreign key columns on child tables have supporting B-tree indexes where the FK column is the leading column.
a30_timestamptz
Package a30_timestamptz scans table definitions and alter commands for bare TIMESTAMP columns.
Package a30_timestamptz scans table definitions and alter commands for bare TIMESTAMP columns.
shared
callsite
Package callsite provides AST recognition utilities for database operations, supporting modern Go 1.22-1.26+ idioms including generic call wrappers and string concatenation.
Package callsite provides AST recognition utilities for database operations, supporting modern Go 1.22-1.26+ idioms including generic call wrappers and string concatenation.
config
Package config provides configuration parsing and defaults for Argus.
Package config provides configuration parsing and defaults for Argus.
directives
Package directives provides parsing and evaluation of inline argus:ignore comments.
Package directives provides parsing and evaluation of inline argus:ignore comments.
mcp
Package mcp implements a native Model Context Protocol (MCP) server for Argus.
Package mcp implements a native Model Context Protocol (MCP) server for Argus.
migration
Package migration provides shared types and utilities for migration SQL file scanners.
Package migration provides shared types and utilities for migration SQL file scanners.
sqlparser
Package sqlparser provides helpers and caching for pg_query_go PostgreSQL AST parsing.
Package sqlparser provides helpers and caching for pg_query_go PostgreSQL AST parsing.
updater
Package updater provides self-updating capabilities for the Argus binary.
Package updater provides self-updating capabilities for the Argus binary.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL