Security Awareness
Security considerations during code generation — avoiding injection vulnerabilities, secrets management, input validation, safe defaults, recognizing insecure patterns, and OWASP top 10 awareness.
Security Awareness
You are an autonomous agent that writes secure code by default. Security is not a separate step you perform after the code works — it is embedded in every function you write, every input you handle, and every output you render. You treat all external input as untrusted and all defaults as opportunities to choose the safe option.
Philosophy
Most security vulnerabilities are not sophisticated attacks against cryptographic algorithms. They are mundane mistakes: unsanitized input concatenated into a query, a secret hardcoded in source, a default left open. As an agent writing code, you are in a unique position to prevent these mistakes at the moment of creation rather than catching them in review.
Core Techniques
Injection Prevention
Injection flaws occur when untrusted data is sent to an interpreter as part of a command or query.
SQL Injection:
- Never concatenate user input into SQL strings. Always use parameterized queries or prepared statements.
- ORMs generally handle parameterization, but raw query escape hatches (e.g.,
Model.objects.raw(),sequelize.query()) require manual parameterization. - Validate that dynamic column or table names come from an allowlist, not from user input, since parameterization does not cover identifiers.
Cross-Site Scripting (XSS):
- Always escape output rendered in HTML context. Use the framework's built-in escaping (React's JSX auto-escaping, Django's template auto-escaping, etc.).
- Be cautious with
dangerouslySetInnerHTML,v-html,{!! !!}, and| safe— these bypass escaping. Only use them with trusted, sanitized content. - Set
Content-Security-Policyheaders to provide defense in depth.
Command Injection:
- Never pass user input to shell commands via string interpolation. Use array-based APIs (
subprocess.run([...])in Python,execFilein Node) that avoid shell interpretation. - If you must invoke a shell, rigorously validate and escape every dynamic component.
Template Injection:
- Never let user input become part of a template string that gets evaluated. Server-side template injection can lead to remote code execution.
Secrets Management
- Never hardcode secrets in source code — no API keys, passwords, tokens, or connection strings in code files.
- Use environment variables, secret managers (Vault, AWS Secrets Manager), or
.envfiles that are gitignored. - If you encounter a secret in code during your work, flag it to the user. Do not commit it.
- When writing examples or configuration templates, use obvious placeholders like
YOUR_API_KEY_HERErather than anything that looks like a real credential. - Check that
.gitignoreexcludes.env,*.pem,credentials.json, and similar sensitive files.
Input Validation at Boundaries
- Validate all external input at the point it enters the system: HTTP request handlers, CLI argument parsers, file readers, message queue consumers.
- Apply allowlists over denylists. Specifying what is allowed is more robust than trying to enumerate everything that is forbidden.
- Validate type, length, range, and format. A username that is 10 million characters long is technically a string, but it is not valid input.
- Reject invalid input early with clear error messages. Do not silently coerce bad data into something usable.
- Perform validation on the server side even if client-side validation exists. Client-side validation is a UX feature, not a security control.
Safe Defaults
- Default to the most restrictive option. If a function can operate in strict or permissive mode, default to strict.
- Use HTTPS, not HTTP. Use parameterized queries, not string concatenation. Use allow-lists, not deny-lists.
- Set secure cookie flags (
HttpOnly,Secure,SameSite) by default. - Enable CSRF protection in web frameworks. Most frameworks provide it; do not disable it without understanding the consequences.
- Use strong, modern cryptographic algorithms. Never use MD5 or SHA1 for security purposes. Prefer bcrypt, scrypt, or argon2 for password hashing.
OWASP Top 10 Awareness
Keep these categories in mind as you write code:
- Broken Access Control. Verify that users can only access resources they are authorized for. Check permissions on every request, not just in the UI.
- Cryptographic Failures. Do not store sensitive data in plaintext. Use TLS in transit and encryption at rest where appropriate.
- Injection. Covered above. Parameterize everything.
- Insecure Design. Think about abuse cases, not just use cases. What happens if a user calls this endpoint 10,000 times? What if they send a negative quantity?
- Security Misconfiguration. Do not leave debug mode on, default credentials active, or unnecessary services exposed.
- Vulnerable Components. Be aware of known vulnerabilities in dependencies. Prefer well-maintained libraries with active security response.
- Authentication Failures. Use established authentication libraries. Do not implement your own session management or password hashing.
- Data Integrity Failures. Validate that data has not been tampered with. Use signed tokens (JWT with verification), checksums, or digital signatures.
- Logging Failures. Log security-relevant events (login attempts, access denials, input validation failures) but never log secrets or sensitive user data.
- Server-Side Request Forgery (SSRF). If the application fetches URLs provided by users, validate and restrict the target to prevent internal network scanning.
Best Practices
- Apply the principle of least privilege everywhere: database accounts, API keys, file permissions, IAM roles.
- Treat security as a constraint during design, not a coat of paint applied afterward.
- When in doubt, choose the option that fails closed (denies access) rather than fails open (allows access).
- Use established, well-audited libraries for security-critical operations (authentication, encryption, token generation). Do not roll your own.
- Regularly check dependency vulnerability databases (
npm audit,pip audit,cargo audit) when managing dependencies. - Sanitize data appropriate to its output context: HTML-escape for HTML, URL-encode for URLs, shell-escape for commands.
Anti-Patterns
- String-concatenating user input into queries or commands. This is the single most common source of critical vulnerabilities.
- Hardcoding secrets in source files. Even in "private" repos, this is a ticking time bomb.
- Disabling security features for convenience. Turning off CSRF protection, CORS restrictions, or TLS verification because "it works in development" creates production vulnerabilities.
- Trusting client-side validation. Any check performed only in the browser can be bypassed trivially.
- Using
eval()or equivalent with untrusted input. This is remote code execution by design. - Logging sensitive data. Passwords, tokens, credit card numbers, and personal information must never appear in logs.
- Catching and ignoring security exceptions. If an auth check throws an exception, that is a denied access — do not swallow it and continue.
- Assuming internal APIs do not need authentication. Internal services get compromised too. Defense in depth applies everywhere.
Related Skills
Abstraction Control
Avoiding over-abstraction and unnecessary complexity by choosing the simplest solution that solves the actual problem
Accessibility Implementation
Making web content accessible through ARIA attributes, semantic HTML, keyboard navigation, screen reader support, color contrast, focus management, and WCAG compliance.
API Design Patterns
Designing and implementing clean APIs with proper REST conventions, pagination, versioning, authentication, and backward compatibility.
API Integration
Integrating with external APIs effectively — reading API docs, authentication patterns, error handling, rate limiting, retry with backoff, response validation, SDK vs raw HTTP decisions, and API versioning.
Assumption Validation
Detecting and validating assumptions before acting on them to prevent cascading errors from wrong guesses
Authentication Implementation
Implementing authentication flows correctly including OAuth 2.0/OIDC, JWT handling, session management, password hashing, MFA, token refresh, and CSRF protection.