Inferensys

Prompt

Code Snippet Security Anti-Pattern Detection Prompt

A practical prompt playbook for using Code Snippet Security Anti-Pattern Detection Prompt in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Code Snippet Security Anti-Pattern Detection Prompt.

This prompt is designed for security engineers and technical documentation reviewers who need to systematically audit code examples embedded in developer documentation, SDK READMEs, API quickstarts, and migration guides for security vulnerabilities. The job-to-be-done is not a general code review but a focused security anti-pattern scan: identifying hardcoded credentials, missing input validation, insecure default configurations, exposed secrets, and outdated cryptographic practices that could be copy-pasted by downstream developers into production systems. The ideal user has security domain knowledge and can triage findings, but the prompt itself encodes the detection patterns so that a senior developer or technical writer can run the initial scan before escalating to a security specialist.

Use this prompt when you have a batch of code snippets extracted from documentation and need a structured, consistent security audit. Required context includes the full code snippet, the programming language or framework, and the documentation context (e.g., 'this is a quickstart example for an authentication endpoint'). The prompt works best with snippets between 5 and 200 lines; larger code blocks should be split into logical units. You must also supply a [RISK_LEVEL] threshold to control sensitivity—'low' for informational flags only, 'medium' for likely vulnerabilities, and 'high' for strict detection of even potential anti-patterns. The prompt expects a defined [OUTPUT_SCHEMA] that maps findings to severity, CWE references, line numbers, and remediation guidance.

Do not use this prompt as a replacement for static analysis security testing (SAST) tools on production codebases, dynamic application security testing (DAST), or manual penetration testing. It is not designed to find novel zero-day vulnerabilities, business logic flaws, or context-dependent authorization bypasses. The prompt is also inappropriate for auditing code that is intentionally insecure for demonstration purposes unless you explicitly set [CONSTRAINTS] to suppress false positives for educational examples. For documentation that includes redacted credentials or placeholder values, add a pre-processing step to mark those as intentional before running the audit, or the prompt will flag them as hardcoded secrets. Always route findings rated 'critical' or 'high' to a human security reviewer before publishing remediation guidance to documentation consumers.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works for detecting security anti-patterns in documented code samples, and where it falls short.

01

Good Fit: Static Code Review

Use when: auditing code snippets in documentation, READMEs, or quickstart guides for hardcoded secrets, weak cryptography, and missing input validation. The prompt excels at pattern matching against known insecure practices in isolated code blocks. Guardrail: Pair with a compilability check to ensure the snippet being reviewed is syntactically valid before security analysis.

02

Bad Fit: Runtime Behavior Analysis

Avoid when: you need to detect vulnerabilities that only manifest at runtime, such as race conditions, memory corruption, or injection flaws that depend on dynamic data flow. The prompt sees only static text, not execution paths. Guardrail: Route runtime security concerns to dynamic analysis tools (SAST/DAST) and use this prompt only for documentation-level code review.

03

Required Inputs

Must provide: the exact code snippet to audit, the language or framework context, and the intended audience (e.g., production example vs. conceptual illustration). Without language context, the prompt cannot distinguish between secure and insecure patterns for that ecosystem. Guardrail: Always include a language identifier and a usage context label to prevent false positives from simplified educational examples.

04

Operational Risk: False Positives in Tutorial Code

Risk: tutorial and getting-started guides often show simplified patterns (hardcoded placeholders, inline credentials for readability) that are insecure in production but intentional for learning. The prompt may flag these as critical vulnerabilities. Guardrail: Add a [CONTEXT] field indicating whether the snippet is production-bound or educational. Suppress critical severity for explicitly marked tutorial code unless a real secret is exposed.

05

Operational Risk: Outdated Crypto Guidance

Risk: the prompt may flag cryptographic algorithms based on its training data cutoff, missing recently deprecated or newly broken primitives. It might also recommend replacements that are themselves outdated. Guardrail: Maintain a living [CRYPTO_POLICY] appendix with your organization's approved algorithms, minimum key lengths, and forbidden primitives. Update this policy independently of the prompt template.

