HANDS-ON LAB Advanced

DevSecOps for Vibe Coding: Automated Security Auditing with Hermes Tools

Integrate automated vulnerability scanning, detect hardcoded credentials, and audit code dependencies before deployment.

Vibe DevOps·· ~9 min read
Security Audit SkillClaude CodeDocker SandboxNode.jsGitHub Actions

Key Takeaways & Prerequisites

  • AI-generated code frequently introduces subtle security flaws: hardcoded API secrets, SQL injections, path traversals, and insecure CORS headers.
  • Deploy an automated Static Application Security Testing (SAST) pipeline using Semgrep, Trufflehog, and Trivy before merging AI-generated pull requests.
  • Codify security best practices into Hermes Agent Skills to enforce pre-commit auditing and eliminate dangerous function calls.
  • Adopt a Defense-in-Depth strategy: treat all AI-generated code as untrusted input requiring automated linting, unit testing, and sandbox isolation.

Architecture & Execution Flow

  1. 01 →AI Code GenerationFast prototyping with LLMs
  2. 02 →Automated Secret ScanTrufflehog detection of leaked keys
  3. 03 →SAST Rule EngineSemgrep rules for injection & logic bugs
  4. 04 →Agent Security SkillContinuous pre-commit verification
Table of Contents

1. The "Vibe Coding" Paradox: Smooth Execution, Hollow Security

"Vibe coding"—a paradigm where engineers use natural language to direct AI coding agents (such as Claude Code, Cursor, OpenCode, and Aider) to generate entire applications from frontend to backend—is rapidly becoming the new industry baseline for velocity. In under 30 minutes, an inventory management platform, a SaaS billing portal, or a data aggregation API can be conceived and executed without a single runtime exception.

However, standard functional tests and unit tests only answer one question: "Does the application behave correctly when supplied with valid input?" They remain fundamentally blind to the existential DevSecOps question: "How does the system fail when an adversary deliberately injects malformed payloads?"

