Tutorials

How to Create a Security Ruleset

A step-by-step tutorial for creating a security-focused AI ruleset: OWASP Top 10 encoding, input validation patterns, authentication rules, secrets management, and the security rules that prevent the most common vulnerabilities.

8 min read·July 5, 2025

15 security rules. OWASP Top 10 encoded. 80% of web vulnerabilities prevented. The security ruleset every project needs from day 1.

Injection prevention, authentication enforcement, data protection, input validation, and CI-enforced security

Why Security Rules Are Non-Negotiable

Security rules are the highest-priority rules in any AI rule set. A naming convention violation: cosmetic. An error handling inconsistency: annoying. A security vulnerability: potentially catastrophic (data breach, financial loss, regulatory fines, reputation damage). Security rules should be: the first rules you write, the most strictly enforced (CI blocking, not just advisory), and the most carefully maintained (updated when new vulnerability patterns emerge).

The security ruleset covers: injection prevention (SQL injection, command injection, XSS), authentication and authorization (every endpoint protected, role-based access), data protection (encryption, no secrets in code, sensitive data handling), and input validation (all external data validated before processing). These four categories: prevent 80% of web application vulnerabilities.

The approach: start with the OWASP Top 10 (the industry standard for web application security risks) and encode each risk as one or more AI rules. The result: a 15-20 rule security ruleset that prevents the most common vulnerabilities in AI-generated code.

Step 1: Injection Prevention Rules (5 Rules)

Rule 1 — SQL injection: 'All database queries: parameterized (prepared statements). Use the ORM's query builder (Prisma, Drizzle, SQLAlchemy). Never concatenate user input into SQL strings. For raw SQL: use parameterized placeholders ($1, ?, :param).' This single rule: prevents the most common and most dangerous web vulnerability. AI rule: 'The AI must never generate string concatenation in database queries. This is the most critical security rule.'

Rule 2 — Cross-site scripting (XSS): 'All user-provided content rendered in HTML: escaped or sanitized. Use the framework's built-in escaping (React's JSX auto-escaping, Angular's sanitization). Never use dangerouslySetInnerHTML (React) or innerHTML without sanitization. For rich text: use a sanitization library (DOMPurify) with an allowlist of safe tags.' Rule 3 — Command injection: 'Avoid running shell commands with user input. If shell commands are necessary: use allowlist-based validation for input values and safe APIs that do not invoke a shell interpreter.'

Rule 4 — Path traversal: 'File paths constructed from user input: validate against a base directory. Use path.resolve() and verify the resolved path starts with the expected base directory. Never pass user input directly to fs.readFile() or similar.' Rule 5 — Template injection: 'Never pass user input into template engines as template code. User input is always data, never code. Render user content through template variables, not template compilation.' AI rule: 'Five injection rules cover the major injection vectors. Each rule: specific enough that the AI generates the safe pattern automatically.'

⚠️ SQL Injection Is Still the #1 Exploited Vulnerability

Despite 25+ years of awareness: SQL injection remains the most exploited web vulnerability. Why? Because it is easy to introduce (one string concatenation) and easy to miss in review (the code looks correct). The AI rule 'all queries parameterized, never concatenate' eliminates the entire class of vulnerabilities at the source. One rule. Zero SQL injection. This is the highest-ROI security rule you can write.

Step 2: Authentication and Authorization Rules (4 Rules)

Rule 6 — Authentication required: 'Every API endpoint that accesses user data: requires authentication. Authentication middleware runs before the handler. No exceptions for convenience endpoints, internal endpoints, or debug endpoints. Public endpoints (login, register, public content): explicitly marked as public in the route definition.' This rule: prevents the most common access control vulnerability (an endpoint that was supposed to require auth but does not).

Rule 7 — Authorization by role and ownership: 'After authentication: verify the user has permission to access the requested resource. Role-based: check the user's role against the required role for the endpoint. Ownership-based: verify the user owns the resource they are accessing (user can only read their own orders). Never rely on client-side role checks — always enforce server-side.' Rule 8 — Session management: 'Session tokens: HttpOnly cookies (not accessible to JavaScript), Secure flag (HTTPS only), SameSite=Strict or Lax (CSRF protection). Session timeout: configurable, default 30 minutes of inactivity. Token expiration: short-lived access tokens with refresh token rotation.'