06

Not a Replacement for Human Review

Risk: teams may treat the prompt's output as a complete security audit, skipping manual review of flagged issues or ignoring context-specific risks the model cannot assess. Guardrail: Every finding must include a human_review_required boolean. Critical and high-severity findings must route to a security engineer for confirmation before publication. The prompt is a triage tool, not a sign-off.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for auditing code snippets in documentation for security anti-patterns.

The prompt below is designed to be copied directly into your AI harness, IDE, or evaluation pipeline. It uses square-bracket placeholders for all dynamic inputs so you can swap in code samples, documentation context, and output format requirements without rewriting the core instruction. The template enforces a structured security audit that flags hardcoded credentials, missing input validation, insecure defaults, exposed secrets, and outdated cryptographic practices in documented code examples.

text
You are a security engineer auditing code snippets in developer documentation. Your task is to identify security anti-patterns that could lead to vulnerabilities if copied by users.

## Input

[CODE_SNIPPET]

## Context

[LANGUAGE]: The programming language of the snippet.
[FRAMEWORK]: The framework or library used, if any.
[DOC_PURPOSE]: What the documentation example is intended to demonstrate.
[SECURITY_POLICY]: Optional. Internal security standards or rules to check against.

## Audit Categories

For each category below, determine if the snippet contains an anti-pattern. Provide a finding only when an issue exists.

1. **Hardcoded Credentials**: API keys, passwords, tokens, secrets, or connection strings in plain text.
2. **Missing Input Validation**: User-supplied data used without sanitization, validation, or parameterization.
3. **Insecure Defaults**: Debug mode enabled, permissive CORS, disabled certificate verification, default admin credentials.
4. **Exposed Secrets in Logs or Output**: Credentials or sensitive data written to stdout, logs, or error messages.
5. **Outdated Cryptographic Practices**: MD5, SHA1, DES, RC4, weak key lengths, or deprecated cipher suites.
6. **Injection Vulnerabilities**: SQL, command, LDAP, XPath, or template injection via unsanitized input.
7. **Missing Authentication or Authorization Checks**: Endpoints or functions lacking access control.
8. **Insecure Data Storage**: Plaintext storage of sensitive data, missing encryption at rest.
9. **Dependency Risks**: Use of known-vulnerable library versions or unmaintained packages.
10. **Error Information Leakage**: Stack traces, system paths, or internal details exposed to users.

## Output Format

Return a JSON object with this exact schema:

{
  "snippet_id": "string or null if not provided",
  "language": "string",
  "framework": "string or null",
  "overall_risk": "none" | "low" | "medium" | "high" | "critical",
  "findings": [
    {
      "category": "string from audit categories above",
      "severity": "low" | "medium" | "high" | "critical",
      "line_numbers": "string describing location, e.g., 'lines 4-7'",
      "description": "string explaining the vulnerability",
      "exploit_scenario": "string describing how an attacker could exploit this",
      "remediation": "string with the secure alternative",
      "cwe_id": "string or null, e.g., 'CWE-798'"
    }
  ],
  "secure_rewrite": "string containing a corrected version of the snippet, or null if no changes needed"
}

## Constraints

- Only report findings that are actually present. Do not invent issues.
- If the snippet is a minimal example for illustration, note this in the finding description but still flag the risk.
- For each finding, provide a concrete, compilable remediation.
- If no issues are found, return an empty findings array and overall_risk of "none".
- Do not include commentary outside the JSON output.

[ADDITIONAL_CONSTRAINTS]

To adapt this template, replace each bracketed placeholder with your actual inputs. The [CODE_SNIPPET] accepts raw code as a string—escape quotes and newlines as needed for your JSON transport. The [SECURITY_POLICY] placeholder can reference internal standards like "OWASP Top 10 2021" or your organization's specific secure coding guidelines. The [ADDITIONAL_CONSTRAINTS] field lets you inject extra rules, such as ignoring certain categories for tutorial code or requiring specific CWE mappings. After adapting, run the prompt through your evaluation harness with known-vulnerable and known-clean snippets to calibrate detection accuracy before production use.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Code Snippet Security Anti-Pattern Detection Prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[CODE_SNIPPET]

