How to Write Custom Semgrep Rules for Your Own Codebase

October 28, 2026

Public Semgrep rulesets catch generic bugs: SQL injection, hardcoded secrets, weak crypto. They cannot catch the mistake your team keeps making — calling the internal pricing service without the tenant header, or reading a config value before the feature flag loads.

Those are the rules worth writing. They take 20 minutes each and they encode knowledge that otherwise lives in one person’s head.

What does a Semgrep rule consist of?

Five keys minimum: id, languages, severity, message, pattern (or a pattern combinator).

rules:
  - id: internal-pricing-no-tenant-header
    languages: [typescript]
    severity: ERROR
    message: >-
      Call pricingClient.quote() through quoteWithTenant(), which sets the
      X-Tenant header. Direct calls return the wrong currency.
    patterns:
      - pattern: pricingClient.quote(...)
      - pattern-not-inside: |
          function quoteWithTenant(...) {
            ...
          }
    metadata:
      category: correctness
      confidence: HIGH

The rule id should read like a sentence about the bug. internal-pricing-no-tenant-header is searchable later; rule-17 isn’t.

metadata is free-form and shows up in JSON output. Putting confidence and category there lets you filter later without rewriting rules.

How do pattern combinators work?

Individual patterns match code shape. Combinators compose them, and this is where rules stop being brittle.

  • patterns: all must match
  • pattern-either: any may match
  • pattern-not: must not match
  • pattern-inside: the match must occur inside this structure
  • pattern-not-inside: excluded if inside this structure
  • pattern-not-regex: exclusion by regex over the matched code

The guard pattern is the workhorse. A rule for “no raw SQL string concatenation” fires on every execute(...); adding pattern-not-inside: | sanitizeQuery(...) { ... } makes it respect the escape hatch your team already has.

Metavariables are the other half. $X matches one expression, $...ARGS matches any number of arguments, $FUNC matches a name you can reuse.

patterns:
  - pattern: $LOG.info($MSG, ...)
  - metavariable-regex:
      metavariable: $MSG
      regex: '(?i).*(password|token|secret).*'

That flags log lines that mention credentials. It’s crude and it will have false positives — but it’s exactly the kind of rule a generic registry can’t write, because it depends on your logging conventions.

metavariable-pattern goes further: apply a nested pattern to what a metavariable captured, so you can say “the first argument is a literal string” or “it’s a call to os.environ“.

How does taint mode work?

Taint tracking answers “does untrusted data reach a dangerous sink?” without you listing every intermediate expression. That’s the difference between a rule that finds three instances and one that finds all of them.

rules:
  - id: tenant-id-from-request-to-query
    languages: [python]
    severity: ERROR
    message: Filter by tenant must come from the session, never from the request body.
    mode: taint
    pattern-sources:
      - pattern: request.json[$KEY]
      - pattern: request.args.get(...)
    pattern-sinks:
      - pattern: db.execute(..., $TENANT, ...)
    pattern-sanitizers:
      - pattern: current_user.tenant_id
      - pattern: validate_tenant(...)
    metadata:
      category: security

Sources are where untrusted data enters. Sinks are where it must not reach unsanitized. Sanitizers break the chain — if data passed through one, it’s considered clean.

Sane starting point: set sources to your framework’s request objects and sinks to your data layer’s query builders. Then run on the repo and look at what fires. If a rule fires on 200 lines, the sanitizers are wrong, not the code.

Taint mode has scope limits worth knowing. It tracks within a function and through direct calls. It doesn’t follow data through a queue, a database, or an HTTP hop to another service. Multi-service taint is a different class of tool.

How do you test a rule before trusting it?

Semgrep has built-in annotation-based testing, and using it is the difference between a rule you can maintain and one that silently stops matching after a refactor.

Create tests/internal-pricing-no-tenant-header.ts:

ruleid: internal-pricing-no-tenant-header
pricingClient.quote(cart);

ok: internal-pricing-no-tenant-header
quoteWithTenant(cart, tenantId);

ruleid: asserts the next line matches. ok: asserts it doesn’t. Run:

semgrep --test

Then update CI to run --test whenever a rule file changes. Rules rot quietly — a refactor renames pricingClient and the rule matches nothing, and your scan reports zero findings with no indication it’s broken.

Two more testing habits worth the effort:

  • Test against the real codebase. semgrep --config custom.yml --dryrun shows findings without severity gating. If the count is zero on a repo where you know the bug exists, the rule is broken.
  • Keep a todo baseline. semgrep --baseline-commit origin/main reports only findings introduced since that commit. It lets you adopt a strict rule on a legacy codebase without fixing 300 existing violations first.

How do you ship rules to a team?

A semgrep/ directory in the repo, symlinked or copied into CI, is enough for up to about 15 rules. Each file gets a comment explaining the bug it prevents and a link to the incident that motivated it.

Local config composition:

semgrep --config p/default --config ./semgrep/

Multiple --config flags merge. Keep the public ruleset for breadth and put your own in ./semgrep/ for depth.

Beyond 15 rules, a shared rules repo consumed via --config pointed at a git URL is worth it — but only when two teams need the same rules. One team with a shared repo is overhead with no payoff, and the rules will drift anyway.

What types of rules are worth writing?

Ranked by return:

  1. Forbidden API calls — deprecated functions, direct DB access outside the repository layer, unvalidated external calls. Zero false positives if the API is unambiguous.
  2. Taint rules for your stack — request data to a query, header to a log line, file upload to a shell. Highest value, most tuning.
  3. Logging hygiene — PII, tokens, full request bodies.
  4. Style you actually enforce — if a linter already covers it, skip; Semgrep is slower than ESLint.

Anything a linter handles is a waste of a Semgrep rule. The cases above are ones where the linter can’t see across functions or won’t know your domain.

Quick Summary

  • A custom rule needs id, languages, severity, message and a pattern; combine with patterns, pattern-either, pattern-inside.
  • Taint mode (mode: taint) finds data flows from sources to sinks without listing intermediates.
  • Add sanitizers that reflect your real escape hatches or taint rules flood with noise.
  • Write ruleid:/ok: test files and run semgrep --test in CI — untested rules rot silently.
  • Use --baseline-commit to adopt strict rules on legacy code without fixing old violations first.
  • Prioritise forbidden-API rules and taint rules; anything a linter already covers isn’t worth the effort.
Tags: