Semgrep Rules

semgrep-rules

Covers Semgrep, writing a rule that flags a code pattern, or a lighter static analysis (SAST) gate than CodeQL that needs no code database: Registry rulesets and custom YAML rules, semgrep ci with diff-aware baselines, nosemgrep suppressions, path filters, severity filters and JSON, SARIF, GitLab or JUnit output.

When to use

Use for any question or task about Semgrep, writing a rule that flags a code pattern, or a lighter static analysis (SAST) gate than CodeQL that needs no code database.

/plugin install qa-security-scanning@testland-qa

First time in Claude Code? Add the marketplace with /plugin marketplace add testland/qa

View source (opens in a new tab)
Skill
Version
v1.1.6
Updated
November 12, 2026

Overview

Per semgrep.dev/docs/getting-started/quickstart (opens in new window):

Semgrep is a fast pattern-based static analyzer covering 30+ languages with a registry of community + paid rulesets and straightforward YAML rule authoring. The semgrep ci subcommand adds CI-aware features (baseline-diff, organization policies, metrics).

Per semgrep.dev/docs/cli-reference (opens in new window):

"semgrep scan: Local scans without account requirement; doesn't return failing codes by default.

semgrep ci: Pipeline execution with organization policies, diff-aware scanning, returns failing codes on findings."

When to use

  • The repo has a .semgrep.yml / .semgrep/ directory or wants zero-config registry rulesets.
  • The user needs PR-time SAST without standing up SonarQube or CodeQL infrastructure.
  • A team prefers pattern-DSL rule authoring over semantic-database query languages.

Step 1 - Install

Per sg-quick (opens in new window):

# macOS
brew install semgrep

# Linux/macOS
pipx install semgrep
# or
uv tool install semgrep

# Windows (PowerShell)
pipx install semgrep

# Docker (CI-friendly)
docker pull semgrep/semgrep

Step 2 - First scan

semgrep scan --config auto

Per sg-cli (opens in new window), --config auto "Auto-fetch rules from registry based on project." Specific rulesets:

semgrep scan --config p/owasp-top-ten     # OWASP Top 10
semgrep scan --config p/default            # broad community ruleset
semgrep scan --config p/python --config p/javascript   # multiple: repeat --config

Step 3 - Custom rule authoring

A minimal Semgrep rule in .semgrep.yml:

rules:
  - id: hardcoded-jwt-secret
    pattern: jwt.sign($PAYLOAD, "...")
    message: Hardcoded JWT secret detected
    languages: [javascript, typescript]
    severity: ERROR
    metadata:
      cwe: "CWE-798: Use of Hard-coded Credentials"

Pattern operators: pattern, pattern-either, pattern-not, metavariable-pattern, pattern-inside. Validate rule syntax:

semgrep validate --config .semgrep.yml

(Per sg-cli (opens in new window) subcommand list.)

Test the rule before it gates CI

Keep custom rules in rules/, one file per rule, and put a test file next to each with the same basename (rules/hardcoded-jwt-secret.yaml → rules/hardcoded-jwt-secret.js). Each annotation is a comment on the line just before the code it describes: ruleid: must match (guards against false negatives), ok: must not (guards against false positives) (sg-test (opens in new window)):

// ruleid: hardcoded-jwt-secret
jwt.sign(payload, "s3cr3t");

// ok: hardcoded-jwt-secret
jwt.sign(payload, process.env.JWT_SECRET);
semgrep --test rules/

Add one ruleid: line per variant the rule must catch (aliased import, template literal, wrapped call). todoruleid: / todook: record known gaps without failing the run (sg-test (opens in new window)).

Step 4 - CI integration with baseline diff

Per sg-cli (opens in new window): "--baseline-commit=VAL - Only show results that are not found in this commit hash". Diff-aware mode fails only NEW findings on the PR; pre-existing findings are tracked but don't block - critical for legacy adoption. The baseline commit must exist locally, so check out full history. semgrep scan exits 0 on findings unless --error is set ("Exit 1 if there are findings").

jobs:
  semgrep:
    runs-on: ubuntu-latest
    container:
      image: semgrep/semgrep
    steps:
      - uses: actions/checkout@v5
        with:
          fetch-depth: 0
      - run: >
          semgrep scan --config p/default --config rules/
          --baseline-commit "${{ github.event.pull_request.base.sha }}"
          --error --sarif --output semgrep.sarif
      - uses: github/codeql-action/upload-sarif@v3
        if: always()
        with: { sarif_file: semgrep.sarif }

