Security for AI-generated code
Brands AI mentions
Also mentioned rarely: Checkmarx, GitHub Advanced Security, Dependabot, Docker, GitHub, Trivy, TruffleHog, OSV Scanner, OWASP Zed Attack Proxy (ZAP), SonarQube, GitHub Actions, ESLint, npm, pip-audit, Checkov, Socket, Checkmarx One, Veracode, Ruff, OWASP Dependency-Check, govulncheck, Syft, Firecracker, GitHub Copilot, Cycode, Semgrep Guardian, Sonarsource, Bandit, Aikido, GitGuardian, AFL++, DeepCode AI, Black Duck, Ordo, Pylint, Checkmarx One Developer Assist, Endor Labs, pytest, OpenSSF Scorecard, GitLab CI, OWASP, NIST Secure Software Development Framework, CodeRabbit AI, GitHub Code Security, OX Security
- SemgrepChatGPTChatGPT 82%Google AI ModeGoogle AI Mode 79%
- SnykChatGPTChatGPT 51%Google AI ModeGoogle AI Mode 63%
- CodeQLChatGPTChatGPT 59%Google AI ModeGoogle AI Mode 19%
- Snyk CodeChatGPTChatGPT 24%Google AI ModeGoogle AI Mode 52%
- GitleaksChatGPTChatGPT 49%Google AI ModeGoogle AI Mode 23%
Pages AI cites most for this topic
Third-party sites shaping AI recommendations here
- GitHub - gitleaks/gitleaks: Find secrets with Gitleaks 🔑 · GitHub (opens in a new tab)11%
github.com · Names CodeRabbit AI, GitLab, GitHub
- GitHub - semgrep/semgrep: Lightweight static analysis for many languages. Find bug variants with patterns that look like source code. · GitHub (opens in a new tab)10%
github.com · Names Figma, Snowflake, GitLab
Questions and answers
ChatGPTNov 20, 2026
Securing and validating AI-generated code: workflows, tools, and best practices
The safest way to handle code generated by large language models (LLMs) is to treat it as untrusted third-party code until it has passed independent verification.
AI-generated code can be syntactically correct, pass basic tests, and still contain serious security vulnerabilities. It may also introduce outdated dependencies, insecure defaults, hardcoded credentials, hidden assumptions, or unnecessary permissions.
I recommend a defense-in-depth workflow with seven stages:
AI-generated code security pipeline
-
Inspect and understand
Review the generated code, architecture, assumptions, and changes.
-
Sanitize and normalize
Remove secrets, unsafe constructs, unnecessary functionality, and suspicious dependencies.
-
Analyze statically
Run SAST, linting, and secure coding checks.
-
Validate dependencies
Check packages, versions, vulnerabilities, licenses, and software provenance.
-
Test dynamically
Run unit, integration, fuzz, and security tests in an isolated environment.
-
Verify and review
Conduct human code review and threat modeling.
-
Deploy with safeguards
Use CI/CD security gates, least privilege, monitoring, and rollback mechanisms.
The important principle is that no individual tool establishes that generated code is safe. Multiple independent verification techniques should be combined.
1. Tools for verifying and sanitizing generated code
The following tools cover complementary parts of the security lifecycle.
A. Static application security testing (SAST)
SAST examines source code without executing it. It is particularly useful for detecting insecure patterns introduced by an LLM.
Semgrep
(Recommended)
- Detects SQL injection, command injection, insecure APIs, and other coding patterns.
- Supports custom security rules.
- Can run locally and in CI/CD.
GitHub CodeQL
- Performs semantic analysis of code.
- Identifies vulnerabilities through data-flow and control-flow analysis.
- Integrates with GitHub pull requests and code scanning.
SonarQube
- Finds security issues, bugs, and maintainability problems.
- Supports multiple programming languages.
- Provides continuous inspection and quality gates.
Bandit
- Specializes in Python security analysis.
- Detects dangerous functions, weak cryptography, and unsafe configurations.
Example commands:
bash# Python security scanning bandit -r ./src # Semgrep security rules semgrep scan --config auto ./src # JavaScript/TypeScript linting npx eslint .B. Dependency and software supply-chain verification
LLMs sometimes recommend outdated, nonexistent, or malicious packages. This is a particularly important risk because a seemingly harmless generated import can introduce vulnerable third-party code.
Tool Primary purpose OSV-Scanner Detects known vulnerabilities in dependencies Snyk Dependency and code vulnerability analysis OWASP Dependency-Check Identifies dependencies with known CVEs Trivy Scans dependencies, containers, and infrastructure Syft Generates software bills of materials (SBOMs) Useful commands:
bash# JavaScript dependencies npm audit # Python dependencies pip-audit # Scan a project with Trivy trivy fs . # Generate an SBOM syft dir:. -o cyclonedx-jsonRecommended practices:
- Pin dependency versions.
- Verify package names and maintainers.
- Review package release histories.
- Block dependencies with unacceptable known vulnerabilities.
- Generate and retain an SBOM.
- Use trusted package registries and lockfiles.
OWASP specifically warns against accepting package recommendations from AI without independent verification.
C. Secret and sensitive-information detection
Generated code can inadvertently contain API keys, credentials, tokens, private keys, and connection strings.
Gitleaks
Scans repositories and Git history for exposed secrets.
TruffleHog
Detects secrets and can verify whether certain credentials are active.
Example:
bashgitleaks detect --source . --redactFor sanitization, also:
- Remove hardcoded secrets and replace them with environment variables or a secrets manager.
- Rotate any credentials that may already have been exposed.
- Exclude
.env, private keys, and credential files from AI coding-tool context. - Scan Git history, not just the latest working directory.
Importantly, deleting a credential from the current file does not invalidate a credential already exposed in Git history.
D. Dynamic application security testing (DAST)
DAST tests the application while it is running. It can expose issues that source-code analysis misses.
Tool Application OWASP ZAP Web application security testing Burp Suite Web and API security testing Nuclei Template-based security checks AFL++ Coverage-guided fuzz testing Jazzer JVM fuzz testing For example, OWASP ZAP can help identify:
- Missing security headers.
- Authentication weaknesses.
- Cross-site scripting.
- Injection vulnerabilities.
- Insecure application configurations.
Only run active security tests against systems you own or are explicitly authorized to test.
E. Infrastructure and configuration scanning
AI-generated Dockerfiles, Kubernetes manifests, Terraform files, and CI/CD pipelines also need security review.
Useful tools:
- Checkov — infrastructure-as-code security.
- Trivy — container and configuration scanning.
- Hadolint — Dockerfile linting.
- KICS — infrastructure configuration security.
Look for:
- Containers running as root.
- Excessive cloud IAM permissions.
- Publicly exposed storage.
- Missing encryption.
- Unpinned container images.
- Insecure CI/CD permissions.
- Secrets embedded in deployment configurations.
2. A practical end-to-end workflow
Here is how I would implement a repeatable verification process for code produced by ChatGPT, Claude, Copilot, Cursor, or other AI coding assistants.
Suggested verification sequence
Stage 1 — AI-generated code
Treat output as untrusted input
Stage 2 — Isolation and sanitization
- Separate branch or disposable workspace
- Remove secrets and sensitive data
- Inspect all changed files
- Verify external dependencies
Stage 3 — Automated analysis
- Semgrep / CodeQL
- Gitleaks
- OSV-Scanner / Trivy
- Linting and type checking
Stage 4 — Controlled execution and testing
- Unit and integration tests
- Fuzz testing
- DAST
- Container isolation
- Restricted network access
Stage 5 — Independent security review
- Threat modeling
- Manual review
- Authentication and authorization review
- Business logic verification
Stage 6 — Approved release
Only after all required security gates pass
3. Automating the workflow with CI/CD
The most effective approach is to make security verification automatic rather than relying on developers to remember individual checks.
For GitHub-based projects, a practical combination is:
- GitHub Actions for workflow orchestration.
- Semgrep or CodeQL for static analysis.
- Gitleaks for secrets.
- Trivy or OSV-Scanner for dependency vulnerabilities.
- Unit and integration tests for functional verification.
- OWASP ZAP for authorized dynamic testing.
- Mandatory human approval before merging.
Example GitHub Actions workflow
The following is a starting point for a Python project. It illustrates how to combine several independent checks.
yamlname: AI Code Security Checks on: pull_request: push: branches: [main] permissions: contents: read jobs: security: runs-on: ubuntu-latest steps: - name: Checkout source uses: actions/checkout@v4 with: fetch-depth: 0 - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.12" - name: Install dependencies run: pip install -r requirements.txt - name: Run unit tests run: pytest - name: Run Bandit run: | pip install bandit bandit -r ./src - name: Run Semgrep uses: semgrep/semgrep-action@v1 - name: Scan dependencies run: | pip install pip-audit pip-audit - name: Scan for secrets uses: gitleaks/gitleaks-action@v2 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}Important production considerations:
This is an illustrative starting workflow, not a complete hardened pipeline. Pin third-party GitHub Actions to reviewed full commit SHAs, use controlled dependency installation, and configure permissions and secrets carefully.
In particular:
- Do not give untrusted pull-request code access to production credentials.
- Do not execute generated code directly on a developer's workstation before inspection.
- Run tests in disposable, isolated environments.
- Make security checks mandatory before merging.
- Have an independent reviewer approve changes involving authentication, cryptography, permissions, or deployment configuration.
GitHub supports integrating CodeQL and third-party scanning tools into code scanning workflows.
4. Additional security checks specifically for LLM-generated code
Traditional application security tools are necessary, but they don't address every risk introduced by AI coding agents.
I would add the following specialized checks.
Risk Verification technique Hallucinated packages Verify package existence, ownership, and history Malicious dependencies Dependency reputation and supply-chain checks Prompt injection Inspect untrusted instructions in repository content Hidden code changes Compare complete Git diffs Unicode obfuscation Detect invisible characters and homoglyphs Insecure generated tests Independently create adversarial test cases Overprivileged agents Restrict filesystem, network, and credential access Sensitive code leakage Audit AI context and provider data-handling settings Unsafe CI modifications Require separate review of workflow changes One particularly important issue is prompt injection through repository content.
For example, an AI coding agent might read a README, issue description, source comment, or dependency documentation containing malicious instructions. If the agent has shell access, repository write permissions, or credentials, those instructions can influence its actions.
Recommended safeguards:
- Treat repository files and external documentation as untrusted data.
- Restrict agent permissions to the minimum necessary.
- Require approval for package installation, network access, and sensitive file modifications.
- Keep deployment keys and production secrets outside the agent's environment.
- Audit unexpected changes, commands, and network activity.
OWASP's 2026 Secure Coding with AI guidance specifically addresses these emerging risks, including agent permissions, dependency hallucinations, and review of unexpected modifications.
5. How to prioritize security findings
Not every scanner finding deserves the same response. Establish severity-based release gates.
Severity Example Recommended action Critical Remote code execution, exposed production credentials Block release immediately High Authentication bypass, SQL injection Block until remediated Medium Insecure configuration, insufficient validation Remediate or require documented exception Low Minor hardening issue Track and schedule remediation Combine automated findings with contextual assessment. A scanner's severity score alone does not establish exploitability.
For example, a dependency vulnerability in an unused code path may have a different practical risk from a vulnerability reachable through a public API.
6. Standards and frameworks worth adopting
These provide a foundation for building a repeatable, auditable process.
OWASP Secure Coding with AI Cheat Sheet
(Especially relevant)
AI-specific recommendations covering agent security, dependency verification, prompt injection, code review, and sensitive information.
NIST Secure Software Development Framework (SSDF)
Establishes secure development practices across preparation, software protection, secure production, and vulnerability response.
Also look at NIST SP 800-218A, which addresses generative AI and dual-use foundation model development.
OWASP DevSecOps Guideline
Provides practical guidance for integrating SAST, SCA, secret scanning, and human review into development workflows.
OWASP SAMM
Helps organizations assess and improve their software assurance maturity, including AI-assisted development practices.
AI-assisted development guidance
csrc.nist.govpages.nist.govowasp.github.ioowaspsamm.org
7. My recommended tool stack
If I were building a practical AI-generated code verification system today, I would start with this combination:
Security function Recommended tool Static analysis Semgrep Deeper code analysis CodeQL Python security Bandit Secret detection Gitleaks Dependency scanning OSV-Scanner Container/IaC scanning Trivy SBOM generation Syft Dynamic testing OWASP ZAP Fuzz testing AFL++ / Jazzer CI/CD orchestration GitHub Actions Security standards OWASP + NIST SSDF (Recommended starting point)
Start with Semgrep, Gitleaks, OSV-Scanner, and automated tests. Add CodeQL, Trivy, DAST, and fuzz testing as your application and security requirements grow.
8. What a mature implementation should achieve
Ultimately, the goal is to build an automated system that produces a verifiable security record for every AI-generated code change.
A useful release checklist:
AI-generated code release checklist (/ complete)
9. Further direction: building an AI code security gateway
There is also an interesting opportunity to build a dedicated security gateway between LLMs and software repositories.
Such a system could:
- Intercept code generated by an LLM.
- Identify and classify generated files.
- Perform automated sanitization and secret detection.
- Run SAST, dependency, and configuration scans.
- Execute code in a sandbox.
- Generate security findings and remediation suggestions.
- Require human approval before allowing code into the production repository.
This would be particularly useful in organizations where developers use multiple AI coding assistants.
One important design decision: use deterministic security scanners as the enforcement mechanism. An additional LLM can help explain findings and suggest fixes, but should not be the authority that declares its own generated code safe.
Research sources
The most useful starting references for further investigation are:
- OWASP Secure Coding with AI Cheat Sheet.
- OWASP SAMM: AI-Assisted Development.
- OWASP Secure Code Review.
- NIST Secure Software Development Framework.
- GitHub Code Scanning Documentation.
- NIST DevSecOps Reference Model.
A useful next research direction would be to design a reference architecture for an automated LLM-generated code verification platform, including its sandbox, scanning engine, policy enforcement, CI/CD integration, and human approval process.
Pages cited in this answer 19
- semgrep.devSemgrep App Security Platform | AI-assisted SAST, SCA and Secrets Detection
- codeql.github.comCodeQL
- sonarsource.comSonarQube | Code Quality, Security & Verification Tools | Sonar
- bandit.readthedocs.ioWelcome to Bandit — Bandit documentation
- cheatsheetseries.owasp.orgSecure Coding with AI - OWASP Cheat Sheet Series
- owasp.github.ioWSTG - Latest | OWASP Foundation
- github.comGitHub - gitleaks/gitleaks: Find secrets with Gitleaks 🔑 · GitHub
- trufflesecurity.comTruffle Security Co.
- cheatsheetseries.owasp.orgSecure Code Review - OWASP Cheat Sheet Series
- zaproxy.orgZAP
- owasp.orgWeb Security Testing Guide | OWASP Foundation
- docs.github.comCode scanning - GitHub Docs
- docs.github.comAbout GitHub Advanced Security - GitHub Docs
- owaspsamm.orgSAMM Guidance for AI-Assisted Development | OWASP SAMM
- csrc.nist.govSecure Software Development Framework | CSRC
- pages.nist.govAppendix C SSDF Analysis New — Secure Software Development, Security, and Operations (DevSecOps) Practices documentation
- owasp.github.ioSecure Code Review - OWASP DevSecOps Guideline
- owasp.github.ioOWASP DevSecOps Guideline
- pages.nist.gov1. Introduction — Secure Software Development, Security, and Operations (DevSecOps) Practices documentation
Google AI ModeNov 20, 2026
Securing, sanitizing, and verifying AI-generated code requires a
multi-layered pipelinethat shifts security left into the prompt loop, the local environment, and the CI/CD pipeline.Phase 1: In-IDE & Prompt-Time Guardrails (Prevention)
Catch insecure patterns, hallucinated packages, and exposed secrets before code ever hits a pull request.
- Context-Window & Policy Injection
- Tool: Salt Code (or similar MCP/IDE guardrails)
- What it does: Integrates directly into AI coding assistants (Claude Code, Cursor, Windsurf, GitHub Copilot) via Model Context Protocol (MCP) servers to inject security policies (OWASP, MCP Security Top 10) straight into the agent's context window.
- Secret & Credential Scanners
- Tool: GitGuardian or TruffleHog (IDE extensions)
- What it does: Automatically scans local file changes in real-time to flag hardcoded API keys, tokens, or credentials frequently hallucinated or pasted by LLMs.
- Dependency & Hallucination Check
- Tool: Snyk Open Source or Socket.dev
- What it does: Cross-references every imported package against public registries to ensure the AI hasn't suggested an outdated, vulnerable, or "phantom/hallucinated" package that an attacker could typosquat.
Phase 2: Static Analysis & Agentic Verification (Detection & Remediation)
Because industry data shows AI code maintains a ~56% security pass rate (struggling heavily with logic flaws and XSS), deterministic and AI-hybrid scanning is mandatory.
- Agentic Developer Security Agents
- Tool: Checkmarx Developer Assist or Cycode (Agentic Code Scanning)
- What it does: Operates inside the coding-agent loop to detect, autonomously propose or apply fixes, and re-check security issues as code is generated.
- Deep Static Application Security Testing (SAST)
- Tool: Snyk Code, Veracode , or Checkmarx One
- What it does: Deep-scans the Abstract Syntax Tree (AST) of the generated codebase for standard vulnerabilities (SQLi, auth bypass, cross-site scripting).
- Infrastructure & Container Sanity Checks
- Tool: Aikido Security or GitHub Advanced Security (GHAS)
- What it does: Quick-scans generated Dockerfiles, Terraform/IaC scripts, and GitHub Actions workflows for misconfigurations before deployment.
Phase 3: Runtime & Dynamic Verification (Sanitization)
Verify that the application actually behaves safely under stress and inputs are properly sanitized.
- Dynamic Application Security Testing (DAST) & Fuzzing
- Tool: OWASP ZAP or Nuclei
- What it does: Black-box tests the running local or staging build against active payloads, checking if the AI's input-handling and sanitization logic actually holds up.
- Container & Sandbox Execution
- Tool: Docker / Firecracker MicroVMs
- What it does: Always run newly vibe-coded or experimental agent output inside an isolated, ephemeral sandbox or container with dropped network capabilities and restricted file system permissions.
Recommended Verification Workflow
Show Code Hide Code Download diagram SVG
ASCII[Prompt AI / Vibe Code] │ ▼ (IDE Level) [Local Secret & Package Audit: Socket.dev / GitGuardian] │ ▼ (Pull Request) [Agentic / SAST Scan: Cycode / Checkmarx Developer Assist] │ ▼ (CI/CD Pipeline) [Policy Enforcement & Container/DAST Sandbox Test] │ ▼ [Human Code Review / Sign-off]To tailor this pipeline to your stack, could you clarify:
- Which AI coding assistants or workflows are you primarily using (e.g., Cursor, Claude Code, GitHub Copilot)?
- What programming languages and frameworks does your project rely on most?
-
ChatGPTOct 5, 2026
Yes. The safest approach is to treat AI-generated code as untrusted third-party code until it passes the same—and preferably stronger—controls as human-written code. OWASP’s current guidance specifically recommends human ownership, automated security testing, dependency verification, sandboxing, and careful review of agent-generated changes.
A practical workflow
1. Generate in isolation
- Have the AI work on a branch or disposable worktree.
- For agentic tools that can execute commands, use a dev container/VM with restricted filesystem and network access.
- Don't expose
.envfiles, SSH keys, cloud credentials, or production secrets to the agent.
2. Review the diff before running it Look at every changed file, not just the code the AI was asked to write. Pay particular attention to:
package.json/ build scripts- CI workflows
- Dockerfiles
- dependency/lock files
- authentication and authorization code
- database queries
- cryptography
- tests that were deleted or weakened
OWASP specifically calls out out-of-scope edits and test manipulation as recurring risks with coding agents.
3. Verify dependencies before installing Don't blindly accept an AI-suggested package. Check that it actually exists, has a credible maintainer history, and isn't a suspicious newly registered/low-download package. Then run your normal SCA/dependency scanner. OWASP recommends tools such as
npm audit,pip-audit,govulncheck, andcargo audit, as applicable.4. Run multiple automated security layers
Check What it catches Examples SAST Vulnerable code patterns Semgrep, CodeQL SCA Vulnerable/transitive dependencies Snyk, Dependabot, OSV tools Secret scanning API keys, tokens, credentials GitHub Secret Scanning, Gitleaks IaC scanning Unsafe cloud/container configuration Checkov, Trivy DAST Runtime vulnerabilities OWASP ZAP, Burp Suite Tests Functional regressions Your normal unit/integration tests Fuzz/adversarial tests Edge cases AI may miss AFL++, Jazzer, property-based tests OWASP recommends running SAST, SCA, and secret scanning on every PR; its AI-specific guidance additionally recommends IaC/DAST/IAST where appropriate.
Tools I'd consider
Semgrep is a particularly good fit for an AI-code gate because it can run in the IDE, pre-commit, and CI, and supports static analysis and security rules.
Snyk is useful when you want SAST + dependency/SCA analysis + secrets and IDE/PR integration in one security workflow. Its current tooling explicitly supports scanning AI-generated code as it is written.
If you're already on GitHub, GitHub Code Security/CodeQL + Dependabot + secret scanning gives you a strong baseline. GitHub's Copilot cloud agent also performs security validation and a second code-review pass, but that should complement—not replace—your independent security controls.
The key architectural pattern
I'd implement the pipeline roughly like this:
AI generates code ↓ isolated branch / container ↓ human reviews raw diff ↓ dependency verification ↓ SAST ──┐ SCA ───┤ Secrets┤ IaC ───┤──→ CI security gate Tests ─┤ DAST ──┘ ↓ human security/code review ↓ merge ↓ normal production monitoringThe important distinction is “AI review” versus “independent validation.” If the same model generates the code, writes the tests, and then says the code is secure, you've created a correlated failure mode. OWASP explicitly recommends adversarial/negative tests and human review rather than treating a passing AI-generated test suite as proof of security.
One extra control that's easy to overlook
For agentic coding, the agent itself is part of your attack surface. Repository issues, PR comments, README files, dependency documentation, and web pages can contain indirect prompt injections that influence an agent. Keep agent permissions narrow, restrict network egress, and don't give a coding agent production credentials.
If I were setting this up for a typical GitHub project, my minimum viable stack would be isolated coding environment + protected PR + Semgrep/CodeQL + dependency scanning + Gitleaks/secret scanning + tests + mandatory human review, with stricter two-person review for authentication, authorization, CI/CD, and deployment changes.
Pages cited in this answer 8
- cheatsheetseries.owasp.orgSecure Coding with AI - OWASP Cheat Sheet Series
- owasp.github.ioSecure Code Review - OWASP DevSecOps Guideline
- github.comGitHub - semgrep/semgrep: Lightweight static analysis for many languages. Find bug variants with patterns that look like source code. · GitHub
- semgrep.devSemgrep App Security Platform | AI-assisted SAST, SCA and Secrets Detection
- snyk.ioSecure AI-Generated Code | AI Coding Tools | AI Code Auto-fix | Snyk
- snyk.ioSnyk AI Security Platform | Secure Code, Agents & Apps | Snyk
- docs.github.comRisks and mitigations for GitHub Copilot cloud agent - GitHub Docs
- github.comGitHub Advanced Security · Built-in protection for every repository · GitHub
Google AI ModeOct 5, 2026
Integrating AI-generated code safely requires treating Large Language Model (LLM) outputs like code from an untrusted junior developer: functional, fast, but frequently optimized for completion over secure defaults or architectural cohesion.
A robust workflow combines pre-generation guardrails, automated pipeline validation , and human-in-the-loop review.
Step-by-Step Secure Integration Workflow
- Pre-Generation / IDE Guardrails
- Feed context-aware prompts by scoping your AI assistant (e.g., using
.cursorrulesor custom instructions in GitHub Copilot or Cursor ) with explicit coding standards, framework constraints, and forbidden patterns (like hardcoded secrets or raw SQL queries). - Utilize frameworks that enforce secure-by-default rules during generation.
- Feed context-aware prompts by scoping your AI assistant (e.g., using
- Automated CI/CD Quality and Security Gates
- Never let AI code bypass standard static analysis. Every commit containing AI contributions must pass automated checks before human review.
- Run SAST (Static Application Security Testing) to catch injection flaws, memory leaks, and insecure cryptography.
- Run SCA (Software Composition Analysis) specifically to check for AI "slopsquatting" or hallucinated package dependencies (where an AI invents a non-existent package name that an attacker could register maliciously).
- Targeted Human Code Review
- Reviewers must pay special attention to authorization, boundary conditions, and tenant isolation—areas where LLMs lack the wider architectural context of your system.
- Enforce a strict "you own what you merge" policy so developers don't rubber-stamp AI-generated pull requests.
Essential Security Tools for Validation & Cleaning
- Static Analysis (SAST)
- Traditional/Deterministic: Tools like Snyk Code or Checkmarx scan code patterns instantly for hardcoded credentials, known vulnerabilities, and bad syntax.
- AI-Aware/Reasoning Security: Platforms like Kodem Security or OX Security analyze runtime behavior and semantic logic to catch deeper authorization issues (like Insecure Direct Object References) that simple rule-based linters miss.
- Dependency & Supply Chain Scanners (SCA)
- Use tools like Socket.dev or Snyk Open Source to verify that any third-party libraries or modules recommended by the AI actually exist, are actively maintained, and are free from malware.
- Secret Detection
- Integrate tools like GitGuardian or TruffleHog into your pre-commit hooks and CI pipeline. LLMs have a bad habit of generating realistic-looking dummy API keys or tokens that accidentally match real production secrets.
If you'd like, let me know:
- What languages and frameworks your codebase uses
- Which AI tools your team currently relies on (e.g., Copilot, ChatGPT, Claude)
I can help tailor a specific CI/CD pipeline configuration or linting rule set for your stack.
Google AI ModeNov 29, 2026
Securing LLM-generated code requires a [Highlight start] defense-in-depth pipeline [Highlight end] . Because AI models frequently hallucinate deprecated APIs, miss subtle edge cases, or introduce classic vulnerabilities (like SQL injection or insecure deserialization), you cannot trust raw output straight from the chat window or inline assistant.
A reliable, multi-stage workflow to verify, sanitize, and secure AI-generated code breaks down across four distinct layers:
1. In-IDE & Real-Time Generation (While Coding)
Catch issues before the code even lands in your local git status.
- Scrub Secrets from Prompts: Never paste live production API keys, customer PII, or internal tokens into an LLM chat or local prompt. Use fake mock values or environment variables.
- Real-time SAST (Static Application Security Testing): Run continuous linters and security scanners right in your editor. Tools like Snyk Code or Sonar flag insecure patterns as the IDE autocomplete populates them.
- Strict Licensing Checks: LLMs can regurgitate copy-pasted proprietary or GPL-licensed snippets. Use tools or IDE extensions that cross-reference suggested blocks against open-source repositories to avoid legal traps.
2. Automated Pull Request & Graph Review (Pre-Merge)
Treat the LLM like a junior developer whose code must survive a strict peer review.
- AI-Powered PR Reviewers: Deploy specialized PR agents like CodeRabbit or Greptile to analyze the entire pull request against your codebase's dependency graph rather than just looking at isolated lines.
- Adversarial AI Security Scanners: Use deep-reasoning security tools like Claude Security or Black Duck Signal which actively attempt to reason through logic flaws, BOLA (Broken Object Level Authorization), and IDOR vulnerabilities.
- Automated Test Generation: Force a policy where any LLM-generated function must be accompanied by unit tests generated or verified alongside it. Run them in CI/CD before human eyes ever look at the PR.
3. Sandboxed Execution & Dynamic Testing (Sanitization)
If the LLM wrote scripts, infrastructure-as-code, or data-handling routines, test them safely.
- Ephemeral/Isolated Environments: Never execute AI-generated code directly on your local machine or a shared development server with network access. Run it inside short-lived Docker containers or ephemeral micro-VMs with restricted outbound network privileges.
- Dependency & Supply Chain Scan (SCA): LLMs love to invent packages, or recommend abandoned/typosquatted packages (e.g., calling
import super-helper-libwhen it doesn’t exist or is malicious). Run Software Composition Analysis (SCA) to verify every imported dependency. - Input/Output Sanitization Pipelines: If the generated code processes user inputs, wrap it in strict type-checking, parameterized queries, and input validation schemas (e.g., Pydantic, Zod) to neutralize logic or injection payloads.
4. Repository-Wide & Post-Merge Governance
- Continuous Compliance Auditing: Integrate automated remediation and policy engines into GitHub Advanced Security or GitLab Ultimate to track what percentage of your repo is AI-assisted and flag drift.
- Human-in-the-Loop Sign-off: Enforce a strict rule that a human developer must read, understand, and refactor the core logic of any block larger than a simple utility function.
To tailor this to your stack, tell me:
- Which LLMs or coding assistants are you using (e.g., Cursor, GitHub Copilot, Claude Code)?
- What programming languages/frameworks make up your primary codebase?
ChatGPTNov 29, 2026
When using large language models (LLMs) to generate code, the safest approach is to treat all AI-generated code as untrusted, third-party code until it has passed verification, security testing, and human review.
You should build a security pipeline around the LLM rather than relying on prompts such as "write secure code" or "check your work."
I recommend implementing a defense-in-depth workflow with six stages:
- Validate – Check that generated code meets functional and security requirements.
- Sanitize – Validate inputs, outputs, dependencies, and generated artifacts.
- Analyze – Run static analysis and vulnerability detection.
- Test – Execute tests in isolated environments.
- Review – Require human approval for sensitive changes.
- Monitor – Track vulnerabilities and security issues after deployment.
1. Recommended secure coding workflow
LLM code generation
Treat output as untrusted
Input and output validation
Schema checks, policy checks, secrets detection
Automated security analysis
SAST, dependency scanning, license checks
Isolated execution and testing
Unit tests, integration tests, sandboxing
Human security review
Approval for sensitive changes
Controlled deployment
Monitoring, logging, rollback
A failed security check should stop the pipeline or quarantine the generated artifact rather than allowing it to proceed automatically.
2. Verification and static analysis tools
Use multiple independent tools. No single scanner can reliably identify every security problem.
Here is a practical toolset:
Tool Purpose Recommended use Semgrep Static code analysis Find insecure coding patterns CodeQL Semantic vulnerability analysis Analyze data flows and security flaws SonarQube Code quality and security Detect bugs and maintainability issues Gitleaks Secret detection Find exposed API keys and credentials OSV-Scanner Dependency analysis Identify vulnerable packages Trivy Infrastructure and dependency scanning Scan containers, filesystems, and dependencies Bandit Python security analysis Detect common Python security issues Useful references:
My recommendation: Start with Semgrep, Gitleaks, OSV-Scanner, and your language's native test and lint tools. Add CodeQL for more advanced analysis.
What should you verify?
Your automated checks should cover:
- SQL injection and unsafe database queries.
- Cross-site scripting (XSS).
- Command injection risks.
- Insecure deserialization.
- Authentication and authorization weaknesses.
- Hardcoded passwords, tokens, and API keys.
- Insecure cryptographic algorithms.
- Unsafe file and path handling.
- Vulnerable or outdated dependencies.
- Excessive permissions and insecure configurations.
For generated code, pay special attention to hallucinated packages: an LLM can invent a package name or recommend a real package with a misleadingly similar name.
Verify package existence, publisher identity, version, integrity, and maintenance status before installing it.
3. Sanitizing LLM-generated code
This is an important distinction: you cannot make arbitrary generated source code safe simply by sanitizing its text.
Instead, validate the structure and constrain how the output is consumed.
I recommend five controls.
A. Enforce structured output
Require the LLM to return code in an expected format, such as a JSON object containing:
- Language
- File path
- Source code
- Dependencies
- Declared permissions
- Test cases
Validate the JSON against a strict schema before processing it.
B. Validate file paths
Prevent generated files from writing outside an approved workspace.
Reject:
- Absolute paths.
- Directory traversal.
- Unexpected file extensions.
- Changes to protected configuration files.
- Unexpected executable files.
C. Protect downstream interpreters
Never blindly pass generated output into:
- Shell commands.
- SQL queries.
- HTML rendering.
- Template engines.
- Dynamic code execution.
Use parameterized SQL, context-aware output encoding, safe APIs, and strict argument validation.
D. Validate dependencies
Require explicit approval for new dependencies. Pin versions and use lockfiles. Verify package provenance and checksums where available.
E. Detect secrets and sensitive information
Scan generated code and build artifacts for:
- API keys.
- Private keys.
- Passwords.
- Access tokens.
- Internal URLs.
- Personally identifiable information.
If a real credential is exposed, revoke or rotate it rather than simply deleting it from the generated file.
OWASP specifically identifies insecure output handling and excessive agency as major LLM application security risks. Its guidance also emphasizes that keyword filters alone are not reliable security boundaries.
4. Execute generated code in a sandbox
(Critical security control)
Never let generated code execute directly on your production machine or an unrestricted CI runner.
Use an isolated execution environment.
Recommended controls:
Control Implementation Filesystem Temporary workspace, restricted mounts Network Disabled by default Permissions Non-root user Resources CPU, memory, and execution time limits Secrets No production credentials Processes Restrict process creation Cleanup Destroy environment after execution Tools worth considering:
- Docker – Container isolation.
- Podman – Rootless container execution.
- gVisor – Additional isolation for container workloads.
- Firecracker – Lightweight virtual-machine isolation.
For highly untrusted code, prefer a hardened microVM or similarly strong isolation boundary over relying on a default container alone.
5. Build an automated CI/CD security pipeline
Every generated code change should pass through your existing software development security pipeline.
A practical GitHub Actions workflow could look like this:
yamlname: AI Generated Code Security on: pull_request: workflow_dispatch: permissions: contents: read jobs: security: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 - name: Validate generated files run: python scripts/validate_output.py - name: Run linting run: make lint - name: Run unit tests run: make test - name: Scan source code uses: semgrep/semgrep-action@v1 with: config: p/security-audit - name: Scan for secrets uses: gitleaks/gitleaks-action@v2 - name: Scan dependencies run: osv-scanner scan --lockfile=package-lock.json - name: Build verification run: make buildThis is an illustrative starting point, not a production-ready security configuration. Pin third-party actions to verified full commit SHAs, review their permissions, and configure scanners to fail on your defined security thresholds.
Also:
- Require pull-request approval.
- Prevent direct deployment from an LLM.
- Block merges when critical security checks fail.
- Keep production deployment credentials outside the generation environment.
- Generate build provenance and retain audit records.
For software supply-chain assurance, investigate SLSA (Supply-chain Levels for Software Artifacts).
6. Add LLM-specific security testing
Traditional application security testing is necessary, but it isn't sufficient when AI is involved.
You also need to test how your LLM behaves when generating code under adversarial or unusual conditions.
Test What you're looking for Prompt injection Malicious instructions influencing generated code Dependency hallucination Nonexistent or malicious package recommendations Secret leakage Credentials appearing in generated output Permission escalation Code requesting unnecessary privileges Unsafe tool calls Generated commands with unintended side effects Test fabrication LLM claiming tests passed without actually executing them Insecure defaults Debug mode, weak authentication, permissive configurations Useful resources:
- OWASP Secure Coding with AI Cheat Sheet
- OWASP AI/LLM Security Testing Guide
- OWASP Top 10 for Agentic Applications 2026
One particularly important principle: don't allow an LLM to approve its own security review. An AI reviewer can be a useful additional layer, but it should not replace independent verification.
7. Require human review for sensitive changes
Not every generated change needs the same level of scrutiny.
I recommend a risk-based approval model:
Risk level Examples Approval (Low) Documentation, formatting, simple utility functions Automated checks (Medium) Business logic, API integrations, database changes Developer review (High) Authentication, authorization, cryptography, payment processing Security review and developer approval For high-risk code, require:
- A documented security review.
- Tests for expected and invalid inputs.
- Verification of access-control boundaries.
- Review of all dependencies.
- Explicit approval before deployment.
8. My recommended implementation stack
If I were building this system from scratch, I would start with the following:
Semgrep
Static analysis and insecure coding patterns
Gitleaks
Credential and secret detection
OWASP Dependency-Check
Known vulnerable dependency detection
Docker or gVisor
Isolated execution of generated code
Docker ·
GitHub Actions
Automated security gates and CI/CD
CodeQL
Advanced source-code vulnerability analysis
9. Implementation checklist
Here is the order I'd prioritize implementation:
Security implementation progress
/
[Reset checklist]
10. Two standards worth following
For a more formal security program, use these as your foundation:
- NIST SSDF (SP 800-218): Establishes secure software development practices throughout the software lifecycle. NIST also has a generative-AI-specific SSDF profile, SP 800-218A. NIST SSDF resources.
- OWASP LLM Security: Covers AI-specific risks such as prompt injection, insecure output handling, excessive agency, and sensitive information disclosure. OWASP LLM Top 10.
My final recommendation
The most important architectural decision is to separate the LLM from the systems that validate and execute its output.
Your LLM should be able to propose code, but it should not independently decide whether that code is safe, grant itself permissions, or deploy its own changes.
I'd like to tailor the architecture to your actual development environment.
What are you primarily using LLMs to generate?
1. Primary programming language
Python
JavaScript / TypeScript
Java / C#
C / C++ / Rust
Multiple languages
2. How are you using LLMs?
IDE coding assistant (Copilot, Cursor, etc.)
Direct API integration
Autonomous coding agents
Internal code generation platform
3. Development scale
Personal / small team
Production engineering team
Enterprise environment
[Build my security architecture]
Pages cited in this answer 17
- github.comGitHub Code Security · GitHub
- github.comdocs/content/code-security/concepts/secret-security/secret-scanning.md at main · github/docs · GitHub
- csrc.nist.govSP 800-218, Secure Software Development Framework (SSDF) Version 1.1: Recommendations for Mitigating the Risk of Software Vulnerabilities | CSRC
- owasp.github.ioOWASP Top 10 for Large Language Model Applications | OWASP Foundation
- cheatsheetseries.owasp.orgLLM Prompt Injection Prevention - OWASP Cheat Sheet Series
- github.comslsa/spec/build-track-basics.md at main · slsa-framework/slsa · GitHub
- cheatsheetseries.owasp.orgSecure Coding with AI - OWASP Cheat Sheet Series
- owasp.github.ioAI/LLM Application Security Testing and Red Teaming - OWASP DevSecOps Guideline
- genai.owasp.orgOWASP Top 10 for Agentic Applications 2026
- semgrep.devSemgrep App Security Platform | AI-assisted SAST, SCA and Secrets Detection
- github.comGitHub - gitleaks/gitleaks: Find secrets with Gitleaks 🔑 · GitHub
- owasp.orgOWASP Dependency-Check | OWASP Foundation
- docker.comDocker | Secure Sandboxes for AI Agents
- gvisor.devThe Sandbox Kernel for Agents - gVisor
- github.comGitHub Actions · CI/CD and automations · Agentic Workflows · Workflows · GitHub
- codeql.github.comCodeQL
- csrc.nist.govSecure Software Development Framework | CSRC
ChatGPTOct 12, 2026
The strongest match is Semgrep Guardian, from Semgrep. It is specifically designed to scan AI-generated code as developers write it, detect vulnerabilities, malicious packages, and hardcoded secrets, and help fix issues directly in the IDE. It integrates with tools including Cursor, Claude Code, GitHub Copilot, VS Code, and Windsurf.
Leading providers to evaluate
1. Semgrep Guardian — best fit for AI coding agents
Scans code when an AI agent writes it, with protections for vulnerable code, secrets, and malicious dependencies.
Best for: proactive, automated guardrails.
2. Snyk Code — best for broader developer workflows
Provides real-time vulnerability scanning in IDEs, inline remediation guidance, and security checks for AI-generated code.
Best for: teams wanting scanning and fixes in their existing development workflow.
3. Checkmarx Developer Assist — best for enterprise IDE security
Scans human-written and AI-generated code in real time, highlights vulnerabilities and exposed secrets, and offers AI-assisted remediation.
Best for: organizations already using Checkmarx or seeking enterprise security controls.
My recommendation
Start by evaluating Semgrep Guardian if your developers use AI coding agents such as Cursor, Claude Code, or Codex and you want vulnerabilities caught at the moment code is generated. Evaluate Snyk as well if you need broader IDE and repository scanning.
Whichever provider you choose, verify that it scans every AI-generated change, catches secrets and vulnerable dependencies, supports your team's actual IDEs, and can enforce policies rather than merely report findings.
Google AI ModeOct 12, 2026
Several modern application security platforms and IDE extensions provide real-time scanning specifically tailored to catch vulnerabilities in AI-generated code snippets (such as those from Copilot, Cursor, or ChatGPT) before they get committed or pushed to production.
Top providers offering real-time or shift-left IDE-level security scanning include:
- Snyk Code : Known for ultra-fast, real-time static application security testing (SAST) directly inside developer IDEs (like VS Code, JetBrains) as code is written or generated.
- Semgrep Code : Offers rapid, highly customizable rule-based scanning that integrates smoothly into both the IDE and CI/CD pipelines to flag insecure patterns instantly.
- GitHub Advanced Security (GHAS): Features real-time secret scanning and code scanning (via CodeQL) natively inside GitHub workflows and developer environments, which is ideal if your team uses GitHub Copilot.
- Checkmarx One : Provides comprehensive enterprise SAST with deep context awareness, tracking code origin and flagging vulnerabilities early in the development lifecycle.
- AI Agent Security Scanner by Cisco : A specialized IDE extension built for modern AI-assisted IDEs (like Cursor, VS Code, Windsurf) that scans raw AI-generated snippets, agent skills, and MCP configurations for injection risks and data exfiltration patterns.
If you'd like to narrow this down, tell me:
- What IDE or coding assistants (e.g., VS Code, Cursor, GitHub Copilot) do your developers use?
- Are you looking for IDE plugins (real-time as they type) or CI/CD gatekeepers (pull-request blocking)?
Pages cited in this answer 4
- augmentcode.com8 AI SAST Tools for 2026 Tested and Compared | Augment Code
- opsmx.com9 Best AI for Code Security Scanning Tools Compared 2026
- marketplace.visualstudio.comAI Agent Security Scanner for IDEs - Visual Studio Marketplace
- blogs.cisco.comIntroducing the AI Agent Security Scanner for IDEs: Verify Your Agents - Cisco Blogs
Since Jul 7Data through Nov 29, 2026Based on 97 AI answers
For agents: this page as Markdown, https://parse.gl/topics/security-for-ai-generated-code.md. JSON, MCP · free for the last 90 days, checks from $0.01
This page
Read and search
Connect
npx -y parse-gl check <domain>Copy the CLI commandAn agent can save work before signup: POST https://agent.parse.gl/v1/workspaces
What it costs
Prices: https://parse.gl/pricing.md
Map of the site: https://parse.gl/llms.txt