Secure Coding Practices
Comprehensive guidance for implementing security-first development patterns with defensive programming techniques and proactive threat mitigation strategies.
When to Use This Skill
- Implementing authentication and authorization systems
- Processing user input or external data
- Handling sensitive data (PII, credentials, financial information)
- Building APIs and web services
- Managing cryptographic operations (hashing, encryption)
- Conducting security-focused code reviews
- Establishing secure development standards for teams
- Evaluating third-party dependencies and libraries
- Designing error handling and logging strategies
- Implementing session management and token handling
Core Security Principles
Defense in Depth
Apply multiple layers of security controls - never rely on a single protection mechanism.
Fail Securely
When errors occur, default to the secure state (deny access, reject input, log event).
Least Privilege
Grant minimum necessary permissions - users, services, and databases should have only required access.
Trust Nothing
Validate all input, encode all output, verify all sources, authenticate all requests.
Quick Reference
| Task |
Load reference |
| Input validation & sanitization |
skills/secure-coding-practices/references/input-validation.md |
| Output encoding & XSS prevention |
skills/secure-coding-practices/references/output-encoding.md |
| Authentication & sessions |
skills/secure-coding-practices/references/authentication.md |
| Cryptography & key management |
skills/secure-coding-practices/references/cryptography.md |
| Dependencies & supply chain |
skills/secure-coding-practices/references/dependencies.md |
| Error handling & logging |
skills/secure-coding-practices/references/error-handling.md |
| Secure defaults & configuration |
skills/secure-coding-practices/references/secure-defaults.md |
Workflow
- Identify security requirements - Authentication, authorization, data protection, compliance
- Load relevant references - Use Quick Reference table to find specific guidance
- Implement security controls - Apply patterns from references with proper context
- Validate implementation - Test with security scanners, penetration testing, code review
- Monitor and maintain - Regular security audits, dependency updates, vulnerability scanning
Security Checklist
Input Validation:
Output Encoding:
Authentication & Authorization:
Cryptography:
Dependencies:
Error Handling & Logging:
Common Mistakes
- Using client-side validation as sole defense (always validate server-side)
- Blocklisting instead of allowlisting (define what's allowed, not forbidden)
- Exposing stack traces or internal errors to users
- Hardcoding secrets in source code
- Using Math.random() for security-critical operations
- Not implementing rate limiting on authentication endpoints
- Loose equality comparisons allowing type coercion attacks
- Trusting user input in database queries (SQL injection)
- Missing output encoding based on context (XSS vulnerabilities)
- Insufficient password hashing (weak algorithms or low work factor)
High-Risk Code Patterns
Watch for these patterns in code reviews:
- String concatenation in SQL queries (injection risk)
- Direct file path construction from user input (traversal risk)
- eval(), Function(), or exec() with user input (code injection)
- Deserialization of untrusted data (RCE risk)
- Hardcoded secrets or credentials (exposure risk)
- Missing authentication/authorization checks (access control)
- Weak cryptography (MD5, SHA1, ECB mode)
- Verbose error messages in production (information disclosure)
- Missing input validation (injection, DoS)
- Insecure session configuration (hijacking risk)
Resources
OWASP Resources:
Standards & Guidelines:
Tools:
- SAST: SonarQube, Semgrep, CodeQL
- DAST: OWASP ZAP, Burp Suite
- SCA: Snyk, npm audit, Dependabot
- Secrets Detection: TruffleHog, git-secrets
1---
2name: secure-coding-practices
3description: Secure coding practices and defensive programming patterns for building security-first applications. Use when implementing authentication, handling user input, managing sensitive data, or conducting secure code reviews.
4keywords:
5 - code security
6 - defense in depth
7 - input validation
8 - least privilege
9 - output encoding
10 - sanitization
11 - secure by design
12 - secure coding
13 - security hardening
14 - threat modeling
15file_patterns:
16 - '**/*secret*.py'
17 - '**/*secret*.ts'
18 - '**/auth/**'
19 - '**/security/**'
20confidence: 0.87
21---
22
23# Secure Coding Practices
24
25Comprehensive guidance for implementing security-first development patterns with defensive programming techniques and proactive threat mitigation strategies.
26
27## When to Use This Skill
28
29- Implementing authentication and authorization systems
30- Processing user input or external data
31- Handling sensitive data (PII, credentials, financial information)
32- Building APIs and web services
33- Managing cryptographic operations (hashing, encryption)
34- Conducting security-focused code reviews
35- Establishing secure development standards for teams
36- Evaluating third-party dependencies and libraries
37- Designing error handling and logging strategies
38- Implementing session management and token handling
39
40## Core Security Principles
41
42### Defense in Depth
43Apply multiple layers of security controls - never rely on a single protection mechanism.
44
45### Fail Securely
46When errors occur, default to the secure state (deny access, reject input, log event).
47
48### Least Privilege
49Grant minimum necessary permissions - users, services, and databases should have only required access.
50
51### Trust Nothing
52Validate all input, encode all output, verify all sources, authenticate all requests.
53
54## Quick Reference
55
56| Task | Load reference |
57| --- | --- |
58| Input validation & sanitization | `skills/secure-coding-practices/references/input-validation.md` |
59| Output encoding & XSS prevention | `skills/secure-coding-practices/references/output-encoding.md` |
60| Authentication & sessions | `skills/secure-coding-practices/references/authentication.md` |
61| Cryptography & key management | `skills/secure-coding-practices/references/cryptography.md` |
62| Dependencies & supply chain | `skills/secure-coding-practices/references/dependencies.md` |
63| Error handling & logging | `skills/secure-coding-practices/references/error-handling.md` |
64| Secure defaults & configuration | `skills/secure-coding-practices/references/secure-defaults.md` |
65
66## Workflow
67
681. **Identify security requirements** - Authentication, authorization, data protection, compliance
692. **Load relevant references** - Use Quick Reference table to find specific guidance
703. **Implement security controls** - Apply patterns from references with proper context
714. **Validate implementation** - Test with security scanners, penetration testing, code review
725. **Monitor and maintain** - Regular security audits, dependency updates, vulnerability scanning
73
74## Security Checklist
75
76**Input Validation:**
77- [ ] Validate all user input server-side with allowlists
78- [ ] Use schema validation libraries (Joi, Yup, Zod)
79- [ ] Implement strict type checking
80- [ ] Sanitize file paths and prevent traversal
81
82**Output Encoding:**
83- [ ] Apply context-aware encoding (HTML, JS, URL, SQL)
84- [ ] Use templating engines with auto-escaping
85- [ ] Implement Content Security Policy (CSP)
86- [ ] Set secure HTTP headers (Helmet.js)
87
88**Authentication & Authorization:**
89- [ ] Hash passwords with bcrypt/Argon2 (salt rounds ≥12)
90- [ ] Implement secure session management
91- [ ] Use HTTPS-only cookies with HttpOnly and SameSite
92- [ ] Apply rate limiting on authentication endpoints
93- [ ] Verify authorization on every request
94
95**Cryptography:**
96- [ ] Use AES-256-GCM for encryption
97- [ ] Generate keys with crypto.randomBytes()
98- [ ] Store secrets in environment variables or KMS
99- [ ] Never roll your own crypto
100
101**Dependencies:**
102- [ ] Run npm audit regularly
103- [ ] Lock dependency versions in package.json
104- [ ] Use Snyk/Dependabot for monitoring
105- [ ] Verify package integrity (SRI for CDN)
106
107**Error Handling & Logging:**
108- [ ] Return generic error messages to users
109- [ ] Log errors with correlation IDs
110- [ ] Never log passwords, tokens, or PII
111- [ ] Monitor security events and alerts
112
113## Common Mistakes
114
115- Using client-side validation as sole defense (always validate server-side)
116- Blocklisting instead of allowlisting (define what's allowed, not forbidden)
117- Exposing stack traces or internal errors to users
118- Hardcoding secrets in source code
119- Using Math.random() for security-critical operations
120- Not implementing rate limiting on authentication endpoints
121- Loose equality comparisons allowing type coercion attacks
122- Trusting user input in database queries (SQL injection)
123- Missing output encoding based on context (XSS vulnerabilities)
124- Insufficient password hashing (weak algorithms or low work factor)
125
126## High-Risk Code Patterns
127
128Watch for these patterns in code reviews:
1291. String concatenation in SQL queries (injection risk)
1302. Direct file path construction from user input (traversal risk)
1313. eval(), Function(), or exec() with user input (code injection)
1324. Deserialization of untrusted data (RCE risk)
1335. Hardcoded secrets or credentials (exposure risk)
1346. Missing authentication/authorization checks (access control)
1357. Weak cryptography (MD5, SHA1, ECB mode)
1368. Verbose error messages in production (information disclosure)
1379. Missing input validation (injection, DoS)
13810. Insecure session configuration (hijacking risk)
139
140## Resources
141
142**OWASP Resources:**
143- **OWASP Top 10**: https://owasp.org/Top10/
144- **OWASP Cheat Sheet Series**: https://cheatsheetseries.owasp.org/
145- **OWASP ASVS**: Application Security Verification Standard
146- **OWASP Dependency-Check**: https://owasp.org/www-project-dependency-check/
147
148**Standards & Guidelines:**
149- **NIST Cybersecurity Framework**: https://www.nist.gov/cyberframework
150- **NIST SP 800-63B**: Digital Identity Guidelines (Authentication)
151- **CWE Top 25**: https://cwe.mitre.org/top25/
152
153**Tools:**
154- **SAST**: SonarQube, Semgrep, CodeQL
155- **DAST**: OWASP ZAP, Burp Suite
156- **SCA**: Snyk, npm audit, Dependabot
157- **Secrets Detection**: TruffleHog, git-secrets