Skip to content

security

Deep security patterns for threat modeling, OWASP, authentication, API security, container/supply chain, LLM, and zero-trust

seniorv1.0.0senior/skills/security
View source on GitHub

Security

Threat Modeling

STRIDE (per-element)

| Threat | Definition | Example | |--------|------------|---------| | Spoofing | Impersonate identity | JWT forged signature | | Tampering | Modify data | SQL injection | | Repudiation | Deny action | Missing audit logs | | Information Disclosure | Leak data | IDOR endpoint | | Denial of Service | Exhaust resources | Rate limit bypass | | Elevation of Privilege | Gain unauthorized access | Role escalation |

PASTA

  • Stage 1: Define business objectives.
  • Stage 2: Define technical scope (data flow, trust boundaries).
  • Stage 3: Application decomposition (threat enumeration).
  • Stage 4: Threat analysis (attack trees).
  • Stage 5: Vulnerability identification (CVE mapping).
  • Stage 6: Risk analysis (DREAD, CVSS).
  • Stage 7: Countermeasure prioritization.

LINDDUN (privacy-focused)

  • Linkability, Identifiability, Non-repudiation, Detectability, Disclosure of information, Unawareness, Non-compliance.

OWASP Top 10 Prevention

| # | Risk | Mitigation | |---|------|------------| | A01 | Broken Access Control | Centralized authorization, deny-by-default | | A02 | Cryptographic Failures | Use strong KDFs (Argon2id, bcrypt 12+ rounds) | | A03 | Injection | Parameterized queries, input validation | | A04 | Insecure Design | Threat modeling in design phase | | A05 | Security Misconfiguration | Automated hardening (CIS benchmarks) | | A06 | Vulnerable Components | SBOM, Dependabot, renovate | | A07 | Auth Failures | MFA, rate-limit login, secure session mgmt | | A08 | Data Integrity Failures | Signed JWTs, CSP, SRI | | A09 | Logging Failures | Structured logging to SIEM, alert on auth events | | A10 | SSRF | URL allowlist, disable internal network access |

Authentication Patterns

| Protocol | Use | Notes | |----------|-----|-------| | OAuth2 Authorization Code + PKCE | Third-party access | State + nonce params, never use implicit flow | | OIDC (OpenID Connect) | User identity | id_token + access_token, verify iss/aud/azp | | SAML2 | Enterprise SSO | XML signatures, IdP-initiated/SP-initiated | | WebAuthn / Passkeys | Passwordless | FIDO2, navigator.credentials.create/get, resident keys |

JWT Best Practices

import jwt
from datetime import timedelta, timezone

payload = {
    "sub": str(user.id),
    "iss": "https://auth.example.com",
    "aud": "https://api.example.com",
    "exp": datetime.now(timezone.utc) + timedelta(hours=1),
    "iat": datetime.now(timezone.utc),
    "jti": str(uuid.uuid4()),
}
token = jwt.encode(payload, private_key, algorithm="ES256")
  • Use asymmetric algorithms (ES256, RS256), never alg: none.
  • Validate iss, aud, exp, jti on every request.
  • Short expiry + refresh token rotation.

API Security

  • Rate limiting: sliding window (Redis), per-key + per-IP.
  • Input validation: JSON Schema, Pydantic, Zod.
  • Output encoding: Content-Type enforcement, response sanitization.
  • CORS: restrict Access-Control-Allow-Origin to specific origins.
  • API keys: hash before storing, prefix with type (e.g., sk_live_).

Container Security

  • Image scanning: Trivy, Grype, Snyk.
  • Minimal base images: distroless, chainguard, scratch.
  • Read-only root filesystem: readOnlyRootFilesystem: true.
  • Drop capabilities: securityContext: { capabilities: { drop: ["ALL"] } }.
  • No privilege escalation: allowPrivilegeEscalation: false.
  • Runtime security: Falco (syscall monitoring), AppArmor, seccomp.

Supply Chain Security

  • SLSA Levels: L1 (provenance), L2 (hosted build), L3 (hardened build), L4 (hermetic + reproducible).
  • SBOM: CycloneDX or SPDX, generated by syft, cdxgen.
  • Sigstore / Cosign: Sign container images, verify in admission controller.
  • Dependency pinning: Lockfiles, hash-pinned deps, Dependabot + renovate.

LLM Security

Prompt Injection

# Defense: input sanitization + output validation
def safe_prompt(user_input: str) -> str:
    sanitized = sanitize(user_input)
    return f"""You are a helpful assistant.
    {INSTRUCTIONS}
    User: {sanitized}
    Assistant:"""
  • OWASP LLM Top 10: LLM01 prompt injection, LLM02 data leakage, LLM03 supply chain.
  • RAG security: Index access controls, query sanitization, PII redaction in responses.
  • Model security: Adversarial input detection, rate limiting, usage monitoring.

Zero-Trust Architecture

  • Core principle: Never trust, always verify.
  • Micro-segmentation: Per-workload firewall rules (CiliumNetworkPolicy).
  • Identity-based access: SPIFFE (mTLS identity), OPA for policy.
  • Continuous verification: Session expiry, device posture checks.
  • Reference architecture: Google BeyondCorp, Zscaler ZPA, Cloudflare Zero Trust.