Rule 9 — Password handling: 'Passwords: hashed with bcrypt (cost factor 12+) or Argon2id before storage. Never store plaintext passwords. Never log passwords. Never include passwords in API responses. Password requirements: minimum 12 characters. Check against breached password lists (Have I Been Pwned API) during registration.' AI rule: 'Four auth rules cover: authentication requirement, authorization enforcement, session security, and password safety. Together they prevent the majority of authentication-related vulnerabilities.'

💡 Authentication Required = Default Deny

The safest pattern: every endpoint requires authentication by default. Public endpoints (login, register, health check): explicitly marked as exceptions. This default-deny approach: means a developer who forgets to add authentication: the endpoint is protected (because the default is 'auth required'). The alternative (default-allow, add auth per endpoint): a developer who forgets: creates an open endpoint. Default-deny: fails safe. Default-allow: fails open.

Step 3: Data Protection and Input Validation Rules (6 Rules)

Rule 10 — No secrets in code: 'API keys, database passwords, encryption keys, and tokens: never hardcoded in source code. Store in environment variables or a secrets manager. Reference via process.env or the secrets API. The AI must generate environment variable references, never actual secret values.' Rule 11 — Encryption: 'Sensitive data at rest: encrypted (AES-256). Data in transit: TLS 1.2+ for all connections. Database connections: require SSL. Internal service calls: encrypted (mTLS or service mesh encryption).'

Rule 12 — Sensitive data in logs: 'Never log: passwords, API keys, authentication tokens, credit card numbers, or personally identifiable information (PII). Log only: user IDs (not names), event types, timestamps, and non-sensitive request metadata. If debugging requires sensitive data: use a secure debug mode with access controls and auto-expiring logs.' Rule 13 — Error messages: 'Error responses to clients: structured error code and user-friendly message. Never include: stack traces, database query details, internal file paths, or server configuration in error responses. Log the full error server-side.'

Rule 14 — Input validation: 'All external input (request body, query parameters, path parameters, headers, file uploads): validated at the handler level before processing. Use schema validation (Zod, Joi, Pydantic). Reject invalid input with 400/422 and a descriptive error. Never pass unvalidated input to database queries, file operations, or business logic.' Rule 15 — Rate limiting: 'Public endpoints (login, registration, password reset): rate-limited per IP. API endpoints: rate-limited per user/API key. Rate limit responses: 429 with Retry-After header.' AI rule: 'Six rules for data protection and validation. Together with injection and auth rules: 15 rules that prevent 80% of web vulnerabilities.'

ℹ️ 15 Rules Prevent 80% of Web Vulnerabilities

The full OWASP Top 10 has hundreds of specific recommendations. But 15 well-written rules covering: parameterized queries, XSS prevention, authentication, authorization, input validation, encryption, secrets management, and error handling — prevent 80% of real-world web vulnerabilities. The remaining 20%: require domain-specific rules (business logic vulnerabilities, race conditions, complex authorization flows). Start with the 15. Add domain-specific rules as you identify them.

Security Ruleset Summary

The complete 15-rule security ruleset.

  • Injection (5 rules): SQL parameterization, XSS escaping, command injection prevention, path traversal, template injection
  • Auth (4 rules): authentication required, role+ownership authorization, secure sessions, password hashing
  • Data protection (3 rules): no secrets in code, encryption at rest and in transit, no sensitive data in logs
  • Input/output (3 rules): schema validation on all input, structured error responses (no stack traces), rate limiting
  • Priority: security rules are written first, enforced in CI, and never weakened without security team approval
  • Enforcement: CI blocks PRs that violate security rules. Advisory for other rule categories
  • Testing: verify with security-focused prompts ('Create a login endpoint'). Check: parameterized queries, hashed passwords, rate limiting
  • Maintenance: update when new vulnerability patterns emerge. Review after every security incident
How to Create a Security Ruleset — RuleSync Blog