Security Best Practices

Security Best Practices automation and integration

Security Best Practices is a community skill for implementing application security patterns that protect against common vulnerabilities including injection attacks, authentication bypasses, data exposure, misconfiguration, and inadequate secrets management across web and API applications.

What Is This?

Overview

Security Best Practices provides implementation patterns for defending applications against the most prevalent security threats. It covers input validation and sanitization, authentication and authorization patterns, secrets management, secure communication configuration, and dependency vulnerability scanning. The skill translates security principles into concrete code patterns that developers can apply directly to their applications.

Who Should Use This

This skill serves developers building web applications that handle user data, backend engineers implementing API authentication and authorization layers, and teams preparing applications for security audits or compliance requirements.

Why Use It?

Problems It Solves

SQL injection and cross-site scripting remain among the most exploited vulnerabilities despite being well understood. Hardcoded secrets in source code get exposed through repository leaks. Misconfigured CORS policies expose APIs to unauthorized cross-origin access. Default framework settings often prioritize convenience over security, leaving applications vulnerable until explicitly hardened. Dependency chains introduce transitive vulnerabilities from packages that developers never directly chose.

Core Highlights

Input validation patterns prevent injection attacks through parameterized queries and content sanitization. Authentication implementations cover password hashing, token management, and session security. Secrets management uses environment variables and vaults instead of hardcoded credentials. Security header configuration defends against XSS, clickjacking, and content type sniffing through proper HTTP response headers.

How to Use It?

Basic Usage

import hashlib
import secrets
import hmac
from dataclasses import dataclass

@dataclass
class SecureAuth:
    pepper: str

    def hash_password(self, password: str) -> str:
        salt = secrets.token_hex(32)
        combined = f"{self.pepper}{salt}{password}"
        hashed = hashlib.pbkdf2_hmac(
            "sha256", combined.encode(), salt.encode(), 100_000
        )
        return f"{salt}:{hashed.hex()}"

    def verify_password(self, password: str, stored: str) -> bool:
        salt, hash_hex = stored.split(":")
        combined = f"{self.pepper}{salt}{password}"
        check = hashlib.pbkdf2_hmac(
            "sha256", combined.encode(), salt.encode(), 100_000
        )
        return hmac.compare_digest(check.hex(), hash_hex)

    def generate_token(self, length: int = 32) -> str:
        return secrets.token_urlsafe(length)

Real-World Examples

import re
from html import escape

class InputValidator:
    EMAIL_PATTERN = re.compile(r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$")

    def sanitize_html(self, text: str) -> str:
        return escape(text)

    def validate_email(self, email: str) -> bool:
        return bool(self.EMAIL_PATTERN.match(email)) and len(email) <= 254

    def validate_length(self, value: str, min_len: int, max_len: int) -> bool:
        return min_len <= len(value) <= max_len

class SecurityHeaders:
    HEADERS = {
        "X-Content-Type-Options": "nosniff",
        "X-Frame-Options": "DENY",
        "Strict-Transport-Security": "max-age=31536000; includeSubDomains",
        "Content-Security-Policy": "default-src 'self'",
        "X-XSS-Protection": "0",
        "Referrer-Policy": "strict-origin-when-cross-origin"
    }

    def apply(self, response):
        for header, value in self.HEADERS.items():
            response.headers[header] = value
        return response

Advanced Tips

Use constant-time comparison functions for token and password verification to prevent timing attacks. Implement rate limiting on authentication endpoints to slow brute force attempts. Rotate secrets on a schedule and after any suspected compromise event. Run dependency vulnerability scans in CI to catch known issues before deployment.

When to Use It?

Use Cases

Harden a web application before deployment by applying security headers and input validation. Implement authentication that follows current password storage best practices. Prepare an application for a security audit by addressing common vulnerability categories systematically.

Related Topics

OWASP Top 10 vulnerability categories, penetration testing methodology, secure coding standards, dependency vulnerability scanning, compliance frameworks, and API security guidelines.

Important Notes

Requirements

Understanding of the application architecture and its attack surface. Access to environment variable or secrets management systems for credential storage. Familiarity with the framework security features available in the project tech stack. A CI pipeline for running automated security scans on every code change.

Usage Recommendations

Do: validate all external input at system boundaries before processing. Use parameterized queries for all database operations without exception. Keep dependencies updated and monitor for security advisories affecting project packages.

Don't: implement custom cryptography when established libraries provide tested solutions. Disable security features during development and forget to re-enable them for production. Log sensitive data such as passwords, tokens, or personal information.

Limitations

Security patterns address known vulnerability categories but cannot prevent zero-day exploits. Code-level defenses complement but do not replace infrastructure security measures like firewalls and network segmentation. Automated scanning catches known patterns but requires manual review for business logic vulnerabilities. Security is an ongoing process, not a one-time checklist, requiring continuous monitoring and updates as new threats emerge.