S

Security Compliance Toolkit

Enterprise-grade skill for guides, security, professionals, implementing. Includes structured workflows, validation checks, and reusable patterns for development.

SkillClipticsdevelopmentv1.0.0MIT
0 views0 copies

Security Compliance Toolkit

A comprehensive skill for implementing security controls, compliance frameworks, and vulnerability prevention in web applications. Covers OWASP Top 10 mitigations, authentication hardening, data protection, audit logging, and regulatory compliance patterns.

When to Use This Skill

Choose this skill when:

  • Implementing authentication, authorization, and session management securely
  • Hardening APIs against injection, XSS, CSRF, and SSRF attacks
  • Adding audit logging and compliance reporting for SOC 2 or GDPR requirements
  • Reviewing code for security vulnerabilities before production deployment
  • Setting up secrets management, encryption at rest, and TLS configuration

Consider alternatives when:

  • Need penetration testing tooling → use a security testing skill
  • Working on network/infrastructure security → use a DevSecOps skill
  • Building OAuth/OIDC identity provider → use an identity provider skill
  • Need container security scanning → use a container security skill

Quick Start

// Security middleware stack for Express/Node.js import helmet from 'helmet'; import rateLimit from 'express-rate-limit'; import cors from 'cors'; // Apply security headers app.use(helmet({ contentSecurityPolicy: { directives: { defaultSrc: ["'self'"], scriptSrc: ["'self'", "'nonce-{random}'"], styleSrc: ["'self'", "'unsafe-inline'"], imgSrc: ["'self'", "data:", "https:"], connectSrc: ["'self'", "https://api.example.com"], }, }, hsts: { maxAge: 31536000, includeSubDomains: true, preload: true }, })); // Rate limiting app.use('/api/', rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes max: 100, standardHeaders: true, legacyHeaders: false, })); // CORS with explicit origins app.use(cors({ origin: ['https://app.example.com'], credentials: true, methods: ['GET', 'POST', 'PUT', 'DELETE'], }));

Core Concepts

OWASP Top 10 Mitigations

VulnerabilityMitigationImplementation
Injection (SQL/NoSQL)Parameterized queriesORM/prepared statements, never string concat
Broken AuthMFA, secure sessionsbcrypt hashing, JWT rotation, session timeout
XSSOutput encodingCSP headers, template auto-escaping, DOMPurify
CSRFToken validationSameSite cookies, anti-CSRF tokens
SSRFURL validationAllowlist domains, block private IPs
Security MisconfigurationHardened defaultsHelmet.js, disable debug in prod
Broken Access ControlAuthorization middlewareRBAC/ABAC, resource-level checks
Cryptographic FailuresStrong algorithmsAES-256-GCM, bcrypt cost 12+, TLS 1.3

Input Validation and Sanitization

import { z } from 'zod'; import DOMPurify from 'isomorphic-dompurify'; // Schema validation at API boundary const createUserSchema = z.object({ email: z.string().email().max(254).toLowerCase(), password: z.string().min(12).max(128) .regex(/[A-Z]/, 'Must contain uppercase') .regex(/[0-9]/, 'Must contain number') .regex(/[^A-Za-z0-9]/, 'Must contain special character'), name: z.string().min(1).max(100).trim(), bio: z.string().max(500).transform(val => DOMPurify.sanitize(val)), }); // Middleware for request validation function validate(schema: z.ZodType) { return (req: Request, res: Response, next: NextFunction) => { const result = schema.safeParse(req.body); if (!result.success) { return res.status(400).json({ error: 'Validation failed', details: result.error.issues.map(i => ({ field: i.path.join('.'), message: i.message, })), }); } req.body = result.data; next(); }; }

Audit Logging Pattern

interface AuditEvent { timestamp: string; actor: { id: string; email: string; ip: string }; action: string; resource: { type: string; id: string }; outcome: 'success' | 'failure'; metadata: Record<string, unknown>; } class AuditLogger { async log(event: AuditEvent): Promise<void> { // Write to append-only audit log (immutable) await this.store.append({ ...event, timestamp: new Date().toISOString(), id: crypto.randomUUID(), }); } async logAuth(userId: string, action: string, success: boolean, req: Request) { await this.log({ timestamp: new Date().toISOString(), actor: { id: userId, email: '', ip: req.ip }, action: `auth.${action}`, resource: { type: 'session', id: req.sessionID || '' }, outcome: success ? 'success' : 'failure', metadata: { userAgent: req.get('user-agent') }, }); } }

Configuration

ParameterTypeDefaultDescription
passwordMinLengthnumber12Minimum password length
bcryptCostFactornumber12bcrypt hashing rounds
sessionTimeoutnumber3600Session inactivity timeout (seconds)
rateLimitMaxnumber100Max requests per window per IP
csrfProtectionbooleantrueEnable CSRF token validation
auditLogRetentionnumber365Days to retain audit logs

Best Practices

  1. Validate all input at system boundaries, reject by default — Every API endpoint must validate request bodies, query parameters, and headers against strict schemas. Use allowlists rather than denylists — reject anything not explicitly permitted.

  2. Hash passwords with bcrypt at cost factor 12 or higher — Never use MD5, SHA-256, or plain hashing for passwords. bcrypt includes a salt and is intentionally slow. Increase cost factor as hardware improves. Consider Argon2id for new applications.

  3. Implement defense in depth for authorization — Check permissions at the route level (middleware), the service level (business logic), and the data level (row-level security). A bug in one layer shouldn't grant unauthorized access.

  4. Log security events immutably and completely — Authentication attempts, permission changes, data access, and admin actions must produce audit logs. Logs must be append-only and tamper-evident. Include actor, action, resource, and outcome in every entry.

  5. Rotate secrets and tokens on a schedule — API keys, JWT signing keys, database passwords, and encryption keys must be rotated periodically. Use a secrets manager (Vault, AWS Secrets Manager) rather than environment variables for production secrets.

Common Issues

CSRF tokens not working with SPAs — Traditional CSRF tokens rely on server-rendered forms. For SPAs, use the double-submit cookie pattern: set a random token in a cookie and require the same value in a custom header. SameSite=Strict cookies also prevent CSRF for same-site requests.

Rate limiting bypassed via distributed IPs — IP-based rate limiting fails against distributed attacks. Combine IP limiting with user/API-key-based limits. For unauthenticated endpoints, add CAPTCHA or proof-of-work challenges when rate limits are exceeded.

Sensitive data appearing in logs — Passwords, tokens, and PII must never appear in application logs. Use a structured logging library with field redaction. Define a denylist of field names (password, token, ssn, creditCard) that are automatically masked in log output.

Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates