Security Principles — Data-Driven

Design your application by principle, not by patching. The data shows layered controls reduce breach speed & impact.
Principles

Core principles

Least privilege: limit access (users, services, keys). Defense in depth: apply multiple independent controls (eg validation + CSP + sanitization). Fail secure: defaults are secure; errors reveal minimal info.

Data-driven tips

Monitor key metrics: auth failures, password reset rates, exception spikes, JWT rejection, 4xx/5xx rates. Use thresholds and anomaly detection — automated tuning reduces mean time to detect (MTTD).

Checklist

OWASP Top 10 mapped to policies

Map each Top 10 item to a concrete policy & measurable controls (SLA for remediation, CI pipelines, scanners).

Top-10 Highlights

  1. A01:2021 – Broken Access Control → enforce RBAC, ABAC, test rules
  2. A02 – Cryptographic Failures → keys, TLS, MFA for key ops
  3. A03 – Injection → prepared statements, parameterized queries
  4. A04 – Insecure Design → threat models, secure design reviews
  5. A05 – Security Misconfiguration → hardened images, automated scans
  6. A06 – Vulnerable Components → dependency scanning, pinning
  7. A07 – Identification & Authentication → multi-factor, token rotation
  8. A08 – Software & Data Integrity Failures → signed artifacts, reproducible builds
  9. A09 – Security Logging & Monitoring → retention, alerting, SOAR integration
  10. A10 – Server-Side Request Forgery (SSRF) & others → denylist egress, egress proxies

Actionable mapping

For each OWASP item: a) prevent with code/config, b) detect with tests & runtime sensors, c) respond with incident playbook. Example: Broken Access Control → automated access tests + runtime RBAC auditing logs.
MTTD
Target: < 24h
MTTR
Target: < 72h
Coverage
SAST/DAST ≥ 90%

Authentication & Authorization

Make auth friction smart: protect account recovery, rotate keys, require MFA on sensitive paths.
Auth

Design & controls

  • Use strong hashing for passwords (Argon2id preferred; bcrypt or scrypt acceptable). Use per-user salt, memory-hard params tuned for latency & cost.
  • Prefer short-lived access tokens + refresh with rotation. Use refresh token rotation pattern to detect theft.
  • Implement MFA (TOTP + push + FIDO2) for all privileged operations and admins.
  • Enforce account lockout/backoff & notify on suspicious resets.

Code & config

Example: Authorization check (express-like pseudo)
// Principle: check privileges at every entry point
async function authorize(user, resource, action){
  // minimal example: ABAC + explicit deny
  if(!user || user.disabled) throw new Error('unauthenticated');
  const policy = await getPolicyFor(resource);
  if(policy.deny.includes(user.role)) throw new Error('forbidden');
  if(!policy.allowedActions.includes(action)) throw new Error('forbidden');
  // log decision for auditing
  audit('authz', {user:user.id, resource, action});
  return true;
}

Checklist

Input Validation & XSS

Validate early, encode late. Never trust client input; use allowlists. Prefer contextual encoding to prevent XSS.

XSS prevention

  1. Use server-side output encoding for HTML, JS, URL, CSS contexts. Use templating frameworks with auto-encoding.
  2. Implement CSP with strict directives and nonces where possible. Prefer disallowing inline scripts/styles.
  3. Sanitize untrusted HTML only with a secure library and allowlist.

Example CSP header

Recommended strict baseline with nonce
Content-Security-Policy:
  default-src 'none';
  script-src 'self' 'nonce-';
  style-src 'self' 'nonce-';
  img-src 'self' data:;
  connect-src 'self' https://api.example.com;
  frame-ancestors 'none';
  base-uri 'self';
  block-all-mixed-content;

Checklist

Sessions & Cookies

Protect session tokens at rest, in-flight, and during rotation. Prefer cookies with strict attributes for browser sessions.

Cookie attributes

