> For the complete documentation index, see [llms.txt](https://docs.sonarsource.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.sonarsource.com/sonarqube-cli/analysis/secrets-detection.md).

# Secrets detection

Hardcoded credentials in source code are one of the most common and most preventable security incidents. Secrets detection works with SonarQube Cloud, SonarQube Server, and with no server connection at all. The SonarQube CLI ships secrets scanning in three forms, each tuned for a different moment in the developer workflow:

* Ad-hoc: `sonar analyze secrets` scans files or stdin from your terminal or a script.
* Git layer: `sonar integrate git` installs a hook that blocks commits or pushes containing secrets.
* AI agent layer: `sonar integrate claude` installs a `UserPromptSubmit` hook (scans the prompt you send to Claude) and a `PreToolUse` hook (runs before file reads/writes). `sonar integrate copilot` installs a pre-tool-use hook. `sonar integrate codex` installs a `UserPromptSubmit` hook for Codex, plus instructions that tell Codex to scan a file for secrets before reading it. `sonar integrate cursor` installs a `beforeSubmitPrompt` hook plus `beforeReadFile` and `preToolUse` hooks that scan files before the agent reads them. These integrations block any operation that would expose a secret.

Use any combination of the three.

## Prerequisites

* [The SonarQube CLI is installed and authenticated](/sonarqube-cli/quickstart-guide.md).

Secrets detection runs locally on your machine. No code leaves your machine for the scan itself.

## Scan on demand

`sonar analyze secrets` reads files (or standard input) and reports any hardcoded credentials it finds. Use it to check a file before committing, audit an `.env` file, or run as part of a CI step.

### Scan a single file

```bash
sonar analyze secrets src/config.ts
```

### Scan multiple paths or a directory

```bash
sonar analyze secrets src/ infra/
```

### Scan from standard input

```bash
cat .env | sonar analyze secrets --stdin
```

### Use in a script

The command exits with code `51` when it finds secrets and `0` when it finds none. Wire it into any pipeline:

```bash
sonar analyze secrets .
if [ $? -eq 51 ]; then
  echo "Secrets found — failing the build."
  exit 1
fi
```

See [Exit codes](/sonarqube-cli/using-sonarqube-cli/exit-codes.md) for the full table.

### Terminal output

On a clean run, `sonar analyze secrets` prints a green checkmark row per scanned file and ends with `No issues found · Nms`. When secrets are detected, findings are grouped by file with a warning marker; each line shows the description, masked value, and rule key, followed by `N secret(s) found · Nms`.

### Scan warnings

Some scanner conditions (for example, a custom-rules download failure) produce advisory warnings instead of aborting the scan. In text output these appear as `Scan warning:` lines. They don't change the exit code — a clean scan still exits `0`, and a detection still exits `51`.

## Block secrets at the Git layer

Install a Git hook so commits or pushes containing secrets are rejected before they reach a remote:

```bash
sonar integrate git --hook pre-commit
```

Pre-push hooks and global (machine-wide) installation are also supported. For setup, hook behavior with Husky and the pre-commit framework, and override options, see [Git hooks](/sonarqube-cli/integrations/git-hooks.md).

## Block secrets at the AI agent layer

When you give an AI coding assistant access to your repository, it can accidentally exfiltrate secrets by reading and including them in prompts sent to the model provider. The SonarQube CLI prevents this by installing a hook that runs **before** the agent reads or writes files.

* **Claude Code:** [Claude Code](/sonarqube-cli/integrations/claude-code.md)
* **GitHub Copilot CLI:** [GitHub Copilot CLI](/sonarqube-cli/integrations/github-copilot-cli.md)
* **Cursor:** [Cursor](/sonarqube-cli/integrations/cursor.md)

After installation, restart the agent. From then on, any attempt by the agent to access a file containing a secret is blocked, and the agent is told why.

## When scanning is inactive

Secrets hooks fail closed when they cannot run a scan. If you're not authenticated or the `sonar-secrets` analyzer binary is missing, the hook blocks the operation instead of silently allowing it through.

* **Git hooks** (`pre-commit`, `pre-push`): the commit or push is blocked (exit code `1`) with a message telling you to run `sonar auth login` or re-run `sonar integrate`. See [git-hooks.md](/sonarqube-cli/integrations/git-hooks.md#runtime-requirements).
* **Agent hooks** (Claude Code, GitHub Copilot CLI, Cursor, Codex, Antigravity): the prompt or file read is blocked with an agent-specific deny response and the same remediation message.

Scan errors during an otherwise healthy run (for example, a network failure mid-scan) still fail open on agent hooks. On Cursor file-read hooks, only exit code `2` is treated as a deny; other non-zero exit codes are hook errors that fail open. The auth-and-binary gate is separate from that scan-error path.

## False positives and tuning

Secrets detection is intentionally sensitive; missing a real credential is much worse than catching test fixtures. The analyzer already ignores obviously fake values, so most false positives come from test fixtures that look like real provider-issued credentials.

When that happens:

* **Keep realistic-looking test fixtures outside of source.** Move them into ignored files (`.env.test`) or fixture directories outside `src/`.
* **Use environment variables in tests** where possible, even when the value is a fake.

If you believe a finding is genuinely wrong, share it on the [community forum](https://community.sonarsource.com/tag/secrets); we use these reports to tune detection.

### Custom secret rules from SonarQube Server

When the SonarQube CLI is authenticated against a SonarQube Server instance, it automatically downloads and executes custom secret rules (instances of the rule template **S6784**) defined on that server. Rules are cached locally and refreshed on each run. If the download fails, the SonarQube CLI falls back to a stale cache with a warning. No CLI flag is required; the feature activates automatically when the SonarQube CLI is authenticated.

> **Note:** Custom secret rules are not yet available on SonarQube Cloud. Support is planned.

## What the scanner looks for

Secrets detection uses the same engine that powers SonarQube's server-side secret detection rules. It looks for patterns issued by major providers (AWS, GCP, GitHub, Stripe, SonarQube tokens, and many more) as well as generic high-entropy strings used in credential-shaped contexts.

## Why an obvious "password" is not always reported

Secrets detection is a layered pipeline that intentionally filters aggressively to keep false-positive rates low. Working through the layers, common reasons a hardcoded value is not reported:

1. **The file extension is in the rejected-extensions list.** For example, `.md`, `.mdx`, `.html`, `.adoc`, `.example`, `.sample`, `.template`, `.dist` are skipped by every rule. This is the most likely reason.
2. **The value is a simple word** (e.g. `password`, `mypassword`, `123456`), rejected by the fake-password filter.
3. **The value has low entropy** (e.g. `letmein`, `abc123def`), rejected by the entropy filter. Pass `--disable-entropy-filter` to surface it as a low-confidence finding.
4. **The file is in a `docs/` or `test/` directory**, or is named like a test file, silently skipped by automatic test-file detection. Pass `--disable-test-file-detection` to surface findings in those files as low-confidence.
5. **The file extension is not in the inclusions list** (and the file has no assigned language), never reached by the scanner at all.

All of these layers are intentional. The goal is to surface real, leaked credentials, not every string that looks vaguely secret-like.

## Feedback

Found a false positive, a crash, or a pattern that should be detected? Tell us on the [Sonar Community forum, secrets tag](https://community.sonarsource.com/tag/secrets).

## Related pages <a href="#related-pages" id="related-pages"></a>

* [Git hooks](/sonarqube-cli/integrations/git-hooks.md)
* [Claude Code](/sonarqube-cli/integrations/claude-code.md)
* [GitHub Copilot CLI](/sonarqube-cli/integrations/github-copilot-cli.md)
* [Exit codes](/sonarqube-cli/using-sonarqube-cli/exit-codes.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.sonarsource.com/sonarqube-cli/analysis/secrets-detection.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
