Skip to content

About

Fast concurrent secret scanner for Git repositories with signature, keyword, and entropy-based detection, built in Go with optional full history scanning.

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

git-scanner

A fast, concurrent Go CLI for detecting leaked API keys, tokens, credentials, and high entropy secrets across working trees and full Git commit histories.

Go Version License: AGPL-3.0

git-scanner combines embedded provider signatures, two-tier keyword heuristics, and Shannon entropy analysis into a concurrent scanning pipeline built on go-git and cobra. It works against local directories, remote repositories (http://, https://, git@, ssh://), and full commit histories without checking out historical commits on disk.


Features

  • Three-Layer Secret Detection:
    • 48 embedded regex signatures (internal/detector/sign.json) covering AWS, OpenAI, Anthropic, GitHub, GitLab, Stripe, Slack, Discord, Supabase, database URIs, private keys, and more—with support for overriding via --signatures.
    • Two-tier keyword heuristics (internal/detector/keyword.go) pairing high-confidence identifiers (api_key, aws_secret_access_key, client_secret) with generic credential keys (token, secret, password) and filtering common placeholders (XXXX, CHANGEME, EXAMPLE, PLACEHOLDER).
    • Shannon entropy detection (internal/detector/entropy.go) using a stack-allocated frequency table to flag unknown high-randomness tokens (>= 30 chars, default threshold > 5.0 bits/char) while filtering hashes, JWTs, PEM headers, and repeated characters.
  • Working-Tree & Topological History Modes:
    • Working-tree mode walks files concurrently across a bounded worker pool (runtime.NumCPU() by default or --workers).
    • History mode (--history) sorts commits topologically (Kahn's algorithm, oldest to newest), diffs each commit against its parent via merkletrie, and streams changed/inserted blobs directly via f.Reader() without buffering full commit trees.
  • Secret Lifecycle State Machine: Tracks where each secret was introduced, the commit in which it was removed (including zero-finding cleanup commits), total exposed commits, and whether it remains active in HEAD.
  • Configurable Filtering & Ignore Rules: Supports .gitscannerignore files, repeatable --exclude globs, custom --ext extension lists, and --entropy-threshold tuning.
  • Safe Output & CI Integration: Redacts secrets while preserving recognizable prefixes, writes reports with 0600 file permissions in Markdown or JSON (with embedded phase timings and counters), prints a structured SCAN SUMMARY, and supports --fail-on-findings for CI gates.

How It Works

git-scanner architecture and scan pipeline

Pipeline Walkthrough

  1. Entry & Configuration (main.go, cmd/scan.go, internal/config)

    • main.go creates a signal-aware context (SIGINT/SIGTERM) and delegates to Cobra's scan subcommand.
    • config.Config validates mutually exclusive targets (--local or --repo), worker counts, entropy bounds (0–8), and output format (markdown or json).
  2. Engine Initialization & Target Resolution (internal/engine, internal/repo)

    • engine.Run compiles either the 48 embedded rules in sign.json or a custom --signatures file via detector.NewEngine / detector.NewEngineFromFile.
    • repo.Resolve validates local paths with os.Stat or clones remote http://, https://, git@, and ssh:// URLs into os.TempDir() (shallow --depth 1 for working-tree scans; full clone when --history is enabled) and cleans up temporary clones when the scan finishes.
    • Any .gitscannerignore in the resolved root is loaded and merged with --exclude patterns into a walker.Filter.
  3. Mode Dispatch (--history vs. Working Tree)

    • Working-Tree Pipeline (internal/walker, internal/worker): walker.WalkWithFilter traverses the directory tree, skips excluded paths and non-matching extensions, and feeds file paths into a buffered jobs channel (capacity 200) consumed by --workers concurrent goroutines.
    • History Diff Pipeline (internal/git, internal/lifecycle): git.ScanHistoryDiffs collects commits, orders them topologically (oldest -> newest) using Kahn's algorithm, computes parent-tree diffs with merkletrie, and distributes changed/inserted *object.File blobs across workers that enforce ShouldScanGitFile (<= 500 KB) and stream contents directly with f.Reader().
  4. Line Scanning & 3-Layer Detection (internal/scanner, internal/detector)

    • Workers stream lines using pooled 64 KB–1 MB bufio.Scanner buffers (sync.Pool), running regex signatures, keyword heuristics, and Shannon entropy checks per line.
    • For regex rules with capture groups, extractSecretMatch extracts the matched secret token rather than storing the entire source line.
  5. Post-Processing (internal/aggregator, internal/lifecycle)

    • Working-Tree Mode: aggregator.Aggregate deduplicates findings using Finding.DedupKey() (file + line + type + match) and sorts deterministically by file path and line number.
    • History Mode: lifecycle.buildLifecycleFromDiffs replays commit scan results in topological order, clearing prior state for touched paths and tracking active secrets per file to compute IntroducedCommit, RemovedCommit, ExposureCommits, ExposureWindow, and StillPresentInHEAD.
  6. Redaction, Reporting & Telemetry (internal/utils, internal/output, internal/metrics)

    • utils.SanitizeSecret masks the middle of every secret while preserving known provider prefixes (e.g., sk-ant-api03-, ghp_, AKIA).
    • output prints findings to stdout and optionally writes Markdown or JSON reports (0600 permissions), with JSON reports embedding ScanMetrics phase timings and counters.
    • metrics.ScanMetrics prints a SCAN SUMMARY block, and --fail-on-findings exits non-zero (FindingsError) when one or more findings are detected.

Installation

Prerequisites

  • Go: 1.25.0 or newer (matching go.mod)
  • Git (optional): Needed only if running external OSS benchmark tests (make test-all)

Build from Source

git clone https://github.com/Dharshan2208/git-scanner.git
cd git-scanner
make build
./git-scanner scan --local .

Install via go install

go install github.com/Dharshan2208/git-scanner@latest
git-scanner scan --local /path/to/repo

Run via Docker

docker build -t git-scanner .
docker run --rm -v "$(pwd):/workspace:ro" git-scanner scan --local /workspace

Run Without Building

go run . scan --local .

Usage

Common Examples

# Scan the current working tree and print redacted findings + summary
./git-scanner scan --local .

# Clone and scan a remote repository, saving a Markdown report
./git-scanner scan --repo https://github.com/OWNER/REPO --output report.md

# Scan full Git commit history and export JSON with lifecycle metadata and metrics
./git-scanner scan --local /path/to/repo --history --output report.json --format json

# Run in CI with custom extensions, exclusions, and non-zero exit on findings
./git-scanner scan --local . --ext .go,.py,.env --exclude "testdata/**" --fail-on-findings

Sample Output

$ ./git-scanner scan --local . --output report.md
Resolved Path :  .
[FOUND] .env | Anthropic API Key | Line : 4
       Match: sk-ant-api03-abcd...wxyz
Scanning completed.....
Total findings : 1
Report saved to: report.md

────────────────────────────────────────────────────────
  SCAN SUMMARY
────────────────────────────────────────────────────────
  Wall time       : 21.4ms
    ├─ resolve    : 120µs
    ├─ walk       : 1.8ms
    ├─ scan       : 18.2ms
    ├─ aggregate  : 14.1ms
    ├─ output     : 1.1ms
  Throughput      : 514 files/s
  Files
    Discovered : 11
    Scanned    : 11
    Skipped    : 4
    Data       : 42.3 KB
  Findings        : 1
    ├─ Anthropic API Key   : 1
────────────────────────────────────────────────────────

CLI Reference

git-scanner scan (--local <path> | --repo <url>) [flags]

--local and --repo are mutually exclusive; one of them is required.

Flag / Environment Default Description
--local <path> "" Local directory to scan.
--repo <url> "" Remote Git URL (http://, https://, git@, ssh://) cloned into os.TempDir() and removed after scan.
--history false Scan Git commit diffs in topological order and attach secret lifecycle metadata (disables shallow clone for --repo).
--output <file> "" File path to save a report (0600 permissions; stdout only when omitted).
--format <fmt> markdown Report format when --output is set: markdown (md) or json.
--signatures <file> "" Path to a custom signatures JSON file overriding the 48 embedded rules.
--exclude <pattern> [] Glob or path pattern to exclude (repeatable; combined with .gitscannerignore).
--ext <list> (31 defaults) File extensions to scan (comma-separated or repeatable, e.g. --ext .go,.py).
--workers <n> NumCPU Number of concurrent worker goroutines.
--entropy-threshold <f> 5.0 Shannon entropy cutoff (0–8) for high-entropy detection.
--fail-on-findings false Return a non-zero exit code (FindingsError) if any findings are detected.
SSH_AUTH_SOCK (env) (system) Used implicitly by go-git / ssh-agent when cloning private git@ or ssh:// repositories.

Configuration & Filtering

.gitscannerignore

If a .gitscannerignore file exists in the target repository root, git-scanner loads patterns from it automatically (ignoring blank lines and # comments) and merges them with --exclude:

# Ignore test fixtures and generated assets
testdata/
fixtures/**
*.min.js
mock_secrets.json

Custom Signatures (--signatures)

Custom signature files follow the same schema as internal/detector/sign.json. If a regex defines capture groups, git-scanner extracts the final non-empty capture group as the secret match:

{
  "signatures": [
    {
      "name": "Internal Service Token",
      "pattern": "SVC_TOKEN=([A-Za-z0-9_\\-]{24,})"
    }
  ]
}

Scanning Scope & Defaults

  • Default extensions (31): .go, .js, .jsx, .ts, .tsx, .py, .rb, .php, .java, .rs, .c, .sh, .bash, .zsh, .ps1, .env, .json, .yaml, .yml, .toml, .ini, .cfg, .conf, .properties, .xml, .sql, .tf, .tfvars, .pem, .key, .txt (override with --ext).
  • Default skipped directories (11): .git, node_modules, vendor, dist, build, temp, .venv, venv, __pycache__, target, .next.
  • Default skipped files (6): package-lock.json, yarn.lock, pnpm-lock.yaml, go.sum, composer.lock, .DS_Store.
  • Size & line limits: Blobs larger than 500 KB are skipped in --history mode; single lines exceeding 1 MB return bufio.ErrTooLong.

Project Structure

.
├── cmd/                     # Cobra root and scan commands + CLI tests
├── docs/
│   └── how-it-works.png     # Architecture & pipeline diagram
├── internal/
│   ├── aggregator/          # Finding deduplication and deterministic sorting
│   ├── config/              # CLI/scan configuration and .gitscannerignore matching
│   ├── detector/            # Embedded sign.json (48 rules), Engine loader, keyword & entropy checks
│   ├── engine/              # Unified scan pipeline orchestrator
│   ├── git/                 # Kahn topological sort and merkletrie parent-diff traversal
│   ├── lifecycle/           # Streaming diff scanner and secret exposure state machine
│   ├── metrics/             # Atomic counters, phase timers, and SCAN SUMMARY formatter
│   ├── output/              # Console, Markdown, and JSON reporters (0600 file mode)
│   ├── repo/                # Local path validation and context-aware remote cloning
│   ├── scanner/             # Pooled buffered line/stream scanner and match extractor
│   ├── types/               # Shared Finding struct and DedupKey
│   ├── utils/               # Prefix-preserving secret redaction and hash truncation
│   ├── walker/              # Filesystem and git-tree file filters
│   └── worker/              # Concurrent worker pool
├── tests/
│   └── benchmark_test.go    # Synthetic pipeline tests, leak checks, and OSS benchmarks
├── CONTRIBUTING.md          # Development workflow and signature authoring rules
├── Dockerfile               # Multi-stage Alpine container image
├── LICENSE                  # GNU AGPL-3.0
├── Makefile                 # Build, fmt, vet, test, bench, lint, and clean targets
├── go.mod / go.sum          # Go module dependencies
└── main.go                  # Entry point and SIGINT/SIGTERM context setup

Development & Testing

Use the Makefile targets or run Go tooling directly:

# Run offline unit, integration, and race-detector tests
make test          # go test -race -short ./...

# Run all tests including external OSS repository checks (requires network + git)
make test-all      # go test -race ./...

# Run benchmarks
make bench         # go test -bench=. -benchmem -benchtime=3x ./tests/

# Format, vet, and lint
make fmt
make vet
make lint          # golangci-lint run ./...

Limitations

  • History diff scanning inspects diffs against each commit's primary parent (c.Parent(0)), and lifecycle tracking evaluates across all collected refs rather than per-branch HEAD scoping.
  • Binary files and extensions outside the configured list are skipped.
  • Heuristic rules (keyword and entropy) may occasionally surface non-secret high-randomness strings.
  • Single lines larger than 1 MB exceed the scanner's token buffer (bufio.ErrTooLong).

Contributing

Contributions are welcome! See CONTRIBUTING.md for development setup, Conventional Commit guidelines, and rules for adding new secret signatures.


License

Licensed under the GNU Affero General Public License v3.0 (AGPL-3.0).

About

Fast concurrent secret scanner for Git repositories with signature, keyword, and entropy-based detection, built in Go with optional full history scanning.

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages