Vibe Coding Framework
  • 💻Introduction
  • 🧠Getting Started
    • Guide for Project Managers
    • Guide for System Owners
  • 🫣Dunning-Kruger Effect
  • Document Organisation
  • Core Concepts
    • What is Vibe Coding
  • Benefits and Challenges
  • Framework Philosophy
  • Security Tools
  • Framework Components
    • Prompt Engineering System
    • Verification Protocols
    • Security Toolkit
    • Documentation Generator
  • Refactoring Tools
  • Team Collaboration
  • Implementation Guide
    • For Individual Developers
  • For Engineering Teams
  • For Enterprises
  • Best Practices
    • Code Review Guidelines
  • Security Checks
  • Documentation Standards
  • Collaboration Workflows
  • Case Studies
    • Success Stories
  • Lessons Learned
  • Examples
    • Enterprise Case Study: Oracle Application Modernisation
    • Local email processing system
  • Resources
    • Tools and Integrations
      • Tools and Integrations Overview
      • Local LLM Solutions
      • Prompt Management Systems
  • Learning Materials
    • Test Your knowledge - Quiz 1
    • Test your knowledge - Quiz 2
  • Community Resources
  • Document Templates
    • AI Assisted Development Policy
    • AI Prompt Library Template
    • AI-Generated Code Verification Report
    • Maintainability Prompts
    • Security-Focused Prompts
    • Testing Prompts
    • [Language/Framework]-Specific Prompts
  • Framework Evolution
    • Versioning Policy
    • Contribution Guidelines
  • Roadmap
  • Glossary of terms
  • Patreon
    • Patroen Membership
  • Contact and Social
  • CREDITS
    • Different tools were used to build this site. Thanks to:
  • The Founder
Powered by GitBook
On this page
  • Security-Focused Prompts
  • Introduction
  • Core Security Principles
  • Prompt Templates
  • Component-Specific Security Prompts
  • OWASP Top 10 Mitigation Prompts
  • Best Practices for Security-Focused Prompts
  • Evaluating Security Results
  • Example: Before and After
  • Security Anti-Patterns to Avoid
  • Conclusion
  1. Document Templates

Security-Focused Prompts

Security-Focused Prompts

Introduction

Security-focused prompts are specialized instructions designed to guide AI systems in generating code that adheres to security best practices and mitigates common vulnerabilities. This collection provides templates and patterns to ensure that AI-generated code is not only functional but also secure by design.

Core Security Principles

When crafting security-focused prompts, ensure they embody these fundamental security principles:

  1. Defense in Depth: Request multiple layers of security controls rather than relying on a single protection mechanism

  2. Least Privilege: Specify that code should operate with minimal necessary permissions and access

  3. Input Validation: Explicitly request comprehensive validation of all external inputs

  4. Secure Defaults: Require secure default configurations rather than optional security features

  5. Fail Securely: Instruct that error conditions should never compromise security

  6. Security by Design: Embed security requirements from the beginning rather than as an afterthought

Prompt Templates

General Security-Focused Template

SITUATION: [Describe the system, existing architecture, and security context]
CHALLENGE: Create [describe component] that prioritizes security while ensuring functionality
AUDIENCE: Development team with security requirements for [specific compliance/security standard]
FORMAT:
- Implement proper input validation for all external data
- Use parameterized queries for all database operations
- Apply the principle of least privilege throughout
- Include comprehensive error handling that doesn't leak sensitive information
- Add security-focused comments explaining protection mechanisms
FOUNDATIONS:
- Follow OWASP Top 10 mitigation strategies
- Implement proper authentication and authorization checks
- Validate all inputs with appropriate sanitization
- Use secure cryptographic practices where needed
- Handle sensitive data according to [relevant compliance standards]
- Include security-focused logging without exposing sensitive information

Authentication Component Template