Set-Cookie: session=eyJ...; HttpOnly; Secure; SameSite=Strict; Path=/; Max-Age=3600

HttpOnly prevents JS access; Secure mandates TLS; SameSite mitigates CSRF (Lax/Strict depending on UX).

Session best practices

  • Short session TTL for sensitive apps. Use refresh tokens for longer UX with rotating refresh.
  • Store session state server-side or use signed/encrypted tokens with audience & expiry.
  • Invalidate sessions on password reset or explicit logout; provide admin session revocation APIs.

Checklist

Transport Layer & TLS

Strong TLS and proper certificate management are table stakes. Prefer TLS 1.3, forward secrecy, and strict certificate validation.

TLS configuration essentials

  • TLS 1.3 only where possible. If supporting TLS 1.2, disable weak ciphers; enable ECDHE for forward secrecy.
  • HSTS header with long max-age and preload when ready: Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
  • OCSP stapling enabled; monitor certificate expiry and automations for renewal (ACME).

Example Nginx snippet

# nginx TLS 1.3 strong config
ssl_protocols TLSv1.3 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_session_tickets off;
ssl_stapling on;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

Checklist

Security Headers & CSP (deep)

Use layered headers: CSP, HSTS, X-Frame-Options, Referrer-Policy, Permissions-Policy. Strict headers reduce exploit surface.

Essential headers

Referrer-Policy: no-referrer-when-downgrade
Permissions-Policy: camera=(), microphone=(), geolocation=()
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Expect-CT: max-age=86400, enforce

Deploying CSP gradually

Start in report-only mode to gather violations: use report-uri/report-to. Then iterate to enforcement. Consider nonce-or-hash approach for necessary inline scripts.

Checklist

Storage & Data Protection

Encrypt sensitive data at rest & in transit. Apply field-level encryption for PII, and protect keys with KMS/HSM and rotation policies.

Key management

  • Use managed KMS with strong IAM policies and least privilege. Rotate keys quarterly or per policy.
  • Never store raw credentials or secrets in code or plain text. Use secret managers & ephemeral credentials (IAM roles).

Data minimization & retention

Collect only required data; apply retention policies and automated deletion; use pseudonymization when possible.

Checklist

Dependencies & Supply-Chain Security

Treat third-party code as high-risk: scan, pin, validate, and sign artifacts. Use reproducible builds and minimal dependencies.

Practical steps

  • Automated SBOM generation and dependency scanning (Snyk, OSS Index, etc.). Block critical vulnerabilities in CI/CD gates.
  • Pin dependencies and prefer lockfiles. Set up alerts for transitive dependency issues.
  • Sign artifacts (container images, packages) and verify signatures in production image policies.

Checklist

CI/CD & Testing

Shift left: run SAST, dependency checks, secrets scanning, and SBOM generation in CI. Use reproducible pipelines and least-privileged runners.

Pipeline controls

  • Fail builds on high severity findings. Provide auto-PR remediations for low/mid severity where safe.
  • Isolate build environments and rotate service tokens between stages. Use ephemeral runners to reduce exposure.
  • Automate infrastructure scanning (IaC checks) and enforce secure baseline images.

Checklist

Logging, Monitoring & Incident Response

Design logging for detection and forensics. Centralize logs, ensure immutability/retention, and run playbook drills.

Monitoring essentials

  • Log auth decisions, critical errors, and policy violations. Telemetry must include request IDs and user context for traceability.
  • Build alerts on anomalous patterns (credential stuffing, sudden traffic to admin endpoints, spikes in 401/403).
  • Run tabletop exercises and automate IR steps where possible: isolate container, rotate keys, revoke sessions.

Checklist

Master Checklist (Exportable)

All required items collated. Use export to CSV to integrate with trackers.

Quick Quiz — Test your basics

Select the best answer and submit. Instant feedback.

1) Best header to enforce HTTPS?
2) Recommended password hashing?