With a Semgrep AppSec Platform token, semgrep ci runs the rules configured there, takes the same --baseline-commit, and fails on findings by default; it does not accept --config (sg-cli (opens in new window)). There is no --baseline-ref flag.

Step 5 - False-positive triage (MANDATORY)

Suppression mechanisms in priority order:

MechanismExampleWhen to use
Per-line nosemgrep comment# nosemgrep: hardcoded-passwordJustified single-line exception
nosemgrep block# nosemgrep: rule-id above a code blockMulti-line exception
paths.exclude in configexclude: ["**/*_pb.go"]Generated files / vendored code
Baseline ref--baseline-commit <PR base SHA> (Step 4)Legacy debt; ratchet
Organization-level rule disableSemgrep AppSec Platform UITeam-wide policy

Justification template (mandatory in code):

# nosemgrep: hardcoded-password
# Reason: Test fixture; password never reaches production runtime
# Reviewer: alice@example.com (2026-05-15)
# Expires: 2026-12-15
TEST_PASSWORD = "test-only-password-do-not-deploy"

Per sg-cli (opens in new window) severity filter for triage workflow:

semgrep scan --severity ERROR --json   # only critical findings

Cadence: every quarter, audit nosemgrep suppressions for staleness. Expired ones removed; persistent ones reviewed for escalation.

Step 6 - CLI reference (formats, flags, exit codes)

Gate on exit 0 = clean, 1 = findings, 2 = fatal error. The full output-format flags, performance-tuning flags, and complete exit-code table are in references/cli-reference.md.

Anti-patterns

Anti-patternWhy it failsFix
--config=auto everywhereRulesets drift; no ownershipPin specific rulesets (Step 2)
nosemgrep without justificationBecomes invisible debtRequired justification template (Step 5)
No baseline refEvery legacy finding blocks; team disables--baseline-commit <PR base SHA> (Step 4)
Custom rule with no ruleid: / ok: test fileA pattern edit silently stops matching a variantsemgrep --test rules/ in CI (Step 3)
semgrep scan in CIDoesn't return failing exit code by defaultUse semgrep ci (Step 1 quote)
Mix --severity ERROR with --baseline-commit poorlyCan mask real new findingsSeverity filter at output stage, not scan stage

Limitations

  • Pattern matching can miss cross-file taint flows; for those, pair with codeql-queries.
  • Registry rulesets evolve; pin specific versions for production.
  • Semgrep AppSec Platform features (org policies, supply-chain scanning) are paid; the OSS engine covers the patterns above.

References

Full flag, output-format, and exit-code detail for semgrep-rules. The SKILL.md spine keeps the common commands; this file holds the exhaustive tables. All entries per semgrep.dev/docs/cli-reference (opens in new window).

Output formats

FlagPurpose
--jsonSemgrep JSON format (for multi-scanner triage)
--sarifSARIF format (GitHub Code Scanning upload)
--gitlab-sastGitLab SAST format (GitLab Security Dashboard)
--junit-xmlJUnit XML (test reporters)
--textDefault human-readable
--output VALWrite to file or URL

Performance flags

semgrep scan -j 8 --timeout 10 --max-target-bytes 5000000
  • -j VALUE - Parallelism degree (default: 3)
  • --timeout=DOUBLE - Per-rule per-file timeout in seconds (default: 5.0)
  • --max-target-bytes=VALUE - Skip files exceeding size (default: 1000000)

Exit codes

CodeMeaning
0Success, no issues
1Issues detected (with --error flag)
2Fatal error
3Invalid syntax in scanned language
4Invalid pattern in rule
5Invalid YAML configuration
7Invalid rule in configuration
8Unsupported language specified
13Invalid API key

The spine gates on 0 (pass) / 1 (findings) / 2 (fatal); the rest signal config or rule authoring errors.

  • Review the PR that strips every scanner suppression out of the repo
  • Flipping the monolith's shadow check to blocking, after it missed one
  • We need a pattern for LED-2291 that does not light up our own shell helper
  • The blocking check goes green on the file we deliberately broke
  • Sign off on the tuning proposal for our 22-minute security check

Get new posts by email.

Occasional email with new Testland posts and plugin releases.

Unsubscribe any time. Privacy policy