SITUATION: Building an authentication system for [describe application] using [specify technology stack]
CHALLENGE: Create a secure authentication system that protects against common authentication vulnerabilities
AUDIENCE: Security-conscious development team with compliance requirements
FORMAT:
- Implement industry standard authentication patterns
- Include comprehensive security controls
- Use clear, security-focused function naming
- Document security considerations and protections
- Implement proper separation of authentication concerns
FOUNDATIONS:
- Use secure password hashing with appropriate algorithms (bcrypt/Argon2/PBKDF2)
- Implement proper password policies and validation
- Include protection against brute force attacks (rate limiting, account lockout)
- Add multi-factor authentication support
- Implement secure session management
- Add CSRF protection for authentication forms
- Ensure secure credential storage and transmission
- Include protections against common authentication bypasses
SPECIFIC REQUIREMENTS:
- Never store passwords in plaintext or using weak hashing
- Implement secure password reset functionality
- Ensure authentication state cannot be manipulated
- Include comprehensive logging of authentication events
- Add secure remember-me functionality if required

Data Access Security Template

SITUATION: Creating data access components for [describe application] using [specify database technology]
CHALLENGE: Implement secure data access that protects against injection attacks and unauthorized access
AUDIENCE: Developers who need to access data securely
FORMAT:
- Use repository pattern with security best practices
- Implement proper parameterization for all queries
- Include access control checks at the data layer
- Document security considerations for each operation
FOUNDATIONS:
- Use parameterized queries exclusively (no string concatenation)
- Implement proper input validation before database operations
- Add row-level security where appropriate
- Include proper error handling that doesn't leak information
- Implement least privilege database access
- Add proper connection security (TLS, authentication)
- Use secure credential management for database access
SPECIFIC REQUIREMENTS:
- Prevent SQL/NoSQL injection in all forms
- Implement proper transaction management
- Add data access audit logging
- Include protection against excessive data exposure

API Security Template

SITUATION: Developing a [public/internal] API for [describe purpose] using [specify technology]
CHALLENGE: Create a secure API that protects against common API vulnerabilities
AUDIENCE: Developers consuming the API and security reviewers
FORMAT:
- Follow RESTful/GraphQL security best practices
- Implement comprehensive authentication and authorization
- Include proper input validation and output encoding
- Document security features and requirements
FOUNDATIONS:
- Implement proper authentication (API keys, OAuth, JWT as appropriate)
- Add authorization checks for all endpoints
- Include rate limiting and throttling
- Implement proper CORS configuration
- Add security headers in responses
- Use HTTPS for all endpoints
- Implement proper input validation
- Include secure error handling
SPECIFIC REQUIREMENTS:
- Protect against OWASP API Top 10 vulnerabilities
- Implement proper token validation and handling
- Add protection against parameter tampering
- Include security-focused logging
- Implement API versioning securely

Frontend Security Template

SITUATION: Building frontend components for [describe application] using [specify framework]
CHALLENGE: Create secure frontend implementations that protect against client-side vulnerabilities
AUDIENCE: Frontend developers with security responsibilities
FORMAT:
- Implement secure rendering practices
- Use proper output encoding for all dynamic content
- Include client-side validation (in addition to server-side)
- Document security considerations for component usage
FOUNDATIONS:
- Protect against Cross-Site Scripting (XSS)
- Implement proper CSRF protection for forms
- Use secure localStorage/sessionStorage practices
- Add proper Content Security Policy implementation
- Implement sensitive data handling on frontend
- Include secure authentication state management
SPECIFIC REQUIREMENTS:
- Sanitize all user-generated content before rendering
- Implement proper DOM manipulation methods
- Use secure cookie attributes (HttpOnly, Secure, SameSite)
- Add protection against clickjacking
- Include secure iframe usage if applicable

Component-Specific Security Prompts

Secure File Upload Implementation

SITUATION: Implementing file upload functionality for [describe application]
CHALLENGE: Create a secure file upload system that prevents security vulnerabilities
AUDIENCE: Developers implementing file handling functionality
FORMAT:
- Create a comprehensive file upload security implementation
- Document all security controls and their purpose
- Implement proper separation of validation and processing
- Include clear error handling for security violations
FOUNDATIONS:
- Validate file type, size, and content thoroughly
- Implement proper file storage security
- Use secure file naming and path handling
- Add protection against path traversal attacks
- Implement virus/malware scanning if applicable
- Add proper access controls for uploaded files
- Include security-focused logging of upload events
SPECIFIC REQUIREMENTS:
- Never rely only on client-side validation
- Implement content type verification beyond file extension
- Store files outside the web root if possible
- Generate random file names for storage
- Implement proper file access authorization