The code sample to audit for security anti-patterns

def connect(host, user, password): return db.connect(host, user, password, ssl=False)

Must be non-empty string. Validate length > 0. If snippet exceeds model context window, split into chunks with overlap markers.

[LANGUAGE]

Programming language or framework context for accurate pattern detection

Python 3.11

Must match a known language identifier. Validate against allowlist of supported languages. Unknown languages should trigger a fallback to generic pattern detection with a confidence warning.

[SECURITY_POLICY_REFERENCE]

Link or identifier for the organization's security standards to check against

OWASP Top 10 2021, CIS Benchmark v8

Optional but recommended. If provided, validate URL reachability or internal policy ID existence. If null, prompt defaults to OWASP Top 10 and CWE Top 25.

[SEVERITY_THRESHOLD]

Minimum severity level to include in the audit report

MEDIUM

Must be one of: CRITICAL, HIGH, MEDIUM, LOW, INFO. Validate enum membership. Invalid values should default to MEDIUM with a warning logged.

[CONTEXT]

Surrounding documentation or usage notes that explain the snippet's intended purpose

This function is used in an internal admin tool behind a VPN. Credentials are passed at runtime.

Optional string. If provided, model should use it to reduce false positives for patterns that are safe in context. Validate length does not exceed 20% of total prompt budget.

[OUTPUT_FORMAT]

Desired structure for the security audit report

JSON with fields: finding_id, severity, cwe_id, location, description, remediation, false_positive_likelihood

Must be a valid format descriptor. Validate against supported output schemas: JSON, MARKDOWN_TABLE, SARIF. Unsupported formats should fall back to JSON with a warning.

[FALSE_POSITIVE_EXAMPLES]

Known safe patterns that resemble anti-patterns but are acceptable in this codebase

Hardcoded 'localhost:9092' is a metrics endpoint with no auth required by design.

Optional array of strings. Each example should be a clear description of the pattern and why it is acceptable. Validate array length does not exceed 5 entries to avoid diluting detection.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the security anti-pattern detection prompt into a documentation pipeline with validation, retries, and human review gates.

This prompt is designed to operate as a pre-publication gate in a documentation CI/CD pipeline, not as a one-off audit tool. The implementation harness should treat each code snippet as a discrete unit of work, passing it through the prompt with consistent [LANGUAGE], [FRAMEWORK], and [RISK_LEVEL] parameters derived from the document's metadata. The model's output must be parsed into a structured JSON object containing a findings array, a severity enum (CRITICAL, HIGH, MEDIUM, LOW, NONE), and a requires_human_review boolean. This structured output is the contract between the prompt and the rest of the pipeline—without it, automated gating decisions become brittle and error-prone.

Validation and retry logic is critical because the prompt operates in a high-stakes security context. After receiving the model response, the harness must validate that: (1) the output parses as valid JSON matching the expected schema, (2) every finding includes a snippet_line reference that maps to an actual line in the input code block, (3) severity is one of the allowed enum values, and (4) cwe_id fields, when present, correspond to real CWE entries. If validation fails, implement a single retry with the error message injected into [CONSTRAINTS] as a correction instruction. If the retry also fails, escalate the snippet to the human review queue rather than silently accepting a malformed response. Log every validation failure and retry attempt with the snippet ID, model, timestamp, and error details for observability.

