A fast, concurrent Go CLI for detecting leaked API keys, tokens, credentials, and high entropy secrets across working trees and full Git commit histories.
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.
- 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 (>= 30chars, default threshold> 5.0bits/char) while filtering hashes, JWTs, PEM headers, and repeated characters.
- 48 embedded regex signatures (
- 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 viamerkletrie, and streams changed/inserted blobs directly viaf.Reader()without buffering full commit trees.
- Working-tree mode walks files concurrently across a bounded worker pool (
- 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
.gitscannerignorefiles, repeatable--excludeglobs, custom--extextension lists, and--entropy-thresholdtuning. - Safe Output & CI Integration: Redacts secrets while preserving recognizable prefixes, writes reports with
0600file permissions in Markdown or JSON (with embedded phase timings and counters), prints a structuredSCAN SUMMARY, and supports--fail-on-findingsfor CI gates.
-
Entry & Configuration (
main.go,cmd/scan.go,internal/config)main.gocreates a signal-aware context (SIGINT/SIGTERM) and delegates to Cobra'sscansubcommand.config.Configvalidates mutually exclusive targets (--localor--repo), worker counts, entropy bounds (0–8), and output format (markdownorjson).
-
Engine Initialization & Target Resolution (
internal/engine,internal/repo)engine.Runcompiles either the 48 embedded rules insign.jsonor a custom--signaturesfile viadetector.NewEngine/detector.NewEngineFromFile.repo.Resolvevalidates local paths withos.Stator clones remotehttp://,https://,git@, andssh://URLs intoos.TempDir()(shallow--depth 1for working-tree scans; full clone when--historyis enabled) and cleans up temporary clones when the scan finishes.- Any
.gitscannerignorein the resolved root is loaded and merged with--excludepatterns into awalker.Filter.
-
Mode Dispatch (
--historyvs. Working Tree)- Working-Tree Pipeline (
internal/walker,internal/worker):walker.WalkWithFiltertraverses the directory tree, skips excluded paths and non-matching extensions, and feeds file paths into a bufferedjobschannel (capacity200) consumed by--workersconcurrent goroutines. - History Diff Pipeline (
internal/git,internal/lifecycle):git.ScanHistoryDiffscollects commits, orders them topologically (oldest -> newest) using Kahn's algorithm, computes parent-tree diffs withmerkletrie, and distributes changed/inserted*object.Fileblobs across workers that enforceShouldScanGitFile(<= 500 KB) and stream contents directly withf.Reader().
- Working-Tree Pipeline (
-
Line Scanning & 3-Layer Detection (
internal/scanner,internal/detector)- Workers stream lines using pooled
64 KB–1 MBbufio.Scannerbuffers (sync.Pool), running regex signatures, keyword heuristics, and Shannon entropy checks per line. - For regex rules with capture groups,
extractSecretMatchextracts the matched secret token rather than storing the entire source line.
- Workers stream lines using pooled
-
Post-Processing (
internal/aggregator,internal/lifecycle)- Working-Tree Mode:
aggregator.Aggregatededuplicates findings usingFinding.DedupKey()(file + line + type + match) and sorts deterministically by file path and line number. - History Mode:
lifecycle.buildLifecycleFromDiffsreplays commit scan results in topological order, clearing prior state for touched paths and tracking active secrets per file to computeIntroducedCommit,RemovedCommit,ExposureCommits,ExposureWindow, andStillPresentInHEAD.
- Working-Tree Mode:
-
Redaction, Reporting & Telemetry (
internal/utils,internal/output,internal/metrics)utils.SanitizeSecretmasks the middle of every secret while preserving known provider prefixes (e.g.,sk-ant-api03-,ghp_,AKIA).outputprints findings to stdout and optionally writes Markdown or JSON reports (0600permissions), with JSON reports embeddingScanMetricsphase timings and counters.metrics.ScanMetricsprints aSCAN SUMMARYblock, and--fail-on-findingsexits non-zero (FindingsError) when one or more findings are detected.
- Go:
1.25.0or newer (matchinggo.mod) - Git (optional): Needed only if running external OSS benchmark tests (
make test-all)
git clone https://github.com/Dharshan2208/git-scanner.git
cd git-scanner
make build
./git-scanner scan --local .go install github.com/Dharshan2208/git-scanner@latest
git-scanner scan --local /path/to/repodocker build -t git-scanner .
docker run --rm -v "$(pwd):/workspace:ro" git-scanner scan --local /workspacego run . scan --local .# 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$ ./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
────────────────────────────────────────────────────────
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. |
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.jsonCustom 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,})"
}
]
}- 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 KBare skipped in--historymode; single lines exceeding1 MBreturnbufio.ErrTooLong.
.
├── 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
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 ./...- 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-branchHEADscoping. - 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 MBexceed the scanner's token buffer (bufio.ErrTooLong).
Contributions are welcome! See CONTRIBUTING.md for development setup, Conventional Commit guidelines, and rules for adding new secret signatures.
Licensed under the GNU Affero General Public License v3.0 (AGPL-3.0).