Payment Processing Security

SITUATION: Implementing payment processing for [describe application]
CHALLENGE: Create a secure payment system that protects sensitive financial information
AUDIENCE: Developers working with payment data under PCI DSS requirements
FORMAT:
- Implement secure payment processing patterns
- Document compliance considerations
- Include comprehensive security controls
- Add proper separation of payment concerns
FOUNDATIONS:
- Minimize storage of sensitive payment data
- Implement tokenization where possible
- Use proper encryption for any stored payment data
- Add comprehensive audit logging
- Implement strong authentication for payment actions
- Include fraud detection mechanisms
- Add proper error handling that doesn't leak information
SPECIFIC REQUIREMENTS:
- Ensure PCI DSS compliance considerations
- Implement proper card validation
- Add protection against common payment attacks
- Include transaction security mechanisms
- Implement secure refund processes

OWASP Top 10 Mitigation Prompts

Injection Prevention

FOUNDATIONS:
- Use parameterized queries for all database operations
- Implement context-aware output encoding
- Validate all input data against strict schemas
- Use ORMs with secure configuration
- Implement proper character encoding
- Add protection against all injection types (SQL, NoSQL, OS Command, LDAP)

Broken Authentication Mitigation

FOUNDATIONS:
- Implement multi-factor authentication
- Use secure session management
- Add protection against automated attacks
- Implement secure password policies
- Use secure password recovery mechanisms
- Include account lockout for failed attempts
- Add secure credential storage using strong hashing

Sensitive Data Exposure Prevention

FOUNDATIONS:
- Encrypt sensitive data at rest and in transit
- Implement proper key management
- Minimize storage of sensitive data
- Add proper access controls for sensitive information
- Include data classification and handling policies
- Use secure protocols for data transmission
- Implement proper caching controls

XML External Entity Attack Prevention

FOUNDATIONS:
- Disable XML external entity processing
- Implement secure XML parsers
- Use less complex data formats when possible (JSON)
- Add proper input validation for XML documents
- Include whitelisting of XML sources
- Implement XML schema validation

Broken Access Control Mitigation

FOUNDATIONS:
- Implement server-side access control checks
- Use role-based access control consistently
- Add proper session management
- Implement principle of least privilege
- Include access control logging and monitoring
- Add deny-by-default authorization policy
- Implement proper authentication verification

Best Practices for Security-Focused Prompts

Request Threat Modeling

Include threat modeling considerations in your prompts:

Please consider these threat scenarios:
- Authenticated user attempting to access another user's data
- Unauthenticated attacker attempting to bypass authentication
- Injection of malicious code or commands
- Interception of sensitive data in transit
- Elevation of privilege attacks

Specify Security Testing Requirements

Request built-in security testing guidance:

Please include security testing considerations:
- Test cases for authentication bypass attempts
- Validation testing with malicious inputs
- Authorization bypass testing approaches
- Session management testing
- Encryption validation testing

Request Security Documentation

Explicitly request security-focused documentation:

Please include security documentation covering:
- Security controls implemented and their purpose
- Potential attack vectors considered and mitigated
- Secure configuration requirements
- Security assumptions and limitations
- Guidance for security testing

Specify Compliance Requirements

Include relevant compliance standards:

Please ensure compliance with:
- OWASP ASVS Level [1/2/3] requirements for [specific controls]
- GDPR requirements for user data handling
- PCI DSS requirements for payment information
- HIPAA requirements for health information
- [Other relevant standards]

Evaluating Security Results

When evaluating AI-generated code for security, consider these questions:

  1. Input Validation: Is all external input properly validated and sanitized?

  2. Authentication: Are authentication mechanisms implemented securely?

  3. Authorization: Are proper access controls implemented and enforced?

  4. Data Protection: Is sensitive data properly protected at rest and in transit?

  5. Error Handling: Do errors fail securely without information disclosure?

  6. Logging: Is security-relevant information properly logged without sensitive data exposure?

  7. Dependencies: Are dependencies secure and properly configured?

Example: Before and After

Before: Insecure Authentication Implementation

function loginUser(username, password) {
  // Get user from database
  const query = `SELECT * FROM users WHERE username = '${username}' AND password = '${password}'`;
  const user = db.execute(query);
  
  if (user) {
    // Set session
    session.user = user;
    return true;
  }
  return false;
}