Model selection and tool integration should favor models with strong code reasoning capabilities. For most documentation pipelines, a capable mid-tier model (such as Claude 3.5 Sonnet or GPT-4o) provides sufficient accuracy for anti-pattern detection without the latency and cost of frontier models. However, for [RISK_LEVEL] values of CRITICAL—such as authentication code, cryptographic operations, or payment handling—consider routing to a stronger model or requiring mandatory human review regardless of the model's confidence. The harness should integrate with existing static analysis tools (Semgrep, CodeQL, or language-specific linters) by using their findings as pre-filtering signals: snippets that pass static analysis with zero findings can skip the LLM review entirely, reducing cost and latency. Snippets flagged by static analysis should be enriched with the tool's findings in [CONTEXT] before being sent to the prompt, giving the model additional signals to work with.

Human review integration is non-negotiable for CRITICAL and HIGH severity findings. The harness should route these findings to a review queue (GitHub issues, Jira tickets, or a dedicated review UI) with the original snippet, the model's finding, the static analysis results, and a pre-populated remediation suggestion. For MEDIUM findings, consider a confidence threshold: if the model's self-reported confidence is below 0.85, escalate to human review; otherwise, auto-generate a documentation fix PR with the suggested remediation. LOW severity findings can be logged for periodic batch review. Never auto-merge security-related documentation changes without human approval when the finding involves credential handling, cryptography, authentication, or authorization logic. The harness should also track false positive rates by requiring reviewers to classify each escalated finding as CONFIRMED, FALSE_POSITIVE, or NEEDS_CLARIFICATION, feeding this data back into prompt refinement and model selection decisions over time.

IMPLEMENTATION TABLE

Expected Output Contract

Define the exact shape of the security audit output so downstream systems can parse, display, and route findings reliably.

Field or ElementType or FormatRequiredValidation Rule

finding_id

string (slug)

Must match pattern SEC-###. Unique per snippet.

severity

enum: CRITICAL, HIGH, MEDIUM, LOW, INFO

Must be one of the allowed enum values. CRITICAL reserved for exposed live credentials.

cwe_id

string (CWE-XXX)

Must match pattern CWE-\d{1,4}. Validate against a known CWE list if available.

vulnerability_title

string (max 120 chars)

Must be a concise, human-readable summary. Cannot be empty or null.

offending_snippet

string (code block)

Must be an exact, escaped substring from [CODE_SAMPLE]. Cannot be paraphrased.

remediation_guidance

string (markdown)

Must contain a corrected code example. Length must be > 50 characters.

requires_human_review

boolean

Must be true if severity is CRITICAL or HIGH. Otherwise, can be false.

confidence_score

number (0.0 - 1.0)

If present, must be a float between 0.0 and 1.0. Null allowed if model cannot estimate.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when using an LLM to audit code snippets for security anti-patterns, and how to prevent it in production.

01

False Negatives on Context-Dependent Vulnerabilities

What to watch: The model misses vulnerabilities that depend on how a function is called, not just its internal logic. A snippet showing a parameterized SQL query looks safe, but the calling code might concatenate user input before passing it. Guardrail: Always prompt the model to flag missing context and request the calling code. Pair the prompt with a static analysis tool that traces data flow across files.

02

Over-Flagging of Secure-by-Default Patterns

What to watch: The model flags modern framework features as insecure because they resemble legacy anti-patterns. For example, a React component using dangerouslySetInnerHTML with a DOMPurify sanitizer may be incorrectly flagged. Guardrail: Include a [FRAMEWORK_CONTEXT] variable specifying the language, version, and libraries in use. Instruct the model to suppress findings when secure wrappers or sanitizers are present.

03

Hallucinated CVE or CWE References

What to watch: The model invents plausible-sounding CVE numbers or maps findings to incorrect CWE categories to appear authoritative. This erodes trust in the audit report. Guardrail: Add a strict constraint: Do not cite specific CVE IDs unless they are provided in the [KNOWN_VULNERABILITIES] context. Reference only CWE categories. Validate any generated IDs against a local database before publishing.

04

Ignoring Insecure Defaults in Configuration Snippets

