1---2name: security3description: Framework-agnostic security rules including input validation, auth principles, CORS, API headers, rate limiting, secret management, authentication patterns (JWT, OAuth2, session, MFA), web protection (CSRF, XSS, injection defense, TLS), container security, and software supply chain security (SBOM, Cosign, Sigstore, SLSA). Use when implementing security-related code.4license: MIT5---6# Security Rules78## 1. Input Validation Principles910| Rule | Purpose |11| ------------------------------------- | ---------------------------------------- |12| Validate at API boundary | Reject bad input early |13| Whitelist over blacklist | Allow known-good, reject everything else |14| Validate type, length, range, format | Prevent injection and overflow |15| Sanitize output, not just input | Prevent XSS in responses |16| Never trust client-side validation | Always re-validate server-side |1718---1920## 2. Authentication and Authorization Principles2122- Apply least privilege — grant minimum permissions needed23- Use role-based access control (RBAC) at endpoint level24- Apply defense in depth — check authorization in service layer, not just URL25- Use method-level security for fine-grained control26- Log all authentication failures and authorization denials27- Never rely on URL-based security alone2829---3031## 3. CORS Principles3233- Never use wildcard (`*`) origins in production34- Explicitly list allowed origins, methods, and headers35- Set `maxAge` to reduce preflight requests36- Separate CORS config per environment (dev may be more permissive)3738---3940## 4. API Security Headers4142| Header | Value | Purpose |43| ---------------------------- | ------------------------------------- | ------------------------- |44| `X-Content-Type-Options` | `nosniff` | Prevent MIME sniffing |45| `X-Frame-Options` | `DENY` | Prevent clickjacking |46| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains` | Force HTTPS |47| `Cache-Control` | `no-store` | Prevent sensitive caching |48| `X-XSS-Protection` | `0` | Disable (use CSP instead) |4950---5152## 5. Rate Limiting Guidelines5354### Recommended Limits5556| Endpoint Type | Limit | Window |57| ------------------ | -------- | ---------- |58| Public API | 100 req | Per minute |59| Authenticated API | 1000 req | Per minute |60| Login/Auth | 10 req | Per minute |61| File upload | 10 req | Per hour |6263### Response Headers6465- `X-RateLimit-Limit`: Maximum requests allowed in window66- `X-RateLimit-Remaining`: Requests remaining in current window67- `X-RateLimit-Reset`: Timestamp when the window resets6869---7071## 6. Sensitive Data in Responses7273### Never Expose7475- Password hashes76- Internal IDs when external IDs exist77- Stack traces or internal error details78- Database column names in error messages79- Server version or framework information8081### Response Filtering8283- Use dedicated response DTOs — never return entities directly84- Exclude internal fields (password, internal flags, audit metadata)85- Map entities to response objects at the API boundary8687---8889## 7. Secret Management Principles9091- Store secrets in environment variables or secret manager (Vault, AWS SSM, etc.)92- Never commit secrets to version control93- Rotate secrets periodically (at least every 90 days)94- Use different secrets per environment95- Revoke and rotate immediately if any secret is exposed96- Never provide default values for secrets in configuration files9798---99100## 8. Anti-Patterns101102- Hardcoding secrets in source code or config files103- Returning entities directly from API endpoints104- Using wildcard CORS in production105- Missing rate limiting on authentication endpoints106- Logging sensitive data (passwords, tokens, PII)107- Trusting client-side validation without server-side checks108- Exposing detailed error internals in API responses109- **Security by Obscurity**: Relying solely on hiding for security. Design systems to be secure even when exposed110- **Rolling Your Own Crypto**: Using unverified custom encryption algorithms. Use standard libraries (AES, RSA, bcrypt)111- **Excessive Permissions**: Violating the principle of least privilege. Grant only the minimum required permissions112- **Delayed Security Updates**: Postponing known CVE patches increases attack exposure. Apply patches immediately113114---115116## 9. OWASP Top 10 Awareness117118[OWASP](https://owasp.org/) (Open Worldwide Application Security Project) publishes the industry-standard list of the most critical web application security risks. The [OWASP Top 10](https://owasp.org/www-project-top-ten/) is updated every 3-4 years (latest: 2021) and serves as the de facto security baseline for code reviews, audits, and compliance.119120When writing code, be vigilant against all 10 categories:121122| # | Vulnerability | Prevention |123| --- | ------------------------------------------ | ------------------------------------------------------- |124| A01 | Broken Access Control | Check authorization at service layer; deny by default |125| A02 | Cryptographic Failures | Encrypt at rest and in transit; use strong algorithms |126| A03 | Injection (SQL, Cmd, LDAP, XSS) | Use parameterized queries; never concatenate user input |127| A04 | Insecure Design | Apply threat modeling; use secure design patterns |128| A05 | Security Misconfiguration | No default credentials; disable debug in production |129| A06 | Vulnerable and Outdated Components | Keep dependencies updated; monitor CVE databases |130| A07 | Identification and Authentication Failures | Use established auth libraries; enforce MFA |131| A08 | Software and Data Integrity Failures | Verify integrity of updates; use digital signatures |132| A09 | Security Logging and Monitoring Failures | Log security events; ensure logs are tamper-resistant |133| A10 | Server-Side Request Forgery (SSRF) | Validate and whitelist outbound URLs |134135## 10. Container and Supply Chain Security136137Securing containers and the software supply chain is essential for modern cloud-native deployments.138For detailed patterns, see [references/container-supply-chain.md](references/container-supply-chain.md).139140### Key Rules141142- Use minimal base images (distroless, Alpine) — reduce attack surface143- Run containers as non-root user — set `USER` directive in Dockerfile144- Generate and attest SBOMs (Software Bill of Materials) with Syft or Trivy145- Sign container images with Cosign (Sigstore keyless signing)146- Enforce admission policies (OPA/Gatekeeper, Kyverno) in Kubernetes clusters147- Target SLSA Build Level 2+ for production workloads — provenance attestation required148149### Supply Chain Controls150151| Control | Tool | Purpose |152| ------- | ---- | ------- |153| Image scanning | Trivy, Grype | Vulnerability detection |154| Image signing | Cosign (Sigstore) | Authenticity and integrity |155| SBOM generation | Syft | Dependency inventory |156| Policy enforcement | Kyverno, OPA | Admission control |157| Provenance | SLSA | Build process attestation |158159---160161## Related Skills162163- For secret lifecycle management (rotation, storage, detection), see [secrets-management](../secrets-management/) skill164- For Kubernetes security (RBAC, NetworkPolicy, Pod Security), see [k8s-workflow](../k8s-workflow/) skill165166## Additional References167168- For authentication and authorization implementation patterns, see [references/authentication.md](references/authentication.md)169- For web protection (CSRF, XSS, injection defense, TLS), see [references/web-protection.md](references/web-protection.md)170- For container and supply chain security (SBOM, Cosign, SLSA, Kyverno, image hardening), see [references/container-supply-chain.md](references/container-supply-chain.md)171- For Spring Boot implementation patterns (SecurityFilterChain, Bean Validation), see `spring-framework` skill — [references/security.md](../spring-framework/references/security.md)