After: Secure Authentication Implementation

/**
 * Authenticates a user with appropriate security controls
 * 
 * Security features:
 * - Parameterized query to prevent SQL injection
 * - Password hashing with bcrypt
 * - Rate limiting for failed attempts
 * - Secure session handling
 * - Comprehensive error handling
 * 
 * @param {string} username The user's username
 * @param {string} password The user's password attempt
 * @returns {Object} Authentication result with user info or error
 */
async function loginUser(username, password) {
  try {
    // Input validation
    if (!username || !password || typeof username !== 'string' || typeof password !== 'string') {
      throw new Error('Invalid credentials format');
    }
    
    // Rate limiting check
    const attemptsKey = `login_attempts:${ipAddress}`;
    const attempts = await rateLimit.get(attemptsKey) || 0;
    
    if (attempts >= MAX_LOGIN_ATTEMPTS) {
      logger.security.warn('Login rate limit exceeded', {
        username, 
        ipAddress,
        attemptCount: attempts
      });
      throw new Error('Too many login attempts. Please try again later.');
    }
    
    // Get user with parameterized query
    const query = 'SELECT * FROM users WHERE username = ?';
    const user = await db.execute(query, [username]);
    
    if (!user) {
      // Increment failed attempts
      await rateLimit.increment(attemptsKey);
      
      // Use consistent timing to prevent timing attacks
      await securityUtils.consistentTiming();
      
      logger.security.info('Failed login attempt - user not found', { 
        username,
        ipAddress 
      });
      return { success: false, message: 'Invalid credentials' };
    }
    
    // Verify password with secure comparison
    const passwordValid = await bcrypt.compare(password, user.passwordHash);
    
    if (!passwordValid) {
      // Increment failed attempts
      await rateLimit.increment(attemptsKey);
      
      logger.security.info('Failed login attempt - invalid password', { 
        username,
        ipAddress 
      });
      return { success: false, message: 'Invalid credentials' };
    }
    
    // Check account status
    if (user.status !== 'active') {
      logger.security.info('Login attempt on inactive account', { 
        username,
        status: user.status,
        ipAddress 
      });
      return { success: false, message: 'Account is not active' };
    }
    
    // Reset failed attempts on successful login
    await rateLimit.reset(attemptsKey);
    
    // Create secure session with appropriate expiration
    const sessionToken = await securityUtils.generateSecureToken();
    await sessions.create({
      token: sessionToken,
      userId: user.id,
      expiresAt: Date.now() + SESSION_DURATION,
      ipAddress
    });
    
    // Log successful login
    logger.security.info('Successful login', { 
      username,
      userId: user.id,
      ipAddress 
    });
    
    // Return success without exposing sensitive user data
    return {
      success: true,
      user: {
        id: user.id,
        username: user.username,
        displayName: user.displayName,
        roles: user.roles
      },
      token: sessionToken
    };
  } catch (error) {
    logger.error('Login error', { 
      error: error.message,
      username
    });
    return { success: false, message: 'Authentication error occurred' };
  }
}

Security Anti-Patterns to Avoid

When reviewing AI-generated code, watch for these common security issues:

  1. String Concatenation in Queries: Using string concatenation instead of parameterized queries

  2. Inadequate Input Validation: Missing or incomplete validation of external input

  3. Hardcoded Credentials: Embedding secrets or credentials in code

  4. Missing Access Controls: Failing to check authorization before actions

  5. Insecure Cryptography: Using outdated or weak cryptographic algorithms

  6. Verbose Error Messages: Exposing sensitive information in error responses

  7. Client-Side Security Only: Relying solely on client-side validation

Include specific requirements to avoid these in your prompts.

Conclusion

Security-focused prompts are essential for generating code that's secure by design rather than as an afterthought. By explicitly guiding AI tools to implement proper security controls, you reduce the risk of vulnerabilities in your applications.

Remember that security is an ongoing process. Even with security-focused prompts, always perform proper security testing and code review to ensure protection against evolving threats. By investing in security from the start through well-crafted prompts, you build more resilient and trustworthy systems.

PreviousMaintainability PromptsNextTesting Prompts

Last updated 1 month ago