What to watch: The model focuses on application code and overlooks infrastructure-as-code or configuration files (e.g., Terraform, Dockerfiles, CI/CD YAML) that expose ports, disable TLS, or hardcode secrets. Guardrail: Explicitly include configuration files in the [INPUT] and instruct the model to audit them for the same security categories. Use a separate pass for infrastructure-specific anti-patterns.

05

Inconsistent Severity Classification

What to watch: The model rates a hardcoded test credential as CRITICAL in one snippet and LOW in another, making it impossible to triage findings programmatically. Guardrail: Provide a strict [SEVERITY_RUBRIC] in the prompt with concrete criteria for each level (e.g., CRITICAL: Exploitable remotely without authentication). Use a second LLM call or a rule-based classifier to normalize the final severity.

06

Failure to Detect Subtle Cryptographic Weaknesses

What to watch: The model correctly flags MD5 but misses insecure configurations of secure algorithms, such as AES in ECB mode, RSA with 1024-bit keys, or hardcoded static IVs. Guardrail: Add a specific [CRYPTO_CONSTRAINTS] section listing banned algorithms, modes, and minimum key sizes. Instruct the model to verify not just the algorithm name but its parameters and mode of operation.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating whether the prompt correctly identifies security anti-patterns in code snippets before the output is shipped to documentation reviewers.

CriterionPass StandardFailure SignalTest Method

Hardcoded Credential Detection

Flags all instances of hardcoded API keys, passwords, tokens, or secrets in [CODE_SNIPPET]

Misses a plaintext credential or flags a placeholder like [YOUR_API_KEY] as a real secret

Run against a golden set of 10 snippets with known embedded credentials and 5 with safe placeholders

Missing Input Validation Flagging

Identifies code paths where user-supplied [INPUT] reaches a dangerous sink without sanitization or validation

Reports no finding when unsanitized input flows to SQL query, shell command, or file path

Test with snippets containing SQL injection, command injection, and path traversal vulnerabilities

Insecure Default Identification

Detects use of debug mode enabled, default admin credentials, or permissive CORS settings in example code

Misses DEBUG=True in Django settings snippet or Access-Control-Allow-Origin: * in configuration example

Validate against a curated set of framework-specific insecure default patterns

Outdated Cryptographic Practice Flagging

Flags use of MD5, SHA1 for security purposes, DES, RC4, or hardcoded static IVs/nonces

Passes a snippet using hashlib.md5() for password hashing without comment

Run against snippets with known weak algorithms and verify each flagged instance includes the algorithm name

Exposed Secret in Logging or Error Output

Detects when sensitive data like tokens, PII, or session IDs are written to logs or error messages

Misses console.log(apiKey) or print(f'Connected as {password}') in example code

Test with snippets that log variables named token, secret, password, or key

Severity Classification Accuracy

Assigns CRITICAL to credential exposure, HIGH to injection flaws, MEDIUM to insecure defaults, LOW to informational findings

Classifies a hardcoded production database password as MEDIUM or LOW severity

Evaluate against a labeled severity dataset with 20 findings and require exact match on CRITICAL and HIGH

False Positive Rate on Safe Patterns

Does not flag parameterized queries, environment variable references, or properly validated input as vulnerabilities

Flags os.getenv('API_KEY') as a hardcoded credential or parameterized SQL as injection risk

Run against 15 snippets known to be secure and require zero HIGH or CRITICAL false positives

Output Schema Compliance

Returns valid JSON matching [OUTPUT_SCHEMA] with all required fields present and correct types

Missing severity field, line_number as string instead of integer, or remediation field empty

Validate output with JSON Schema validator after each test run and reject non-conforming responses

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single language target. Remove strict output schema requirements initially—accept free-text findings to iterate faster on detection patterns.

code
Analyze the following [LANGUAGE] code snippet for security anti-patterns.
Focus on: hardcoded credentials, missing input validation, insecure defaults.

[CODE_SNIPPET]

Watch for

  • Over-flagging low-risk patterns (e.g., console.log in examples)
  • Missing context about whether the snippet is a demo or production code
  • No severity classification, making triage harder
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.