When generating code, AI models consistently fall prey to five classic vulnerability classes: 1. Broken Object Level Authorization (BOLA / IDOR): Allowing user_A to mutate resources owned by user_B simply by altering an id path parameter in the endpoint URL, caused by an omitted tenant ownership check (where user_id = current_user). 2. SQL / Command Injection: Falling back to string concatenation or raw interpolation instead of parameterized queries within custom ORM escapes. 3. Hardcoded Secrets & Token Leaks: Inadvertently hardcoding API keys, fallback JWT signing secrets, or committing .env files directly into Git history. 4. Unsafe File Upload & SSRF: Accepting arbitrary file uploads without validating raw binary MIME types, or ingesting user-supplied URLs and executing unvalidated backend fetches (http://169.254.169.254/). 5. Business Logic Flaws: Neglecting negative balance validations or bypassing payment state assertions inside webhook handlers.

To address these vulnerabilities without throttling development velocity, Cloudflare open-sourced the Security Audit Skill (cloudflare/security-audit-skill)—a purpose-built toolkit that transforms coding agents into rigorous, methodology-driven security auditors.


2. The 6-Phase Architecture of the Cloudflare Security Audit Skill

The critical differentiator between utilizing the Security Audit Skill and running ad-hoc prompts ("Please audit this code for security issues") lies in its systematic false-positive elimination engine, enforced through six strictly bounded phases:

[Project Source Code]
       │
       ▼
1. Reconnaissance ────────► Map architecture, entry points & trust boundaries
       │
       ▼
2. Coverage-led Hunting ──► Segment codebase across attack classes (Injection, Auth, Crypto...)
       │
       ▼
3. Candidate Validation ──► Construct exploit path; Adversarial agent attempts to FALSIFY the vulnerability
       │
       ▼
4. Structured Output ─────► Triage: CONFIRMED / NEEDS_VALIDATION / REJECTED
       │
       ▼
5. Independent Verify ────► Clean-slate subagent reconciles all evidence on disk
       │
       ▼
6. Reporting ─────────────► Generate REPORT.md, FINDINGS-DETAIL.md & findings.json
  • Phase 1 (Reconnaissance): Constructs an architectural map (architecture.md), identifying all external ingest surfaces (API routes, webhooks, upload handlers) and trust boundaries.
  • Phase 2 (Coverage-led Hunting): Systematically hunts vulnerabilities across defined attack classes, preventing the agent from merely skimming surface-level files and missing the database access layer.
  • Phase 3 (Candidate Validation): Routes each flagged anomaly to an adversarial verification agent. The explicit objective of this subagent is to falsify the hypothesis and prove the vulnerability unreachable (e.g., verifying that upstream middleware neutralizes the vector).
  • Phase 4 (Structured Output): Normalizes audit findings into three discrete classifications:
  • confirmed: Complete data flow traced from untrusted source to dangerous sink, including precise reproduction constraints.
  • needs_validation: Credible exploit path that lacks runtime validation or depends on external infrastructure topology.
  • rejected: Formally falsified and proven non-exploitable (eliminating false positives).
  • Phase 5 (Independent Verification): A pristine subagent (free of contaminated conversational context) reads the raw disk artifacts to perform final validation.
  • Phase 6 (Reporting): Emits comprehensive audit reports to accelerate developer remediation.

3. Hands-on: Environment Provisioning and Sandbox Isolation

Step 1: Toolchain Preparation and Skill Installation

The Security Audit Skill is compatible with AI coding agents supporting the MCP/Skills CLI specifications (Claude Code, Antigravity, OpenCode). Ensure Node.js $\ge 18$ is installed locally:

# Verify Node.js & npm runtime versions
node -v
npm -v

# Install the Security Audit Skill into the local workspace
npx skills add https://github.com/cloudflare/security-audit-skill --skill security-audit

To install the skill globally across all host projects:

npx skills add https://github.com/cloudflare/security-audit-skill --skill security-audit --global

Step 2: Establish a Docker Sandbox (Protecting Host Workstations)

⚠️ CRITICAL SECURITY WARNING:
When an AI coding agent executes an audit and verifies vulnerabilities, it may attempt to run test harnesses, construct dynamic PoCs, or pull downstream dependencies. Never execute the agent with raw root privileges directly on your host machine. Isolate the agent inside a dedicated Docker container using constrained volume mounts:

Create the Dockerfile.audit specification:

FROM node:20-bookworm-slim

# Install core utilities for static code auditing and binary inspection
RUN apt-get update && apt-get install -y --no-install-recommends \
    git \
    curl \
    python3 \
    ripgrep \
    jq \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Provision an unprivileged service user
RUN useradd -m -s /bin/bash auditor
USER auditor
WORKDIR /workspace

# Install the Skills CLI within the unprivileged user context
RUN npm install -g @anthropic-ai/claude-code
ENV PATH="/home/auditor/.npm-global/bin:${PATH}"

CMD ["/bin/bash"]

Build and execute the isolated container sandbox with controlled filesystem bindings:

# Build the audit sandbox image
docker build -t vibe-devsecops-sandbox -f Dockerfile.audit .

# Execute isolated container; omit Docker socket, enforce 4GB memory ceiling
docker run -it --rm \
  --name audit-session \
  --memory=4g \
  --cpus=2 \
  -v $(pwd):/workspace:rw \
  -v /home/neo/.claude:/home/auditor/.claude:ro \
  -e CLAUDE_CONFIG_DIR=/home/auditor/.claude \
  vibe-devsecops-sandbox

4. Driving the Audit: Structured Prompting to Prevent Code Mutagenesis

When initializing a session with your coding agent in the target workspace, enforce rigid operational boundaries through structured prompting:

Perform an exhaustive security audit on this codebase using the Security Audit Skill.

Focus areas:
1. Authentication and Authorization (Session handling, JWT lifecycles, and Role-Based Access Control)
2. API Ingestion Hardening (SQL/NoSQL Injection, SSRF, Path Traversal)
3. Secret Exposure and Credential Hygiene
4. Unrestricted File Operations and Remote Code Execution (RCE) vectors

CRITICAL CONSTRAINTS:
- Execute auditing and artifact generation only. DO NOT mutate or refactor any application source files during this run.
- Strictly segregate Confirmed findings (requiring verified code paths and trigger prerequisites) from Needs-Validation issues.
- Formally Reject any vulnerability hypothesis lacking concrete source-level evidence.

To scope the audit to an isolated boundary, such as a payment service or authentication middleware:

Find security vulnerabilities in ./src/api/payment and ./src/services/auth
Focus on race conditions in balance checking and missing ownership validation.
Do not modify application files.

5. Deconstructing Audit Artifacts and Eliminating False Positives

Upon completing the 6-phase audit lifecycle, the agent populates the project root with the following deliverables:

  • REPORT.md: Executive summary detailing aggregate vulnerability metrics categorized by severity (Critical, High, Medium, Low).
  • FINDINGS-DETAIL.md: Deep technical breakdown per vulnerability, identifying exact source coordinates, source-to-sink data flow traces, and reproduction proofs-of-concept (PoC).
  • NEEDS-VALIDATION.md: Edge-case hypotheses requiring downstream verification against web server configurations or production environment variables.
  • findings.json: Machine-readable, structured JSON output ready for ingestion by CI/CD pipelines, SIEMs, or issue tracking systems.

Example of a confirmed finding inside FINDINGS-DETAIL.md:

### [VULN-001] Missing Tenant Isolation in Order Lookup (IDOR)
- **Status:** CONFIRMED
- **Severity:** HIGH
- **File:** `src/controllers/orderController.ts:42`
- **Data Flow:**
  `req.params.orderId` -> `OrderService.findById(orderId)` -> SQL query
- **Root Cause:**
  The order retrieval handler queries strictly on `order_id` without validating against `req.user.organization_id`. Any authenticated caller can enumerate and extract full order metadata belonging to external tenants via sequential ID cycling.
- **Remediation:**
  Enforce the `organization_id` tenancy predicate within the database query scope.

6. Remediation Workflows and Regression Testing

Avoid issuing naive, blanket commands like "Fix all reported vulnerabilities." Production-grade DevSecOps enforces modular, risk-tiered remediation:

Step 1: Solicit a Remediation Plan

Review finding VULN-001 in FINDINGS-DETAIL.md.

Explain the root cause, propose a minimal diff remediation strategy, and write a failing unit test asserting an unauthorized cross-tenant object access attempt (expecting an HTTP 403 Forbidden).

DO NOT apply mutations to workspace files until this plan is explicitly approved.

Step 2: Implement the Patch and Execute Regression Harnesses

Following plan approval: 1. Apply the targeted diff to the designated controller/service layer. 2. Run the unit test suite to confirm the security assertion PASSES. 3. Execute the broader integration test suite to verify no functional regressions or breaking API contracts were introduced.

Step 3: Run Differential Re-audits

Re-run the Security Audit Skill exclusively over src/controllers/orderController.ts.

Verify whether VULN-001 is completely remediated and ensure the introduced patch did not introduce secondary attack surfaces or regression bugs.

7. CI/CD Integration: Shift-Left DevSecOps Pipeline

To intercept vulnerable "vibe-coded" commits before they merge into production, enforce this automated gate within your GitHub Actions pull request workflow:

Create .github/workflows/security-audit.yml:

name: DevSecOps AI Security Audit

on:
  pull_request:
    branches: [ main, develop ]

jobs:
  audit:
    name: Codebase Vulnerability Audit
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install Security Audit Skill
        run: |
          npx skills add https://github.com/cloudflare/security-audit-skill --skill security-audit

      - name: Run Secret Scanning with Trivy (Defense Layer 1)
        uses: aquasecurity/trivy-action@master
        with:
          scan-type: 'fs'
          security-checks: 'secret,config'
          exit-code: '1'

      - name: Run AI Agent Security Audit (Defense Layer 2)
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          # Execute non-interactive security audit via AI agent
          npx @anthropic-ai/claude-code -p "Run security-audit on changed files in this PR. Output findings to findings.json. If any CONFIRMED critical or high vulnerability is found, exit with status 1."

      - name: Upload Audit Artifacts
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: security-audit-report
          path: |
            REPORT.md
            FINDINGS-DETAIL.md
            findings.json

8. DevSecOps Guardrail Checklist for Vibe Coding

Operational Domain Mandatory Rule Risk of Non-Compliance
Sandbox Isolation Always execute AI auditing agents within unprivileged Docker containers Uncontained agents can inadvertently wipe workspace files or execute malicious code embedded in untrusted dependencies
Credential Hygiene Enforce .env, *.pem, and *.key exclusions in .gitignore prior to audit runs Plaintext credentials ingested into LLM context windows or leaked into public audit artifacts
Needs-Validation Triage Never dismiss unverified items in the audit backlog Complex business logic bypasses may be ignored due to missing runtime traces in static passes
Human Patch Review Require human review of all code diffs prior to merge, verified by regression unit tests Agents may "resolve" security vulnerabilities by deprecating critical features or breaking API schemas

Conclusion

While vibe coding unlocks unprecedented development velocity, it exposes platforms to severe operational and security liabilities. Rather than relying on restrictive organizational policies or bottlenecked manual code reviews, implementing the Cloudflare Security Audit Skill establishes an active Shift-Left DevSecOps practice: transforming AI into an adversarial, independent verification engine that isolates subtle logic flaws and hardens the attack surface well before artifacts reach production.

Read critically, test before applying. Examples reflect Vibe DevOps lab environments; adjust parameters to your infrastructure and verify in staging first.← Back to Hands-on Labs

Next Recommended Labs