# Write a Semgrep rule to catch a risky code pattern

Produces a working Semgrep rule with test cases, so you can block a bug or security pattern across your codebase.

- Topic: Software Development
- Framework: Few-Shot
- Level: Standard
- Tags: Coding, Write, Code, Fill-in Template
- Source: https://www.thinkwithprompt.com/prompts/write-a-semgrep-rule-to-catch-a-risky-code-pattern

## Prompt

```text
Write a Semgrep rule that catches a code pattern I want to find or block.

**Language:** [e.g. Python, JavaScript/TypeScript, Java, Go]
**What to catch:** [DESCRIBE the bug, security issue, or banned API - e.g. "SQL built with string formatting passed to cursor.execute"]
**Bad code examples:** [PASTE 2-3 SNIPPETS that should match]
**Good code examples:** [PASTE SNIPPETS that must NOT match]
**Where it runs:** [CI, pre-commit, IDE]
**Severity and fix advice:** [what developers should do instead]

Return:
1. The rule in YAML with: id, message (why it matters and how to fix), severity, languages, and the pattern logic. Use the simplest construct that works: pattern, then patterns / pattern-either / pattern-not / pattern-inside / metavariable-regex, and taint mode (pattern-sources / pattern-sinks / pattern-sanitizers) only if the issue is about data flowing from input to a dangerous call.
2. A test file with `# ruleid:` and `# ok:` annotations covering every bad and good example, plus 2 edge cases you think could cause false positives or misses.
3. An explanation of each part of the rule in plain language.
4. Known limitations (e.g. cross-file flows, aliasing, wrappers) and how to reduce false positives.
5. An autofix (`fix:`) only if the replacement is safe in every matched case; otherwise say why not.

Tell me the command to run the tests locally. If my examples are ambiguous, state the assumption you made.
```

## What to fill in

- e.g. Python, JavaScript/TypeScript, Java, Go
- PASTE 2-3 SNIPPETS that should match
- PASTE SNIPPETS that must NOT match
- CI, pre-commit, IDE
- what developers should do instead

Free to copy and use. From ThinkWithPrompt (https://www.thinkwithprompt.com/), a library of 2,663 curated AI prompts.
