> ## Documentation Index
> Fetch the complete documentation index at: https://docs.rafter.so/llms.txt
> Use this file to discover all available pages before exploring further.

# Secret Scanning

> Detect secrets in your code before they leak

# Secret Scanning

Rafter scans your code for secrets and credentials to prevent accidental leaks.

## Quick Start

Scan a directory for secrets:

```bash theme={null}
rafter secrets .
```

> **Note:** `rafter agent scan` still works but is deprecated — it will be removed in a future major version.

## Detected Secret Types

Rafter detects 21+ types of secrets:

<AccordionGroup>
  <Accordion title="Cloud Providers" icon="cloud">
    * AWS Access Keys & Secret Keys
    * Google API Keys & OAuth credentials
    * Azure credentials
  </Accordion>

  <Accordion title="Version Control" icon="code-branch">
    * GitHub Personal Access Tokens
    * GitHub OAuth Tokens
    * GitHub App Tokens
    * GitHub Refresh Tokens
  </Accordion>

  <Accordion title="Payment & SaaS" icon="credit-card">
    * Stripe API Keys (live & restricted)
    * Slack Tokens & Webhooks
    * Twilio API Keys
  </Accordion>

  <Accordion title="Package Registries" icon="box">
    * npm Access Tokens
    * PyPI API Tokens
  </Accordion>

  <Accordion title="Databases & Keys" icon="database">
    * Database connection strings (postgres, mysql, mongodb)
    * Private keys (RSA, DSA, EC, OpenSSH)
    * JWT tokens
    * Generic API keys
  </Accordion>
</AccordionGroup>

## Usage Examples

### Scan Specific File

```bash theme={null}
rafter secrets ./config.js
```

### Scan Directory

```bash theme={null}
rafter secrets ./src
```

### Quiet Mode (CI/CD)

Only output if secrets are found:

```bash theme={null}
rafter secrets --quiet
```

Exits with code `1` if secrets found, perfect for CI pipelines.

### JSON Output

Get machine-readable results:

```bash theme={null}
rafter secrets --json > scan-results.json
```

### Watch Mode

Watch a path for file changes and re-scan automatically:

```bash theme={null}
rafter secrets --watch .
```

Findings are printed inline and logged to `audit.jsonl` in real time. Press Ctrl+C to stop. Watch mode does not exit on findings — it keeps watching.

<Note>Requires `chokidar` (Node, bundled) or `watchdog` (Python: `pip install watchdog`).</Note>

### Diff Scanning

Scan only files changed since a git ref:

```bash theme={null}
# Scan changes since last commit
rafter secrets --diff HEAD~1

# Scan changes since a branch point
rafter secrets --diff main

# Scan changes since a tag
rafter secrets --diff v1.0.0
```

Useful for CI pipelines that only need to check new or modified files.

## Output Format

When secrets are found, Rafter shows:

```
⚠️  Found secrets in 1 file(s):

📄 src/config.js
  🔴 [CRITICAL] AWS Access Key ID
     Location: Line 12
     Pattern: AWS Access Key ID detected
     Redacted: AKIA************MPLE

  🔴 [CRITICAL] GitHub Personal Access Token
     Location: Line 18
     Pattern: GitHub Personal Access Token detected
     Redacted: ghp_****************************stuv
```

### Severity Levels

<Card title="Severity Indicators">
  * 🔴 **Critical**: Immediate security risk (AWS keys, database passwords)
  * 🟠 **High**: Significant risk (generic API keys, bearer tokens)
  * 🟡 **Medium**: Moderate risk (connection strings without credentials)
  * 🟢 **Low**: Low risk (public keys, non-sensitive patterns)
</Card>

## Smart Redaction

Rafter uses smart redaction to show context without exposing secrets:

* **Short secrets** (≤8 chars): Fully redacted (`********`)
* **Long secrets** (>8 chars): Show first 4 and last 4 characters

Example: `AKIAIOSFODNN7EXAMPLE` → `AKIA************MPLE`

## Pre-Commit Scanning

Integrate with git commits:

```bash theme={null}
# Before committing
rafter secrets

# Or use rafter agent exec (scans automatically)
rafter agent exec "git commit -m 'Add feature'"
```

## Excluding Files

Rafter automatically skips:

* Binary files (images, PDFs, executables)
* Build directories (`node_modules`, `dist`, `build`, `.next`)
* Version control (`.git`)
* IDE folders (`.vscode`, `.idea`)

## CI/CD Integration

### GitHub Actions

```yaml theme={null}
- name: Scan for secrets
  run: |
    npm install -g @rafter-security/cli
    rafter secrets --quiet
```

Exit code `1` will fail the pipeline if secrets are detected.

### GitLab CI

```yaml theme={null}
scan-secrets:
  script:
    - npm install -g @rafter-security/cli
    - rafter secrets --quiet
```

## Audit Trail

All scans are logged to `~/.rafter/audit.jsonl`:

```bash theme={null}
# View recent scans
rafter agent audit --event scan_executed

# View secret detections
rafter agent audit --event secret_detected
```

## False Positives

If you encounter false positives:

1. **Exclude patterns** via config:
   ```bash theme={null}
   rafter agent config set agent.patterns.exclude '["test_key_*"]'
   ```

2. **Report issues**: Help improve detection at [rafter-cli/issues](https://github.com/raftersecurity/rafter-cli/issues)

## Advanced Usage

### Scan with Custom Patterns

Define custom patterns in `.rafter.yml`:

```yaml theme={null}
scan:
  custom_patterns:
    - name: "Internal API Key"
      regex: "INTERNAL_[A-Z0-9]{32}"
      severity: critical
```

See [Policy File](/guides/agent-security/policy-file) for full configuration options.

### Engine Selection

Rafter ships two scan engines, selectable via `--engine`:

```bash theme={null}
rafter secrets --engine patterns      # built-in regex (21+ patterns)
rafter secrets --engine betterleaks   # Betterleaks binary (more patterns; v0.8.0+)
rafter secrets --engine auto          # default: try Betterleaks, fall back to patterns
```

Install Betterleaks (the gitleaks successor maintained by the same authors) via `rafter agent init --with-betterleaks` for enhanced detection.

### Respecting `.gitignore`

When the scan target sits inside a git work tree, Rafter honors `.gitignore` by default — files the repo has excluded (build outputs, vendored deps, scratch envs) are not scanned. Every gitignore semantic git itself supports is honored: nested `.gitignore` files, negations, `.git/info/exclude`, and the configured global excludes file.

```bash theme={null}
rafter secrets .                    # default — respects .gitignore
rafter secrets . --no-gitignore     # scan everything, ignore .gitignore
```

Scans against directories outside a git work tree (a plain unversioned folder) fall back to scanning every candidate file, since there's no work tree for the filter to consult.

The `betterleaks` engine has always honored `.gitignore` (gitleaks ancestry); the built-in `patterns` engine reached parity in the same release that introduced `--no-gitignore`.

## Best Practices

<Card title="Recommended Workflow" icon="list-check">
  1. Run `rafter secrets` before every commit
  2. Configure pre-commit hooks for automation
  3. Use `--quiet` mode in CI/CD pipelines
  4. Review audit logs regularly
  5. Report false positives to improve accuracy
</Card>

## Next Steps

<CardGroup cols={2}>
  <Card title="Command Execution" icon="terminal" href="/guides/agent-security/command-execution">
    Learn about safe command execution
  </Card>

  <Card title="Command Reference" icon="book" href="/guides/agent-security/reference">
    Complete CLI command reference
  </Card>
</CardGroup>
