Software Security & AppSec — Quick Reference Production-grade security patterns for building secure applications in Jan 2026. Covers OWASP Top 10:2025 (stable) https://owasp.org/Top10/2025/ plus OWASP API Security Top 10 (2023) https://owasp.org/API-Security/ and secure SDLC baselines (NIST SSDF) https://csrc.nist.gov/publications/detail/sp/800-218/final. --- When to Use This Skill Activate this skill when: - Implementing authentication or authorization systems - Handling user input that could lead to injection attacks (SQL, XSS, command injection) - Designing secure APIs or web applications…

)[2]);\n\n return hashCost \u003c currentCost;\n};\n\nconst loginAndRehash = async (email, password) => {\n const user = await authenticateUser(email, password);\n\n // Rehash if using old cost factor\n if (needsRehash(user.passwordHash)) {\n const newHash = await hashPassword(password);\n await User.findByIdAndUpdate(user.id, { passwordHash: newHash });\n }\n\n return user;\n};\n```\n\n### Pattern 2: Argon2 (Best for New Projects)\n\n```javascript\nconst argon2 = require('argon2');\n\n// Hash password\nconst hashPassword = async (password) => {\n const hash = await argon2.hash(password, {\n type: argon2.argon2id, // Hybrid mode (recommended)\n memoryCost: 2 ** 16, // 64 MB\n timeCost: 3, // 3 iterations\n parallelism: 1 // 1 thread\n });\n\n return hash;\n};\n\n// Verify password\nconst verifyPassword = async (password, hash) => {\n try {\n return await argon2.verify(hash, password);\n } catch (error) {\n return false;\n }\n};\n```\n\n**Argon2 Type Selection:**\n- **argon2id**: Hybrid (recommended) - resistant to both side-channel and GPU attacks\n- **argon2i**: Data-independent - best for password hashing\n- **argon2d**: Data-dependent - best for cryptocurrency\n\n### Pattern 3: scrypt\n\n```javascript\nconst crypto = require('crypto');\n\n// Hash password\nconst hashPassword = (password) => {\n return new Promise((resolve, reject) => {\n const salt = crypto.randomBytes(16);\n\n crypto.scrypt(password, salt, 64, {\n N: 16384, // CPU/memory cost\n r: 8, // Block size\n p: 1, // Parallelization\n maxmem: 32 * 1024 * 1024 // 32 MB\n }, (err, derivedKey) => {\n if (err) reject(err);\n\n resolve(salt.toString('hex') + ':' + derivedKey.toString('hex'));\n });\n });\n};\n\n// Verify password\nconst verifyPassword = (password, hash) => {\n return new Promise((resolve, reject) => {\n const [salt, key] = hash.split(':');\n\n crypto.scrypt(password, Buffer.from(salt, 'hex'), 64, {\n N: 16384,\n r: 8,\n p: 1,\n maxmem: 32 * 1024 * 1024\n }, (err, derivedKey) => {\n if (err) reject(err);\n\n resolve(derivedKey.toString('hex') === key);\n });\n });\n};\n```\n\n**Never Use:**\n- [FAIL] MD5\n- [FAIL] SHA-1\n- [FAIL] Plain SHA-256 (without salting and iterations)\n- [FAIL] Custom password hashing schemes\n\n---\n\n## Symmetric Encryption\n\n### Pattern 1: AES-256-GCM (Recommended)\n\n```javascript\nconst crypto = require('crypto');\n\n// Encrypt data\nconst encrypt = (plaintext, key) => {\n // Key must be 32 bytes for AES-256\n if (key.length !== 32) {\n throw new Error('Key must be 32 bytes');\n }\n\n // Generate random IV (12 bytes for GCM)\n const iv = crypto.randomBytes(12);\n\n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);\n\n let ciphertext = cipher.update(plaintext, 'utf8', 'hex');\n ciphertext += cipher.final('hex');\n\n // Get authentication tag\n const authTag = cipher.getAuthTag();\n\n return {\n ciphertext,\n iv: iv.toString('hex'),\n authTag: authTag.toString('hex')\n };\n};\n\n// Decrypt data\nconst decrypt = (ciphertext, key, iv, authTag) => {\n const decipher = crypto.createDecipheriv(\n 'aes-256-gcm',\n key,\n Buffer.from(iv, 'hex')\n );\n\n // Set authentication tag\n decipher.setAuthTag(Buffer.from(authTag, 'hex'));\n\n let plaintext = decipher.update(ciphertext, 'hex', 'utf8');\n plaintext += decipher.final('utf8');\n\n return plaintext;\n};\n\n// Example: Encrypt user data\nconst encryptUserData = (data, masterKey) => {\n const plaintext = JSON.stringify(data);\n const encrypted = encrypt(plaintext, masterKey);\n\n // Store in database\n return {\n data: encrypted.ciphertext,\n iv: encrypted.iv,\n authTag: encrypted.authTag\n };\n};\n\nconst decryptUserData = (encrypted, masterKey) => {\n const plaintext = decrypt(\n encrypted.data,\n masterKey,\n encrypted.iv,\n encrypted.authTag\n );\n\n return JSON.parse(plaintext);\n};\n```\n\n**Key Generation:**\n```javascript\n// Generate random 256-bit key\nconst generateKey = () => {\n return crypto.randomBytes(32);\n};\n\n// Derive key from password (for user-encrypted data)\nconst deriveKey = async (password, salt) => {\n return new Promise((resolve, reject) => {\n crypto.scrypt(password, salt, 32, {\n N: 16384,\n r: 8,\n p: 1\n }, (err, derivedKey) => {\n if (err) reject(err);\n resolve(derivedKey);\n });\n });\n};\n```\n\n### Pattern 2: AES-256-CBC (Legacy Support)\n\n```javascript\n// Use GCM instead if possible (CBC doesn't provide authentication)\n\nconst encryptCBC = (plaintext, key) => {\n const iv = crypto.randomBytes(16);\n const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);\n\n let ciphertext = cipher.update(plaintext, 'utf8', 'hex');\n ciphertext += cipher.final('hex');\n\n return {\n ciphertext,\n iv: iv.toString('hex')\n };\n};\n\nconst decryptCBC = (ciphertext, key, iv) => {\n const decipher = crypto.createDecipheriv(\n 'aes-256-cbc',\n key,\n Buffer.from(iv, 'hex')\n );\n\n let plaintext = decipher.update(ciphertext, 'hex', 'utf8');\n plaintext += decipher.final('utf8');\n\n return plaintext;\n};\n```\n\n**Never Use:**\n- [FAIL] DES / 3DES\n- [FAIL] RC4\n- [FAIL] AES-ECB mode\n- [FAIL] Hardcoded encryption keys\n- [FAIL] Same IV for multiple encryptions\n\n---\n\n## Asymmetric Encryption\n\n### Pattern 1: RSA\n\n```javascript\nconst crypto = require('crypto');\n\n// Generate RSA key pair\nconst generateKeyPair = () => {\n return new Promise((resolve, reject) => {\n crypto.generateKeyPair('rsa', {\n modulusLength: 4096, // 4096 bits (2048 minimum)\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: process.env.KEY_PASSPHRASE\n }\n }, (err, publicKey, privateKey) => {\n if (err) reject(err);\n resolve({ publicKey, privateKey });\n });\n });\n};\n\n// Encrypt with public key\nconst encryptRSA = (plaintext, publicKey) => {\n const buffer = Buffer.from(plaintext, 'utf8');\n\n const encrypted = crypto.publicEncrypt(\n {\n key: publicKey,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256'\n },\n buffer\n );\n\n return encrypted.toString('base64');\n};\n\n// Decrypt with private key\nconst decryptRSA = (ciphertext, privateKey, passphrase) => {\n const buffer = Buffer.from(ciphertext, 'base64');\n\n const decrypted = crypto.privateDecrypt(\n {\n key: privateKey,\n passphrase,\n padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,\n oaepHash: 'sha256'\n },\n buffer\n );\n\n return decrypted.toString('utf8');\n};\n```\n\n**RSA Best Practices:**\n- Minimum 2048-bit keys (4096 recommended for long-term security)\n- Use OAEP padding (never use PKCS1 v1.5)\n- Protect private keys with strong passphrases\n- Rotate keys periodically\n\n### Pattern 2: Elliptic Curve (ECDH)\n\n```javascript\n// Generate ECDH key pair\nconst generateECDHKeyPair = () => {\n return crypto.generateKeyPairSync('ec', {\n namedCurve: 'secp256k1', // Or 'prime256v1', 'secp384r1'\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem'\n }\n });\n};\n\n// Derive shared secret\nconst deriveSharedSecret = (privateKey, publicKey) => {\n const ecdh = crypto.createECDH('secp256k1');\n ecdh.setPrivateKey(privateKey, 'pem');\n\n const otherPublicKey = crypto.createPublicKey(publicKey);\n const sharedSecret = ecdh.computeSecret(otherPublicKey);\n\n return sharedSecret;\n};\n```\n\n---\n\n## Digital Signatures\n\n### Pattern 1: RSA-PSS\n\n```javascript\n// Sign data\nconst signData = (data, privateKey, passphrase) => {\n const sign = crypto.createSign('SHA256');\n sign.update(data);\n sign.end();\n\n const signature = sign.sign({\n key: privateKey,\n passphrase,\n padding: crypto.constants.RSA_PKCS1_PSS_PADDING,\n saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST\n });\n\n return signature.toString('base64');\n};\n\n// Verify signature\nconst verifySignature = (data, signature, publicKey) => {\n const verify = crypto.createVerify('SHA256');\n verify.update(data);\n verify.end();\n\n return verify.verify(\n {\n key: publicKey,\n padding: crypto.constants.RSA_PKCS1_PSS_PADDING,\n saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST\n },\n Buffer.from(signature, 'base64')\n );\n};\n\n// Example: Sign API request\nconst signRequest = (requestBody, privateKey) => {\n const timestamp = Date.now();\n const payload = JSON.stringify({ ...requestBody, timestamp });\n\n const signature = signData(payload, privateKey, process.env.KEY_PASSPHRASE);\n\n return {\n payload,\n signature,\n timestamp\n };\n};\n```\n\n### Pattern 2: ECDSA\n\n```javascript\n// Sign with ECDSA\nconst signECDSA = (data, privateKey) => {\n const sign = crypto.createSign('SHA256');\n sign.update(data);\n sign.end();\n\n const signature = sign.sign(privateKey);\n return signature.toString('base64');\n};\n\n// Verify ECDSA signature\nconst verifyECDSA = (data, signature, publicKey) => {\n const verify = crypto.createVerify('SHA256');\n verify.update(data);\n verify.end();\n\n return verify.verify(publicKey, Buffer.from(signature, 'base64'));\n};\n```\n\n---\n\n## Hashing\n\n### Pattern 1: SHA-256 (Data Integrity)\n\n```javascript\n// Hash data\nconst hashData = (data) => {\n const hash = crypto.createHash('sha256');\n hash.update(data);\n return hash.digest('hex');\n};\n\n// HMAC (keyed hash for message authentication)\nconst hmac = (data, key) => {\n const hmac = crypto.createHmac('sha256', key);\n hmac.update(data);\n return hmac.digest('hex');\n};\n\n// Example: File integrity check\nconst verifyFileIntegrity = async (filepath, expectedHash) => {\n const fileBuffer = await fs.readFile(filepath);\n const actualHash = hashData(fileBuffer);\n\n return actualHash === expectedHash;\n};\n\n// Example: API request signing\nconst signAPIRequest = (requestData, secretKey) => {\n const payload = JSON.stringify(requestData);\n const signature = hmac(payload, secretKey);\n\n return {\n payload,\n signature\n };\n};\n\nconst verifyAPIRequest = (payload, signature, secretKey) => {\n const expectedSignature = hmac(payload, secretKey);\n return crypto.timingSafeEqual(\n Buffer.from(signature),\n Buffer.from(expectedSignature)\n );\n};\n```\n\n**Hash Functions:**\n- **SHA-256**: Standard for data integrity\n- **SHA-384/512**: Higher security margin\n- **SHA-3**: Latest standard (Keccak)\n\n**Never Use:**\n- [FAIL] MD5\n- [FAIL] SHA-1\n- [FAIL] CRC32 (for security purposes)\n\n---\n\n## Random Number Generation\n\n### Pattern 1: Cryptographically Secure Random\n\n```javascript\n// Generate random bytes\nconst generateRandomBytes = (length) => {\n return crypto.randomBytes(length);\n};\n\n// Generate random token\nconst generateToken = () => {\n return crypto.randomBytes(32).toString('hex');\n};\n\n// Generate random UUID\nconst generateUUID = () => {\n return crypto.randomUUID();\n};\n\n// Generate random integer in range\nconst randomInt = (min, max) => {\n const range = max - min;\n const bytesNeeded = Math.ceil(Math.log2(range) / 8);\n const maxValue = Math.pow(256, bytesNeeded);\n const randomValue = crypto.randomBytes(bytesNeeded).readUIntBE(0, bytesNeeded);\n\n // Avoid modulo bias\n if (randomValue >= maxValue - (maxValue % range)) {\n return randomInt(min, max);\n }\n\n return min + (randomValue % range);\n};\n```\n\n**Never Use:**\n- [FAIL] Math.random() for security purposes\n- [FAIL] Timestamp-based \"random\" values\n- [FAIL] Sequential IDs for security tokens\n\n---\n\n## TLS/SSL Configuration\n\n### Pattern 1: Node.js HTTPS Server\n\n```javascript\nconst https = require('https');\nconst fs = require('fs');\n\nconst options = {\n key: fs.readFileSync('/path/to/private-key.pem'),\n cert: fs.readFileSync('/path/to/certificate.pem'),\n ca: fs.readFileSync('/path/to/ca-cert.pem'),\n\n // TLS 1.3 only\n minVersion: 'TLSv1.3',\n maxVersion: 'TLSv1.3',\n\n // Cipher suites (TLS 1.3 ciphers)\n ciphers: [\n 'TLS_AES_256_GCM_SHA384',\n 'TLS_AES_128_GCM_SHA256',\n 'TLS_CHACHA20_POLY1305_SHA256'\n ].join(':'),\n\n // Prefer server cipher order\n honorCipherOrder: true,\n\n // Disable session resumption (optional, for max security)\n sessionTimeout: 0\n};\n\nconst server = https.createServer(options, app);\nserver.listen(443);\n```\n\n### Pattern 2: Express Security Headers\n\n```javascript\nconst helmet = require('helmet');\n\napp.use(helmet({\n // Strict Transport Security\n hsts: {\n maxAge: 31536000,\n includeSubDomains: true,\n preload: true\n },\n\n // Certificate Transparency\n expectCt: {\n maxAge: 86400,\n enforce: true\n }\n}));\n```\n\n**TLS Best Practices:**\n- Use TLS 1.3 only (disable 1.2, 1.1, 1.0)\n- Use strong cipher suites\n- Enable HSTS with preload\n- Implement certificate pinning for mobile apps\n- Use certificate transparency\n- Rotate certificates before expiration\n\n---\n\n## Key Management\n\n### Pattern 1: Environment Variables\n\n```javascript\n// Load from .env file\nrequire('dotenv').config();\n\nconst SECRET_KEY = Buffer.from(process.env.SECRET_KEY, 'hex');\nconst JWT_SECRET = process.env.JWT_SECRET;\n\n// Never hardcode keys\n// BAD: const SECRET_KEY = 'hardcoded-key-12345';\n```\n\n### Pattern 2: Key Management Service\n\n```javascript\nconst AWS = require('aws-sdk');\nconst kms = new AWS.KMS();\n\n// Encrypt data with KMS\nconst encryptWithKMS = async (plaintext) => {\n const params = {\n KeyId: process.env.KMS_KEY_ID,\n Plaintext: plaintext\n };\n\n const result = await kms.encrypt(params).promise();\n return result.CiphertextBlob.toString('base64');\n};\n\n// Decrypt data with KMS\nconst decryptWithKMS = async (ciphertext) => {\n const params = {\n CiphertextBlob: Buffer.from(ciphertext, 'base64')\n };\n\n const result = await kms.decrypt(params).promise();\n return result.Plaintext.toString('utf8');\n};\n\n// Generate data encryption key\nconst generateDataKey = async () => {\n const params = {\n KeyId: process.env.KMS_KEY_ID,\n KeySpec: 'AES_256'\n };\n\n const result = await kms.generateDataKey(params).promise();\n\n return {\n plaintextKey: result.Plaintext,\n encryptedKey: result.CiphertextBlob.toString('base64')\n };\n};\n```\n\n### Pattern 3: HashiCorp Vault\n\n```javascript\nconst vault = require('node-vault')({\n endpoint: process.env.VAULT_ADDR,\n token: process.env.VAULT_TOKEN\n});\n\n// Store secret\nconst storeSecret = async (path, data) => {\n await vault.write(path, { data });\n};\n\n// Retrieve secret\nconst retrieveSecret = async (path) => {\n const result = await vault.read(path);\n return result.data.data;\n};\n\n// Example usage\nconst getEncryptionKey = async () => {\n const secret = await retrieveSecret('secret/data/encryption-key');\n return Buffer.from(secret.key, 'hex');\n};\n```\n\n**Key Management Best Practices:**\n- Never commit keys to version control\n- Use key management services (AWS KMS, Azure Key Vault, HashiCorp Vault)\n- Rotate keys periodically\n- Implement key versioning\n- Secure key backup and recovery\n- Separate encryption keys by environment\n- Use envelope encryption for large data\n\n---\n\n## References\n\n- [NIST Cryptographic Standards](https://csrc.nist.gov/projects/cryptographic-standards-and-guidelines)\n- [NIST SP 800-63B](https://pages.nist.gov/800-63-3/sp800-63b.html)\n- [OWASP Cryptographic Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html)\n- [Mozilla SSL Configuration Generator](https://ssl-config.mozilla.org/)\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":17359,"content_sha256":"75e88faee04d496b75a2844ea9ab2bc87d58f872fb6791f4ccd008aac174c0b4"},{"filename":"references/dotnet-efcore-crypto-security.md","content":"# .NET/EF Core Crypto Integration Security\n\nSecurity rules for **C#/.NET crypto/fintech services** using **Entity Framework Core**. Apply these rules in addition to general AppSec patterns.\n\n---\n\n## Security Rules\n\n### No Secrets in Code\n\n- API keys, tokens, connection strings must come from configuration or environment variables\n- Never hardcode credentials, private keys, or wallet seeds\n\n### No Sensitive Data in Logs\n\n- Tokens, passwords, private keys, wallet addresses with balances must not appear in logs\n- Mask or exclude PII and financial data from log output\n\n### Input Validation\n\n- All external inputs validated before use (null/empty, format, ranges)\n- Use `decimal` for all financial/crypto values — never `double` or `float`\n\n### Database Security\n\n- SQL queries must use ORM (EF Core) or parameterized queries — never string concatenation\n- No dynamic SQL construction\n\n### Error Messages\n\n- Error responses must not expose internal technical details (stack traces, configuration values, connection strings)\n- Use generic user-facing messages with detailed server-side logging\n\n---\n\n## C# Security Patterns\n\n```csharp\n// Good: Secrets from configuration\nvar apiKey = configuration[\"ExternalApi:ApiKey\"];\nvar connectionString = configuration.GetConnectionString(\"CryptoDb\");\n\n// Bad: Hardcoded secrets\nvar apiKey = \"sk-live-abc123...\"; // NEVER DO THIS\n\n// Good: Safe logging\n_logger.LogInformation(\"Processing transaction {TransactionId}\", transaction.Id);\n\n// Bad: Sensitive data in logs\n_logger.LogInformation(\"Processing with key {ApiKey}\", apiKey); // NEVER LOG SECRETS\n\n// Good: Parameterized query with EF Core\nvar wallet = await _context.Wallets\n .Where(w => w.Address == walletAddress)\n .FirstOrDefaultAsync(cancellationToken);\n\n// Good: Financial precision\ndecimal amount = 100.50m;\ndecimal fee = amount * 0.001m;\n\n// Bad: Floating point for money\ndouble amount = 100.50; // NEVER USE FOR FINANCIAL VALUES\n```\n\n---\n\n## Async & Error Handling\n\n```csharp\n// Good: Proper async with cancellation\npublic async Task\u003cResult\u003cWallet>> GetWalletAsync(string address, CancellationToken ct)\n{\n try\n {\n var wallet = await _context.Wallets\n .AsNoTracking()\n .FirstOrDefaultAsync(w => w.Address == address, ct);\n\n return wallet is null\n ? Result\u003cWallet>.Fail(\"Wallet not found\")\n : Result\u003cWallet>.Success(wallet);\n }\n catch (Exception ex)\n {\n _logger.LogError(ex, \"Failed to get wallet {Address}\", address);\n return Result\u003cWallet>.Fail(\"Failed to retrieve wallet\");\n }\n}\n\n// Bad: Blocking call\nvar wallet = _context.Wallets.FirstOrDefault(w => w.Address == address); // No async!\n\n// Bad: Swallowed exception\ntry { ... }\ncatch { } // NEVER DO THIS\n```\n\n---\n\n## Database (EF Core) Patterns\n\n```csharp\n// Good: AsNoTracking for read-only\nvar transactions = await _context.Transactions\n .AsNoTracking()\n .Where(t => t.WalletId == walletId)\n .ToListAsync(ct);\n\n// Good: Selective Include\nvar wallet = await _context.Wallets\n .Include(w => w.Transactions.Where(t => t.Status == Status.Pending))\n .FirstOrDefaultAsync(w => w.Id == id, ct);\n\n// Bad: N+1 query pattern\nforeach (var wallet in wallets)\n{\n var balance = await _context.Balances\n .FirstOrDefaultAsync(b => b.WalletId == wallet.Id); // Query per iteration!\n}\n\n// Good: Batch load\nvar walletIds = wallets.Select(w => w.Id).ToList();\nvar balances = await _context.Balances\n .Where(b => walletIds.Contains(b.WalletId))\n .ToDictionaryAsync(b => b.WalletId, ct);\n```\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":3560,"content_sha256":"553f944f623a2e4ddaa9d5db39d50f710c2c6d5dc7501ea1c34712777e9af135"},{"filename":"references/incident-response-playbook.md","content":"# Security Incident Response Playbook (Jan 2026)\n\nComprehensive incident response procedures covering team structure, detection, containment, evidence handling, communication, remediation, recovery, and post-incident review. Designed for software teams from seed-stage startups to enterprise.\n\n---\n\n## IR Team Composition and Roles\n\nEvery incident needs clear ownership. Scale team size to incident severity.\n\n| Role | Responsibility | Who (Typical) |\n|------|---------------|---------------|\n| **Incident Commander (IC)** | Owns decision authority, coordinates response, sets priorities | Engineering manager, senior SRE, CISO |\n| **Technical Lead** | Investigates root cause, directs containment and remediation | Senior engineer with domain knowledge |\n| **Communications Lead** | Drafts internal/external messaging, manages stakeholder updates | Head of comms, product manager, legal |\n| **Scribe** | Records timeline, decisions, actions in real time | Any team member |\n| **Subject Matter Expert** | Provides domain-specific knowledge (e.g., auth, infra, data) | Relevant engineer or architect |\n\n### Escalation Contact Sheet\n\nMaintain a living document with:\n\n- Primary and backup for each role\n- Phone numbers (not just Slack handles)\n- Timezone coverage\n- External contacts: legal counsel, cyber insurance broker, forensics firm\n- Regulatory contacts: DPA (GDPR), state AG offices (US breach laws)\n\n```text\nTEMPLATE:\nRole | Primary | Backup | Phone\nIncident Commander | [Name] | [Name] | +1-XXX-XXX-XXXX\nTechnical Lead | [Name] | [Name] | +1-XXX-XXX-XXXX\nCommunications Lead | [Name] | [Name] | +1-XXX-XXX-XXXX\nLegal Counsel | [Firm/Name] | [Firm/Name] | +1-XXX-XXX-XXXX\nForensics Retainer | [Firm] | — | +1-XXX-XXX-XXXX\nCyber Insurance | [Broker/Carrier] | — | +1-XXX-XXX-XXXX\n```\n\n---\n\n## Detection and Triage\n\n### Severity Classification\n\n| Severity | Definition | Response Time | Escalation |\n|----------|-----------|---------------|------------|\n| **P0 — Critical** | Active data breach, credential compromise affecting production, ransomware, supply chain attack | Immediate (\u003c 15 min) | IC + CISO + Legal + Exec |\n| **P1 — High** | Confirmed vulnerability actively exploited, unauthorized access detected, customer PII exposed | \u003c 1 hour | IC + Technical Lead + Comms |\n| **P2 — Medium** | Vulnerability discovered (not exploited), suspicious activity requiring investigation, failed intrusion attempt | \u003c 4 hours | Technical Lead + Security team |\n| **P3 — Low** | Minor policy violation, low-risk vulnerability, security tool misconfiguration | \u003c 24 hours | Security team standard triage |\n\n### Triage Decision Tree\n\n```text\nAlert received:\n ├─ Is there active data exfiltration?\n │ └─ YES → P0, activate IR team immediately\n ├─ Are production credentials compromised?\n │ └─ YES → P0, begin secret rotation\n ├─ Is unauthorized access confirmed?\n │ ├─ To customer data → P0\n │ └─ To internal systems → P1\n ├─ Is a known vulnerability being exploited?\n │ └─ YES → P1\n ├─ Suspicious activity, no confirmed impact?\n │ └─ P2, investigate within 4 hours\n └─ Policy violation or configuration issue?\n └─ P3, standard workflow\n```\n\n### Detection Sources\n\n| Source | What It Catches | Priority |\n|--------|----------------|----------|\n| SIEM alerts (Splunk, Datadog, ELK) | Anomalous patterns, correlation rules | Automated, high priority |\n| WAF/IDS (Cloudflare, AWS WAF) | Known attack signatures, rate anomalies | Automated |\n| Dependency scanner (Snyk, Dependabot) | Vulnerable packages | Automated, P2-P3 |\n| Bug bounty / responsible disclosure | External findings | Manual, severity varies |\n| Customer report | Data they should not see, account compromise | Manual, triage immediately |\n| Employee report | Suspicious email, credential phishing | Manual, triage within 1 hour |\n| Code review finding | Hardcoded secrets, auth bypass | Manual, P2-P3 |\n\n---\n\n## Containment Procedures by Incident Type\n\n### Credential Leak\n\n```text\nIMMEDIATE (\u003c 30 minutes):\n1. Identify scope: which credentials, where leaked (GitHub, logs, public repo)\n2. Rotate all affected credentials:\n - API keys → generate new, revoke old\n - Database passwords → rotate, update connection strings\n - JWT signing keys → rotate, invalidate all active sessions\n - SSH keys → regenerate and redeploy\n3. Audit access logs for compromised credential usage\n4. Check for unauthorized changes made with compromised credentials\n5. Force logout all sessions if user-facing tokens compromised\n\nFOLLOW-UP (\u003c 4 hours):\n6. Enable MFA on affected accounts if not already active\n7. Review and restrict credential scope (least privilege)\n8. Scan entire codebase and CI/CD for additional hardcoded secrets\n9. Implement or verify secret scanning (GitHub Advanced Security, GitLeaks)\n```\n\n### Data Breach\n\n```text\nIMMEDIATE (\u003c 15 minutes):\n1. Determine data type: PII, financial, health, credentials\n2. Identify affected records count and user population\n3. Preserve evidence (do NOT delete logs or affected data)\n4. Block the attack vector (disable endpoint, block IP, revoke access)\n5. Engage legal counsel (triggers notification obligations)\n\nCONTAINMENT (\u003c 2 hours):\n6. Isolate affected systems (network segmentation)\n7. Capture forensic images of affected servers/databases\n8. Review access logs for data exfiltration timeline\n9. Determine if breach is ongoing or contained\n10. Begin notification timeline tracking (GDPR: 72 hours starts now)\n\nCOMMUNICATION (\u003c 24 hours):\n11. Internal stakeholder briefing\n12. Regulatory notification assessment (see Legal section below)\n13. Customer notification preparation\n14. Media holding statement if public exposure likely\n```\n\n### DDoS Attack\n\n```text\nIMMEDIATE:\n1. Confirm DDoS vs traffic spike (check source distribution)\n2. Activate CDN/WAF DDoS protection (Cloudflare Under Attack, AWS Shield)\n3. Enable aggressive rate limiting\n4. Scale infrastructure if auto-scaling available\n5. Block identified attack IPs/ranges at edge\n\nSUSTAINED ATTACK:\n6. Engage CDN/hosting provider support\n7. Implement geographic filtering if attack is region-specific\n8. Enable CAPTCHA on critical endpoints\n9. Consider temporary maintenance mode for non-critical services\n10. Monitor for secondary attacks (DDoS as distraction)\n```\n\n### Supply Chain Compromise\n\n```text\nIMMEDIATE:\n1. Identify compromised package, version, and scope\n2. Check SBOM: which services use the affected package?\n3. Pin to last known good version\n4. Block deployment pipeline\n5. Scan for indicators of compromise (IOCs) specific to the package\n\nCONTAINMENT:\n6. Audit what the compromised package could access (env vars, network, filesystem)\n7. Rotate any credentials the package could have exfiltrated\n8. Review build artifacts for tampering\n9. Check for persistence mechanisms (cron jobs, modified configs)\n10. Report to package registry (npm, PyPI) and relevant CERT\n```\n\n---\n\n## Evidence Collection\n\n### Log Preservation\n\n```bash\n# Immediately preserve logs before rotation or deletion\n# Application logs\naws s3 cp /var/log/app/ s3://incident-evidence/INC-2026-001/app-logs/ --recursive\n\n# Access logs\naws s3 cp /var/log/nginx/ s3://incident-evidence/INC-2026-001/access-logs/ --recursive\n\n# Database audit logs\npg_dump --table=audit_log > incident_audit_$(date +%Y%m%d_%H%M%S).sql\n\n# Cloud provider audit trail\naws cloudtrail lookup-events \\\n --start-time \"2026-01-15T00:00:00Z\" \\\n --end-time \"2026-01-16T00:00:00Z\" \\\n > cloudtrail_events.json\n```\n\n### Forensic Imaging\n\n| Asset Type | Tool | Procedure |\n|------------|------|-----------|\n| Cloud VM | Cloud provider snapshot | Create snapshot before any changes; tag with incident ID |\n| Container | `docker commit` + `docker save` | Capture running state; preserve image layers |\n| Database | Point-in-time snapshot | Use cloud provider snapshot; do not rely on logical backup alone |\n| Memory | `LiME` (Linux), cloud memory capture | Capture before reboot; volatile evidence lost on power cycle |\n\n### Chain of Custody\n\nEvery piece of evidence must have:\n\n```text\nEvidence ID: INC-2026-001-E003\nDescription: Application server access logs, Jan 15-16 2026\nCollected by: [Name], [Role]\nCollection time: 2026-01-16T14:30:00Z\nCollection method: aws s3 cp from production server\nHash (SHA-256): a3f2b1c4d5e6f7...\nStorage location: s3://incident-evidence/INC-2026-001/\nAccess restricted to: IR team members only\n```\n\n---\n\n## Communication Templates\n\n### Internal Stakeholder Notification (P0/P1)\n\n```text\nSUBJECT: [SECURITY INCIDENT] INC-2026-XXX — [Brief Description]\n\nSEVERITY: P[X]\nSTATUS: [Investigating | Contained | Remediated]\nINCIDENT COMMANDER: [Name]\n\nWHAT HAPPENED:\n[1-2 sentence description of what was detected]\n\nCURRENT IMPACT:\n- Users affected: [count or scope]\n- Data involved: [type of data, if known]\n- Services affected: [list]\n\nCURRENT ACTIONS:\n1. [Action taken or in progress]\n2. [Action taken or in progress]\n\nNEXT UPDATE: [Time] or in [X] hours\nBRIDGE: [Slack channel / video link]\n\nDO NOT:\n- Discuss externally until Communications Lead approves\n- Share details outside the listed distribution\n```\n\n### Customer Notification (Data Breach)\n\n```text\nSUBJECT: Important Security Notice from [Company]\n\nDear [Customer],\n\nWe are writing to inform you of a security incident that may have\naffected your account information.\n\nWHAT HAPPENED:\n[Clear, factual description. Avoid jargon.]\n\nWHAT INFORMATION WAS INVOLVED:\n[Specific data types: email, name, etc. Be precise.]\n\nWHAT WE ARE DOING:\n[Actions taken to contain and remediate]\n\nWHAT YOU CAN DO:\n- [Specific action: change password, enable MFA, monitor accounts]\n- [Specific action: contact information for questions]\n\nWe sincerely apologize for this incident. We are committed to\nprotecting your information and have taken the following steps to\nprevent a recurrence: [brief list].\n\nFor questions: [dedicated support email/phone]\nIncident details: [status page URL]\n\n[Name], [Title]\n```\n\n### Regulatory Notification Checklist\n\n```text\nREGULATION | DEADLINE | REQUIRED CONTENT\nGDPR (EU/EEA) | 72 hours to DPA | Nature, categories, approx records,\n | | consequences, measures taken\nCCPA/CPRA (CA) | \"Expedient\" | Categories, rights, what happened\nHIPAA (US health) | 60 days (>500) | Description, types, steps to protect,\n | annual (\u003c500) | investigation, contact, mitigation\nPCI DSS | Immediately | Card brands, acquirer, forensic\n | | investigation details\nSEC (public co.) | 4 business days | Material cybersecurity incident\n | after materiality| description\nState breach laws | Varies by state | See state-specific requirements\n```\n\n---\n\n## Remediation Checklists\n\n### Secret Rotation\n\n- [ ] Identify all secrets that may be compromised\n- [ ] Generate new secrets (strong entropy, proper length)\n- [ ] Update secrets in secrets manager (not in code or CI/CD variables)\n- [ ] Deploy updated configuration to all affected services\n- [ ] Verify services function correctly with new secrets\n- [ ] Revoke old secrets (after confirming new ones work)\n- [ ] Audit secret access logs for unauthorized use during exposure window\n\n### Access Revocation\n\n- [ ] Identify compromised accounts or sessions\n- [ ] Force logout all active sessions for affected accounts\n- [ ] Require password reset with MFA verification\n- [ ] Revoke OAuth tokens and API keys for affected users\n- [ ] Review and remove unauthorized access grants\n- [ ] Audit privilege escalation attempts\n\n### Patch Deployment\n\n- [ ] Identify vulnerable code or dependency\n- [ ] Develop or obtain patch\n- [ ] Test patch in staging environment\n- [ ] Deploy to production (hotfix pipeline)\n- [ ] Verify fix addresses the vulnerability\n- [ ] Scan for similar vulnerabilities elsewhere in codebase\n- [ ] Update WAF rules if applicable (virtual patching)\n\n---\n\n## Recovery Procedures\n\n### Service Restoration\n\n```text\nRECOVERY SEQUENCE:\n1. Verify containment is complete (no ongoing attack)\n2. Deploy patched/remediated code\n3. Restore from clean backups if data was corrupted\n4. Gradually re-enable services (canary → staged → full)\n5. Monitor closely for 24-48 hours post-restoration\n6. Verify all security controls are active\n7. Confirm logging and alerting are functioning\n```\n\n### Monitoring Enhancement\n\nAfter every incident, add or improve monitoring:\n\n| What to Add | Why | Tool |\n|-------------|-----|------|\n| Alert for the specific attack pattern | Catch recurrence | SIEM rule |\n| Anomaly detection on affected data store | Detect similar attacks | Datadog, CloudWatch |\n| Canary tokens in sensitive locations | Early warning for access | canarytokens.org |\n| Enhanced logging on affected endpoints | Deeper visibility | Application logging |\n| Failed auth rate alert | Brute-force detection | Rate limiter + alerting |\n\n---\n\n## Post-Incident Review (Blameless Postmortem)\n\n### Template\n\n```text\nINCIDENT POSTMORTEM: INC-2026-XXX\nDate: [Date]\nDuration: [Start] to [Resolved]\nSeverity: P[X]\nAuthors: [IR team members]\n\nSUMMARY\n[2-3 sentence overview of what happened and impact]\n\nTIMELINE (UTC)\n[Time] — [Event]\n[Time] — [Event]\n[Time] — [Event]\n(Include detection, escalation, containment, remediation, resolution)\n\nIMPACT\n- Users affected: [count]\n- Data exposed: [type and scope]\n- Downtime: [duration]\n- Financial impact: [estimate if available]\n\nROOT CAUSE\n[Technical explanation of the vulnerability or failure]\n\nCONTRIBUTING FACTORS\n1. [Factor that enabled or worsened the incident]\n2. [Factor]\n\nWHAT WENT WELL\n- [Effective detection, fast response, good communication]\n\nWHAT COULD BE IMPROVED\n- [Gaps in detection, slow escalation, unclear ownership]\n\nACTION ITEMS\n| ID | Action | Owner | Deadline | Priority |\n|----|--------|-------|----------|----------|\n| 1 | [Fix] | [Who] | [When] | P[X] |\n| 2 | [Fix] | [Who] | [When] | P[X] |\n\nLESSONS LEARNED\n[Key takeaways for the broader team]\n```\n\n### Postmortem Principles\n\n- **Blameless**: Focus on systems and processes, not individuals\n- **Honest**: Document what actually happened, not what should have happened\n- **Actionable**: Every finding produces a tracked action item with an owner\n- **Shared**: Publish internally (redacted if needed) so the whole org learns\n- **Reviewed**: Follow up on action items at 30-day and 90-day marks\n\n---\n\n## Legal and Regulatory Notification Requirements\n\n### GDPR 72-Hour Rule\n\n```text\nGDPR Article 33 — Notification to DPA:\n- Deadline: 72 hours from awareness of breach\n- \"Awareness\" = when you have reasonable certainty, not when alert fired\n- If beyond 72 hours: must explain delay\n- If risk to individuals: notify them directly (Article 34)\n\nREQUIRED INFORMATION:\n1. Nature of the breach (categories and approx. number of records)\n2. Name and contact of DPO\n3. Likely consequences\n4. Measures taken or proposed to address the breach\n```\n\n### US State Breach Notification\n\n| State | Deadline | Threshold | AG Notification |\n|-------|----------|-----------|-----------------|\n| California (CCPA/CPRA) | \"Expedient\" (typically 45 days) | Unencrypted PI | > 500 residents |\n| New York (SHIELD Act) | \"Expedient\" | Private information | Any number |\n| Texas | 60 days | Sensitive PI | > 250 residents |\n| Florida | 30 days | PI | > 500 residents |\n| Illinois (PIPA) | \"Expedient\" | PI | Any number |\n\n**Note**: State laws change frequently. Verify current requirements with legal counsel for each incident.\n\n---\n\n## IR Automation — SOAR Playbooks\n\nSecurity Orchestration, Automation, and Response (SOAR) can automate repetitive IR tasks.\n\n### Automatable Actions\n\n| Trigger | Automated Action | Tool |\n|---------|------------------|------|\n| GitHub secret detected | Revoke token, notify owner, create ticket | GitHub Advanced Security + webhook |\n| Multiple failed logins (>10 in 5 min) | Temporary IP block, alert security team | WAF rule + SIEM |\n| Known malicious IP detected | Block at edge, enrich with threat intel | Cloudflare + threat feed |\n| Vulnerability scan finds critical CVE | Create P1 ticket, notify owners, block deploy | Snyk + Jira integration |\n| Anomalous data access pattern | Capture session details, alert, prepare for containment | SIEM + SOAR |\n\n### Example: Automated Secret Leak Response\n\n```yaml\n# GitHub Actions workflow for leaked secret response\nname: Secret Leak Response\non:\n secret_scanning_alert:\n types: [created]\n\njobs:\n respond:\n runs-on: ubuntu-latest\n steps:\n - name: Get alert details\n id: alert\n uses: actions/github-script@v7\n with:\n script: |\n const alert = context.payload.alert;\n core.setOutput('type', alert.secret_type);\n core.setOutput('location', alert.html_url);\n\n - name: Create incident ticket\n uses: atlassian/gajira-create@v3\n with:\n project: SEC\n issuetype: Incident\n summary: 'Secret leaked: ${{ steps.alert.outputs.type }}'\n description: |\n A secret of type ${{ steps.alert.outputs.type }} was detected.\n Location: ${{ steps.alert.outputs.location }}\n Action required: Rotate immediately.\n\n - name: Notify security team\n uses: slackapi/slack-github-action@v1\n with:\n channel-id: 'C0SECURITY'\n slack-message: |\n :rotating_light: Secret leak detected\n Type: ${{ steps.alert.outputs.type }}\n Action: Rotate immediately\n```\n\n---\n\n## Anti-Patterns\n\n| Anti-Pattern | Why It Fails | Correct Approach |\n|-------------|-------------|------------------|\n| No documented IR plan | Chaos during real incident | Write and rehearse IR plan quarterly |\n| Single point of contact | Unavailable person blocks response | Primary + backup for every role |\n| Investigating before containing | Attack continues during analysis | Contain first, investigate second |\n| Deleting evidence during cleanup | Cannot determine scope or root cause | Preserve first, then clean |\n| Blaming individuals in postmortem | People hide information next time | Blameless postmortem culture |\n| Notifying only after full investigation | Regulatory deadlines missed | Start notification clock at awareness |\n| No IR rehearsal | First real incident exposes all gaps | Quarterly tabletop exercises |\n| Shared credentials for IR tools | Audit trail impossible | Individual accounts for all IR systems |\n\n---\n\n## References\n\n- [NIST SP 800-61r3 — Computer Security Incident Handling Guide](https://csrc.nist.gov/pubs/sp/800/61/r3/final)\n- [SANS Incident Handler's Handbook](https://www.sans.org/white-papers/33901/)\n- [GDPR Article 33 — Notification of a personal data breach](https://gdpr-info.eu/art-33-gdpr/)\n- [CISA Incident Reporting](https://www.cisa.gov/reporting)\n- [PagerDuty Incident Response Documentation](https://response.pagerduty.com/)\n\n---\n\n## Cross-References\n\n- [SKILL.md](../SKILL.md) — Parent skill overview and incident response patterns section\n- [security-business-value.md](security-business-value.md) — Breach cost data and IR team ROI\n- [supply-chain-security.md](supply-chain-security.md) — Supply chain incident response procedures\n- [cryptography-standards.md](cryptography-standards.md) — Key rotation procedures referenced in remediation\n- [common-vulnerabilities.md](common-vulnerabilities.md) — Vulnerability patterns that trigger incidents\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":19679,"content_sha256":"386070ec0310171ba6696e679af9e6eebccbfdf9dd4677e43579c984f97cd69f"},{"filename":"references/input-validation.md","content":"# Input Validation & Sanitization\n\nComprehensive guide to preventing injection attacks through proper input validation and output encoding.\n\n---\n\n## Core Principles\n\n**1. Never Trust User Input**: All input from users, external systems, or files is potentially malicious\n**2. Allowlist Over Blocklist**: Define what IS allowed, not what ISN'T\n**3. Validate Early, Sanitize Late**: Validate at entry, sanitize at output\n**4. Defense in Depth**: Multiple layers of validation and encoding\n**5. Context-Specific Encoding**: Different encoding for HTML, JavaScript, SQL, URLs\n\n---\n\n## Input Validation Patterns\n\n### Pattern 1: Allowlist Validation\n\n```javascript\n// Good: Strict allowlist for username\nconst validateUsername = (username) => {\n // Only alphanumeric and underscore, 3-20 characters\n const regex = /^[a-zA-Z0-9_]{3,20}$/;\n\n if (!regex.test(username)) {\n throw new ValidationError('Username must be 3-20 alphanumeric characters or underscores');\n }\n\n return username;\n};\n\n// Good: Email validation\nconst validateEmail = (email) => {\n const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\n\n if (!regex.test(email) || email.length > 254) {\n throw new ValidationError('Invalid email format');\n }\n\n return email.toLowerCase().trim();\n};\n\n// Good: Phone number validation\nconst validatePhone = (phone) => {\n // E.164 format: +[country code][number]\n const regex = /^\\+[1-9]\\d{1,14}$/;\n\n if (!regex.test(phone)) {\n throw new ValidationError('Phone number must be in E.164 format');\n }\n\n return phone;\n};\n\n// Good: URL validation\nconst validateUrl = (url) => {\n try {\n const parsed = new URL(url);\n\n // Only allow HTTP/HTTPS\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n throw new ValidationError('Only HTTP/HTTPS URLs allowed');\n }\n\n // Optional: Check domain allowlist\n const allowedDomains = ['example.com', 'api.example.com'];\n if (!allowedDomains.includes(parsed.hostname)) {\n throw new ValidationError('Domain not allowed');\n }\n\n return url;\n } catch (error) {\n throw new ValidationError('Invalid URL');\n }\n};\n```\n\n### Pattern 2: Data Type Validation\n\n```javascript\n// Good: Type validation with schema\nconst Joi = require('joi');\n\nconst userSchema = Joi.object({\n username: Joi.string().alphanum().min(3).max(20).required(),\n email: Joi.string().email().required(),\n age: Joi.number().integer().min(13).max(120).required(),\n website: Joi.string().uri().optional(),\n bio: Joi.string().max(500).optional()\n});\n\nconst validateUser = (data) => {\n const { error, value } = userSchema.validate(data, {\n abortEarly: false,\n stripUnknown: true\n });\n\n if (error) {\n const errors = error.details.map(detail => ({\n field: detail.path.join('.'),\n message: detail.message\n }));\n\n throw new ValidationError('Validation failed', { errors });\n }\n\n return value;\n};\n\n// Usage\napp.post('/api/users', (req, res) => {\n try {\n const validatedData = validateUser(req.body);\n const user = await User.create(validatedData);\n res.json(user);\n } catch (error) {\n res.status(400).json({ error: error.message });\n }\n});\n```\n\n### Pattern 3: File Upload Validation\n\n```javascript\nconst multer = require('multer');\nconst path = require('path');\nconst crypto = require('crypto');\n\n// Good: Comprehensive file upload validation\nconst storage = multer.diskStorage({\n destination: (req, file, cb) => {\n cb(null, '/uploads/temp/');\n },\n filename: (req, file, cb) => {\n // Generate random filename to prevent directory traversal\n const randomName = crypto.randomBytes(16).toString('hex');\n const ext = path.extname(file.originalname);\n cb(null, `${randomName}${ext}`);\n }\n});\n\nconst upload = multer({\n storage,\n limits: {\n fileSize: 5 * 1024 * 1024, // 5MB\n files: 1\n },\n fileFilter: (req, file, cb) => {\n // Allowlist MIME types\n const allowedMimes = [\n 'image/jpeg',\n 'image/png',\n 'image/gif',\n 'application/pdf'\n ];\n\n if (!allowedMimes.includes(file.mimetype)) {\n return cb(new Error('Invalid file type'));\n }\n\n // Allowlist extensions\n const allowedExts = ['.jpg', '.jpeg', '.png', '.gif', '.pdf'];\n const ext = path.extname(file.originalname).toLowerCase();\n\n if (!allowedExts.includes(ext)) {\n return cb(new Error('Invalid file extension'));\n }\n\n cb(null, true);\n }\n});\n\n// Additional validation: Verify file content\nconst verifyFileContent = async (filepath, expectedMime) => {\n const FileType = await import('file-type');\n const type = await FileType.fileTypeFromFile(filepath);\n\n if (!type || type.mime !== expectedMime) {\n throw new ValidationError('File content does not match extension');\n }\n\n return true;\n};\n\n// Usage\napp.post('/api/upload', upload.single('file'), async (req, res) => {\n try {\n // Verify file content matches MIME type\n await verifyFileContent(req.file.path, req.file.mimetype);\n\n // Scan for malware (optional)\n // await scanForMalware(req.file.path);\n\n // Move to permanent storage\n const finalPath = `/uploads/${req.file.filename}`;\n await fs.rename(req.file.path, finalPath);\n\n res.json({ filename: req.file.filename });\n } catch (error) {\n // Clean up file on error\n await fs.unlink(req.file.path).catch(() => {});\n res.status(400).json({ error: error.message });\n }\n});\n```\n\n### Pattern 4: SVG File Upload Security (2024)\n\nSVG files can contain embedded JavaScript and are a common XSS vector. Apply multiple defense layers:\n\n```javascript\nconst DOMPurify = require('isomorphic-dompurify');\nconst sharp = require('sharp');\nconst fs = require('fs').promises;\n\n// Strategy 1: SVG Sanitization (preserve vector format)\nconst sanitizeSvgFile = async (filepath) => {\n const svgContent = await fs.readFile(filepath, 'utf8');\n\n // Whitelist-based sanitization\n const clean = DOMPurify.sanitize(svgContent, {\n USE_PROFILES: { svg: true, svgFilters: true },\n ALLOWED_TAGS: [\n 'svg', 'circle', 'ellipse', 'line', 'path', 'polygon',\n 'polyline', 'rect', 'g', 'defs', 'clipPath', 'linearGradient',\n 'radialGradient', 'stop', 'filter', 'feGaussianBlur',\n 'feOffset', 'feBlend', 'feColorMatrix'\n ],\n ALLOWED_ATTR: [\n 'width', 'height', 'viewBox', 'xmlns', 'fill', 'stroke',\n 'stroke-width', 'd', 'cx', 'cy', 'r', 'rx', 'ry', 'x', 'y',\n 'x1', 'y1', 'x2', 'y2', 'points', 'id', 'class', 'transform',\n 'gradientUnits', 'gradientTransform', 'offset', 'stop-color',\n 'stop-opacity', 'stdDeviation', 'in', 'result'\n ],\n FORBID_TAGS: [\n 'script', 'foreignObject', 'iframe', 'embed', 'object',\n 'use', 'image', 'a', 'animate', 'animateTransform', 'set'\n ],\n FORBID_ATTR: [\n 'onload', 'onclick', 'onmouseover', 'onerror', 'onbegin',\n 'onend', 'onrepeat', 'onabort', 'onfocus', 'onblur',\n 'xlink:href', 'href'\n ]\n });\n\n // Additional validation: Check for data URIs\n if (clean.includes('data:') || clean.includes('javascript:')) {\n throw new ValidationError('Forbidden content detected in SVG');\n }\n\n return clean;\n};\n\n// Strategy 2: Convert SVG to Raster (most secure)\nconst convertSvgToRaster = async (svgPath, outputPath) => {\n const svgBuffer = await fs.readFile(svgPath);\n\n await sharp(svgBuffer)\n .png()\n .resize(2000, 2000, {\n fit: 'inside',\n withoutEnlargement: true\n })\n .toFile(outputPath);\n\n return outputPath;\n};\n\n// Strategy 3: Serve with CSP (if preserving SVG)\nconst serveSvgWithCSP = (req, res, next) => {\n res.setHeader('Content-Security-Policy', \"script-src 'none'; style-src 'none'\");\n res.setHeader('X-Content-Type-Options', 'nosniff');\n res.setHeader('Content-Type', 'image/svg+xml');\n next();\n};\n\n// Comprehensive SVG upload handler\napp.post('/api/upload-svg', upload.single('svg'), async (req, res) => {\n try {\n const file = req.file;\n\n // Validate SVG extension\n if (path.extname(file.originalname).toLowerCase() !== '.svg') {\n throw new ValidationError('Invalid file extension');\n }\n\n // Validate MIME type\n if (file.mimetype !== 'image/svg+xml') {\n throw new ValidationError('Invalid MIME type');\n }\n\n // Validate filename doesn't bypass with spaces (CVE-2024-11404)\n if (file.originalname.includes(' .svg') || /\\s+\\.svg$/i.test(file.originalname)) {\n throw new ValidationError('Invalid filename format');\n }\n\n // Option A: Sanitize and preserve as SVG\n const cleanSvg = await sanitizeSvgFile(file.path);\n const svgPath = `/uploads/svg/${crypto.randomUUID()}.svg`;\n await fs.writeFile(svgPath, cleanSvg);\n\n // Option B: Convert to PNG (recommended for user avatars, etc.)\n const pngPath = `/uploads/images/${crypto.randomUUID()}.png`;\n await convertSvgToRaster(file.path, pngPath);\n\n // Clean up temp file\n await fs.unlink(file.path);\n\n res.json({\n svg: svgPath, // Serve with CSP\n png: pngPath // Safe to serve normally\n });\n } catch (error) {\n await fs.unlink(req.file.path).catch(() => {});\n res.status(400).json({ error: error.message });\n }\n});\n\n// SVG serving route with CSP\napp.get('/uploads/svg/:filename', serveSvgWithCSP, async (req, res) => {\n const filename = path.basename(req.params.filename);\n const filepath = path.join('/uploads/svg', filename);\n\n // Additional security: Validate file exists and is in allowed directory\n const resolvedPath = path.resolve(filepath);\n const uploadsDir = path.resolve('/uploads/svg');\n\n if (!resolvedPath.startsWith(uploadsDir)) {\n return res.status(403).json({ error: 'Forbidden' });\n }\n\n res.sendFile(resolvedPath);\n});\n```\n\n### Pattern 5: Advanced File Content Validation\n\n```javascript\n// Verify file content matches claimed type (magic bytes)\nconst validateFileContent = async (filepath, claimedMime) => {\n const FileType = await import('file-type');\n const buffer = await fs.readFile(filepath);\n\n // Check magic bytes\n const detectedType = await FileType.fileTypeFromBuffer(buffer);\n\n if (!detectedType) {\n throw new ValidationError('Unable to detect file type');\n }\n\n if (detectedType.mime !== claimedMime) {\n throw new ValidationError(\n `File content (${detectedType.mime}) does not match claimed type (${claimedMime})`\n );\n }\n\n // Additional checks for image files\n if (claimedMime.startsWith('image/')) {\n const sharp = require('sharp');\n\n try {\n const metadata = await sharp(filepath).metadata();\n\n // Validate dimensions\n if (metadata.width > 10000 || metadata.height > 10000) {\n throw new ValidationError('Image dimensions too large');\n }\n\n // Detect decompression bombs\n const pixelCount = metadata.width * metadata.height;\n if (pixelCount > 100000000) { // 100 megapixels\n throw new ValidationError('Image too large (possible decompression bomb)');\n }\n } catch (error) {\n throw new ValidationError('Invalid or corrupt image file');\n }\n }\n\n return true;\n};\n```\n\n### File Upload Security Checklist\n\n**Validation:**\n\n- [ ] Validate file extension (allowlist, case-insensitive)\n- [ ] Validate MIME type (server-side, not client `Content-Type`)\n- [ ] Verify file content matches claimed type (magic bytes)\n- [ ] Validate file size limits\n- [ ] Check filename for path traversal attempts\n- [ ] Detect CVE-2024-11404 bypass (spaces before extension)\n\n**SVG-Specific:**\n\n- [ ] Sanitize SVG with DOMPurify or convert to raster\n- [ ] Remove script tags, foreignObject, event handlers\n- [ ] Block data URIs and javascript: protocols\n- [ ] Serve SVGs with CSP: script-src 'none'\n- [ ] Validate SVG only contains safe elements/attributes\n\n**Storage:**\n\n- [ ] Generate random filenames (crypto.randomUUID())\n- [ ] Store outside web root or serve from separate domain\n- [ ] Use path.resolve() and verify paths stay in allowed directory\n- [ ] Set restrictive file permissions\n\n**Serving:**\n\n- [ ] Set X-Content-Type-Options: nosniff\n- [ ] Validate path before serving (prevent traversal)\n- [ ] Add CSP headers for SVG/HTML files\n- [ ] Consider malware scanning for untrusted uploads\n\n---\n\n## SQL Injection Prevention\n\n### Pattern 1: Parameterized Queries\n\n```javascript\n// Bad: String concatenation (VULNERABLE)\nconst getUserBad = async (email) => {\n const query = `SELECT * FROM users WHERE email = '${email}'`;\n const [rows] = await db.execute(query);\n return rows[0];\n};\n\n// Attack: email = \"' OR '1'='1\"\n// Result: SELECT * FROM users WHERE email = '' OR '1'='1'\n// Returns all users!\n\n// Good: Parameterized query\nconst getUserGood = async (email) => {\n const query = 'SELECT * FROM users WHERE email = ?';\n const [rows] = await db.execute(query, [email]);\n return rows[0];\n};\n\n// Good: Named parameters (PostgreSQL)\nconst getUserPg = async (email) => {\n const query = 'SELECT * FROM users WHERE email = $1';\n const result = await pool.query(query, [email]);\n return result.rows[0];\n};\n\n// Good: Multiple parameters\nconst searchUsers = async (name, role, active) => {\n const query = `\n SELECT * FROM users\n WHERE name LIKE ?\n AND role = ?\n AND active = ?\n `;\n const [rows] = await db.execute(query, [`%${name}%`, role, active]);\n return rows;\n};\n```\n\n### Pattern 2: ORM Usage\n\n```javascript\n// Good: Sequelize ORM\nconst getUserSequelize = async (email) => {\n return await User.findOne({\n where: { email }\n });\n};\n\nconst searchUsersSequelize = async (filters) => {\n return await User.findAll({\n where: {\n name: { [Op.like]: `%${filters.name}%` },\n role: filters.role,\n active: filters.active\n }\n });\n};\n\n// Good: Prisma ORM\nconst getUserPrisma = async (email) => {\n return await prisma.user.findUnique({\n where: { email }\n });\n};\n\n// Good: TypeORM\nconst getUserTypeORM = async (email) => {\n return await userRepository.findOne({\n where: { email }\n });\n};\n```\n\n### Pattern 3: Escaping (Last Resort)\n\n```javascript\n// Only use if parameterized queries are not possible\nconst mysql = require('mysql2');\n\nconst escapeAndQuery = async (email) => {\n const escapedEmail = mysql.escape(email);\n const query = `SELECT * FROM users WHERE email = ${escapedEmail}`;\n const [rows] = await db.execute(query);\n return rows[0];\n};\n\n// Still vulnerable to second-order SQL injection!\n// Always prefer parameterized queries.\n```\n\n---\n\n## XSS Prevention\n\n### Pattern 1: Output Encoding\n\n```javascript\n// Bad: Direct output (VULNERABLE)\napp.get('/profile', (req, res) => {\n const html = `\n \u003ch1>Welcome, ${req.user.name}\u003c/h1>\n \u003cp>${req.user.bio}\u003c/p>\n `;\n res.send(html);\n});\n\n// Attack: name = \"\u003cscript>alert('XSS')\u003c/script>\"\n// Result: Script executes in browser\n\n// Good: HTML escaping\nconst escapeHtml = (text) => {\n const map = {\n '&': '&',\n '\u003c': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '/': '/'\n };\n\n return text.replace(/[&\u003c>\"'/]/g, (char) => map[char]);\n};\n\napp.get('/profile', (req, res) => {\n const html = `\n \u003ch1>Welcome, ${escapeHtml(req.user.name)}\u003c/h1>\n \u003cp>${escapeHtml(req.user.bio)}\u003c/p>\n `;\n res.send(html);\n});\n\n// Good: Use templating engines with auto-escaping\napp.set('view engine', 'ejs'); // EJS escapes by default\n\napp.get('/profile', (req, res) => {\n res.render('profile', {\n name: req.user.name, // Auto-escaped\n bio: req.user.bio // Auto-escaped\n });\n});\n```\n\n### Pattern 2: HTML Sanitization\n\n```javascript\n// Good: Sanitize rich text input\nconst DOMPurify = require('isomorphic-dompurify');\n\nconst sanitizeHtml = (dirty) => {\n return DOMPurify.sanitize(dirty, {\n ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p', 'ul', 'ol', 'li'],\n ALLOWED_ATTR: ['href', 'title'],\n ALLOWED_URI_REGEXP: /^https?:\\/\\//\n });\n};\n\napp.post('/api/posts', (req, res) => {\n const sanitizedContent = sanitizeHtml(req.body.content);\n\n const post = await Post.create({\n title: req.body.title,\n content: sanitizedContent\n });\n\n res.json(post);\n});\n```\n\n### Pattern 3: Content Security Policy\n\n```javascript\n// Good: Strict CSP headers\napp.use((req, res, next) => {\n res.setHeader('Content-Security-Policy',\n \"default-src 'self'; \" +\n \"script-src 'self' 'nonce-\" + req.nonce + \"'; \" +\n \"style-src 'self' 'unsafe-inline'; \" +\n \"img-src 'self' data: https:; \" +\n \"font-src 'self' data:; \" +\n \"connect-src 'self'; \" +\n \"frame-ancestors 'none'; \" +\n \"base-uri 'self'; \" +\n \"form-action 'self'\"\n );\n\n next();\n});\n\n// Generate nonce for inline scripts\napp.use((req, res, next) => {\n req.nonce = crypto.randomBytes(16).toString('base64');\n next();\n});\n\n// Use nonce in templates\n// \u003cscript nonce=\"${nonce}\">...\u003c/script>\n```\n\n---\n\n## CSRF Prevention\n\n### Pattern 1: Synchronizer Token Pattern\n\n```javascript\nconst csrf = require('csurf');\nconst cookieParser = require('cookie-parser');\n\n// Setup CSRF protection\napp.use(cookieParser());\nconst csrfProtection = csrf({ cookie: true });\n\n// Render form with token\napp.get('/transfer', csrfProtection, (req, res) => {\n res.render('transfer', {\n csrfToken: req.csrfToken()\n });\n});\n\n// Validate token on submission\napp.post('/transfer', csrfProtection, (req, res) => {\n // Token automatically validated by middleware\n processTransfer(req.body);\n res.json({ success: true });\n});\n\n// Client-side: Include token in forms\n// \u003cinput type=\"hidden\" name=\"_csrf\" value=\"{{csrfToken}}\">\n\n// Client-side: Include token in AJAX requests\n// fetch('/transfer', {\n// method: 'POST',\n// headers: {\n// 'CSRF-Token': csrfToken\n// },\n// body: JSON.stringify(data)\n// });\n```\n\n### Pattern 2: Double-Submit Cookie\n\n```javascript\n// Generate CSRF token\nconst generateCsrfToken = () => {\n return crypto.randomBytes(32).toString('hex');\n};\n\n// Set CSRF cookie\napp.use((req, res, next) => {\n if (!req.cookies.csrfToken) {\n const token = generateCsrfToken();\n\n res.cookie('csrfToken', token, {\n httpOnly: false, // Must be readable by JavaScript\n secure: true,\n sameSite: 'strict'\n });\n\n req.csrfToken = token;\n } else {\n req.csrfToken = req.cookies.csrfToken;\n }\n\n next();\n});\n\n// Validate CSRF token\nconst validateCsrfToken = (req, res, next) => {\n const tokenFromCookie = req.cookies.csrfToken;\n const tokenFromHeader = req.headers['x-csrf-token'];\n\n if (!tokenFromCookie || !tokenFromHeader || tokenFromCookie !== tokenFromHeader) {\n return res.status(403).json({ error: 'Invalid CSRF token' });\n }\n\n next();\n};\n\n// Apply to state-changing routes\napp.post('/api/*', validateCsrfToken);\napp.put('/api/*', validateCsrfToken);\napp.delete('/api/*', validateCsrfToken);\n```\n\n### Pattern 3: SameSite Cookies\n\n```javascript\n// Good: SameSite attribute for session cookies\napp.use(session({\n secret: process.env.SESSION_SECRET,\n cookie: {\n secure: true,\n httpOnly: true,\n sameSite: 'strict', // Prevents CSRF attacks\n maxAge: 30 * 60 * 1000\n }\n}));\n\n// Strict: Cookie only sent with same-site requests\n// Lax: Cookie sent with top-level navigation (GET)\n// None: Cookie sent with all requests (requires secure: true)\n```\n\n---\n\n## NoSQL Injection Prevention\n\n```javascript\n// Bad: Direct object injection (VULNERABLE)\nconst getUserBad = async (email) => {\n return await User.findOne({ email: req.body.email });\n};\n\n// Attack: email = { $ne: null }\n// Result: Returns first user (always true condition)\n\n// Good: Validate data type\nconst getUserGood = async (email) => {\n if (typeof email !== 'string') {\n throw new ValidationError('Email must be a string');\n }\n\n return await User.findOne({ email });\n};\n\n// Good: Sanitize MongoDB operators\nconst sanitizeObject = (obj) => {\n if (typeof obj !== 'object' || obj === null) {\n return obj;\n }\n\n const sanitized = {};\n\n for (const [key, value] of Object.entries(obj)) {\n // Remove keys starting with $\n if (key.startsWith('

Software Security & AppSec — Quick Reference Production-grade security patterns for building secure applications in Jan 2026. Covers OWASP Top 10:2025 (stable) https://owasp.org/Top10/2025/ plus OWASP API Security Top 10 (2023) https://owasp.org/API-Security/ and secure SDLC baselines (NIST SSDF) https://csrc.nist.gov/publications/detail/sp/800-218/final. --- When to Use This Skill Activate this skill when: - Implementing authentication or authorization systems - Handling user input that could lead to injection attacks (SQL, XSS, command injection) - Designing secure APIs or web applications…

)) {\n continue;\n }\n\n sanitized[key] = typeof value === 'object'\n ? sanitizeObject(value)\n : value;\n }\n\n return sanitized;\n};\n\nconst getUserSanitized = async (filters) => {\n const sanitizedFilters = sanitizeObject(filters);\n return await User.findOne(sanitizedFilters);\n};\n\n// Good: Use schema validation\nconst userSchema = new mongoose.Schema({\n email: {\n type: String,\n required: true,\n validate: {\n validator: (v) => /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(v),\n message: 'Invalid email format'\n }\n }\n});\n```\n\n---\n\n## Command Injection Prevention\n\n```javascript\n// Bad: Unvalidated shell execution (VULNERABLE)\nconst { exec } = require('child_process');\n\nconst convertImage = (filename) => {\n exec(`convert ${filename} output.png`);\n};\n\n// Attack: filename = \"input.jpg; rm -rf /\"\n// Result: Deletes all files!\n\n// Good: Use libraries instead of shell\nconst sharp = require('sharp');\n\nconst convertImage = async (inputPath) => {\n // Validate input path\n const safePath = path.resolve('/uploads', path.basename(inputPath));\n\n await sharp(safePath)\n .resize(800, 600)\n .toFile('/output/converted.png');\n};\n\n// Good: If shell is necessary, use execFile with array\nconst { execFile } = require('child_process');\n\nconst pingHost = (hostname) => {\n // Strict validation\n const hostnameRegex = /^[a-zA-Z0-9.-]+$/;\n\n if (!hostnameRegex.test(hostname)) {\n throw new ValidationError('Invalid hostname');\n }\n\n // execFile doesn't invoke shell, uses array for args\n execFile('ping', ['-c', '4', hostname], (error, stdout) => {\n if (error) {\n throw error;\n }\n\n console.log(stdout);\n });\n};\n```\n\n---\n\n## Path Traversal Prevention\n\n```javascript\n// Bad: Unvalidated file access (VULNERABLE)\nconst getFileBad = (filename) => {\n const filepath = path.join('/uploads', filename);\n return fs.readFileSync(filepath);\n};\n\n// Attack: filename = \"../../etc/passwd\"\n// Result: Reads system password file!\n\n// Good: Validate and sanitize filename\nconst getFileGood = (filename) => {\n // Remove path separators and null bytes\n const cleanFilename = path.basename(filename).replace(/\\0/g, '');\n\n if (cleanFilename !== filename) {\n throw new ValidationError('Invalid filename');\n }\n\n // Resolve to absolute path and verify it's in allowed directory\n const uploadsDir = path.resolve('/uploads');\n const filepath = path.resolve(uploadsDir, cleanFilename);\n\n if (!filepath.startsWith(uploadsDir)) {\n throw new ValidationError('Path traversal detected');\n }\n\n return fs.readFileSync(filepath);\n};\n\n// Good: Use allowlist for file access\nconst allowedFiles = new Set(['file1.txt', 'file2.pdf', 'image.jpg']);\n\nconst getFileAllowlist = (filename) => {\n if (!allowedFiles.has(filename)) {\n throw new ValidationError('File not found');\n }\n\n const filepath = path.join('/uploads', filename);\n return fs.readFileSync(filepath);\n};\n```\n\n---\n\n## LDAP Injection Prevention\n\n```javascript\n// Bad: Unescaped LDAP filter (VULNERABLE)\nconst searchUserBad = (username) => {\n const filter = `(uid=${username})`;\n return ldapClient.search('ou=users,dc=example,dc=com', { filter });\n};\n\n// Attack: username = \"*)(uid=*\"\n// Result: Returns all users\n\n// Good: Escape LDAP special characters\nconst escapeLdap = (str) => {\n return str.replace(/[\\\\*()]/g, '\\\\{head-tags}');\n};\n\nconst searchUserGood = (username) => {\n const escapedUsername = escapeLdap(username);\n const filter = `(uid=${escapedUsername})`;\n return ldapClient.search('ou=users,dc=example,dc=com', { filter });\n};\n```\n\n---\n\n## Validation Best Practices\n\n### Comprehensive Validation Function\n\n```javascript\nconst validator = {\n // String validation\n string: (value, { minLength = 0, maxLength = Infinity, pattern = null } = {}) => {\n if (typeof value !== 'string') {\n throw new ValidationError('Must be a string');\n }\n\n if (value.length \u003c minLength) {\n throw new ValidationError(`Minimum length is ${minLength}`);\n }\n\n if (value.length > maxLength) {\n throw new ValidationError(`Maximum length is ${maxLength}`);\n }\n\n if (pattern && !pattern.test(value)) {\n throw new ValidationError('Invalid format');\n }\n\n return value;\n },\n\n // Number validation\n number: (value, { min = -Infinity, max = Infinity, integer = false } = {}) => {\n const num = Number(value);\n\n if (isNaN(num)) {\n throw new ValidationError('Must be a number');\n }\n\n if (integer && !Number.isInteger(num)) {\n throw new ValidationError('Must be an integer');\n }\n\n if (num \u003c min) {\n throw new ValidationError(`Minimum value is ${min}`);\n }\n\n if (num > max) {\n throw new ValidationError(`Maximum value is ${max}`);\n }\n\n return num;\n },\n\n // Array validation\n array: (value, { minLength = 0, maxLength = Infinity, itemValidator = null } = {}) => {\n if (!Array.isArray(value)) {\n throw new ValidationError('Must be an array');\n }\n\n if (value.length \u003c minLength) {\n throw new ValidationError(`Minimum length is ${minLength}`);\n }\n\n if (value.length > maxLength) {\n throw new ValidationError(`Maximum length is ${maxLength}`);\n }\n\n if (itemValidator) {\n return value.map((item, index) => {\n try {\n return itemValidator(item);\n } catch (error) {\n throw new ValidationError(`Item ${index}: ${error.message}`);\n }\n });\n }\n\n return value;\n },\n\n // Enum validation\n enum: (value, allowedValues) => {\n if (!allowedValues.includes(value)) {\n throw new ValidationError(`Must be one of: ${allowedValues.join(', ')}`);\n }\n\n return value;\n }\n};\n\n// Usage\nconst validatePost = (data) => {\n return {\n title: validator.string(data.title, { minLength: 1, maxLength: 200 }),\n content: validator.string(data.content, { maxLength: 10000 }),\n tags: validator.array(data.tags, {\n maxLength: 5,\n itemValidator: (tag) => validator.string(tag, { maxLength: 20 })\n }),\n status: validator.enum(data.status, ['draft', 'published', 'archived'])\n };\n};\n```\n\n---\n\n## References\n\n- [OWASP Input Validation Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Input_Validation_Cheat_Sheet.html)\n- [OWASP XSS Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html)\n- [OWASP SQL Injection Prevention](https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html)\n- [OWASP CSRF Prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html)\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":26294,"content_sha256":"f8384c099d1eefb63bcd1eae2311314d9c8ac7f35b11db6218608b7eba904595"},{"filename":"references/operational-playbook.md","content":"## Core Security Principles\n\n**Defense in Depth**: Layer multiple security controls\n**Least Privilege**: Grant minimum necessary permissions\n**Secure by Default**: Security controls enabled out-of-the-box\n**Fail Securely**: Errors should not expose sensitive data or bypass security\n**Complete Mediation**: Validate every access attempt\n**Open Design**: Security through architecture, not obscurity\n\nSee [references/secure-design-principles.md](secure-design-principles.md) for detailed implementation guidance.\n\n---\n\n## OWASP Top 10\n\n1. **Broken Access Control** - Unauthorized access to resources\n2. **Cryptographic Failures** - Weak encryption or exposed sensitive data\n3. **Injection** - SQL, NoSQL, OS command, LDAP injection\n4. **Security Misconfiguration** - Insecure defaults, incomplete configs\n5. **Vulnerable Components** - Outdated libraries with known CVEs\n6. **Insecure Design** - Missing threat modeling and secure patterns\n7. **Authentication Failures** - Weak credential management\n8. **Data Integrity Failures** - Unverified code/data modifications\n9. **Logging Failures** - Insufficient monitoring and incident response\n10. **Server-Side Request Forgery (SSRF)** - Unauthorized server requests\n\nSee [references/owasp-top-10.md](owasp-top-10.md) for detailed prevention strategies.\n\n---\n\n## Pattern: Authentication\n\n**Use when:** Verifying user identity\n\n### JWT-Based Authentication\n\n```javascript\n// Good: Secure JWT implementation\nconst jwt = require('jsonwebtoken');\n\n// Generate token\nconst token = jwt.sign(\n { userId: user.id, role: user.role },\n process.env.JWT_SECRET,\n {\n expiresIn: '15m',\n algorithm: 'HS256',\n issuer: 'your-app',\n audience: 'your-api'\n }\n);\n\n// Verify token\nconst verifyToken = (token) => {\n try {\n return jwt.verify(token, process.env.JWT_SECRET, {\n algorithms: ['HS256'],\n issuer: 'your-app',\n audience: 'your-api'\n });\n } catch (error) {\n throw new AuthenticationError('Invalid token');\n }\n};\n```\n\n### OAuth 2.0 Flow\n\n```text\nClient → Authorization Request → Auth Server\nAuth Server → Authorization Grant → Client\nClient → Access Token Request → Auth Server\nAuth Server → Access Token → Client\nClient → Protected Resource Request (with token) → Resource Server\n```\n\n**Security checklist:**\n\n- [ ] Use secure token storage (httpOnly cookies or secure storage)\n- [ ] Implement token refresh mechanism\n- [ ] Set short token expiration (15-30 minutes)\n- [ ] Use secure JWT signing algorithms (HS256, RS256)\n- [ ] Validate token signature, expiration, issuer, and audience\n- [ ] Never store sensitive data in JWT payload\n- [ ] Implement token revocation/blacklisting\n- [ ] Use HTTPS only\n\nSee [references/authentication-authorization.md](authentication-authorization.md) and [assets/web-application/template-authentication.md](../assets/web-application/template-authentication.md) for complete implementations.\n\n---\n\n## Pattern: Authorization\n\n**Use when:** Controlling access to resources\n\n### Role-Based Access Control (RBAC)\n\n```javascript\n// Good: RBAC middleware\nconst requireRole = (...allowedRoles) => {\n return (req, res, next) => {\n if (!req.user) {\n return res.status(401).json({ error: 'Not authenticated' });\n }\n\n if (!allowedRoles.includes(req.user.role)) {\n return res.status(403).json({ error: 'Insufficient permissions' });\n }\n\n next();\n };\n};\n\n// Usage\napp.delete('/api/users/:id',\n authenticate,\n requireRole('admin', 'moderator'),\n deleteUser\n);\n```\n\n### Attribute-Based Access Control (ABAC)\n\n```javascript\n// Good: Fine-grained ABAC\nconst canAccessResource = (user, resource, action) => {\n const policy = {\n subject: {\n userId: user.id,\n role: user.role,\n department: user.department\n },\n resource: {\n id: resource.id,\n ownerId: resource.ownerId,\n classification: resource.classification\n },\n action: action,\n context: {\n time: new Date(),\n ipAddress: user.ipAddress\n }\n };\n\n return evaluatePolicy(policy);\n};\n```\n\n**Authorization Models:**\n- **RBAC**: Simple role-based permissions (admin, user, moderator)\n- **ABAC**: Complex attribute-based rules (time, location, resource attributes)\n- **ReBAC**: Relationship-based (owner, collaborator, viewer)\n\n**When to use:**\n- RBAC: Limited, well-defined roles (\u003c10 roles)\n- ABAC: Complex, context-dependent permissions\n- Hybrid: Combine RBAC + ABAC for most systems\n\nSee [references/authentication-authorization.md](authentication-authorization.md) and [assets/web-application/template-authorization.md](../assets/web-application/template-authorization.md).\n\n---\n\n## Pattern: Input Validation & Sanitization\n\n**Use when:** Processing any user input\n\n### Allowlist Validation\n\n```javascript\n// Good: Strict allowlist validation\nconst validateUsername = (username) => {\n // Allowlist: alphanumeric + underscore, 3-20 chars\n const regex = /^[a-zA-Z0-9_]{3,20}$/;\n\n if (!regex.test(username)) {\n throw new ValidationError('Invalid username format');\n }\n\n return username;\n};\n\n// Good: Email validation\nconst validateEmail = (email) => {\n const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\n\n if (!regex.test(email) || email.length > 254) {\n throw new ValidationError('Invalid email format');\n }\n\n return email.toLowerCase();\n};\n```\n\n### SQL Injection Prevention\n\n```javascript\n// Bad: String concatenation\nconst query = `SELECT * FROM users WHERE id = ${userId}`;\n\n// Good: Parameterized queries\nconst query = 'SELECT * FROM users WHERE id = ?';\nconst results = await db.execute(query, [userId]);\n\n// Good: ORM (Sequelize example)\nconst user = await User.findOne({ where: { id: userId } });\n```\n\n### XSS Prevention\n\n```javascript\n// Good: HTML sanitization\nconst DOMPurify = require('dompurify');\nconst { JSDOM } = require('jsdom');\n\nconst sanitizeHtml = (dirty) => {\n const window = new JSDOM('').window;\n const purify = DOMPurify(window);\n\n return purify.sanitize(dirty, {\n ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'a', 'p'],\n ALLOWED_ATTR: ['href']\n });\n};\n\n// Good: Output encoding\nconst escapeHtml = (text) => {\n const map = {\n '&': '&',\n '\u003c': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''\n };\n\n return text.replace(/[&\u003c>\"']/g, (char) => map[char]);\n};\n```\n\n**Advanced XSS Vectors (2024-2025):**\n\n- SVG-based XSS via embedded scripts and foreignObject\n- Mutation XSS (mXSS) through DOM reparsing\n- Polyglot payloads working across multiple contexts\n- Context-aware encoding (HTML, JavaScript, CSS, URL)\n\nSee [references/advanced-xss-techniques.md](advanced-xss-techniques.md) for comprehensive coverage of modern attack vectors and defenses.\n\n### CSRF Prevention\n\n```javascript\n// Good: CSRF token validation\nconst csrf = require('csurf');\nconst csrfProtection = csrf({ cookie: true });\n\napp.post('/api/transfer',\n csrfProtection,\n (req, res) => {\n // Token automatically validated\n processTransfer(req.body);\n }\n);\n\n// Client-side: Include token in requests\n\u003cinput type=\"hidden\" name=\"_csrf\" value=\"{{csrfToken}}\">\n```\n\n**Validation checklist:**\n\n- [ ] Server-side validation (never trust client-side only)\n- [ ] Allowlist approach (define what IS allowed)\n- [ ] Input length limits\n- [ ] Data type validation\n- [ ] Parameterized queries for database operations\n- [ ] HTML sanitization for user content\n- [ ] Output encoding before rendering\n- [ ] CSRF tokens for state-changing operations\n- [ ] Content Security Policy (CSP) headers\n- [ ] SVG file sanitization or conversion to raster (2024)\n- [ ] File upload content validation (magic bytes)\n\nSee [references/input-validation.md](input-validation.md) for comprehensive patterns including SVG upload security.\n\n---\n\n## Pattern: Cryptography\n\n**Use when:** Protecting sensitive data\n\n### Password Hashing\n\n```javascript\n// Good: Modern password hashing\nconst bcrypt = require('bcrypt');\n\n// Hash password\nconst hashPassword = async (password) => {\n const saltRounds = 12;\n return await bcrypt.hash(password, saltRounds);\n};\n\n// Verify password\nconst verifyPassword = async (password, hash) => {\n return await bcrypt.compare(password, hash);\n};\n\n// Alternative: Argon2 (recommended for new projects)\nconst argon2 = require('argon2');\n\nconst hashPassword = async (password) => {\n return await argon2.hash(password, {\n type: argon2.argon2id,\n memoryCost: 2 ** 16,\n timeCost: 3,\n parallelism: 1\n });\n};\n```\n\n### Data Encryption\n\n```javascript\n// Good: AES-256-GCM encryption\nconst crypto = require('crypto');\n\nconst encrypt = (text, key) => {\n const iv = crypto.randomBytes(16);\n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);\n\n let encrypted = cipher.update(text, 'utf8', 'hex');\n encrypted += cipher.final('hex');\n\n const authTag = cipher.getAuthTag();\n\n return {\n encrypted,\n iv: iv.toString('hex'),\n authTag: authTag.toString('hex')\n };\n};\n\nconst decrypt = (encrypted, key, iv, authTag) => {\n const decipher = crypto.createDecipheriv(\n 'aes-256-gcm',\n key,\n Buffer.from(iv, 'hex')\n );\n\n decipher.setAuthTag(Buffer.from(authTag, 'hex'));\n\n let decrypted = decipher.update(encrypted, 'hex', 'utf8');\n decrypted += decipher.final('utf8');\n\n return decrypted;\n};\n```\n\n**Cryptography standards:**\n- **Password hashing**: bcrypt (cost 12+), scrypt, Argon2id\n- **Symmetric encryption**: AES-256-GCM\n- **Asymmetric encryption**: RSA-2048+ or ECC (secp256r1)\n- **TLS**: Version 1.3 only\n- **Random values**: Use crypto.randomBytes(), not Math.random()\n- **Key derivation**: PBKDF2, scrypt, or Argon2\n\nSee [references/cryptography-standards.md](cryptography-standards.md) for detailed implementation.\n\n---\n\n## Pattern: Secure API Design\n\n**Use when:** Building REST or GraphQL APIs\n\n### Security Headers\n\n```javascript\n// Good: Comprehensive security headers\nconst helmet = require('helmet');\n\napp.use(helmet({\n contentSecurityPolicy: {\n directives: {\n defaultSrc: [\"'self'\"],\n styleSrc: [\"'self'\", \"'unsafe-inline'\"],\n scriptSrc: [\"'self'\"],\n imgSrc: [\"'self'\", 'data:', 'https:']\n }\n },\n hsts: {\n maxAge: 31536000,\n includeSubDomains: true,\n preload: true\n }\n}));\n\n// Additional headers\napp.use((req, res, next) => {\n res.setHeader('X-Content-Type-Options', 'nosniff');\n res.setHeader('X-Frame-Options', 'DENY');\n res.setHeader('X-XSS-Protection', '1; mode=block');\n res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');\n next();\n});\n```\n\n### Rate Limiting\n\n```javascript\n// Good: Rate limiting\nconst rateLimit = require('express-rate-limit');\n\nconst limiter = rateLimit({\n windowMs: 15 * 60 * 1000, // 15 minutes\n max: 100, // Limit each IP to 100 requests per window\n message: 'Too many requests, please try again later',\n standardHeaders: true,\n legacyHeaders: false\n});\n\napp.use('/api/', limiter);\n\n// Stricter limits for sensitive endpoints\nconst authLimiter = rateLimit({\n windowMs: 15 * 60 * 1000,\n max: 5,\n skipSuccessfulRequests: true\n});\n\napp.post('/api/auth/login', authLimiter, loginHandler);\n```\n\n### CORS Configuration\n\n```javascript\n// Good: Strict CORS configuration\nconst cors = require('cors');\n\nconst corsOptions = {\n origin: (origin, callback) => {\n const allowedOrigins = [\n 'https://app.example.com',\n 'https://admin.example.com'\n ];\n\n if (!origin || allowedOrigins.includes(origin)) {\n callback(null, true);\n } else {\n callback(new Error('Not allowed by CORS'));\n }\n },\n credentials: true,\n optionsSuccessStatus: 200,\n methods: ['GET', 'POST', 'PUT', 'DELETE'],\n allowedHeaders: ['Content-Type', 'Authorization']\n};\n\napp.use(cors(corsOptions));\n```\n\nSee [assets/api/template-secure-api.md](../assets/api/template-secure-api.md) for complete API security implementation.\n\n---\n\n## Common Vulnerabilities & Fixes\n\n### Path Traversal\n\n```javascript\n// Bad: Unsafe file access\nconst filePath = path.join('/uploads', req.params.filename);\n\n// Good: Validate and sanitize\nconst sanitizeFilename = (filename) => {\n // Remove path separators and null bytes\n const clean = filename.replace(/[\\/\\\\.\\0]/g, '');\n\n if (clean !== filename || clean.length === 0) {\n throw new ValidationError('Invalid filename');\n }\n\n return clean;\n};\n\nconst filePath = path.join('/uploads', sanitizeFilename(req.params.filename));\n```\n\n### Command Injection\n\n```javascript\n// Bad: Shell command with user input\nexec(`convert ${userInput} output.png`);\n\n// Good: Use libraries or sanitize\nconst sharp = require('sharp');\nawait sharp(validatedInput).toFile('output.png');\n\n// If shell is necessary: strict validation + escaping\nconst { execFile } = require('child_process');\nconst allowedCommands = ['convert', 'ffmpeg'];\n\nif (!allowedCommands.includes(command)) {\n throw new Error('Invalid command');\n}\n\nexecFile(command, [validatedArg1, validatedArg2]);\n```\n\n### Insecure Deserialization\n\n```javascript\n// Bad: Unsafe deserialization\nconst obj = eval(userInput);\n\n// Good: Use JSON.parse with validation\nconst parseData = (input) => {\n try {\n const data = JSON.parse(input);\n return validateSchema(data);\n } catch (error) {\n throw new ValidationError('Invalid data format');\n }\n};\n```\n\nSee [references/common-vulnerabilities.md](common-vulnerabilities.md) for comprehensive vulnerability catalog.\n\n---\n\n## Security Testing Checklist\n\n**Authentication:**\n- [ ] Password strength requirements enforced\n- [ ] Multi-factor authentication available\n- [ ] Account lockout after failed attempts\n- [ ] Secure password reset flow\n- [ ] Session timeout configured\n\n**Authorization:**\n- [ ] Principle of least privilege applied\n- [ ] Authorization checked on every request\n- [ ] Direct object references protected\n- [ ] Vertical privilege escalation prevented\n- [ ] Horizontal privilege escalation prevented\n\n**Input Validation:**\n- [ ] Server-side validation on all inputs\n- [ ] Allowlist validation approach\n- [ ] Output encoding before rendering\n- [ ] Parameterized queries for database\n- [ ] File upload validation (type, size, content)\n\n**Data Protection:**\n- [ ] Sensitive data encrypted at rest\n- [ ] TLS 1.3 for data in transit\n- [ ] Secrets in environment variables, not code\n- [ ] PII handling complies with regulations\n- [ ] Secure key management\n\n**Error Handling:**\n- [ ] Generic error messages to users\n- [ ] Detailed errors logged server-side\n- [ ] Stack traces not exposed\n- [ ] Failed operations don't leak information\n\n**Logging & Monitoring:**\n- [ ] Security events logged\n- [ ] Sensitive data not in logs\n- [ ] Log integrity protected\n- [ ] Alerting for suspicious activity\n- [ ] Incident response plan documented\n\n---\n\n## Resources (Detailed Guides)\n\nFor comprehensive implementation guides, see:\n\n- [OWASP Top 10 Guide](owasp-top-10.md)\n- [Authentication & Authorization Patterns](authentication-authorization.md)\n- [Input Validation & Sanitization](input-validation.md) - Including SVG upload security\n- [Advanced XSS Techniques](advanced-xss-techniques.md) - SVG XSS, mXSS, polyglots, context-aware encoding (2024-2025)\n- [Cryptography Standards](cryptography-standards.md)\n- [Secure Design Principles](secure-design-principles.md)\n- [Common Vulnerabilities Catalog](common-vulnerabilities.md)\n\n## Templates (Production-Ready)\n\n### Web Application Templates\n\n- [Authentication Template](../assets/web-application/template-authentication.md) — JWT, OAuth2, sessions, MFA implementation\n- [Authorization Template](../assets/web-application/template-authorization.md) — RBAC/ABAC/ReBAC patterns\n\n### API Templates\n\n- [Secure API Template](../assets/api/template-secure-api.md) — API gateway, rate limiting, CORS, security headers\n\n### Cloud-Native Templates\n\n- [Cryptography Template](../assets/cloud-native/crypto-security.md) — Encryption, key management, HSM integration\n\n## External Resources\n\nSee [data/sources.json](../data/sources.json) for 70+ curated security resources including OWASP 2025, supply chain security, zero trust, API security, and compliance standards.\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":15965,"content_sha256":"92ea55a9d5691f6f991ef5fd84310176453a2fa93af689705977ee04792bd970"},{"filename":"references/owasp-top-10.md","content":"# OWASP Top 10:2025 — Detailed Guide\n\nComprehensive guide to the OWASP Top 10:2025 (final release) web application security risks with modern prevention strategies and code examples.\n\n---\n\n## Jan 2026 Baseline\n\n**OWASP Top 10:2025 is now FINAL** (released late 2025): https://owasp.org/Top10/2025/\n\n### Key Changes from 2021 → 2025\n\n| 2021 | 2025 | Change |\n|------|------|--------|\n| A01: Broken Access Control | A01: Broken Access Control | Same (includes SSRF now) |\n| A05: Security Misconfiguration | A02: Security Misconfiguration | Moved UP from #5 |\n| A06: Vulnerable Components | **A03: Software Supply Chain Failures** | **NEW scope** (expanded) |\n| A02: Cryptographic Failures | A04: Cryptographic Failures | Moved DOWN from #2 |\n| A03: Injection | A05: Injection | Moved DOWN from #3 |\n| A04: Insecure Design | A06: Insecure Design | Moved DOWN from #4 |\n| A07: Auth Failures | A07: Authentication Failures | Same |\n| A08: Integrity Failures | A08: Software or Data Integrity Failures | Same |\n| A09: Logging Failures | A09: Logging & Alerting Failures | Same |\n| A10: SSRF | **A10: Mishandling of Exceptional Conditions** | **NEW** (SSRF merged into A01) |\n\n### 2025 Methodology Updates\n\n- Analyzed **589 CWEs** (vs ~400 in 2021)\n- Incorporated **175,000 CVE records** with CVSS scores\n- Focus on **root causes** rather than symptoms\n- Emphasis on design flaws, misconfigurations, and dependency weaknesses\n\n### How to Use This Document\n\n- Use the sections below as practical mitigations and review prompts.\n- For supply chain (A03), see [supply-chain-security.md](supply-chain-security.md).\n- For zero trust context, see [zero-trust-architecture.md](zero-trust-architecture.md).\n\n---\n\n## 1. Broken Access Control\n\n**Risk**: Users can access resources or perform actions beyond their authorization.\n\n### Common Vulnerabilities\n\n- Missing authorization checks on API endpoints\n- Insecure direct object references (IDOR)\n- Vertical privilege escalation (regular user → admin)\n- Horizontal privilege escalation (accessing other users' data)\n- Force browsing to unauthorized pages\n- CORS misconfiguration\n\n### Prevention\n\n```javascript\n// Bad: No authorization check\napp.get('/api/users/:id', async (req, res) => {\n const user = await User.findById(req.params.id);\n res.json(user);\n});\n\n// Good: Verify user can access resource\napp.get('/api/users/:id', authenticate, async (req, res) => {\n const requestedUserId = req.params.id;\n const currentUserId = req.user.id;\n const isAdmin = req.user.role === 'admin';\n\n // Users can only access their own data unless they're admin\n if (requestedUserId !== currentUserId && !isAdmin) {\n return res.status(403).json({ error: 'Forbidden' });\n }\n\n const user = await User.findById(requestedUserId);\n res.json(user);\n});\n```\n\n**Best Practices:**\n- Deny by default, grant access explicitly\n- Check authorization on every request\n- Use indirect object references (tokens/UUIDs instead of sequential IDs)\n- Log and alert on authorization failures\n- Implement server-side access control lists (ACLs)\n- Test for privilege escalation scenarios\n\n---\n\n## 2. Cryptographic Failures\n\n**Risk**: Sensitive data exposed due to weak or missing encryption.\n\n### Common Issues\n\n- Transmitting data in cleartext (HTTP instead of HTTPS)\n- Weak encryption algorithms (DES, MD5, SHA-1)\n- Hard-coded encryption keys\n- Insecure random number generation\n- Missing encryption for sensitive data at rest\n\n### Prevention\n\n```javascript\n// Bad: Weak hashing\nconst crypto = require('crypto');\nconst hash = crypto.createHash('md5').update(password).digest('hex');\n\n// Good: Strong password hashing\nconst bcrypt = require('bcrypt');\nconst hash = await bcrypt.hash(password, 12);\n\n// Good: Secure data encryption\nconst encrypt = (data, key) => {\n const iv = crypto.randomBytes(16);\n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);\n\n let encrypted = cipher.update(data, 'utf8', 'hex');\n encrypted += cipher.final('hex');\n\n return {\n encrypted,\n iv: iv.toString('hex'),\n authTag: cipher.getAuthTag().toString('hex')\n };\n};\n```\n\n**Best Practices:**\n- Enforce HTTPS/TLS 1.3 for all traffic\n- Use AES-256-GCM for symmetric encryption\n- Use bcrypt, scrypt, or Argon2 for password hashing\n- Store encryption keys in secure key management systems (AWS KMS, HashiCorp Vault)\n- Classify data and encrypt sensitive data at rest\n- Use cryptographically secure random number generators\n\n---\n\n## 3. Injection\n\n**Risk**: Untrusted data sent to an interpreter leads to unauthorized commands execution.\n\n### Types\n\n- SQL Injection\n- NoSQL Injection\n- LDAP Injection\n- OS Command Injection\n- XPath Injection\n\n### Prevention\n\n```javascript\n// SQL Injection Prevention\n// Bad: String concatenation\nconst query = `SELECT * FROM users WHERE email = '${userEmail}'`;\n\n// Good: Parameterized query\nconst query = 'SELECT * FROM users WHERE email = ?';\nconst [rows] = await db.execute(query, [userEmail]);\n\n// Good: ORM (Sequelize)\nconst user = await User.findOne({ where: { email: userEmail } });\n\n// NoSQL Injection Prevention\n// Bad: Direct object injection\nconst user = await User.findOne({ email: req.body.email });\n\n// Good: Validate and sanitize\nconst emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/;\nif (!emailRegex.test(req.body.email)) {\n throw new ValidationError('Invalid email format');\n}\nconst user = await User.findOne({ email: req.body.email });\n\n// OS Command Injection Prevention\n// Bad: Unvalidated shell execution\nconst { exec } = require('child_process');\nexec(`ping ${userInput}`);\n\n// Good: Use libraries or strict validation\nconst { execFile } = require('child_process');\nconst allowedHosts = ['example.com', 'test.com'];\n\nif (!allowedHosts.includes(userInput)) {\n throw new ValidationError('Invalid host');\n}\n\nexecFile('ping', ['-c', '4', userInput]);\n```\n\n**Best Practices:**\n- Use parameterized queries or ORMs\n- Apply input validation with allowlists\n- Escape special characters for the specific interpreter\n- Use least privilege for database accounts\n- Implement Web Application Firewall (WAF)\n\n---\n\n## 4. Security Misconfiguration\n\n**Risk**: Insecure default configurations, incomplete setups, or verbose error messages.\n\n### Common Misconfigurations\n\n- Default credentials still in use\n- Unnecessary features enabled\n- Directory listing enabled\n- Detailed error messages exposing stack traces\n- Missing security headers\n- Outdated software versions\n\n### Prevention\n\n```javascript\n// Good: Security headers with Helmet\nconst helmet = require('helmet');\n\napp.use(helmet({\n contentSecurityPolicy: {\n directives: {\n defaultSrc: [\"'self'\"],\n styleSrc: [\"'self'\", \"'unsafe-inline'\"],\n scriptSrc: [\"'self'\"],\n imgSrc: [\"'self'\", 'data:', 'https:']\n }\n },\n hsts: {\n maxAge: 31536000,\n includeSubDomains: true,\n preload: true\n },\n frameguard: { action: 'deny' },\n noSniff: true,\n xssFilter: true\n}));\n\n// Good: Generic error messages in production\napp.use((err, req, res, next) => {\n // Log detailed error server-side\n logger.error('Error:', { error: err, stack: err.stack });\n\n // Return generic message to client\n if (process.env.NODE_ENV === 'production') {\n res.status(500).json({ error: 'Internal server error' });\n } else {\n res.status(500).json({ error: err.message, stack: err.stack });\n }\n});\n```\n\n**Best Practices:**\n- Harden all configurations (OS, framework, database, web server)\n- Disable unnecessary features and services\n- Remove default accounts and passwords\n- Implement security headers (CSP, HSTS, X-Frame-Options)\n- Keep all software up to date\n- Use automated configuration scanning tools\n\n---\n\n## 5. Vulnerable and Outdated Components\n\n**Risk**: Using libraries, frameworks, or modules with known vulnerabilities.\n\n### Prevention\n\n```bash\n# Check for vulnerabilities\nnpm audit\nnpm audit fix\n\n# Use dependency scanning tools\nnpm install -g snyk\nsnyk test\nsnyk monitor\n\n# Check Python dependencies\npip-audit\n\n# Use Dependabot or Renovate for automated updates\n```\n\n**Best Practices:**\n- Inventory all components and versions\n- Monitor CVE databases for component vulnerabilities\n- Use Software Composition Analysis (SCA) tools\n- Remove unused dependencies\n- Only obtain components from official sources\n- Subscribe to security bulletins for components in use\n- Implement automated dependency updates\n\n---\n\n## 6. Insecure Design\n\n**Risk**: Missing or ineffective security controls in design phase.\n\n### Key Concepts\n\n- **Threat modeling**: Identify threats before implementation\n- **Secure design patterns**: Use proven security architectures\n- **Security requirements**: Define security needs early\n\n### Prevention\n\n```javascript\n// Bad: No rate limiting, account enumeration vulnerability\napp.post('/api/auth/login', async (req, res) => {\n const user = await User.findOne({ email: req.body.email });\n\n if (!user) {\n return res.status(401).json({ error: 'Email not found' });\n }\n\n const valid = await bcrypt.compare(req.body.password, user.password);\n\n if (!valid) {\n return res.status(401).json({ error: 'Invalid password' });\n }\n\n const token = generateToken(user);\n res.json({ token });\n});\n\n// Good: Rate limiting, generic error, account lockout\nconst rateLimit = require('express-rate-limit');\n\nconst loginLimiter = rateLimit({\n windowMs: 15 * 60 * 1000,\n max: 5,\n message: 'Too many login attempts, please try again later'\n});\n\napp.post('/api/auth/login', loginLimiter, async (req, res) => {\n const user = await User.findOne({ email: req.body.email });\n\n // Check account lockout\n if (user && user.lockedUntil && user.lockedUntil > Date.now()) {\n return res.status(429).json({ error: 'Account temporarily locked' });\n }\n\n // Validate credentials (constant-time comparison)\n const valid = user && await bcrypt.compare(req.body.password, user.password);\n\n if (!valid) {\n // Increment failed attempts\n if (user) {\n await incrementFailedAttempts(user);\n }\n\n // Generic error (prevent enumeration)\n return res.status(401).json({ error: 'Invalid credentials' });\n }\n\n // Reset failed attempts on success\n await resetFailedAttempts(user);\n\n const token = generateToken(user);\n res.json({ token });\n});\n```\n\n**Best Practices:**\n- Conduct threat modeling during design phase\n- Use established secure design patterns\n- Implement defense in depth\n- Separate duties and enforce least privilege\n- Apply secure defaults\n- Design for failure (fail securely)\n\n---\n\n## 7. Identification and Authentication Failures\n\n**Risk**: Weak authentication mechanisms allowing unauthorized access.\n\n### Common Issues\n\n- Weak password policies\n- Credential stuffing attacks\n- Session fixation\n- Missing multi-factor authentication\n- Predictable session IDs\n- Passwords stored in plaintext\n\n### Prevention\n\n```javascript\n// Good: Strong authentication implementation\nconst authenticateUser = async (email, password, mfaCode) => {\n // Rate limiting handled by middleware\n\n // Find user\n const user = await User.findOne({ email });\n\n if (!user || !(await bcrypt.compare(password, user.passwordHash))) {\n // Constant-time response to prevent timing attacks\n await bcrypt.compare(password, '$2b$12$fixedHashForConstantTime');\n throw new AuthenticationError('Invalid credentials');\n }\n\n // Check MFA if enabled\n if (user.mfaEnabled) {\n const validMfa = await verifyTOTP(user.mfaSecret, mfaCode);\n\n if (!validMfa) {\n throw new AuthenticationError('Invalid MFA code');\n }\n }\n\n // Generate secure session\n const sessionId = crypto.randomBytes(32).toString('hex');\n\n await Session.create({\n sessionId,\n userId: user.id,\n expiresAt: new Date(Date.now() + 30 * 60 * 1000) // 30 minutes\n });\n\n return sessionId;\n};\n```\n\n**Best Practices:**\n- Enforce strong password policies (length, complexity, no common passwords)\n- Implement multi-factor authentication\n- Use account lockout after failed attempts\n- Implement secure session management\n- Generate cryptographically random session IDs\n- Invalidate sessions on logout\n- Implement password reset flow securely\n\n---\n\n## 8. Software and Data Integrity Failures\n\n**Risk**: Code and infrastructure that does not protect against integrity violations.\n\n### Common Issues\n\n- Unsigned software updates\n- Insecure CI/CD pipelines\n- Untrusted serialized data\n- Missing Subresource Integrity (SRI)\n- Unsigned commits\n\n### Prevention\n\n```html\n\u003c!-- Good: Subresource Integrity for CDN resources -->\n\u003cscript\n src=\"https://cdn.example.com/library.js\"\n integrity=\"sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC\"\n crossorigin=\"anonymous\"\n>\u003c/script>\n\n\u003clink\n rel=\"stylesheet\"\n href=\"https://cdn.example.com/styles.css\"\n integrity=\"sha384-ABC123...\"\n crossorigin=\"anonymous\"\n>\n```\n\n```javascript\n// Good: Verify software signatures\nconst verifySignature = (data, signature, publicKey) => {\n const verify = crypto.createVerify('SHA256');\n verify.update(data);\n verify.end();\n\n return verify.verify(publicKey, signature, 'hex');\n};\n```\n\n**Best Practices:**\n- Use digital signatures for software updates\n- Verify integrity of downloaded packages\n- Implement SRI for third-party resources\n- Secure CI/CD pipelines\n- Sign commits and tags in version control\n- Avoid deserializing untrusted data\n- Use dependency lock files\n\n---\n\n## 9. Security Logging and Monitoring Failures\n\n**Risk**: Insufficient logging and monitoring to detect breaches.\n\n### What to Log\n\n- Authentication events (success/failure)\n- Authorization failures\n- Input validation failures\n- Suspicious activity patterns\n- Administrative actions\n- Application errors\n\n### Prevention\n\n```javascript\n// Good: Comprehensive security logging\nconst logger = require('winston');\n\nconst securityLogger = logger.createLogger({\n level: 'info',\n format: logger.format.json(),\n defaultMeta: { service: 'api' },\n transports: [\n new logger.transports.File({ filename: 'security.log' }),\n new logger.transports.Console()\n ]\n});\n\n// Log authentication attempts\napp.post('/api/auth/login', async (req, res) => {\n const { email, password } = req.body;\n\n securityLogger.info('Login attempt', {\n email,\n ip: req.ip,\n userAgent: req.get('user-agent'),\n timestamp: new Date().toISOString()\n });\n\n const user = await authenticateUser(email, password);\n\n if (!user) {\n securityLogger.warn('Failed login', {\n email,\n ip: req.ip,\n reason: 'invalid_credentials'\n });\n\n return res.status(401).json({ error: 'Invalid credentials' });\n }\n\n securityLogger.info('Successful login', {\n userId: user.id,\n email,\n ip: req.ip\n });\n\n res.json({ token: generateToken(user) });\n});\n\n// Never log sensitive data\n// Bad: Logging passwords\nsecurityLogger.info('User data', { email, password });\n\n// Good: Sanitize before logging\nsecurityLogger.info('User data', { email, password: '[REDACTED]' });\n```\n\n**Best Practices:**\n- Log all authentication and authorization events\n- Use centralized logging (ELK, Splunk, CloudWatch)\n- Implement real-time alerting for suspicious activity\n- Never log sensitive data (passwords, tokens, PII)\n- Protect log integrity (append-only, signed logs)\n- Retain logs for adequate period\n- Implement automated log analysis\n\n---\n\n## 10. Mishandling of Exceptional Conditions (NEW in 2025)\n\n**Risk**: Poor error and exception handling leads to unpredictable or insecure behavior.\n\n> **Note**: SSRF (previously A10:2021) is now consolidated into A01: Broken Access Control.\n\n### Common Issues\n\n- **Fail-open behavior**: System grants access when errors occur\n- **Incomplete error recovery**: Partial state changes left after failures\n- **Improper input validation**: Missing validation for edge cases\n- **Resource exhaustion**: Unhandled memory/connection limits\n- **Inconsistent exception handling**: Different error paths with different security postures\n\n### Attack Scenarios\n\n- Triggering errors to bypass authentication checks\n- Exploiting race conditions during error recovery\n- Causing resource exhaustion via malformed inputs\n- Extracting information from verbose error messages\n\n### Prevention\n\n```javascript\n// Bad: Fail-open pattern\nconst checkAuthorization = async (user, resource) => {\n try {\n const hasAccess = await authService.check(user, resource);\n return hasAccess;\n } catch (error) {\n // DANGEROUS: Grants access on error!\n console.error('Auth check failed:', error);\n return true;\n }\n};\n\n// Good: Fail-secure pattern\nconst checkAuthorization = async (user, resource) => {\n try {\n const hasAccess = await authService.check(user, resource);\n return hasAccess;\n } catch (error) {\n // SECURE: Deny access on any error\n logger.error('Authorization check failed', {\n userId: user.id,\n resource,\n error: error.message\n });\n return false;\n }\n};\n\n// Bad: Incomplete transaction recovery\nconst transferFunds = async (from, to, amount) => {\n await debitAccount(from, amount);\n await creditAccount(to, amount); // If this fails, funds are lost!\n};\n\n// Good: Atomic transactions with proper recovery\nconst transferFunds = async (from, to, amount) => {\n const transaction = await db.beginTransaction();\n\n try {\n await debitAccount(from, amount, { transaction });\n await creditAccount(to, amount, { transaction });\n await transaction.commit();\n } catch (error) {\n await transaction.rollback();\n logger.error('Transfer failed, rolled back', { from, to, amount, error });\n throw new TransferError('Transfer failed, no funds moved');\n }\n};\n\n// Good: Resource exhaustion protection\nconst processUpload = async (req, res) => {\n const maxFileSize = 10 * 1024 * 1024; // 10MB\n const timeout = 30000; // 30 seconds\n\n const timeoutPromise = new Promise((_, reject) =>\n setTimeout(() => reject(new Error('Upload timeout')), timeout)\n );\n\n try {\n const result = await Promise.race([\n handleUpload(req, { maxSize: maxFileSize }),\n timeoutPromise\n ]);\n res.json(result);\n } catch (error) {\n if (error.message === 'Upload timeout') {\n return res.status(408).json({ error: 'Request timeout' });\n }\n if (error.code === 'LIMIT_FILE_SIZE') {\n return res.status(413).json({ error: 'File too large' });\n }\n logger.error('Upload failed', { error });\n res.status(500).json({ error: 'Upload failed' });\n }\n};\n```\n\n**Best Practices:**\n\n- **Fail-secure by default**: Deny access when errors occur\n- **Use atomic transactions**: Ensure all-or-nothing operations\n- **Implement timeouts**: Set limits on all external calls and long operations\n- **Handle all error paths**: Every catch block should have explicit handling\n- **Resource limits**: Set memory, connection, and time limits\n- **Consistent error responses**: Same security posture regardless of error type\n- **Log errors server-side**: Detailed logs internally, generic messages to clients\n- **Test error conditions**: Include error scenarios in test suites\n\n### SSRF Prevention (Now Part of A01)\n\nFor Server-Side Request Forgery prevention patterns, see the Broken Access Control section above. Key controls:\n\n- Validate and allowlist all user-supplied URLs\n- Block requests to private IP ranges (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)\n- Disable or validate URL redirects\n- Use network segmentation\n\n---\n\n## References\n\n- [OWASP Top 10](https://owasp.org/Top10/)\n- [OWASP Cheat Sheet Series](https://cheatsheetseries.owasp.org/)\n- [OWASP ASVS](https://owasp.org/www-project-application-security-verification-standard/)\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":19498,"content_sha256":"92c459d81b2951e0e3f5c5f3b41cbb6a2cd22701f3cfd095736281d46c6a61db"},{"filename":"references/secure-design-principles.md","content":"# Secure Design Principles\n\nFoundational security principles for building secure systems from the ground up.\n\n---\n\n## Core Security Principles\n\n### 1. Defense in Depth\n\n**Concept**: Layer multiple security controls so failure of one doesn't compromise the system.\n\n**Implementation:**\n```javascript\n// Layer 1: Input validation\nconst validateInput = (data) => {\n if (!isValid(data)) throw new ValidationError();\n return data;\n};\n\n// Layer 2: Authentication\nconst authenticate = (req, res, next) => {\n if (!req.user) return res.status(401).json({ error: 'Unauthorized' });\n next();\n};\n\n// Layer 3: Authorization\nconst authorize = (req, res, next) => {\n if (!hasPermission(req.user, req.resource)) {\n return res.status(403).json({ error: 'Forbidden' });\n }\n next();\n};\n\n// Layer 4: Rate limiting\nconst rateLimit = createRateLimiter({ max: 100, windowMs: 15 * 60 * 1000 });\n\n// Layer 5: Logging and monitoring\nconst logSecurityEvent = (event) => {\n securityLogger.info(event);\n};\n\n// Apply all layers\napp.post('/api/sensitive-action',\n rateLimit,\n authenticate,\n authorize,\n validateRequest,\n async (req, res) => {\n logSecurityEvent({ action: 'sensitive-action', user: req.user.id });\n const result = await performAction(validateInput(req.body));\n res.json(result);\n }\n);\n```\n\n---\n\n### 2. Principle of Least Privilege\n\n**Concept**: Grant minimum permissions necessary for a task.\n\n**Implementation:**\n```javascript\n// Bad: Single admin role with all permissions\nconst ROLES = {\n ADMIN: ['users:*', 'posts:*', 'settings:*', 'billing:*']\n};\n\n// Good: Granular roles with specific permissions\nconst ROLES = {\n USER_ADMIN: ['users:read', 'users:write'],\n CONTENT_MODERATOR: ['posts:read', 'posts:delete'],\n BILLING_ADMIN: ['billing:read', 'billing:write'],\n SYSTEM_ADMIN: ['settings:read', 'settings:write']\n};\n\n// Database access with least privilege\nconst createDatabaseUser = async () => {\n // App user: only necessary permissions\n await db.execute(`\n CREATE USER app_user WITH PASSWORD 'secure-password';\n GRANT SELECT, INSERT, UPDATE ON users TO app_user;\n GRANT SELECT, INSERT, UPDATE, DELETE ON posts TO app_user;\n -- No DROP, TRUNCATE, or admin privileges\n `);\n\n // Read-only analytics user\n await db.execute(`\n CREATE USER analytics_user WITH PASSWORD 'secure-password';\n GRANT SELECT ON users TO analytics_user;\n GRANT SELECT ON posts TO analytics_user;\n `);\n};\n```\n\n---\n\n### 3. Fail Securely\n\n**Concept**: System should fail in a secure state, not expose sensitive data or bypass security.\n\n**Implementation:**\n```javascript\n// Bad: Error exposes sensitive information\napp.get('/api/users/:id', async (req, res) => {\n try {\n const user = await User.findById(req.params.id);\n res.json(user);\n } catch (error) {\n res.status(500).json({ error: error.message, stack: error.stack });\n }\n});\n\n// Good: Fail securely with generic error\napp.get('/api/users/:id', async (req, res) => {\n try {\n const user = await User.findById(req.params.id);\n\n if (!user) {\n return res.status(404).json({ error: 'User not found' });\n }\n\n res.json(user);\n } catch (error) {\n // Log detailed error server-side\n logger.error('Failed to retrieve user', { error, userId: req.params.id });\n\n // Return generic error to client\n res.status(500).json({ error: 'Internal server error' });\n }\n});\n\n// Bad: Default to allow on error\nconst checkPermission = (user, resource) => {\n try {\n return policyEngine.evaluate(user, resource);\n } catch (error) {\n return true; // BAD: Dangerous: grants access on error\n }\n};\n\n// Good: Default to deny on error\nconst checkPermission = (user, resource) => {\n try {\n return policyEngine.evaluate(user, resource);\n } catch (error) {\n logger.error('Permission check failed', { error, user, resource });\n return false; // GOOD: Secure: denies access on error\n }\n};\n```\n\n---\n\n### 4. Complete Mediation\n\n**Concept**: Check authorization on every access attempt, never cache authorization decisions.\n\n**Implementation:**\n```javascript\n// Bad: Cache authorization decision\nconst userPermissions = {};\n\nconst authorize = async (req, res, next) => {\n const userId = req.user.id;\n\n // BAD: Uses cached permissions (may be stale)\n if (!userPermissions[userId]) {\n userPermissions[userId] = await getPermissions(userId);\n }\n\n if (userPermissions[userId].includes(req.permission)) {\n next();\n } else {\n res.status(403).json({ error: 'Forbidden' });\n }\n};\n\n// Good: Check authorization on every request\nconst authorize = async (req, res, next) => {\n // GOOD: Always fetch fresh permissions\n const permissions = await getPermissions(req.user.id);\n\n if (permissions.includes(req.permission)) {\n next();\n } else {\n res.status(403).json({ error: 'Forbidden' });\n }\n};\n\n// Good: Verify ownership on every access\napp.put('/api/posts/:id', authenticate, async (req, res) => {\n const post = await Post.findById(req.params.id);\n\n // GOOD: Verify ownership every time\n if (post.authorId !== req.user.id && req.user.role !== 'admin') {\n return res.status(403).json({ error: 'Forbidden' });\n }\n\n await post.update(req.body);\n res.json(post);\n});\n```\n\n---\n\n### 5. Separation of Duties\n\n**Concept**: Critical operations require multiple parties or approvals.\n\n**Implementation:**\n```javascript\n// Example: Financial transaction approval\nconst initiateTransfer = async (userId, amount, recipient) => {\n // User initiates transfer\n const transfer = await Transfer.create({\n initiatedBy: userId,\n amount,\n recipient,\n status: 'pending',\n createdAt: new Date()\n });\n\n // Notify approvers\n await notifyApprovers(transfer);\n\n return transfer;\n};\n\nconst approveTransfer = async (transferId, approverId) => {\n const transfer = await Transfer.findById(transferId);\n\n // Cannot approve own transfer\n if (transfer.initiatedBy === approverId) {\n throw new SecurityError('Cannot approve own transfer');\n }\n\n // Require admin role for approval\n const approver = await User.findById(approverId);\n if (approver.role !== 'admin') {\n throw new AuthorizationError('Insufficient permissions');\n }\n\n // Execute transfer\n transfer.status = 'approved';\n transfer.approvedBy = approverId;\n transfer.approvedAt = new Date();\n\n await transfer.save();\n await executeTransfer(transfer);\n\n return transfer;\n};\n```\n\n---\n\n### 6. Open Design (No Security Through Obscurity)\n\n**Concept**: Security should not rely on secrecy of design, only on keys/credentials.\n\n**Implementation:**\n```javascript\n// Bad: Custom \"encryption\" algorithm\nconst obfuscate = (data) => {\n return data.split('').reverse().join(''); // BAD: Weak, obscure\n};\n\n// Good: Standard encryption with secret key\nconst encrypt = (data, key) => {\n const iv = crypto.randomBytes(16);\n const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);\n // ... standard encryption\n};\n\n// Bad: Hide API endpoints\n// /api/v1/secret_admin_panel_xyz123\n\n// Good: Use authentication/authorization\napp.get('/api/v1/admin', authenticate, requireRole('admin'), adminHandler);\n```\n\n---\n\n### 7. Secure by Default\n\n**Concept**: Most secure configuration should be the default.\n\n**Implementation:**\n```javascript\n// Good: Secure defaults\nconst createUser = async (userData) => {\n return await User.create({\n ...userData,\n // GOOD: Secure defaults\n emailVerified: false,\n mfaEnabled: false,\n accountLocked: false,\n role: 'user', // Not admin\n permissions: [], // No permissions by default\n createdAt: new Date()\n });\n};\n\n// Good: Secure cookie defaults\napp.use(session({\n secret: process.env.SESSION_SECRET,\n cookie: {\n secure: true, // GOOD: HTTPS only\n httpOnly: true, // GOOD: No JavaScript access\n sameSite: 'strict', // GOOD: CSRF protection\n maxAge: 30 * 60 * 1000\n }\n}));\n\n// Good: Secure CORS defaults\nconst cors = require('cors');\n\napp.use(cors({\n origin: false, // GOOD: Deny all by default\n credentials: true,\n optionsSuccessStatus: 200\n}));\n\n// Explicitly allow specific origins\napp.use('/api/public', cors({\n origin: ['https://app.example.com']\n}));\n```\n\n---\n\n### 8. Keep It Simple\n\n**Concept**: Simpler systems are easier to secure and audit.\n\n**Implementation:**\n```javascript\n// Bad: Overly complex authorization logic\nconst checkAccess = (user, resource) => {\n if (user.role === 'admin') return true;\n if (user.role === 'moderator' && resource.type === 'post') {\n if (resource.reportCount > 5 || resource.flags.includes('spam')) {\n return true;\n }\n }\n if (user.id === resource.ownerId) {\n if (resource.status !== 'locked' || user.hasPremium) {\n return true;\n }\n }\n // ... more complex conditions\n return false;\n};\n\n// Good: Clear, simple policy-based authorization\nconst policies = [\n new AdminPolicy(), // Admins can do anything\n new OwnershipPolicy(), // Owners can edit their resources\n new ModeratorPolicy() // Moderators can moderate flagged content\n];\n\nconst checkAccess = async (user, resource, action) => {\n for (const policy of policies) {\n const result = await policy.evaluate(user, resource, action);\n if (result === 'allow') return true;\n if (result === 'deny') return false;\n }\n return false; // Deny by default\n};\n```\n\n---\n\n## Secure Design Patterns\n\n### Pattern 1: Threat Modeling (STRIDE)\n\n**STRIDE Framework:**\n- **S**poofing: Identity verification\n- **T**ampering: Data integrity\n- **R**epudiation: Audit logging\n- **I**nformation Disclosure: Data protection\n- **D**enial of Service: Availability\n- **E**levation of Privilege: Authorization\n\n**Example Threat Model:**\n```\nComponent: User Authentication API\n\nThreats:\n1. Spoofing:\n - Attacker impersonates legitimate user\n - Mitigation: Strong password policy, MFA, rate limiting\n\n2. Tampering:\n - JWT tokens modified by attacker\n - Mitigation: Verify JWT signature, use short expiration\n\n3. Repudiation:\n - User denies performing action\n - Mitigation: Log all authentication events with timestamp\n\n4. Information Disclosure:\n - Password hashes leaked via SQL injection\n - Mitigation: Parameterized queries, bcrypt hashing\n\n5. Denial of Service:\n - Brute force login attempts\n - Mitigation: Rate limiting, account lockout, CAPTCHA\n\n6. Elevation of Privilege:\n - Regular user gains admin access\n - Mitigation: Role-based access control, verify on every request\n```\n\n---\n\n### Pattern 2: Zero Trust Architecture\n\n**Concept**: Never trust, always verify - verify every request regardless of source.\n\n**Implementation:**\n```javascript\n// Every request must be authenticated and authorized\nconst zeroTrustMiddleware = [\n // 1. Verify identity\n authenticate,\n\n // 2. Verify device/client\n verifyDeviceFingerprint,\n\n // 3. Verify permissions\n authorize,\n\n // 4. Verify request integrity\n verifyRequestSignature,\n\n // 5. Check risk score\n evaluateRiskScore,\n\n // 6. Log access\n logAccess\n];\n\napp.use('/api/*', zeroTrustMiddleware);\n\n// No implicit trust for internal services\nconst callInternalAPI = async (endpoint, data) => {\n const token = await getServiceToken();\n\n return await fetch(`https://internal-api/${endpoint}`, {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`,\n 'X-Service-ID': process.env.SERVICE_ID\n },\n body: JSON.stringify(data)\n });\n};\n```\n\n---\n\n### Pattern 3: Secure Session Management\n\n```javascript\nconst session = require('express-session');\nconst RedisStore = require('connect-redis').default;\n\napp.use(session({\n store: new RedisStore({ client: redisClient }),\n secret: process.env.SESSION_SECRET,\n resave: false,\n saveUninitialized: false,\n cookie: {\n secure: true,\n httpOnly: true,\n sameSite: 'strict',\n maxAge: 30 * 60 * 1000\n },\n // Regenerate session ID periodically\n rolling: true,\n\n // Session versioning\n genid: (req) => {\n return crypto.randomUUID();\n }\n}));\n\n// Regenerate session on privilege change\nconst elevatePrivileges = (req, res, next) => {\n const oldSessionId = req.sessionID;\n\n req.session.regenerate((err) => {\n if (err) return next(err);\n\n // Copy session data\n req.session.userId = req.user.id;\n req.session.role = 'admin';\n\n // Log session change\n logger.info('Session elevated', {\n oldSessionId,\n newSessionId: req.sessionID,\n userId: req.user.id\n });\n\n next();\n });\n};\n\n// Destroy session on logout\napp.post('/auth/logout', (req, res) => {\n const sessionId = req.sessionID;\n\n req.session.destroy((err) => {\n if (err) {\n logger.error('Session destruction failed', { err, sessionId });\n return res.status(500).json({ error: 'Logout failed' });\n }\n\n res.clearCookie('connect.sid');\n logger.info('User logged out', { sessionId });\n res.json({ message: 'Logged out' });\n });\n});\n```\n\n---\n\n### Pattern 4: Security Boundaries\n\n**Concept**: Define trust boundaries and validate all data crossing them.\n\n```javascript\n// Trust boundary: External API → Application\nconst externalAPIBoundary = async (req, res, next) => {\n // 1. Authenticate API client\n const apiKey = req.headers['x-api-key'];\n if (!await verifyAPIKey(apiKey)) {\n return res.status(401).json({ error: 'Invalid API key' });\n }\n\n // 2. Validate input schema\n try {\n req.validatedData = validateAPISchema(req.body);\n } catch (error) {\n return res.status(400).json({ error: 'Invalid request format' });\n }\n\n // 3. Rate limit\n const allowed = await checkRateLimit(apiKey);\n if (!allowed) {\n return res.status(429).json({ error: 'Rate limit exceeded' });\n }\n\n // 4. Log crossing of trust boundary\n logger.info('External API request', {\n apiKey,\n endpoint: req.path,\n ip: req.ip\n });\n\n next();\n};\n\n// Trust boundary: Application → Database\nconst databaseBoundary = {\n query: async (sql, params) => {\n // 1. Validate SQL (parameterized queries only)\n if (!Array.isArray(params)) {\n throw new SecurityError('Parameterized queries required');\n }\n\n // 2. Log query\n logger.debug('Database query', { sql, params });\n\n // 3. Execute with timeout\n const result = await db.execute(sql, params, { timeout: 5000 });\n\n return result;\n }\n};\n```\n\n---\n\n## Security Checklist\n\n### Design Phase\n- [ ] Conduct threat modeling (STRIDE)\n- [ ] Define security requirements\n- [ ] Identify trust boundaries\n- [ ] Design authentication/authorization\n- [ ] Plan data encryption strategy\n- [ ] Define logging and monitoring\n- [ ] Review architecture with security team\n\n### Implementation Phase\n- [ ] Follow secure coding standards\n- [ ] Implement defense in depth\n- [ ] Apply principle of least privilege\n- [ ] Validate all inputs\n- [ ] Encode all outputs\n- [ ] Use parameterized queries\n- [ ] Implement proper error handling\n\n### Testing Phase\n- [ ] Penetration testing\n- [ ] Security code review\n- [ ] Dependency vulnerability scanning\n- [ ] Static analysis (SAST)\n- [ ] Dynamic analysis (DAST)\n- [ ] Verify authentication/authorization\n- [ ] Test error handling\n\n### Deployment Phase\n- [ ] Secure configuration management\n- [ ] Environment separation\n- [ ] Secrets management\n- [ ] TLS/HTTPS enforcement\n- [ ] Security headers configured\n- [ ] Monitoring and alerting enabled\n- [ ] Incident response plan documented\n\n---\n\n## References\n\n- [OWASP Secure Product Design](https://cheatsheetseries.owasp.org/cheatsheets/Secure_Product_Design_Cheat_Sheet.html)\n- [Microsoft Threat Modeling](https://www.microsoft.com/en-us/securityengineering/sdl/threatmodeling)\n- [NIST Secure Software Development Framework](https://csrc.nist.gov/projects/ssdf)\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":15570,"content_sha256":"11b6c2e930b2fbab8cdf37bc7c287f5408cccff7ca7aa9170394bfa8e99c50bd"},{"filename":"references/security-business-value.md","content":"# Security Business Value & ROI\n\nQuantify security investment returns, model breach costs, and leverage compliance for enterprise sales. This reference transforms security from cost center to revenue driver.\n\n---\n\n## Breach Cost Modeling (2024-2025 Data)\n\n### IBM Cost of a Data Breach Report 2024\n\n| Metric | Global Average | US Average | Healthcare |\n|--------|----------------|------------|------------|\n| **Average breach cost** | $4.88M | $9.36M | $10.93M |\n| **Cost per record** | $165 | $194 | $408 |\n| **Breach lifecycle** | 277 days | 258 days | 213 days |\n| **Detection time** | 204 days | 191 days | 156 days |\n| **Containment time** | 73 days | 67 days | 57 days |\n\n### Cost Amplifiers\n\n| Factor | Cost Impact |\n|--------|-------------|\n| Security skills shortage | +$1.76M |\n| Compliance failures | +$1.08M |\n| Cloud migration | +$0.75M |\n| IoT/OT involvement | +$0.87M |\n| Third-party breach | +$0.87M |\n| Lost business | 38% of total cost |\n\n### Cost Reducers (ROI Justification)\n\n| Control | Cost Reduction | Implementation Cost |\n|---------|----------------|---------------------|\n| **DevSecOps adoption** | -$1.68M (-34%) | $150K-300K/year |\n| **AI/ML security tools** | -$1.76M (-36%) | $200K-500K/year |\n| **Incident response team** | -$2.26M (-46%) | $400K-800K/year |\n| **Employee training** | -$232K (-5%) | $50K-100K/year |\n| **Encryption (extensive)** | -$168K (-3%) | $100K-200K/year |\n| **Security analytics** | -$180K (-4%) | $150K-250K/year |\n\n### ROI Formula\n\n```text\nSecurity ROI = (Risk Reduction - Security Investment) / Security Investment × 100\n\nWhere:\n- Risk Reduction = (Breach Probability × Average Breach Cost) × Control Effectiveness\n- Example: (15% × $4.88M) × 46% reduction = $337K risk reduction\n- Investment: $400K IR team\n- ROI: ($337K - $400K) / $400K = -16% Year 1\n- Break-even: Year 2+ as probability compounds\n```\n\n### Annual Loss Expectancy (ALE) Model\n\n```text\nALE = SLE × ARO\n\nWhere:\n- SLE (Single Loss Expectancy) = Asset Value × Exposure Factor\n- ARO (Annual Rate of Occurrence) = Probability of incident per year\n\nExample: Database breach\n- Asset Value: $50M (customer data, reputation)\n- Exposure Factor: 30% (expected loss)\n- SLE: $15M\n- ARO: 5% (industry average for unprotected systems)\n- ALE: $750K/year\n\nWith controls (ARO reduced to 0.5%):\n- New ALE: $75K/year\n- Risk Reduction: $675K/year\n- Acceptable security investment: Up to $675K/year\n```\n\n---\n\n## Security as Enterprise Sales Enabler\n\n### Compliance → Contract Requirements\n\n| Compliance | Enterprise Requirement | Deal Size Impact |\n|------------|------------------------|------------------|\n| **SOC 2 Type II** | Common enterprise procurement baseline | Enables $100K+ deals |\n| **ISO 27001** | Often expected in EU/regulated markets | Enables $250K+ deals |\n| **HIPAA** | Required for many healthcare use cases | Enables healthcare vertical |\n| **PCI DSS** | Required for many payment processing flows | Enables fintech partnerships |\n| **FedRAMP** | Required for many US federal workloads | Enables $1M+ government deals |\n| **GDPR** | EU data processing | Required for EU market entry |\n\n### Sales Cycle Impact\n\n| Security Posture | Typical Sales Impact |\n|------------------|-----------------|\n| No formal attestation | Longer security reviews and higher drop-off |\n| SOC 2 Type I | Sometimes acceptable for pilots; often requires a roadmap to Type II |\n| SOC 2 Type II | Smoother enterprise procurement and renewals |\n| ISO 27001 + SOC 2 | Strong trust signal, especially in regulated/geographically strict markets |\n\n### Security Questionnaire Acceleration\n\n**Problem:** Security questionnaires average 200-400 questions, 40-80 hours to complete.\n\n**Solution:** Pre-built evidence library\n\n| Control | Evidence Package |\n|---------|------------------|\n| Access management | IAM policies, RBAC docs, access reviews |\n| Encryption | TLS configs, encryption-at-rest policies, key management |\n| Incident response | IR playbooks, tabletop exercises, breach notification procedures |\n| Vendor management | Third-party risk assessments, vendor security reviews |\n| Change management | CI/CD security gates, code review requirements |\n\n**ROI:** Can materially reduce questionnaire time and speed procurement; measure impact in your CRM (cycle time, win rate, and effort hours).\n\n---\n\n## Cost-Benefit Analysis Templates\n\n### Template 1: Security Tool Justification\n\n```markdown\n## Business Case: [Security Tool]\n\n### Problem Statement\n- Current risk exposure: $X/year (ALE calculation)\n- Current detection time: Y days\n- Current false positive rate: Z%\n\n### Proposed Solution\n- Tool: [Name]\n- Annual cost: $A\n- Implementation: $B (one-time)\n\n### Expected Benefits\n- Risk reduction: X% → $C/year saved\n- Detection time: Y → Y' days (Z% improvement)\n- False positives: Z% → Z'% (analyst time saved: $D/year)\n\n### ROI Calculation\n- Year 1: ($C + $D - $A - $B) / ($A + $B) = X%\n- Year 2+: ($C + $D - $A) / $A = Y%\n- Payback period: Z months\n\n### Recommendation\n[Approve/Reject] based on [X-year] ROI of [Y%]\n```\n\n### Template 2: Compliance Investment Justification\n\n```markdown\n## Business Case: [Compliance Certification]\n\n### Market Opportunity\n- Target market: [Enterprise segment]\n- Blocked deals (last 12 months): $X\n- Pipeline requiring compliance: $Y\n\n### Investment Required\n- Audit costs: $A/year\n- Tool costs: $B/year\n- Process changes: $C (one-time)\n- FTE impact: $D/year\n\n### Revenue Impact\n- Unblocked pipeline: $Y × close rate = $E\n- New market access: $F/year\n- Premium pricing: $G/year\n\n### ROI Calculation\n- Total investment: $A + $B + $C + $D = $H\n- Total revenue impact: $E + $F + $G = $I\n- ROI: ($I - $H) / $H = X%\n- Payback period: Z months\n\n### Recommendation\nAchieve [Certification] to unlock $I in revenue\n```\n\n### Template 3: Security Incident Post-Mortem (Business Impact)\n\n```markdown\n## Incident Business Impact: [Incident Name]\n\n### Direct Costs\n| Category | Cost |\n|----------|------|\n| Incident response (internal) | $X |\n| Incident response (external) | $X |\n| Legal/regulatory | $X |\n| Customer notification | $X |\n| Credit monitoring | $X |\n| **Total direct** | $X |\n\n### Indirect Costs\n| Category | Cost |\n|----------|------|\n| Business disruption | $X |\n| Lost customers | $X |\n| Reputation damage (estimated) | $X |\n| Increased insurance premiums | $X |\n| **Total indirect** | $X |\n\n### Prevention Investment\n| Control | Would have prevented? | Cost |\n|---------|----------------------|------|\n| [Control 1] | Yes/Partial/No | $X |\n| [Control 2] | Yes/Partial/No | $X |\n\n### Recommendation\nInvest $Y in [controls] to prevent $Z in future losses\n```\n\n---\n\n## Industry Benchmarks\n\n### Security Spending Benchmarks\n\n| Industry | Security % of IT Budget | Security per Employee |\n|----------|------------------------|----------------------|\n| Financial services | 10-15% | $2,500-3,500 |\n| Healthcare | 6-8% | $1,800-2,500 |\n| Technology | 8-12% | $2,000-3,000 |\n| Retail | 4-6% | $1,200-1,800 |\n| Manufacturing | 3-5% | $800-1,200 |\n| **Recommended minimum** | **6%** | **$1,500** |\n\n### Maturity Investment Levels\n\n| Maturity Level | Investment | Capabilities |\n|----------------|------------|--------------|\n| **Level 1: Basic** | $100K-250K/year | Firewall, antivirus, basic monitoring |\n| **Level 2: Developing** | $250K-500K/year | SIEM, vulnerability scanning, IR plan |\n| **Level 3: Defined** | $500K-1M/year | SOC, pen testing, compliance automation |\n| **Level 4: Managed** | $1M-2M/year | 24/7 SOC, threat hunting, red team |\n| **Level 5: Optimized** | $2M+/year | AI/ML detection, proactive defense, zero trust |\n\n---\n\n## Stakeholder Communication\n\n### Board-Level Security Metrics\n\n| Metric | What It Measures | Target |\n|--------|------------------|--------|\n| **Risk exposure ($)** | Quantified cyber risk | Decreasing trend |\n| **Time to detect** | Mean time to identify breach | \u003c10 days |\n| **Time to contain** | Mean time to contain breach | \u003c30 days |\n| **Compliance status** | % of controls passing audit | >95% |\n| **Third-party risk** | Critical vendor risk score | \u003c3 (of 5) |\n| **Security debt** | Unresolved critical vulnerabilities | \u003c10 |\n\n### CFO-Focused Metrics\n\n| Metric | Business Translation |\n|--------|---------------------|\n| Vulnerability remediation time | Reduced breach probability |\n| False positive rate | Analyst efficiency (cost savings) |\n| Automation coverage | Headcount avoidance |\n| Compliance audit findings | Audit cost predictability |\n| Security tool consolidation | License cost reduction |\n\n### Sales-Focused Security Assets\n\n| Asset | Purpose | Usage |\n|-------|---------|-------|\n| Security whitepaper | Proactive trust building | Send pre-RFP |\n| SOC 2 report (summary) | Evidence of compliance | Security review |\n| Trust center | Self-service security info | Website, sales enablement |\n| Security FAQ | Common objection handling | Sales training |\n| Data processing addendum | GDPR compliance | Contract attachment |\n\n---\n\n## Compliance-Driven Revenue Opportunities\n\n### Vertical Market Access\n\n| Compliance | Market Unlocked | Market Size (TAM) |\n|------------|-----------------|-------------------|\n| HIPAA | Healthcare | $12.2B (health IT) |\n| PCI DSS | E-commerce, Fintech | $6.8T (e-commerce) |\n| FedRAMP | US Government | $92B (federal IT) |\n| StateRAMP | US State/Local | $45B (SLED IT) |\n| ISO 27001 | EU Enterprise | $540B (EU SaaS) |\n| SOC 2 | All B2B SaaS | $197B (B2B SaaS) |\n\n### Compliance as Competitive Moat\n\n**Differentiation Strategy:**\n\n1. **First-mover advantage:** Be first in category with compliance\n2. **Premium positioning:** Security-first pricing (10-20% premium)\n3. **Vendor lock-in:** Compliance switching costs favor incumbents\n4. **Partnership requirements:** Compliance required for integration partners\n\n### Enterprise Trust Center ROI\n\n| Metric | Before Trust Center | After Trust Center |\n|--------|--------------------|--------------------|\n| Security questionnaires/month | 15 | 5 |\n| Hours per questionnaire | 40 | 10 |\n| Sales cycle (enterprise) | 6 months | 4 months |\n| Deal win rate (security objection) | 45% | 72% |\n\n---\n\n## Quick Reference: Security Investment Priorities\n\n### If Budget is $100K-250K (Startup)\n\n1. SOC 2 Type II certification ($50-80K)\n2. Vulnerability management tool ($15-25K)\n3. Security awareness training ($5-10K)\n4. Incident response retainer ($20-40K)\n5. Penetration test ($15-30K)\n\n### If Budget is $250K-500K (Growth)\n\n1. All startup items\n2. SIEM/security analytics ($50-100K)\n3. Security engineer hire ($120-180K)\n4. Bug bounty program ($20-50K)\n5. Third-party risk management ($25-50K)\n\n### If Budget is $500K-1M (Scale)\n\n1. All growth items\n2. 24/7 SOC (MSSP or in-house) ($200-400K)\n3. Red team/pen test program ($75-150K)\n4. Security automation ($50-100K)\n5. ISO 27001 certification ($50-100K)\n\n---\n\n## Sources\n\n- IBM Cost of a Data Breach Report 2024: https://www.ibm.com/reports/data-breach\n- Ponemon Institute research: https://www.ponemon.org/\n- Gartner security spending benchmarks: https://www.gartner.com/en/information-technology/insights/security-risk-management\n- IANS Research security budgets: https://www.iansresearch.com/\n- Verizon DBIR (breach statistics): https://www.verizon.com/business/resources/reports/dbir/\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":11231,"content_sha256":"1c59609875b4093f252c327f490a123935243c865a4420128e2050b1b2d0e7ef"},{"filename":"references/smart-contract-security-auditing.md","content":"# Smart Contract Security Auditing — Comprehensive Methodology\n\nProduction-grade security audit framework for blockchain smart contracts across all major platforms.\n\n---\n\n## Table of Contents\n\n1. [Audit Process Overview](#audit-process-overview)\n2. [Pre-Audit Preparation](#pre-audit-preparation)\n3. [Automated Analysis Tools](#automated-analysis-tools)\n4. [Manual Review Methodology](#manual-review-methodology)\n5. [Platform-Specific Checklists](#platform-specific-checklists)\n6. [Severity Classification](#severity-classification)\n7. [Report Structure](#report-structure)\n8. [Post-Audit Verification](#post-audit-verification)\n\n---\n\n## Audit Process Overview\n\n### Five-Phase Audit Methodology\n\n```\nPhase 1: Preparation (10% of time)\n├── Repository setup\n├── Documentation review\n├── Threat modeling\n└── Scope definition\n\nPhase 2: Automated Analysis (15% of time)\n├── Static analysis (Slither, Mythril)\n├── Linting and style checks\n├── Dependency vulnerability scanning\n└── Gas profiling\n\nPhase 3: Manual Review (50% of time)\n├── Line-by-line code review\n├── Architecture analysis\n├── Business logic verification\n└── Access control validation\n\nPhase 4: Testing & Exploitation (20% of time)\n├── Exploit POC development\n├── Fuzz testing\n├── Invariant testing\n└── Integration testing\n\nPhase 5: Reporting (5% of time)\n├── Finding documentation\n├── Severity classification\n├── Remediation recommendations\n└── Final report delivery\n```\n\n---\n\n## Pre-Audit Preparation\n\n### Initial Questionnaire\n\n**Project Information:**\n1. What is the primary purpose of the smart contract(s)?\n2. What are the expected user flows?\n3. What assets are managed (tokens, NFTs, funds)?\n4. What are the critical invariants that must hold?\n5. Are there any known issues or concerns?\n\n**Technical Details:**\n1. Which blockchain(s) will this deploy to?\n2. What is the expected transaction volume?\n3. Are contracts upgradeable? If so, how?\n4. What external dependencies exist (oracles, DEXs, etc.)?\n5. What previous audits have been conducted?\n\n### Repository Setup\n\n```bash\n# Clone repository\ngit clone https://github.com/project/contracts.git\ncd contracts\n\n# Install dependencies (Solidity example)\nnpm install\n\n# Compile contracts\nnpx hardhat compile\n\n# Run existing tests\nnpx hardhat test\n\n# Check test coverage\nnpx hardhat coverage\n\n# Generate documentation\nnpx hardhat docgen\n```\n\n### Threat Modeling\n\n**Asset Identification:**\n- ETH/SOL/native tokens held\n- ERC20/SPL tokens managed\n- NFTs (ERC721, ERC1155, Metaplex)\n- User data and permissions\n- Protocol configuration parameters\n\n**Attack Surfaces:**\n- Public/external functions\n- Cross-contract calls (CPI, delegatecall)\n- Oracle dependencies\n- Admin/governance functions\n- Upgrade mechanisms\n\n**Trust Boundaries:**\n- User inputs (untrusted)\n- Oracle data (semi-trusted)\n- Multi-sig operators (trusted)\n- Protocol developers (trusted)\n\n---\n\n## Automated Analysis Tools\n\n### Solidity/EVM Tools\n\n**Slither (Static Analysis):**\n```bash\nslither . --print human-summary\nslither . --print contract-summary\nslither . --print function-summary\nslither . --detect reentrancy-eth\nslither . --detect uninitialized-state\nslither . --detect controlled-delegatecall\n\n# Generate report\nslither . --json slither-report.json\n```\n\n**Mythril (Symbolic Execution):**\n```bash\nmyth analyze contracts/Token.sol --solv 0.8.20\nmyth analyze contracts/ --execution-timeout 600\n```\n\n**Echidna (Fuzz Testing):**\n```bash\n# echidna.yaml\ntestMode: assertion\ntestLimit: 50000\ndeployer: \"0x30000\"\nsender: [\"0x10000\", \"0x20000\", \"0x30000\"]\n\n# Run fuzzer\nechidna-test contracts/Token.sol --contract Token --config echidna.yaml\n```\n\n**Manticore (Dynamic Analysis):**\n```bash\nmanticore contracts/Token.sol --contract Token\n```\n\n**Solhint (Linting):**\n```bash\nsolhint 'contracts/**/*.sol'\n```\n\n### Solana/Rust Tools\n\n**Anchor Verify:**\n```bash\nanchor build --verifiable\nsolana-verify verify-from-repo --program-id \u003cPROGRAM_ID> https://github.com/project/program\n```\n\n**Cargo Audit:**\n```bash\ncargo audit\n```\n\n**Clippy (Linting):**\n```bash\ncargo clippy -- -D warnings\n```\n\n**Sec3 Auto-Audit:**\n```bash\n# Solana security scanner\nsec3-cli audit .\n```\n\n### Dependency Scanning\n\n```bash\n# NPM audit\nnpm audit\n\n# Yarn audit\nyarn audit\n\n# Check for known vulnerabilities\nnpx snyk test\n```\n\n---\n\n## Manual Review Methodology\n\n### Line-by-Line Review Process\n\n**Step 1: Entry Points (15 minutes per contract)**\n- Identify all public/external functions\n- Map user-accessible attack surface\n- Document expected vs actual access control\n\n**Step 2: State Variables (10 minutes per contract)**\n- Review storage layout\n- Check initialization\n- Verify mutability (constant, immutable)\n- Look for unprotected state changes\n\n**Step 3: Critical Logic (30-60 minutes per function)**\nFor each critical function:\n1. **Input Validation:** Are all inputs validated?\n2. **Authorization:** Is caller properly authorized?\n3. **State Changes:** Are state changes in correct order (CEI pattern)?\n4. **External Calls:** Are external calls safe (reentrancy, return values)?\n5. **Arithmetic:** Are calculations safe from overflow/underflow/precision loss?\n6. **Events:** Are all state changes logged?\n\n**Step 4: Integration Points (20 minutes per dependency)**\n- Oracle calls: staleness checks, price manipulation\n- DEX integrations: slippage protection, flash loan attacks\n- Token transfers: check return values, approve-transfer pattern\n\n### Architecture Review\n\n**Separation of Concerns:**\n- [ ] Logic separated from storage\n- [ ] Access control isolated\n- [ ] Treasury/funds management separate\n- [ ] Upgradability cleanly implemented\n\n**Upgrade Mechanisms:**\n- [ ] Proxy pattern correctly implemented (UUPS, Transparent, Diamond)\n- [ ] Storage collisions avoided\n- [ ] Initializers protected (`_disableInitializers()`)\n- [ ] Upgrade authorization secured\n\n**Gas Efficiency:**\n- [ ] Storage reads cached\n- [ ] Loops bounded\n- [ ] Storage packing optimized\n- [ ] Events used instead of storage for historical data\n\n### Business Logic Verification\n\n**Protocol Invariants:**\n- Total supply == sum of balances\n- Reserves maintain constant product (AMM)\n- Collateral ratio always >= minimum\n- User withdrawals never exceed deposits\n\n**Economic Security:**\n- Fee calculations round in protocol's favor\n- Rewards distributed fairly\n- No economic exploits (flash loans, oracle manipulation)\n\n---\n\n## Platform-Specific Checklists\n\n### Ethereum/Solidity Checklist\n\n**Critical (P0):**\n- [ ] Reentrancy protection (CEI pattern, ReentrancyGuard)\n- [ ] Access control on privileged functions\n- [ ] Safe arithmetic (Solidity 0.8+ or SafeMath)\n- [ ] External call return values checked\n- [ ] No delegatecall to untrusted contracts\n- [ ] Oracle data validated (staleness, price bounds)\n\n**High (P1):**\n- [ ] ERC20 approve-transfer pattern used correctly\n- [ ] No tx.origin for authentication\n- [ ] Timestamp manipulation considered\n- [ ] Front-running mitigated (commit-reveal, slippage limits)\n- [ ] Gas griefing prevented (no transfer/send, use call)\n\n**Medium (P2):**\n- [ ] Storage variables packed efficiently\n- [ ] Events emitted for state changes\n- [ ] Pausable for emergencies\n- [ ] Upgradeable contracts follow proxy standards\n- [ ] NatSpec documentation complete\n\n**Low (P3):**\n- [ ] Custom errors instead of require strings\n- [ ] Immutable/constant where applicable\n- [ ] No floating pragma\n- [ ] Solhint warnings addressed\n\n### Solana/Anchor Checklist\n\n**Critical (P0):**\n- [ ] All accounts validated (owner, signer, program ID)\n- [ ] PDA seeds unique and collision-resistant\n- [ ] Checked arithmetic used (no overflow)\n- [ ] Signer enforcement with `Signer\u003c'info>`\n- [ ] Account type validation (TokenAccount, Mint, etc.)\n- [ ] CPI targets validated (program IDs, account ownership)\n\n**High (P1):**\n- [ ] No reinitialization attacks (`init` constraint used)\n- [ ] Authority checks (has_one, constraint)\n- [ ] Mint/token account validation\n- [ ] Bump seeds verified in PDAs\n- [ ] Close account security (rent reclaim)\n\n**Medium (P2):**\n- [ ] Account sizes minimized\n- [ ] Zero-copy for large accounts\n- [ ] Compute budget within limits\n- [ ] Custom errors for all failure cases\n\n**Low (P3):**\n- [ ] Clippy warnings addressed\n- [ ] Documentation complete\n- [ ] Test coverage >90%\n\n### CosmWasm Checklist\n\n**Critical (P0):**\n- [ ] All `ExecuteMsg` variants validate sender\n- [ ] Funds handling secure (accept_funds, send_tokens)\n- [ ] Query functions don't modify state\n- [ ] Reentrancy protection (no state between submessages)\n\n**High (P1):**\n- [ ] Integer overflow protection\n- [ ] Decimal precision handled correctly\n- [ ] IBC packet validation\n- [ ] Migration function secured\n\n---\n\n## Severity Classification\n\n### CVSS-Based Scoring\n\n**Critical (9.0-10.0):**\n- Direct theft of funds\n- Unauthorized minting/burning\n- Protocol manipulation leading to loss\n\n**Example:**\n```solidity\n// CRITICAL: Reentrancy allows draining contract\nfunction withdraw() public {\n uint amount = balances[msg.sender];\n (bool success,) = msg.sender.call{value: amount}(\"\");\n balances[msg.sender] = 0; // State change AFTER call\n}\n```\n\n**High (7.0-8.9):**\n- Potential fund loss under specific conditions\n- Access control bypass\n- Oracle manipulation\n\n**Example:**\n```solidity\n// HIGH: Missing access control\nfunction setAdmin(address newAdmin) public {\n admin = newAdmin; // Anyone can become admin\n}\n```\n\n**Medium (4.0-6.9):**\n- State inconsistency\n- DoS attacks\n- Griefing attacks\n\n**Example:**\n```solidity\n// MEDIUM: Unbounded loop DoS\nfunction distributeRewards() public {\n for (uint i = 0; i \u003c users.length; i++) {\n users[i].transfer(reward); // Can exceed gas limit\n }\n}\n```\n\n**Low (1.0-3.9):**\n- Gas inefficiency\n- Code quality issues\n- Best practice violations\n\n**Example:**\n```solidity\n// LOW: Gas inefficiency\nuint256 public balance;\nfunction getBalance() public view returns (uint256) {\n return balance; // Redundant getter (auto-generated)\n}\n```\n\n**Informational (0.0):**\n- Code style\n- Documentation\n- Suggestions\n\n---\n\n## Report Structure\n\n### Executive Summary Template\n\n```markdown\n# Security Audit Report\n\n## Project: [Project Name]\n**Audit Period:** [Start Date] - [End Date]\n**Auditors:** [Names]\n**Commit Hash:** [Git commit hash]\n\n### Summary\n- **Total Issues:** X\n- **Critical:** X\n- **High:** X\n- **Medium:** X\n- **Low:** X\n- **Informational:** X\n\n### Scope\nThe audit covered the following contracts:\n- `ContractA.sol` (XXX lines)\n- `ContractB.sol` (XXX lines)\n\n### Key Findings\n1. [Critical Issue #1 Summary]\n2. [High Issue #1 Summary]\n3. [High Issue #2 Summary]\n\n### Recommendations\n- Fix all Critical and High severity issues before deployment\n- Implement additional test coverage for [specific area]\n- Consider [architectural improvement]\n```\n\n### Finding Template\n\n```markdown\n## [Severity] [Finding ID]: [Title]\n\n### Description\n[Detailed description of the vulnerability]\n\n### Location\n- **File:** `contracts/Token.sol`\n- **Lines:** 123-145\n- **Function:** `withdraw()`\n\n### Impact\n[What could an attacker achieve? What's the potential loss?]\n\n### Proof of Concept\n[Code demonstrating the exploit]\n\nbash\n# Setup\nnpx hardhat test test/exploit.test.ts\n\n### Recommendation\n[How to fix the issue]\n\nsolidity\n// BEFORE (vulnerable)\nfunction withdraw() public {\n uint amount = balances[msg.sender];\n msg.sender.call{value: amount}(\"\");\n balances[msg.sender] = 0;\n}\n\n// AFTER (fixed)\nfunction withdraw() public nonReentrant {\n uint amount = balances[msg.sender];\n balances[msg.sender] = 0;\n (bool success,) = msg.sender.call{value: amount}(\"\");\n require(success, \"Transfer failed\");\n}\n\n\n### References\n- [CWE-XXXX](https://cwe.mitre.org/data/definitions/XXX.html)\n- [SWC-XXX](https://swcregistry.io/docs/SWC-XXX)\n```\n\n### Gas Optimization Template\n\n```markdown\n## Gas Optimization: [Description]\n\n### Current Implementation\nsolidity\n// Uses 50,000 gas\nfor (uint i = 0; i \u003c array.length; i++) {\n data[i] = array[i];\n}\n\n\n### Optimized Implementation\nsolidity\n// Uses 35,000 gas\nuint length = array.length;\nfor (uint i = 0; i \u003c length;) {\n data[i] = array[i];\n unchecked { ++i; }\n}\n\n\n### Gas Savings\n- **Before:** 50,000 gas\n- **After:** 35,000 gas\n- **Savings:** 15,000 gas (30%)\n```\n\n---\n\n## Post-Audit Verification\n\n### Fix Verification Process\n\n1. **Receive Updated Code:**\n - New commit hash provided\n - Developer summary of changes\n\n2. **Verify Each Fix:**\n - [ ] Issue completely resolved\n - [ ] No new issues introduced\n - [ ] Tests added for the fix\n - [ ] Gas impact measured\n\n3. **Regression Testing:**\n ```bash\n # Run all automated tools again\n slither .\n echidna-test contracts/\n npx hardhat test\n npx hardhat coverage\n ```\n\n4. **Final Report:**\n ```markdown\n ## Fix Verification Summary\n\n | Finding ID | Status | Notes |\n |------------|--------|-------|\n | CRIT-01 | [OK] Fixed | Implemented ReentrancyGuard |\n | HIGH-01 | [OK] Fixed | Added access control |\n | MED-01 | [WARNING] Partially | Loop bounded, but limit too high |\n | LOW-01 | [FAIL] Not Fixed | Developer deferred to v2 |\n ```\n\n### Final Checklist\n\n**Before Mainnet Deployment:**\n- [ ] All Critical and High issues resolved\n- [ ] Medium issues resolved or accepted as known risks\n- [ ] Tests updated to cover all fixes\n- [ ] Gas profiling confirms no major regressions\n- [ ] Documentation updated\n- [ ] Multi-sig setup for admin functions\n- [ ] Monitoring and alerting configured\n- [ ] Emergency pause mechanism tested\n- [ ] Upgrade procedures documented\n- [ ] Bug bounty program launched\n\n---\n\n## Tools Reference\n\n### Ethereum/Solidity\n- **Slither:** https://github.com/crytic/slither\n- **Mythril:** https://github.com/ConsenSys/mythril\n- **Echidna:** https://github.com/crytic/echidna\n- **Manticore:** https://github.com/trailofbits/manticore\n- **Certora Prover:** https://www.certora.com/\n- **Halmos:** https://github.com/a16z/halmos\n\n### Solana/Rust\n- **Sec3:** https://www.sec3.dev/\n- **Soteria:** https://github.com/blocksecteam/soteria\n- **Cargo Audit:** https://github.com/rustsec/rustsec\n- **Clippy:** Built into Rust toolchain\n\n### General\n- **Semgrep:** https://semgrep.dev/\n- **CodeQL:** https://codeql.github.com/\n- **Snyk:** https://snyk.io/\n\n---\n\n## Audit Report Examples\n\n### Public Audit Reports\n- [Trail of Bits](https://github.com/trailofbits/publications)\n- [OpenZeppelin](https://blog.openzeppelin.com/security-audits)\n- [Consensys Diligence](https://consensys.io/diligence/audits/)\n- [Certora](https://www.certora.com/audits/)\n- [Quantstamp](https://github.com/quantstamp/audits)\n\n### Learning Resources\n- [Smart Contract Security Best Practices](https://consensys.github.io/smart-contract-best-practices/)\n- [SWC Registry](https://swcregistry.io/)\n- [Secureum Bootcamp](https://secureum.substack.com/)\n- [DeFi Hack Labs](https://github.com/SunWeb3Sec/DeFiHackLabs)\n- [Rekt News](https://rekt.news/)\n\n---\n\n## Conclusion\n\nA thorough security audit combines:\n1. **Automated tools** for breadth (catch common issues fast)\n2. **Manual review** for depth (understand complex logic)\n3. **Testing** for validation (prove exploits work)\n4. **Documentation** for clarity (enable fixes and future audits)\n\n**Remember:** An audit is a snapshot in time. Continuous security monitoring, bug bounties, and regular re-audits are essential for production systems managing significant value.\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":15456,"content_sha256":"b3921ce0265f10a99cb9b214866ccca2db5aa3b999beffbd0988b6c2009ae0fa"},{"filename":"references/supply-chain-security.md","content":"# Supply Chain Security — Modern Best Practices (Jan 2026)\n\nComprehensive guide to software supply chain security focusing on dependency management, SBOM, trusted publishing, and protection against supply chain attacks.\n\n---\n\n## Overview\n\nSupply chain risk is the risk that code you did not author (dependencies, build tooling, CI/CD, registries, container base images, artifact storage, CDNs) is compromised.\n\n**OWASP Top 10:2025 (FINAL)** includes **A03: Software Supply Chain Failures** as a first-class category (elevated from \"Vulnerable and Outdated Components\").\n\n---\n\n## 2026 Updates\n\n### CISA 2025 SBOM Minimum Elements\n\nCISA released updated guidance on Software Bill of Materials (December 2025):\n\n**Required SBOM Fields:**\n- Supplier name\n- Component name and version\n- Unique identifier (PURL, CPE)\n- Dependency relationship\n- Author of SBOM data\n- Timestamp\n\n**Key Changes from 2021:**\n- Machine-readable format required (SPDX 2.3+ or CycloneDX 1.4+)\n- Vulnerability correlation (link to VEX)\n- Continuous updates (not one-time deliverable)\n\n### EU CRA (Cyber Resilience Act)\n\nThe EU CRA became law in 2025, making SBOMs mandatory for products sold in EU:\n- Required for all products with digital elements\n- Must be updated throughout product lifecycle\n- Penalties for non-compliance\n\n### AI-BOM (AI Bill of Materials)\n\nFor AI-native systems, traditional SBOMs don't capture full risk. AI-BOM includes:\n- Models and model versions\n- Training datasets and data provenance\n- Embeddings and vector stores\n- AI service dependencies (OpenAI, Anthropic, etc.)\n- Orchestration frameworks (LangChain, LlamaIndex)\n\n**EU AI Act** (effective August 2, 2025) requires transparency for GPAI models.\n\n### Industry Adoption Status\n\n- **48% of organizations** falling behind on SBOM requirements (Lineaje 2025 survey)\n- Leading ecosystems integrating SBOMs natively into build tools\n- SBOM now a cornerstone of modern software security\n\n---\n\n## OWASP Top 10:2025 - A03: Software Supply Chain Failures\n\n**First-class category in 2025** (expanded from \"Vulnerable and Outdated Components\"):\n- Dependency confusion attacks\n- Malicious package injection\n- Compromised maintainer accounts\n- Build pipeline tampering\n- Unsigned artifacts\n- **Unknown vulnerabilities** from third-parties (new scope)\n\n---\n\n## Common Attack Vectors\n\n- Typosquatting / brandjacking in package registries\n- Dependency confusion (private package name collision)\n- Compromised maintainer accounts and malicious releases\n- Build pipeline compromise (CI tokens, runners, scripts)\n- Artifact substitution (unsigned or unverified binaries/images)\n- Compromised CDN/script injection\n- Compromised transitive dependencies and postinstall scripts\n\n### Reference Incidents (for training)\n\n- CISA alert on the npm “Shai-Hulud” worm (2025-09-23): https://www.cisa.gov/news-events/alerts/2025/09/23/widespread-supply-chain-compromise-impacting-npm-ecosystem\n- xz-utils backdoor disclosure (oss-security, 2024-03-29): https://www.openwall.com/lists/oss-security/2024/03/29/4\n\n---\n\n## Defense-in-Depth Strategy\n\n### 1. Dependency Management\n\n**Lock File Integrity**\n\n```bash\n# Generate lockfiles with integrity hashes\nnpm install --package-lock-only\n\n# Verify lockfile hasn't been tampered with\nnpm ci --audit\n\n# pnpm v10.16+ minimum release age protection\n# pnpm-workspace.yaml\nminReleaseAge: 1440 # 24 hours in minutes\n```\n\n**Dependency Pinning**\n\n```json\n{\n \"dependencies\": {\n \"express\": \"4.18.2\", // Exact version, not ^4.18.2\n \"lodash\": \"4.17.21\",\n \"react\": \"18.2.0\"\n }\n}\n```\n\n**Why pin versions:**\n- Prevents automatic upgrades to compromised versions\n- Allows time for community to detect malicious updates\n- Enables controlled upgrade process with security review\n\n**Automated Dependency Updates**\n\n```yaml\n# .github/dependabot.yml\nversion: 2\nupdates:\n - package-ecosystem: \"npm\"\n directory: \"/\"\n schedule:\n interval: \"weekly\"\n open-pull-requests-limit: 10\n reviewers:\n - \"security-team\"\n labels:\n - \"dependencies\"\n - \"security\"\n # Allow time for community vetting\n pull-request-branch-name:\n separator: \"/\"\n```\n\n---\n\n### 2. Software Bill of Materials (SBOM)\n\n**Generate SBOM**\n\n```bash\n# Using CycloneDX\nnpm install -g @cyclonedx/cyclonedx-npm\ncyclonedx-npm --output-file sbom.json\n\n# Using Syft\nsyft packages dir:. -o json > sbom.json\n\n# Using npm native (npm 8+)\nnpm sbom --sbom-format=cyclonedx > sbom.json\n```\n\n**SBOM Benefits:**\n- Complete inventory of dependencies\n- Vulnerability tracking across supply chain\n- License compliance validation\n- Incident response acceleration\n\n**Track SBOM Changes**\n\n```bash\n# Store SBOMs in version control\ngit add sbom.json\n\n# Compare SBOMs between versions\ndiff sbom-v1.json sbom-v2.json\n```\n\n---\n\n### 3. Trusted Publishing\n\n**GitHub Actions + npm Trusted Publishing (July 2025)**\n\n```yaml\n# .github/workflows/publish.yml\nname: Publish to npm\non:\n release:\n types: [published]\n\njobs:\n publish:\n runs-on: ubuntu-latest\n permissions:\n contents: read\n id-token: write # Required for trusted publishing\n steps:\n - uses: actions/checkout@v4\n - uses: actions/setup-node@v4\n with:\n node-version: '20'\n registry-url: 'https://registry.npmjs.org'\n - run: npm ci\n - run: npm test\n - run: npm publish --provenance --access public\n env:\n NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}\n```\n\n**Benefits:**\n- No long-lived tokens in secrets\n- Cryptographic proof of build origin\n- Build transparency via SLSA provenance\n\n**Verify Package Provenance**\n\n```bash\n# Check if package has provenance\nnpm view express dist.attestations\n\n# Verify provenance\nnpm audit signatures\n```\n\n---\n\n### 4. Authentication Security\n\n**Phishing-Resistant MFA (Required by GitHub 2025)**\n\n```bash\n# Enable hardware security key (WebAuthn)\n# GitHub Account Settings → Security → Two-factor authentication\n# → Register new security key\n\n# Backup codes\n# Store in password manager or secure location\n```\n\n**Best Practices:**\n- Use hardware security keys (YubiKey, Titan Key)\n- Enable MFA on all developer accounts\n- Avoid SMS-based 2FA (vulnerable to SIM swapping)\n- Implement organization-wide MFA policies\n\n---\n\n### 5. Software Composition Analysis (SCA)\n\n**Continuous Vulnerability Scanning**\n\n```bash\n# npm audit (built-in)\nnpm audit --audit-level=moderate\n\n# Snyk\nnpm install -g snyk\nsnyk auth\nsnyk test\nsnyk monitor\n\n# Trivy\ntrivy fs .\n\n# Grype\ngrype dir:.\n```\n\n**CI/CD Integration**\n\n```yaml\n# GitHub Actions\n- name: Run Snyk security scan\n uses: snyk/actions/node@master\n env:\n SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}\n with:\n command: test\n args: --severity-threshold=high\n```\n\n**Automated PR Blocking**\n\n```yaml\n# Block PRs with high/critical vulnerabilities\n- name: Check vulnerabilities\n run: |\n npm audit --audit-level=high\n if [ $? -ne 0 ]; then\n echo \"High/critical vulnerabilities found\"\n exit 1\n fi\n```\n\n---\n\n### 6. SLSA Framework\n\n**Supply-chain Levels for Software Artifacts**\n\n**SLSA Level 1**: Documentation of build process\n**SLSA Level 2**: Tamper-resistant build service\n**SLSA Level 3**: Hardened build platform with provenance\n**SLSA Level 4**: Two-party review + hermetic builds\n\n**Implement SLSA Level 3**\n\n```yaml\n# Use GitHub-hosted runners (trusted build environment)\njobs:\n build:\n runs-on: ubuntu-latest # Isolated, ephemeral environment\n permissions:\n id-token: write # Generate provenance\n contents: read\n steps:\n - uses: actions/checkout@v4\n - run: npm ci --ignore-scripts # Prevent malicious install scripts\n - run: npm run build\n - uses: actions/attest-build-provenance@v1\n with:\n subject-path: 'dist/**'\n```\n\n---\n\n### 7. Artifact Signing\n\n**Sigstore - Keyless Signing**\n\n```bash\n# Install cosign\nbrew install cosign\n\n# Sign artifact (keyless with OIDC)\ncosign sign-blob --yes artifact.tar.gz > artifact.sig\n\n# Verify signature\ncosign verify-blob \\\n --signature artifact.sig \\\n --certificate-identity [email protected] \\\n --certificate-oidc-issuer https://github.com/login/oauth \\\n artifact.tar.gz\n```\n\n**Docker Image Signing**\n\n```bash\n# Sign container image\ncosign sign ghcr.io/org/image:v1.0.0\n\n# Verify before deployment\ncosign verify \\\n --certificate-identity [email protected] \\\n --certificate-oidc-issuer https://github.com/login/oauth \\\n ghcr.io/org/image:v1.0.0\n```\n\n---\n\n### 8. Secure CI/CD Pipeline\n\n**Principle: Least Privilege**\n\n```yaml\n# Minimal permissions\npermissions:\n contents: read\n pull-requests: write\n\njobs:\n test:\n runs-on: ubuntu-latest\n # No write access to secrets or packages\n steps:\n - uses: actions/checkout@v4\n - run: npm ci\n - run: npm test\n```\n\n**Secrets Management**\n\n```yaml\n# Use environment-specific secrets\njobs:\n deploy:\n environment: production\n steps:\n - uses: actions/checkout@v4\n - run: |\n # Secrets scoped to environment\n echo \"Deploying with ${{ secrets.PROD_API_KEY }}\"\n```\n\n**Prevent Script Injection**\n\n```bash\n# Bad: Command injection vulnerability\ngit commit -m \"${{ github.event.issue.title }}\"\n\n# Good: Use environment variables\nexport TITLE=\"${{ github.event.issue.title }}\"\ngit commit -m \"$TITLE\"\n```\n\n---\n\n### 9. Dependency Confusion Prevention\n\n**Use Scoped Packages**\n\n```json\n{\n \"name\": \"@myorg/my-package\",\n \"private\": true\n}\n```\n\n**Namespace Protection**\n\n```bash\n# Reserve namespace on public registry\nnpm org create myorg\n```\n\n**Private Registry Configuration**\n\n```ini\n# .npmrc\n@myorg:registry=https://npm.internal.company.com/\n//npm.internal.company.com/:_authToken=${NPM_TOKEN}\n\n# Public packages still from public registry\nregistry=https://registry.npmjs.org/\n```\n\n---\n\n### 10. Incident Response\n\n**Detection**\n\n```bash\n# Check for compromised dependencies\nnpm audit\n\n# Verify package integrity\nnpm ls --depth=0\nnpm ls --all | grep -i \"suspicious\"\n\n# Check for unexpected network calls\nstrace -e trace=network npm install\n```\n\n**Response Playbook**\n\n1. **Isolate**: Stop deployments, quarantine affected systems\n2. **Identify**: Determine scope of compromise\n3. **Remediate**: Remove malicious dependencies, rotate credentials\n4. **Recover**: Deploy clean versions, verify integrity\n5. **Report**: Notify stakeholders, report to npm/GitHub security\n\n**SBOM-Driven Response**\n\n```bash\n# Check if your project uses compromised package\njq '.components[] | select(.name == \"compromised-package\")' sbom.json\n\n# Find all affected projects\nfind . -name sbom.json -exec grep -l \"compromised-package\" {} \\;\n```\n\n---\n\n## Best Practices Checklist\n\n**Authentication & Access**\n- [ ] Phishing-resistant MFA enabled on all developer accounts\n- [ ] Hardware security keys for critical accounts\n- [ ] Organization-wide MFA policy enforced\n- [ ] Periodic access reviews and key rotation\n\n**Dependency Management**\n- [ ] Exact version pinning (no semver ranges)\n- [ ] pnpm minimumReleaseAge or equivalent delay\n- [ ] Automated dependency updates with security review\n- [ ] Regular `npm audit` and SCA scans\n\n**Build Security**\n- [ ] Trusted publishing implemented (npm, PyPI, RubyGems)\n- [ ] SLSA Level 2+ provenance generation\n- [ ] Artifact signing with Sigstore\n- [ ] Hermetic builds with locked dependencies\n\n**Monitoring & Detection**\n- [ ] SBOM generation and tracking\n- [ ] Continuous vulnerability scanning\n- [ ] Real-time dependency monitoring\n- [ ] Alerting on new vulnerabilities\n\n**Incident Response**\n- [ ] Documented supply chain incident response plan\n- [ ] SBOM-driven impact analysis process\n- [ ] Communication plan for stakeholders\n- [ ] Regular incident response drills\n\n---\n\n## Tools Comparison\n\n| Tool | Focus | Best For |\n|------|-------|----------|\n| **Dependabot** | Automated updates | GitHub native integration |\n| **Snyk** | Vulnerability scanning | Developer-first workflows |\n| **Trivy** | Container + code scanning | Multi-artifact scanning |\n| **Grype** | Vulnerability detection | CLI-first, fast scanning |\n| **Syft** | SBOM generation | Comprehensive inventory |\n| **Sigstore** | Artifact signing | Keyless signing |\n| **SLSA** | Build provenance | End-to-end attestation |\n\n---\n\n## References\n\n- [OWASP Top 10:2025 - A03: Software Supply Chain Failures](https://owasp.org/Top10/2025/A03/)\n- [GitHub's Plan for a More Secure npm Supply Chain](https://github.blog/security/supply-chain-security/our-plan-for-a-more-secure-npm-supply-chain/)\n- [SLSA Framework](https://slsa.dev/)\n- [Sigstore Documentation](https://docs.sigstore.dev/)\n- [OpenSSF Best Practices](https://openssf.org/references/guides/)\n- [CISA Supply Chain Compromise Alerts](https://www.cisa.gov/topics/supply-chain-security)\n- [npm Security Best Practices](https://docs.npmjs.com/about-security-and-npm)\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":12794,"content_sha256":"e7c981b4e351a843df52528a7efc32b7cd73490bed937ba8c5cc99d03a07c0d3"},{"filename":"references/threat-modeling-guide.md","content":"# Threat Modeling Guide — Methodology and Practice (Jan 2026)\n\nPractical threat modeling for software teams. Covers STRIDE, PASTA, data flow diagrams, attack trees, risk scoring, and lightweight approaches for agile teams. Use threat modeling to find security design flaws before they become vulnerabilities in production.\n\n---\n\n## When to Threat Model\n\n| Trigger | Scope | Effort |\n|---------|-------|--------|\n| **New system or service** | Full system DFD, all trust boundaries | 2-4 hours |\n| **Major feature or architecture change** | Incremental: new components and data flows only | 1-2 hours |\n| **New third-party integration** | Integration boundary: data exchange, auth, trust | 30-60 min |\n| **Compliance requirement** (SOC 2, PCI, HIPAA) | Full system review per compliance scope | 4-8 hours |\n| **Post-incident** | Affected subsystem, re-evaluate assumptions | 1-2 hours |\n| **Sprint planning (lightweight)** | New user stories with security implications | 15-30 min |\n\n### When NOT to Threat Model\n\n- Minor UI changes with no data flow changes\n- Documentation-only updates\n- Dependency version bumps (use dependency scanning instead)\n- Bug fixes that don't change architecture or data flow\n\n---\n\n## STRIDE Methodology\n\nSTRIDE is Microsoft's threat classification framework. Each letter represents a threat category that maps to a security property violation.\n\n### STRIDE Categories\n\n| Threat | Security Property Violated | Example | Typical Mitigation |\n|--------|--------------------------|---------|-------------------|\n| **S**poofing | Authentication | Attacker impersonates a user or service | MFA, mTLS, certificate pinning |\n| **T**ampering | Integrity | Attacker modifies data in transit or at rest | HMAC, digital signatures, checksums |\n| **R**epudiation | Non-repudiation | User denies performing an action | Audit logging, digital signatures, timestamps |\n| **I**nformation Disclosure | Confidentiality | Sensitive data exposed to unauthorized party | Encryption (TLS, AES), access control, data classification |\n| **D**enial of Service | Availability | System rendered unavailable | Rate limiting, auto-scaling, CDN, circuit breakers |\n| **E**levation of Privilege | Authorization | User gains higher access than intended | RBAC/ABAC, least privilege, input validation |\n\n### Applying STRIDE\n\nFor each element in your data flow diagram, ask:\n\n```text\nFor [element]:\n S — Can an attacker pretend to be this element or its users?\n T — Can an attacker modify data flowing through or stored by this element?\n R — Can a user deny they performed an action through this element?\n I — Can an attacker read data they shouldn't from this element?\n D — Can an attacker make this element unavailable?\n E — Can an attacker gain unauthorized capabilities through this element?\n```\n\n### STRIDE-per-Element Matrix\n\n| DFD Element | S | T | R | I | D | E |\n|-------------|---|---|---|---|---|---|\n| External entity (user, service) | X | | | | | |\n| Process (application logic) | X | X | X | X | X | X |\n| Data store (database, file) | | X | | X | X | |\n| Data flow (API call, message) | | X | | X | X | |\n| Trust boundary | | | | | | X |\n\n---\n\n## PASTA — Process for Attack Simulation and Threat Analysis\n\nPASTA is a risk-centric, attacker-focused methodology with seven stages. It complements STRIDE by incorporating business context and attacker motivation.\n\n### Seven Stages\n\n| Stage | Activity | Output |\n|-------|----------|--------|\n| 1. Define Objectives | Identify business objectives and security requirements | Business impact analysis, compliance requirements |\n| 2. Define Technical Scope | Document application architecture, technologies, dependencies | Architecture diagrams, technology inventory |\n| 3. Application Decomposition | Create DFDs, identify trust boundaries, enumerate entry points | Data flow diagrams, attack surface inventory |\n| 4. Threat Analysis | Research relevant threats using threat intelligence | Threat library mapped to your application |\n| 5. Vulnerability Analysis | Map known vulnerabilities to attack surface | Vulnerability inventory, CVE mapping |\n| 6. Attack Modeling | Build attack trees, simulate attack scenarios | Attack trees, exploitation scenarios |\n| 7. Risk and Impact Analysis | Score risks, prioritize mitigations | Risk-ranked threat list, mitigation roadmap |\n\n### When to Use PASTA vs STRIDE\n\n| Criterion | STRIDE | PASTA |\n|-----------|--------|-------|\n| **Speed** | Fast (1-2 hours) | Thorough (4-8 hours) |\n| **Focus** | Technical threats per component | Business risk and attacker motivation |\n| **Best for** | Feature-level threat modeling | System-level or compliance-driven reviews |\n| **Team** | Engineering team | Cross-functional (eng + product + security) |\n| **Output** | Threat list per component | Risk-ranked roadmap with business justification |\n\n---\n\n## Data Flow Diagrams (DFDs)\n\nDFDs are the foundation of threat modeling. They visualize how data moves through your system and where trust boundaries exist.\n\n### DFD Elements\n\n| Symbol | Element | Description | Example |\n|--------|---------|-------------|---------|\n| Rectangle | External Entity | User, third-party system, browser | \"Mobile App User\" |\n| Circle | Process | Application logic that transforms data | \"Auth Service\" |\n| Parallel lines | Data Store | Database, file system, cache | \"PostgreSQL\" |\n| Arrow | Data Flow | Data moving between elements | \"HTTPS API call\" |\n| Dashed line | Trust Boundary | Security context change | \"Internet ↔ DMZ\" |\n\n### Example: Web Application DFD\n\n```text\n┌──────────────────────────────────── INTERNET ──────────────────────────────────┐\n│ │\n│ ┌─────────┐ HTTPS ┌──────────┐ │\n│ │ Browser │ ───────────────────────>│ CDN/WAF │ │\n│ └─────────┘ └────┬─────┘ │\n│ │ │\n├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ TRUST BOUNDARY ─ ─│─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┤\n│ │ │\n│ ┌────▼─────┐ ┌──────────┐ │\n│ │ API │──────>│ Auth │ │\n│ │ Gateway │\u003c──────│ Service │ │\n│ └────┬─────┘ └──────────┘ │\n│ │ │\n│ ┌────────────┼────────────┐ │\n│ │ │ │ │\n│ ┌────▼───┐ ┌─────▼────┐ ┌────▼───┐ │\n│ │ User │ │ Order │ │ Payment│ │\n│ │ Service│ │ Service │ │ Service│ │\n│ └────┬───┘ └─────┬────┘ └────┬───┘ │\n│ │ │ │ │\n├ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ DATA BOUNDARY ─ ─ ─│─ ─ ─ ─ ─ ─│─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┤\n│ │ │ │ │\n│ ┌────▼───┐ ┌─────▼────┐ ┌────▼───┐ │\n│ │Users DB│ │Orders DB │ │Payment │ │\n│ │ │ │ │ │ Gateway│ (external) │\n│ └────────┘ └──────────┘ └────────┘ │\n└────────────────────────────────────────────────────────────────────────────────┘\n```\n\n### Trust Boundaries to Identify\n\n| Boundary | What Changes | Threats to Consider |\n|----------|-------------|---------------------|\n| Internet → DMZ | From untrusted to semi-trusted | Spoofing, injection, DoS |\n| DMZ → Internal network | From semi-trusted to trusted | Lateral movement, SSRF |\n| Service → Database | From compute to data | SQL injection, access control |\n| Service → Service | Between microservices | Auth bypass, data tampering |\n| Internal → Third-party | From your control to external | Data leak, supply chain |\n| User → Admin | Privilege level change | Elevation of privilege |\n\n---\n\n## Attack Tree Construction\n\nAttack trees decompose a high-level attack goal into sub-goals, showing the different paths an attacker could take.\n\n### Structure\n\n```text\nGOAL: Steal user payment data\n├─ AND: Gain access to payment database\n│ ├─ OR: SQL injection via search endpoint\n│ │ ├─ Find unparameterized query\n│ │ └─ Bypass WAF rules\n│ ├─ OR: Compromise database credentials\n│ │ ├─ Extract from environment variables\n│ │ ├─ Find in source code / config files\n│ │ └─ Intercept connection string in transit\n│ └─ OR: Exploit SSRF to reach internal database\n│ ├─ Find URL parameter that fetches external resources\n│ └─ Bypass SSRF filters (DNS rebinding, IP encoding)\n├─ AND: Exfiltrate data without detection\n│ ├─ OR: Disable or evade logging\n│ ├─ OR: Use legitimate-looking queries (low and slow)\n│ └─ OR: Exfiltrate through DNS or ICMP channels\n└─ OR: Intercept data in transit\n ├─ TLS downgrade attack\n ├─ Compromise TLS certificate\n └─ Man-in-the-middle via compromised network\n```\n\n### Building Effective Attack Trees\n\n1. Start with the attacker's goal (what they want to achieve)\n2. Decompose into AND/OR nodes (what they need to do)\n3. Continue decomposing until leaf nodes are actionable attack steps\n4. Annotate each leaf with: difficulty (Low/Medium/High), detection likelihood, impact\n5. Identify the cheapest/easiest path — that is what gets exploited first\n\n---\n\n## Threat Modeling for Microservices\n\nMicroservices introduce unique threat modeling concerns not present in monolithic applications.\n\n### Microservices-Specific Threats\n\n| Component | Threats | Mitigations |\n|-----------|---------|-------------|\n| **Service-to-service calls** | Auth bypass, data tampering, replay attacks | mTLS, JWT propagation, request signing |\n| **API gateway** | Single point of failure, auth bypass, rate limit evasion | Redundancy, defense in depth, per-service auth |\n| **Message queues** (Kafka, RabbitMQ) | Message injection, eavesdropping, replay | Encryption in transit, message signing, access control |\n| **Service mesh** (Istio, Linkerd) | Sidecar bypass, control plane compromise | mTLS enforcement, RBAC policies, network policies |\n| **Shared databases** | Cross-service data access, schema confusion | Database-per-service, schema isolation, row-level security |\n| **Service discovery** | Poisoned service registry, DNS spoofing | Authenticated registration, signed service records |\n| **Distributed config** (Consul, etcd) | Secret exposure, config tampering | Encryption at rest, access control, audit logging |\n\n### Microservices DFD Pattern\n\n```text\nFor each service boundary, document:\n1. Inbound data flows: who calls this service, with what auth?\n2. Outbound data flows: what does this service call?\n3. Data stores: what data does this service own?\n4. Shared resources: caches, queues, config stores\n5. Trust level: does this service handle PII, financial data, admin operations?\n```\n\n---\n\n## Threat Modeling for Web Applications\n\n### Standard Web App DFD Components\n\n| Component | STRIDE Focus | Key Questions |\n|-----------|-------------|---------------|\n| Client (browser) | S, T, I | Can client-side code be tampered? Is sensitive data stored client-side? |\n| CDN/Edge | D, T | Can cached content be poisoned? Is edge config secure? |\n| Load balancer | D, S | Can health checks be spoofed? Is TLS terminated securely? |\n| Web server | S, T, R, I, D, E | All STRIDE categories apply to the core application |\n| Session store | S, T, I | Can sessions be hijacked? Is session data encrypted? |\n| Database | T, I, D | SQL injection? Encryption at rest? Backup security? |\n| File storage | T, I | Path traversal? Upload validation? Access control? |\n| Email service | S, R | Can email be spoofed? Are transactional emails logged? |\n| Payment processor | S, T, I | Is communication encrypted? Are webhooks verified? |\n\n---\n\n## Risk Scoring\n\n### CVSS (Common Vulnerability Scoring System)\n\nCVSS v3.1 is the industry standard for vulnerability severity scoring.\n\n| Metric Group | Factors | Purpose |\n|-------------|---------|---------|\n| **Base** | Attack vector, complexity, privileges, user interaction, scope, CIA impact | Intrinsic severity |\n| **Temporal** | Exploit maturity, remediation level, report confidence | Current real-world risk |\n| **Environmental** | Modified base metrics, CIA requirements | Organization-specific context |\n\n| Score Range | Severity | Typical Response |\n|-------------|----------|-----------------|\n| 9.0 - 10.0 | Critical | Patch within 24 hours, P0 incident |\n| 7.0 - 8.9 | High | Patch within 7 days, P1 |\n| 4.0 - 6.9 | Medium | Patch within 30 days, P2 |\n| 0.1 - 3.9 | Low | Patch in next release, P3 |\n\n### DREAD (Simplified Risk Model)\n\nDREAD is simpler than CVSS and useful for threat model workshops where CVSS is too granular.\n\n| Factor | Question | Score |\n|--------|----------|-------|\n| **D**amage | How bad is the impact? | 1-10 |\n| **R**eproducibility | How easy to reproduce? | 1-10 |\n| **E**xploitability | How easy to exploit? | 1-10 |\n| **A**ffected users | How many users impacted? | 1-10 |\n| **D**iscoverability | How easy to find? | 1-10 |\n\n**Risk Score** = (D + R + E + A + D) / 5\n\n| Score | Risk Level | Action |\n|-------|-----------|--------|\n| 8-10 | Critical | Fix immediately |\n| 5-7 | High | Fix in current sprint |\n| 3-4 | Medium | Fix in next sprint |\n| 1-2 | Low | Backlog |\n\n### Custom Risk Matrix\n\nFor organizations that need a tailored approach:\n\n```text\nRisk = Likelihood × Impact\n\nLIKELIHOOD:\n 5 — Almost certain (will happen within months)\n 4 — Likely (known exploits exist, low skill required)\n 3 — Possible (exploits require moderate skill)\n 2 — Unlikely (requires significant effort or insider access)\n 1 — Rare (theoretical, no known exploits)\n\nIMPACT:\n 5 — Catastrophic (full data breach, regulatory penalties, existential)\n 4 — Major (significant data exposure, service outage >4 hours)\n 3 — Moderate (limited data exposure, service degradation)\n 2 — Minor (minimal data exposure, brief disruption)\n 1 — Negligible (no data exposure, no user impact)\n```\n\n| | Impact 1 | Impact 2 | Impact 3 | Impact 4 | Impact 5 |\n|---|---------|---------|---------|---------|---------|\n| **Likelihood 5** | 5 (Med) | 10 (High) | 15 (High) | 20 (Crit) | 25 (Crit) |\n| **Likelihood 4** | 4 (Med) | 8 (High) | 12 (High) | 16 (Crit) | 20 (Crit) |\n| **Likelihood 3** | 3 (Low) | 6 (Med) | 9 (High) | 12 (High) | 15 (High) |\n| **Likelihood 2** | 2 (Low) | 4 (Med) | 6 (Med) | 8 (High) | 10 (High) |\n| **Likelihood 1** | 1 (Low) | 2 (Low) | 3 (Low) | 4 (Med) | 5 (Med) |\n\n---\n\n## Tooling\n\n| Tool | Type | Best For | Cost |\n|------|------|----------|------|\n| **Microsoft Threat Modeling Tool** | Desktop app | STRIDE-based DFD modeling, Windows teams | Free |\n| **OWASP Threat Dragon** | Web/desktop | Open source, cross-platform DFD + threats | Free |\n| **IriusRisk** | SaaS platform | Enterprise, automated threat libraries, compliance mapping | Paid |\n| **Threagile** | CLI (Go) | Infrastructure-as-code threat models, YAML-based | Free |\n| **draw.io / diagrams.net** | Diagramming | Quick DFDs when specialized tools are unavailable | Free |\n| **Miro / FigJam** | Collaborative whiteboard | Remote team workshops, low-fidelity DFDs | Free/Paid |\n\n### Tool Selection Decision\n\n```text\nTeam size and budget:\n ├─ Solo or small team, no budget\n │ └─ OWASP Threat Dragon or draw.io\n ├─ Engineering team, standard process needed\n │ └─ Microsoft Threat Modeling Tool (Windows) or Threagile (CLI)\n ├─ Enterprise, compliance requirements\n │ └─ IriusRisk (automated libraries, audit trail)\n └─ Remote workshop, collaborative session\n └─ Miro or FigJam with DFD template\n```\n\n---\n\n## Lightweight Threat Modeling for Agile Teams\n\nFull STRIDE analysis for every sprint is impractical. Use this 15-minute approach for stories with security implications.\n\n### The 15-Minute Threat Model\n\nRun during sprint planning or design review for any story that:\n- Adds a new API endpoint or data store\n- Changes authentication, authorization, or data flow\n- Integrates a new third-party service\n- Handles PII, financial data, or credentials\n\n```text\nSTEP 1: WHAT ARE WE BUILDING? (3 min)\n- Sketch the data flow on a whiteboard or shared doc\n- Identify: inputs, outputs, data stores, external services\n\nSTEP 2: WHAT CAN GO WRONG? (7 min)\n- Walk through STRIDE for each new/changed component:\n S: Can someone pretend to be someone else?\n T: Can data be modified without detection?\n R: Can someone deny they did something?\n I: Can sensitive data leak?\n D: Can this be taken down?\n E: Can someone get more access than intended?\n\nSTEP 3: WHAT ARE WE GOING TO DO ABOUT IT? (5 min)\n- For each identified threat:\n - Accept (risk is low and within tolerance)\n - Mitigate (add control as part of this story)\n - Defer (create a follow-up security story with justification)\n\nDOCUMENT:\n| Threat | STRIDE | Risk | Action | Owner |\n|--------|--------|------|--------|-------|\n| [threat] | [S/T/R/I/D/E] | [H/M/L] | [Accept/Mitigate/Defer] | [Name] |\n```\n\n### Security Story Template\n\nWhen a threat requires a separate story:\n\n```text\nAS A security engineer,\nI WANT [specific mitigation],\nSO THAT [specific threat] is addressed.\n\nACCEPTANCE CRITERIA:\n- [ ] [Specific, testable security requirement]\n- [ ] [Specific, testable security requirement]\n\nTHREAT CONTEXT:\n- Identified in threat model for [feature]\n- STRIDE category: [S/T/R/I/D/E]\n- Risk score: [H/M/L]\n```\n\n---\n\n## Anti-Patterns\n\n| Anti-Pattern | Why It Fails | Correct Approach |\n|-------------|-------------|------------------|\n| Threat model once, never update | Architecture changes invalidate old model | Re-model on significant architecture changes |\n| Model everything in one session | Fatigue leads to shallow analysis | Scope to specific components or changes |\n| Only security team does threat modeling | Developers know the system best | Collaborative session: devs + security |\n| No follow-through on findings | Threats identified but never mitigated | Track mitigations as backlog items with owners |\n| Focus only on external threats | Insider threats and misconfiguration ignored | Include internal actors and operational errors |\n| Perfect DFD before any analysis | Delays analysis indefinitely | \"Good enough\" DFD; refine as you model |\n| CVSS score without context | 7.5 in isolated system != 7.5 in payment service | Apply environmental scoring to your context |\n| Threat modeling as checkbox exercise | No real threats identified or mitigated | Judge by mitigations shipped, not documents produced |\n\n---\n\n## Threat Model Review Checklist\n\n- [ ] DFD covers all components, data stores, and external services\n- [ ] Trust boundaries are explicitly marked\n- [ ] Each component has been analyzed with STRIDE (or chosen methodology)\n- [ ] Identified threats are scored (CVSS, DREAD, or custom risk matrix)\n- [ ] Each threat has a disposition: Accept, Mitigate, Transfer, or Avoid\n- [ ] Mitigations are assigned to specific owners with deadlines\n- [ ] Model is stored in version control or accessible repository\n- [ ] Model includes date and trigger for next review\n\n---\n\n## References\n\n- [Microsoft STRIDE](https://learn.microsoft.com/en-us/azure/security/develop/threat-modeling-tool-threats)\n- [OWASP Threat Modeling](https://owasp.org/www-community/Threat_Modeling)\n- [OWASP Threat Dragon](https://owasp.org/www-project-threat-dragon/)\n- [PASTA Threat Modeling](https://versprite.com/tag/pasta-threat-modeling/)\n- [Shostack, Adam. Threat Modeling: Designing for Security. Wiley, 2014.](https://shostack.org/books/threat-modeling-book)\n- [NIST SP 800-154 — Guide to Data-Centric Threat Modeling](https://csrc.nist.gov/pubs/sp/800/154/ipd)\n\n---\n\n## Cross-References\n\n- [SKILL.md](../SKILL.md) — Parent skill overview, threat modeling mentioned in decision tree and OWASP A06\n- [secure-design-principles.md](secure-design-principles.md) — Defense in depth, least privilege principles\n- [owasp-top-10.md](owasp-top-10.md) — A06: Insecure Design (threat modeling as primary control)\n- [api-security-patterns.md](api-security-patterns.md) — API-specific threats for API components in DFDs\n- [incident-response-playbook.md](incident-response-playbook.md) — Post-incident threat model review trigger\n- [zero-trust-architecture.md](zero-trust-architecture.md) — Trust boundary design and zero-trust principles\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":22195,"content_sha256":"02e37ca1ef8a228f4823f6f6c15a07874ffbeedd80ca6bbcce44e237d338a739"},{"filename":"references/zero-trust-architecture.md","content":"# Zero Trust Architecture — Implementation Guide\n\nModern security architecture based on \"never trust, always verify\" principles for cloud-native and distributed systems (Jan 2026).\n\n---\n\n## Overview\n\nZero Trust Architecture (ZTA) eliminates implicit trust based on network location, requiring continuous verification of all users, devices, and services regardless of their position relative to network perimeters.\n\n**Key Principle**: Never trust, always verify.\n\n---\n\n## 2026 Updates\n\n### NSA Zero Trust Implementation Guidelines (ZIGs) — January 2026\n\nThe NSA released the first products in the Zero Trust Implementation Guidelines (ZIGs) series on January 14, 2026:\n\n1. **Primer**: Strategy and principles for ZT implementation\n2. **Discovery Phase**: Guidance for beginning ZT journey\n\nKey recommendations:\n\n- Start with identity pillar (strongest security impact)\n- Implement continuous diagnostics and monitoring (CDM)\n- Deploy micro-segmentation incrementally\n- Integrate AI/ML for behavioral analytics and SOAR\n\n### Pentagon Zero Trust Strategy 2.0 (Expected March 2026)\n\nDoD zero trust requirements for FY2027:\n\n- **91 capability outcomes** for target ZT on unclassified/secret networks\n- **61 additional outcomes** for advanced ZT by FY2032\n- Expansion to OT, IoT, defense critical infrastructure, weapon systems\n\n### AI Integration with Zero Trust\n\n2026 organizations implementing Zero Trust with AI report:\n\n- **76% fewer successful breaches**\n- **Incident response time**: Days → Minutes\n- **Behavioral analytics**: Real-time anomaly detection\n- **SOAR integration**: Automated response workflows\n\n---\n\n## NIST Zero Trust Principles (SP 800-207)\n\n1. **All data sources and services are resources**\n2. **Communication is secured regardless of network location**\n3. **Access to resources is granted per-session**\n4. **Access decisions are dynamic and policy-based**\n5. **Enterprise monitors and measures security posture**\n6. **Authentication and authorization are strict before access**\n7. **Collect as much information as possible for security posture**\n\n---\n\n## CISA Zero Trust Maturity Model\n\n### Five Pillars\n\n1. **Identity**: User and device authentication\n2. **Devices**: Endpoint security and compliance\n3. **Networks**: Encrypted, segmented communication\n4. **Applications**: Secure app access and APIs\n5. **Data**: Data classification and protection\n\n### Maturity Levels\n\n- **Traditional**: Perimeter-based security\n- **Initial**: Beginning zero trust implementation\n- **Advanced**: Comprehensive zero trust controls\n- **Optimal**: Fully automated, dynamic zero trust\n\n---\n\n## Architecture Components\n\n### 1. Identity and Access Management (IAM)\n\n**Single Sign-On (SSO)**\n\n```javascript\n// OAuth 2.0 + OpenID Connect flow\nconst express = require('express');\nconst passport = require('passport');\nconst OIDCStrategy = require('passport-azure-ad').OIDCStrategy;\n\npassport.use(new OIDCStrategy({\n identityMetadata: 'https://login.microsoftonline.com/tenant/.well-known/openid-configuration',\n clientID: process.env.CLIENT_ID,\n responseType: 'code id_token',\n responseMode: 'form_post',\n redirectUrl: 'https://app.example.com/auth/callback',\n allowHttpForRedirectUrl: false,\n clientSecret: process.env.CLIENT_SECRET,\n validateIssuer: true,\n issuer: 'https://sts.windows.net/tenant-id/',\n passReqToCallback: false,\n scope: ['profile', 'email', 'openid']\n}, (iss, sub, profile, accessToken, refreshToken, done) => {\n // Verify user and create session\n return done(null, profile);\n}));\n\napp.get('/auth/login',\n passport.authenticate('azuread-openidconnect', {\n failureRedirect: '/login'\n })\n);\n```\n\n**Multi-Factor Authentication (MFA)**\n\n```javascript\n// Verify MFA token\nconst speakeasy = require('speakeasy');\n\nconst verifyMFA = (token, secret) => {\n return speakeasy.totp.verify({\n secret: secret,\n encoding: 'base32',\n token: token,\n window: 1 // Allow 1 time step before/after for clock drift\n });\n};\n\n// Middleware requiring MFA\nconst requireMFA = async (req, res, next) => {\n if (!req.user.mfaEnabled) {\n return res.status(403).json({\n error: 'MFA required but not enabled'\n });\n }\n\n const token = req.headers['x-mfa-token'];\n if (!token || !verifyMFA(token, req.user.mfaSecret)) {\n return res.status(401).json({ error: 'Invalid MFA token' });\n }\n\n next();\n};\n```\n\n---\n\n### 2. Device Security\n\n**Device Posture Assessment**\n\n```javascript\n// Device trust verification middleware\nconst assessDeviceTrust = async (req, res, next) => {\n const deviceId = req.headers['x-device-id'];\n const device = await DeviceRegistry.findById(deviceId);\n\n if (!device) {\n return res.status(403).json({\n error: 'Unknown device'\n });\n }\n\n // Check device compliance\n const checks = {\n osUpdated: device.osVersion >= MIN_OS_VERSION,\n antivirus: device.antivirusEnabled && device.antivirusUpdated,\n encrypted: device.diskEncrypted,\n jailbroken: !device.jailbroken,\n lastSeen: Date.now() - device.lastSeenAt \u003c 24 * 60 * 60 * 1000\n };\n\n const trustScore = Object.values(checks).filter(Boolean).length / Object.keys(checks).length;\n\n if (trustScore \u003c 0.8) {\n return res.status(403).json({\n error: 'Device does not meet security requirements',\n violations: Object.entries(checks)\n .filter(([key, value]) => !value)\n .map(([key]) => key)\n });\n }\n\n req.deviceTrustScore = trustScore;\n next();\n};\n\napp.use('/api', assessDeviceTrust);\n```\n\n---\n\n### 3. Network Segmentation\n\n**Micro-Segmentation with Service Mesh (Istio)**\n\n```yaml\n# Authorization policy - deny by default\napiVersion: security.istio.io/v1beta1\nkind: AuthorizationPolicy\nmetadata:\n name: deny-all\n namespace: production\nspec:\n {} # Empty spec = deny all\n\n---\n# Allow specific service-to-service communication\napiVersion: security.istio.io/v1beta1\nkind: AuthorizationPolicy\nmetadata:\n name: frontend-to-backend\n namespace: production\nspec:\n selector:\n matchLabels:\n app: backend\n action: ALLOW\n rules:\n - from:\n - source:\n principals: [\"cluster.local/ns/production/sa/frontend\"]\n to:\n - operation:\n methods: [\"GET\", \"POST\"]\n paths: [\"/api/*\"]\n```\n\n**Mutual TLS (mTLS)**\n\n```yaml\n# Istio PeerAuthentication - enforce mTLS\napiVersion: security.istio.io/v1beta1\nkind: PeerAuthentication\nmetadata:\n name: default\n namespace: production\nspec:\n mtls:\n mode: STRICT # Require mTLS for all traffic\n```\n\n**Application-Level mTLS**\n\n```javascript\n// Node.js HTTPS server with client certificate verification\nconst https = require('https');\nconst fs = require('fs');\n\nconst options = {\n key: fs.readFileSync('server-key.pem'),\n cert: fs.readFileSync('server-cert.pem'),\n ca: fs.readFileSync('ca-cert.pem'),\n requestCert: true,\n rejectUnauthorized: true\n};\n\nhttps.createServer(options, (req, res) => {\n const cert = req.socket.getPeerCertificate();\n\n if (!req.client.authorized) {\n return res.writeHead(401).end('Unauthorized');\n }\n\n // Verify certificate subject\n if (cert.subject.CN !== 'authorized-client') {\n return res.writeHead(403).end('Forbidden');\n }\n\n res.writeHead(200);\n res.end('Authenticated via mTLS');\n}).listen(8443);\n```\n\n---\n\n### 4. Policy-Based Access Control\n\n**Open Policy Agent (OPA) Integration**\n\n```javascript\n// OPA policy enforcement middleware\nconst axios = require('axios');\n\nconst enforcePolicy = (resource, action) => {\n return async (req, res, next) => {\n const input = {\n user: {\n id: req.user.id,\n roles: req.user.roles,\n groups: req.user.groups\n },\n resource: resource,\n action: action,\n context: {\n time: new Date().toISOString(),\n ip: req.ip,\n deviceTrustScore: req.deviceTrustScore\n }\n };\n\n try {\n const response = await axios.post('http://opa:8181/v1/data/authz/allow', {\n input\n });\n\n if (!response.data.result) {\n return res.status(403).json({\n error: 'Access denied by policy'\n });\n }\n\n next();\n } catch (error) {\n logger.error('OPA evaluation failed', error);\n return res.status(500).json({\n error: 'Policy evaluation failed'\n });\n }\n };\n};\n\n// Usage\napp.delete('/api/users/:id',\n authenticate,\n enforcePolicy('user', 'delete'),\n deleteUser\n);\n```\n\n**OPA Policy (Rego)**\n\n```rego\n# authz.rego\npackage authz\n\nimport future.keywords.if\n\ndefault allow = false\n\n# Allow if user is admin\nallow if {\n input.user.roles[_] == \"admin\"\n}\n\n# Allow user delete if:\n# 1. User is manager\n# 2. Request is during business hours\n# 3. Device trust score > 0.9\nallow if {\n input.resource == \"user\"\n input.action == \"delete\"\n input.user.roles[_] == \"manager\"\n is_business_hours\n input.context.deviceTrustScore > 0.9\n}\n\nis_business_hours if {\n time.weekday(input.context.time) >= 1\n time.weekday(input.context.time) \u003c= 5\n hour := time.clock(input.context.time)[0]\n hour >= 9\n hour \u003c 17\n}\n```\n\n---\n\n### 5. Workload Identity\n\n**SPIFFE/SPIRE Implementation**\n\n```yaml\n# Kubernetes workload identity\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n name: backend-service\n namespace: production\n\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n name: backend\nspec:\n template:\n spec:\n serviceAccountName: backend-service\n containers:\n - name: backend\n image: backend:v1\n env:\n - name: SPIFFE_ENDPOINT_SOCKET\n value: unix:///run/spire/sockets/agent.sock\n volumeMounts:\n - name: spire-agent-socket\n mountPath: /run/spire/sockets\n readOnly: true\n volumes:\n - name: spire-agent-socket\n hostPath:\n path: /run/spire/sockets\n type: Directory\n```\n\n**Retrieve Workload Identity**\n\n```javascript\n// Get SVID (SPIFFE Verifiable Identity Document)\nconst { SpiffeWorkloadApi } = require('@spiffe/node-spiffe');\n\nconst getWorkloadIdentity = async () => {\n const client = new SpiffeWorkloadApi();\n const svid = await client.fetchX509Svid();\n\n return {\n spiffeId: svid.spiffeId.toString(),\n certificate: svid.certificate,\n privateKey: svid.privateKey\n };\n};\n\n// Use SVID for mTLS\nconst identity = await getWorkloadIdentity();\nconst tlsOptions = {\n cert: identity.certificate,\n key: identity.privateKey\n};\n```\n\n---\n\n### 6. Just-In-Time (JIT) Access\n\n**Temporary Privilege Elevation**\n\n```javascript\n// JIT access grant system\nconst grantTemporaryAccess = async (userId, resource, duration) => {\n const grant = {\n userId,\n resource,\n grantedAt: Date.now(),\n expiresAt: Date.now() + duration,\n status: 'active'\n };\n\n await AccessGrants.create(grant);\n\n // Schedule automatic revocation\n setTimeout(async () => {\n await AccessGrants.updateOne(\n { _id: grant._id },\n { status: 'expired' }\n );\n await auditLog('jit_access_expired', grant);\n }, duration);\n\n return grant;\n};\n\n// Verify temporary access\nconst checkJITAccess = async (req, res, next) => {\n const grant = await AccessGrants.findOne({\n userId: req.user.id,\n resource: req.path,\n status: 'active',\n expiresAt: { $gt: Date.now() }\n });\n\n if (!grant) {\n return res.status(403).json({\n error: 'No active temporary access grant'\n });\n }\n\n next();\n};\n\n// Request temporary admin access\napp.post('/api/access/request', authenticate, async (req, res) => {\n const { resource, reason, duration } = req.body;\n\n // Require manager approval\n const approval = await requestApproval({\n requestedBy: req.user.id,\n resource,\n reason,\n duration\n });\n\n if (!approval.approved) {\n return res.status(403).json({\n error: 'Access request denied',\n reason: approval.reason\n });\n }\n\n const grant = await grantTemporaryAccess(\n req.user.id,\n resource,\n duration\n );\n\n res.json({ grant });\n});\n```\n\n---\n\n### 7. Continuous Monitoring\n\n**Security Event Logging**\n\n```javascript\n// Comprehensive security event logging\nconst logSecurityEvent = async (event) => {\n const securityEvent = {\n timestamp: new Date(),\n eventType: event.type,\n severity: event.severity,\n user: {\n id: event.userId,\n ip: event.ip,\n deviceId: event.deviceId\n },\n action: event.action,\n resource: event.resource,\n outcome: event.outcome,\n context: {\n userAgent: event.userAgent,\n geoLocation: event.geoLocation,\n deviceTrustScore: event.deviceTrustScore\n }\n };\n\n await SecurityEvents.create(securityEvent);\n\n // Alert on suspicious activity\n if (event.severity === 'high' || event.outcome === 'denied') {\n await alertSecurityTeam(securityEvent);\n }\n};\n\n// Middleware to log all security-relevant events\napp.use((req, res, next) => {\n res.on('finish', () => {\n logSecurityEvent({\n type: 'api_access',\n severity: res.statusCode >= 400 ? 'high' : 'low',\n userId: req.user?.id,\n ip: req.ip,\n deviceId: req.headers['x-device-id'],\n action: req.method,\n resource: req.path,\n outcome: res.statusCode \u003c 400 ? 'allowed' : 'denied',\n userAgent: req.headers['user-agent']\n });\n });\n next();\n});\n```\n\n---\n\n## Implementation Roadmap\n\n### Phase 1: Foundation (0-3 months)\n- [ ] Implement SSO with MFA\n- [ ] Deploy device management platform\n- [ ] Enable basic network segmentation\n- [ ] Establish security logging\n\n### Phase 2: Advanced Controls (3-6 months)\n- [ ] Deploy service mesh with mTLS\n- [ ] Implement policy-based access control (OPA)\n- [ ] Deploy workload identity (SPIFFE/SPIRE)\n- [ ] Enable continuous device posture assessment\n\n### Phase 3: Optimization (6-12 months)\n- [ ] Implement JIT access\n- [ ] Deploy behavioral analytics\n- [ ] Automate policy enforcement\n- [ ] Full zero trust coverage across all systems\n\n---\n\n## Best Practices\n\n**Identity**\n- Enforce MFA on all accounts\n- Use short-lived credentials (\u003c 1 hour)\n- Implement adaptive authentication based on risk\n- Regular access reviews and least privilege enforcement\n\n**Network**\n- Default deny all traffic\n- Encrypt all communication (TLS 1.3+, mTLS)\n- Micro-segmentation at service level\n- Monitor and log all network flows\n\n**Access Control**\n- Dynamic, context-aware authorization\n- Time-boxed access grants\n- Require re-authentication for sensitive operations\n- Audit all access decisions\n\n**Monitoring**\n- Log all authentication and authorization events\n- Correlate events across identity, device, and network\n- Automated anomaly detection\n- Real-time alerting on policy violations\n\n---\n\n## Tools and Technologies\n\n| Component | Tools |\n|-----------|-------|\n| **Identity Provider** | Okta, Auth0, Azure AD, Keycloak |\n| **Device Management** | Jamf, Intune, Workspace ONE |\n| **Service Mesh** | Istio, Linkerd, Consul Connect |\n| **Policy Engine** | Open Policy Agent (OPA), Styra |\n| **Workload Identity** | SPIFFE/SPIRE, Vault |\n| **SIEM** | Splunk, Elastic Security, Chronicle |\n\n---\n\n## References\n\n- [NIST SP 800-207: Zero Trust Architecture](https://csrc.nist.gov/publications/detail/sp/800-207/final)\n- [CISA Zero Trust Maturity Model](https://www.cisa.gov/zero-trust-maturity-model)\n- [Google BeyondCorp Papers](https://cloud.google.com/beyondcorp)\n- [SPIFFE Specification](https://spiffe.io/docs/)\n- [Open Policy Agent Documentation](https://www.openpolicyagent.org/docs/)\n- [Istio Security](https://istio.io/latest/docs/concepts/security/)\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":15316,"content_sha256":"813f9340587b7e5b1ee5cb44c319a2a980135614aced072df9fc6e4c8213233c"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"Software Security & AppSec — Quick Reference","type":"text"}]},{"type":"paragraph","content":[{"text":"Production-grade security patterns for building secure applications in Jan 2026. Covers OWASP Top 10:2025 (stable) https://owasp.org/Top10/2025/ plus OWASP API Security Top 10 (2023) https://owasp.org/API-Security/ and secure SDLC baselines (NIST SSDF) https://csrc.nist.gov/publications/detail/sp/800-218/final.","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"When to Use This Skill","type":"text"}]},{"type":"paragraph","content":[{"text":"Activate this skill when:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implementing authentication or authorization systems","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Handling user input that could lead to injection attacks (SQL, XSS, command injection)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Designing secure APIs or web applications","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Working with cryptographic operations or sensitive data storage","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conducting security reviews, threat modeling, or vulnerability assessments","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Responding to security incidents or compliance audit requirements","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Building systems that must comply with OWASP, NIST, PCI DSS, GDPR, HIPAA, or SOC 2","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Integrating third-party dependencies (supply chain security review)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implementing zero trust architecture or modern cloud-native security patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Establishing or improving secure SDLC gates (threat modeling, SAST/DAST, dependency scanning)","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"When NOT to Use This Skill","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"General backend development","type":"text","marks":[{"type":"strong"}]},{"text":" without security focus → use ","type":"text"},{"text":"software-backend","type":"text","marks":[{"type":"link","attrs":{"href":"../software-backend/SKILL.md","title":null}}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Infrastructure/cloud security","type":"text","marks":[{"type":"strong"}]},{"text":" (IAM, network security, container hardening) → use ","type":"text"},{"text":"ops-devops-platform","type":"text","marks":[{"type":"link","attrs":{"href":"../ops-devops-platform/SKILL.md","title":null}}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Smart contract auditing","type":"text","marks":[{"type":"strong"}]},{"text":" as primary focus → use ","type":"text"},{"text":"software-crypto-web3","type":"text","marks":[{"type":"link","attrs":{"href":"../software-crypto-web3/SKILL.md","title":null}}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"ML model security","type":"text","marks":[{"type":"strong"}]},{"text":" (adversarial attacks, data poisoning) → use ","type":"text"},{"text":"ai-mlops","type":"text","marks":[{"type":"link","attrs":{"href":"../ai-mlops/SKILL.md","title":null}}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Compliance-only questions","type":"text","marks":[{"type":"strong"}]},{"text":" without implementation → consult compliance team directly","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Quick Reference Table","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Security Task","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Tool/Pattern","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Implementation","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"When to Use","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Primary Auth","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Passkeys/WebAuthn","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"navigator.credentials.create()","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"New apps (2026+), phishing-resistant, broad platform support","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Password Storage","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"bcrypt/Argon2","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"bcrypt.hash(password, 12)","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Legacy auth fallback (never store plaintext)","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Input Validation","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Allowlist regex","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"/^[a-zA-Z0-9_]{3,20}$/","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"All user input (SQL, XSS, command injection prevention)","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SQL Queries","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Parameterized queries","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"db.execute(query, [userId])","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"All database operations (prevent SQL injection)","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"API Authentication","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"OAuth 2.1 + PKCE","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"oauth.authorize({ code_challenge })","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Third-party auth, API access (deprecates implicit flow)","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Token Auth","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"JWT (short-lived)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"jwt.sign(payload, secret, { expiresIn: '15m' })","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Stateless APIs (always validate, 15-30 min expiry)","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Data Encryption","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"AES-256-GCM","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"crypto.createCipheriv('aes-256-gcm')","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Sensitive data at rest (PII, financial, health)","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"HTTPS/TLS","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"TLS 1.3","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Force HTTPS redirects","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"All production traffic (data in transit)","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Access Control","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"RBAC/ABAC","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"requireRole('admin', 'moderator')","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Resource authorization (APIs, admin panels)","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Rate Limiting","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"express-rate-limit","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"limiter({ windowMs: 15min, max: 100 })","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Public APIs, auth endpoints (DoS prevention)","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Security Requirements","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"OWASP ASVS","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Choose L1/L2/L3","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Security requirements baseline + test scope","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Authentication Decision Matrix (Jan 2026)","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Method","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Use Case","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Token Lifetime","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Security Level","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Notes","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Passkeys/WebAuthn","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Primary auth (2026+)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"N/A (cryptographic)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Highest","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Phishing-resistant, broad platform support","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"OAuth 2.1 + PKCE","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Third-party auth","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"5-15 min access","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"High","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Replaces implicit flow, mandatory PKCE","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Session cookies","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Traditional web apps","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"30 min - 4 hrs","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Medium-High","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"HttpOnly, Secure, SameSite=Strict","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"JWT stateless","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"APIs, microservices","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"15-30 min","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Medium","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Always validate signature, short expiry","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"API keys","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Machine-to-machine","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Long-lived","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Low-Medium","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Rotate regularly, scope permissions","type":"text"}]}]}]}]},{"type":"paragraph","content":[{"text":"Jurisdiction notes (verify):","type":"text","marks":[{"type":"strong"}]},{"text":" Authentication assurance requirements vary by country, industry, and buyer. Prefer passkeys/FIDO2; treat SMS OTP as recovery-only/low assurance unless you can justify it.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"OWASP Top 10:2025 Quick Checklist","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"#","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Risk","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Key Controls","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Test","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A01","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Broken Access Control","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"RBAC/ABAC, deny by default, CORS allowlist","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"BOLA, BFLA, privilege escalation","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A02","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Security Misconfiguration","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Harden defaults, disable unused features, error handling","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Default creds, stack traces, headers","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A03","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Supply Chain Failures","type":"text","marks":[{"type":"strong"}]},{"text":" (NEW)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SBOM, dependency scanning, SLSA, code signing","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Outdated deps, typosquatting, compromised packages","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A04","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Cryptographic Failures","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"TLS 1.3, AES-256-GCM, key rotation, no MD5/SHA1","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Weak ciphers, exposed secrets, cert validation","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A05","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Injection","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Parameterized queries, input validation, output encoding","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SQLi, XSS, command injection, LDAP injection","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A06","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Insecure Design","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Threat modeling, secure design patterns, abuse cases","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Design flaws, missing controls, trust boundaries","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A07","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Authentication Failures","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"MFA/passkeys, rate limiting, secure password storage","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Credential stuffing, brute force, session fixation","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A08","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Integrity Failures","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Code signing, CI/CD pipeline security, SRI","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Unsigned updates, pipeline poisoning, CDN tampering","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A09","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Logging Failures","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Structured JSON, SIEM integration, correlation IDs","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Missing logs, PII in logs, no alerting","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"A10","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Exceptional Conditions","type":"text","marks":[{"type":"strong"}]},{"text":" (NEW)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Fail-safe defaults, complete error recovery, input validation","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Error handling gaps, fail-open, resource exhaustion","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Decision Tree: Security Implementation","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"text"},"content":[{"text":"Security requirement: [Feature Type]\n ├─ User Authentication?\n │ ├─ Session-based? → Cookie sessions + CSRF tokens\n │ ├─ Token-based? → JWT with refresh tokens (references/authentication-authorization.md)\n │ └─ Third-party? → OAuth2/OIDC integration\n │\n ├─ User Input?\n │ ├─ Database query? → Parameterized queries (NEVER string concatenation)\n │ ├─ HTML output? → DOMPurify sanitization + CSP headers\n │ ├─ File upload? → Content validation, size limits, virus scanning\n │ └─ API parameters? → Allowlist validation (references/input-validation.md)\n │\n ├─ Sensitive Data?\n │ ├─ Passwords? → bcrypt/Argon2 (cost factor 12+)\n │ ├─ PII/financial? → AES-256-GCM encryption + key rotation\n │ ├─ API keys/tokens? → Environment variables + secrets manager\n │ └─ In transit? → TLS 1.3 only\n │\n ├─ Access Control?\n │ ├─ Simple roles? → RBAC (assets/web-application/template-authorization.md)\n │ ├─ Complex rules? → ABAC with policy engine\n │ └─ Relationship-based? → ReBAC (owner, collaborator, viewer)\n │\n └─ API Security?\n ├─ Public API? → Rate limiting + API keys\n ├─ CORS needed? → Strict origin allowlist (never *)\n └─ Headers? → Helmet.js (CSP, HSTS, X-Frame-Options)","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Security ROI & Business Value (Jan 2026)","type":"text"}]},{"type":"paragraph","content":[{"text":"Security investment justification and compliance-driven revenue. Full framework: ","type":"text"},{"text":"references/security-business-value.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/security-business-value.md","title":null}}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Quick Breach Cost Reference","type":"text"}]},{"type":"paragraph","content":[{"text":"Indicative figures (source: IBM Cost of a Data Breach 2024; refresh for current year): https://www.ibm.com/reports/data-breach","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Metric","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Global Avg","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"US Avg","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Impact","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Avg breach cost","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"$4.88M","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"$9.36M","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Budget justification baseline","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Cost per record","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"$165","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"$194","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Data classification priority","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Detection time","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"204 days","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"191 days","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SIEM/monitoring ROI","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"DevSecOps adoption","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"-$1.68M","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"-34%","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Shift-left justification","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"IR team","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"-$2.26M","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"-46%","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Highest ROI control","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Compliance → Enterprise Sales","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Certification","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Deals Unlocked","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Sales Impact","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SOC 2 Type II","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"$100K+ enterprise","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Typically reduces security questionnaire friction","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"ISO 27001","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"$250K+ EU enterprise","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Preferred vendor status","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"HIPAA","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Healthcare vertical","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Market access","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"FedRAMP","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"$1M+ government","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"US gov market entry","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"ROI Formula (Quick Reference)","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"text"},"content":[{"text":"Security ROI = (Risk Reduction - Investment) / Investment × 100\n\nRisk Reduction = Breach Probability × Avg Cost × Control Effectiveness\nExample: 15% × $4.88M × 46% = $337K/year risk reduction","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Incident Response Patterns (Jan 2026)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Security Incident Playbook","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Phase","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Actions","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Detect","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Alert fires, user report, automated scan","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Contain","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Isolate affected systems, revoke compromised credentials","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Investigate","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Collect logs, determine scope, identify root cause","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Remediate","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Patch vulnerability, rotate secrets, update defenses","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Recover","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Restore services, verify fixes, update monitoring","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Learn","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Post-mortem, update playbooks, share lessons","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Security Logging Requirements","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"What to Log","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Format","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Retention","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Authentication events","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"JSON with correlation ID","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"90 days minimum","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Authorization failures","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"JSON with user context","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"90 days minimum","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Data access (sensitive)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"JSON with resource ID","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"1 year minimum","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Security scan results","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SARIF format","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"1 year minimum","type":"text"}]}]}]}]},{"type":"paragraph","content":[{"text":"Do:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Include correlation IDs across services","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Log to SIEM (Splunk, Datadog, ELK)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Mask PII in logs","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Avoid:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Logging passwords, tokens, or keys","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Unstructured log formats","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Missing timestamps or context","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Common Security Mistakes","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"FAIL Bad Practice","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"PASS Correct Approach","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Risk","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"query = \"SELECT * FROM users WHERE id=\" + userId","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"db.execute(\"SELECT * FROM users WHERE id=?\", [userId])","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SQL injection","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Storing passwords in plaintext or MD5","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"bcrypt.hash(password, 12)","type":"text","marks":[{"type":"code_inline"}]},{"text":" or Argon2","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Credential theft","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"res.send(userInput)","type":"text","marks":[{"type":"code_inline"}]},{"text":" without encoding","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"res.send(DOMPurify.sanitize(userInput))","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"XSS","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Hardcoded API keys in source code","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Environment variables + secrets manager","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Secret exposure","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Access-Control-Allow-Origin: *","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Explicit origin allowlist","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"CORS bypass","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"JWT with no expiration","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"expiresIn: '15m'","type":"text","marks":[{"type":"code_inline"}]},{"text":" + refresh tokens","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Token hijacking","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Generic error messages to logs","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Structured JSON with correlation IDs","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Debugging blind spots","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SMS OTP as primary factor","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Passkeys/WebAuthn or TOTP (keep SMS for recovery-only)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Credential phishing","type":"text"}]}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":3},"content":[{"text":"Optional: AI/Automation Extensions","type":"text"}]},{"type":"blockquote","content":[{"type":"paragraph","content":[{"text":"Note","type":"text","marks":[{"type":"strong"}]},{"text":": Security considerations for AI systems. Skip if not building AI features.","type":"text"}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"LLM Security Patterns","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Threat","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Mitigation","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Prompt injection","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Input validation, output filtering, sandboxed execution","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Data exfiltration","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Output scanning, PII detection","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Model theft","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"API rate limiting, watermarking","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Jailbreaking","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Constitutional AI, guardrails","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"AI-Assisted Security Tools","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Tool","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Use Case","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Semgrep","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Static analysis with AI rules","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Snyk Code","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"AI-powered vulnerability detection","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"GitHub CodeQL","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Semantic code analysis","type":"text"}]}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":".NET/EF Core Crypto Integration Security","type":"text"}]},{"type":"paragraph","content":[{"text":"For C#/.NET crypto/fintech services using Entity Framework Core, see:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/dotnet-efcore-crypto-security.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/dotnet-efcore-crypto-security.md","title":null}}]},{"text":" — Security rules and C# patterns","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Key rules summary:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No secrets in code — use configuration/environment variables","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No sensitive data in logs (tokens, keys, PII)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use ","type":"text"},{"text":"decimal","type":"text","marks":[{"type":"code_inline"}]},{"text":" for financial values, never ","type":"text"},{"text":"double","type":"text","marks":[{"type":"code_inline"}]},{"text":"/","type":"text"},{"text":"float","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"EF Core or parameterized queries only — no dynamic SQL","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Generic error messages to users, detailed logging server-side","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Navigation","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Core Resources (Updated 2024-2026)","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"Security Business Value & ROI","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/security-business-value.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/security-business-value.md","title":null}}]},{"text":" — Breach cost modeling, security ROI formulas, compliance → enterprise sales, investment justification templates","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"2025 Updates & Modern Architecture","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/supply-chain-security.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/supply-chain-security.md","title":null}}]},{"text":" — Dependency, build, and artifact integrity (SLSA, provenance, signing)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/zero-trust-architecture.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/zero-trust-architecture.md","title":null}}]},{"text":" — NIST SP 800-207, service identity, policy-based access","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/owasp-top-10.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/owasp-top-10.md","title":null}}]},{"text":" — OWASP Top 10:2025 (final) guide + 2021→2025 diffs","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/advanced-xss-techniques.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/advanced-xss-techniques.md","title":null}}]},{"text":" — 2024-2025 XSS: mutation XSS, polyglots, SVG attacks, context-aware encoding","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"API Security, Incident Response & Threat Modeling","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/api-security-patterns.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/api-security-patterns.md","title":null}}]},{"text":" — OWASP API Security Top 10, BOLA/BFLA, rate limiting, API keys, GraphQL/gRPC security","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/incident-response-playbook.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/incident-response-playbook.md","title":null}}]},{"text":" — IR team roles, severity triage, containment by incident type, evidence handling, communication templates, postmortem","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/threat-modeling-guide.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/threat-modeling-guide.md","title":null}}]},{"text":" — STRIDE, PASTA, data flow diagrams, attack trees, risk scoring (CVSS/DREAD), lightweight agile threat modeling","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"Foundation Security Patterns","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/secure-design-principles.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/secure-design-principles.md","title":null}}]},{"text":" — Defense in depth, least privilege, secure defaults","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/authentication-authorization.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/authentication-authorization.md","title":null}}]},{"text":" — AuthN/AuthZ flows, OAuth 2.1, JWT best practices, RBAC/ABAC","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/input-validation.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/input-validation.md","title":null}}]},{"text":" — Allowlist validation, SQL injection, XSS, CSRF prevention, file upload security","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/cryptography-standards.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/cryptography-standards.md","title":null}}]},{"text":" — AES-256-GCM, Argon2, TLS 1.3, key management","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/common-vulnerabilities.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/common-vulnerabilities.md","title":null}}]},{"text":" — Path traversal, command injection, deserialization, SSRF","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"External References","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"data/sources.json","type":"text","marks":[{"type":"link","attrs":{"href":"data/sources.json","title":null}}]},{"text":" — 70+ curated security resources (OWASP 2025, supply chain, zero trust, API security, compliance)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Shared checklists: ","type":"text"},{"text":"../software-clean-code-standard/assets/checklists/secure-code-review-checklist.md","type":"text","marks":[{"type":"link","attrs":{"href":"../software-clean-code-standard/assets/checklists/secure-code-review-checklist.md","title":null}}]},{"text":", ","type":"text"},{"text":"../software-clean-code-standard/assets/checklists/backend-api-review-checklist.md","type":"text","marks":[{"type":"link","attrs":{"href":"../software-clean-code-standard/assets/checklists/backend-api-review-checklist.md","title":null}}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Templates by Domain","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"Web Application Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"assets/web-application/template-authentication.md","type":"text","marks":[{"type":"link","attrs":{"href":"assets/web-application/template-authentication.md","title":null}}]},{"text":" — Secure authentication flows (JWT, OAuth2, sessions, MFA)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"assets/web-application/template-authorization.md","type":"text","marks":[{"type":"link","attrs":{"href":"assets/web-application/template-authorization.md","title":null}}]},{"text":" — RBAC/ABAC/ReBAC policy patterns","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"API Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"assets/api/template-secure-api.md","type":"text","marks":[{"type":"link","attrs":{"href":"assets/api/template-secure-api.md","title":null}}]},{"text":" — Secure API gateway, rate limiting, CORS, security headers","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"Cloud-Native Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"assets/cloud-native/crypto-security.md","type":"text","marks":[{"type":"link","attrs":{"href":"assets/cloud-native/crypto-security.md","title":null}}]},{"text":" — Cryptography usage, key management, HSM integration","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"Blockchain & Web3 Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/smart-contract-security-auditing.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/smart-contract-security-auditing.md","title":null}}]},{"text":" — ","type":"text"},{"text":"NEW","type":"text","marks":[{"type":"strong"}]},{"text":": Smart contract auditing, vulnerability patterns, formal verification, Solidity security","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Related Skills","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"Security Ecosystem","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"../software-backend/SKILL.md","type":"text","marks":[{"type":"link","attrs":{"href":"../software-backend/SKILL.md","title":null}}]},{"text":" — API implementation patterns and error handling","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"../software-architecture-design/SKILL.md","type":"text","marks":[{"type":"link","attrs":{"href":"../software-architecture-design/SKILL.md","title":null}}]},{"text":" — Secure system decomposition and dependency design","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"../ops-devops-platform/SKILL.md","type":"text","marks":[{"type":"link","attrs":{"href":"../ops-devops-platform/SKILL.md","title":null}}]},{"text":" — DevSecOps pipelines, secrets management, infrastructure hardening","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"../software-crypto-web3/SKILL.md","type":"text","marks":[{"type":"link","attrs":{"href":"../software-crypto-web3/SKILL.md","title":null}}]},{"text":" — Smart contract security, blockchain vulnerabilities, DeFi patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"../qa-testing-strategy/SKILL.md","type":"text","marks":[{"type":"link","attrs":{"href":"../qa-testing-strategy/SKILL.md","title":null}}]},{"text":" — Security testing, SAST/DAST integration, penetration testing","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"AI/LLM Security","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"../ai-llm/SKILL.md","type":"text","marks":[{"type":"link","attrs":{"href":"../ai-llm/SKILL.md","title":null}}]},{"text":" — LLM security patterns including prompt injection prevention","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"../ai-mlops/SKILL.md","type":"text","marks":[{"type":"link","attrs":{"href":"../ai-mlops/SKILL.md","title":null}}]},{"text":" — ML model security, adversarial attacks, privacy-preserving ML","type":"text"}]}]}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"Quality & Resilience","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"../qa-resilience/SKILL.md","type":"text","marks":[{"type":"link","attrs":{"href":"../qa-resilience/SKILL.md","title":null}}]},{"text":" — Resilience, safeguards, failure handling, chaos engineering","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"../qa-refactoring/SKILL.md","type":"text","marks":[{"type":"link","attrs":{"href":"../qa-refactoring/SKILL.md","title":null}}]},{"text":" — Security-focused refactoring patterns","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Trend Awareness Protocol","type":"text"}]},{"type":"paragraph","content":[{"text":"IMPORTANT","type":"text","marks":[{"type":"strong"}]},{"text":": When users ask recommendation questions about application security, you MUST use WebSearch to check current trends before answering. If WebSearch is unavailable, use ","type":"text"},{"text":"data/sources.json","type":"text","marks":[{"type":"code_inline"}]},{"text":" + web browsing and state what you verified vs assumed.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Trigger Conditions","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"What's the best approach for [authentication/authorization]?\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"What should I use for [secrets/encryption/API security]?\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"What's the latest in application security?\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"Current best practices for [OWASP/zero trust/supply chain]?\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"Is [security approach] still recommended in 2026?\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"What are the latest security vulnerabilities?\"","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"\"Best auth solution for [use case]?\"","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Required Searches","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Search: ","type":"text"},{"text":"\"application security best practices 2026\"","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Search: ","type":"text"},{"text":"\"OWASP Top 10 2025 2026\"","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Search: ","type":"text"},{"text":"\"[authentication/authorization] trends 2026\"","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Search: ","type":"text"},{"text":"\"supply chain security 2026\"","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"What to Report","type":"text"}]},{"type":"paragraph","content":[{"text":"After searching, provide:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Current landscape","type":"text","marks":[{"type":"strong"}]},{"text":": What security approaches are standard NOW","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Emerging threats","type":"text","marks":[{"type":"strong"}]},{"text":": New vulnerabilities or attack vectors","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Deprecated/declining","type":"text","marks":[{"type":"strong"}]},{"text":": Approaches that are no longer secure","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Recommendation","type":"text","marks":[{"type":"strong"}]},{"text":": Based on fresh data and current advisories","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Example Topics (verify with fresh search)","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"OWASP Top 10 updates","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Passkeys and passwordless authentication","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"AI security concerns (prompt injection, model poisoning)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Supply chain security (SBOMs, dependency scanning)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Zero trust architecture implementation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"API security (BOLA, broken auth)","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Pre-Implementation Security Gate","type":"text"}]},{"type":"paragraph","content":[{"text":"Before building any feature that involves storage, uploads, or user-generated content:","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Threat model first","type":"text","marks":[{"type":"strong"}]},{"text":": Identify what an attacker could do with this feature (file upload → malware, storage → data exfiltration, user content → XSS).","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Check OWASP mapping","type":"text","marks":[{"type":"strong"}]},{"text":": Map the feature to relevant OWASP Top 10 categories above.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Define constraints before coding","type":"text","marks":[{"type":"strong"}]},{"text":": Set file type allowlist, size limits, storage isolation, and access controls before writing the first line.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Review existing security patterns","type":"text","marks":[{"type":"strong"}]},{"text":": Check if the project already has upload/storage security utilities to reuse.","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Building storage/upload features without upfront security constraints leads to retroactive hardening that is more expensive and error-prone.","type":"text"}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Operational Playbooks","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/operational-playbook.md","type":"text","marks":[{"type":"link","attrs":{"href":"references/operational-playbook.md","title":null}}]},{"text":" — Core security principles, OWASP summaries, authentication patterns, and detailed code examples","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Fact-Checking","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use web search/web fetch to verify current external facts, versions, pricing, deadlines, regulations, or platform behavior before final answers.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Prefer primary sources; report source links and dates for volatile information.","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"If web access is unavailable, state the limitation and mark guidance as unverified.","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}}]},"metadata":{"date":"2026-06-05","name":"software-security-appsec","author":"@skillopedia","source":{"stars":60,"repo_name":"ai-agents-public","origin_url":"https://github.com/vasilyu1983/ai-agents-public/blob/HEAD/frameworks/shared-skills/skills/software-security-appsec/SKILL.md","repo_owner":"vasilyu1983","body_sha256":"b38cf2e8b19d981c45086dd8b4675d44784b537d67ff937f1bf1a5478427220a","cluster_key":"235d2b360fc8eb2bbcccf1925c5d184fb9874345cf89d94a6ef343dceb072c61","clean_bundle":{"format":"clean-skill-bundle-v1","source":"vasilyu1983/ai-agents-public/frameworks/shared-skills/skills/software-security-appsec/SKILL.md","attachments":[{"id":"c801e41f-dab4-584e-979e-e51a3a7623ae","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/c801e41f-dab4-584e-979e-e51a3a7623ae/attachment.md","path":"assets/api/template-secure-api.md","size":19659,"sha256":"09c55ded1e66b23b12953454441114cbfb7230b9e6d0d86bd892f980e4e28ba6","contentType":"text/markdown; charset=utf-8"},{"id":"b45bb554-f7cf-56d8-9e49-975480ac1b7c","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b45bb554-f7cf-56d8-9e49-975480ac1b7c/attachment.md","path":"assets/cloud-native/crypto-security.md","size":11583,"sha256":"3d9cf8e862f85cfb477d87bf9d3d03a4647bf219234d22e098d78b9beae53253","contentType":"text/markdown; charset=utf-8"},{"id":"8e70744c-2db3-50d8-9bd2-3d952c6c2df2","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/8e70744c-2db3-50d8-9bd2-3d952c6c2df2/attachment.md","path":"assets/mobile/template-mobile-security.md","size":24172,"sha256":"c1d486ee7e5745d0fe7c043730ad2657424136db936877d0709139beb167a793","contentType":"text/markdown; charset=utf-8"},{"id":"14ef3e1d-fff5-5fee-acda-50e9d95a420b","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/14ef3e1d-fff5-5fee-acda-50e9d95a420b/attachment.md","path":"assets/web-application/template-authentication.md","size":15701,"sha256":"94180e2e445228db08f8c18fdb8c1fee99f4e6bfc3c9c4c0d16e2043645eb765","contentType":"text/markdown; charset=utf-8"},{"id":"2e6846d7-2c74-5edf-b69d-7948bf79787e","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/2e6846d7-2c74-5edf-b69d-7948bf79787e/attachment.md","path":"assets/web-application/template-authorization.md","size":21862,"sha256":"d34a065816538035753d648588ac7255a45c0dbc4eeef6b74a10689998e3ae5b","contentType":"text/markdown; charset=utf-8"},{"id":"d72fdeb0-80c9-5faa-9d81-aa833a1c84fe","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/d72fdeb0-80c9-5faa-9d81-aa833a1c84fe/attachment.json","path":"data/sources.json","size":29281,"sha256":"cc12deaea99a7e96e7d7853fd2448a29016c9c2b4dc07e3c5260401780d5a4d1","contentType":"application/json; charset=utf-8"},{"id":"becd1fa1-7787-5f0e-b5ff-c75c46d4f0fe","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/becd1fa1-7787-5f0e-b5ff-c75c46d4f0fe/attachment.md","path":"references/advanced-xss-techniques.md","size":21353,"sha256":"c945dc0774c1bd8927763c9616edd98e50a90c718eefa8b74f0f7588a491fcfe","contentType":"text/markdown; charset=utf-8"},{"id":"a1071095-fac6-51c6-8570-0c47029a8e92","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/a1071095-fac6-51c6-8570-0c47029a8e92/attachment.md","path":"references/api-security-patterns.md","size":20847,"sha256":"23980cf6074bc40318117a874003a2685e86959a8e3134f01665cd9b794474f0","contentType":"text/markdown; charset=utf-8"},{"id":"48c76e39-2edd-541b-ab6f-0fd68cefc664","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/48c76e39-2edd-541b-ab6f-0fd68cefc664/attachment.md","path":"references/authentication-authorization.md","size":23489,"sha256":"72ca67fb873c0f9daefccdac3a05b65e4d3e84224fe1fa1b63b9e72be194f5a3","contentType":"text/markdown; charset=utf-8"},{"id":"b981be53-c8cf-52be-9b53-7fbd36e57a0a","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b981be53-c8cf-52be-9b53-7fbd36e57a0a/attachment.md","path":"references/common-vulnerabilities.md","size":17741,"sha256":"275bfd0ff9f534304bb304e186898b94124d9d528983632a4acf8b709392fdb6","contentType":"text/markdown; charset=utf-8"},{"id":"3727d0a6-8d60-5c1a-97d4-9436a96ef7e3","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/3727d0a6-8d60-5c1a-97d4-9436a96ef7e3/attachment.md","path":"references/cryptography-standards.md","size":17359,"sha256":"75e88faee04d496b75a2844ea9ab2bc87d58f872fb6791f4ccd008aac174c0b4","contentType":"text/markdown; charset=utf-8"},{"id":"5be194da-2cb4-5e99-ac01-03d6cb65439d","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/5be194da-2cb4-5e99-ac01-03d6cb65439d/attachment.md","path":"references/dotnet-efcore-crypto-security.md","size":3560,"sha256":"553f944f623a2e4ddaa9d5db39d50f710c2c6d5dc7501ea1c34712777e9af135","contentType":"text/markdown; charset=utf-8"},{"id":"6c907056-68c9-5c1c-ab1d-6dc56c4c707b","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/6c907056-68c9-5c1c-ab1d-6dc56c4c707b/attachment.md","path":"references/incident-response-playbook.md","size":19679,"sha256":"386070ec0310171ba6696e679af9e6eebccbfdf9dd4677e43579c984f97cd69f","contentType":"text/markdown; charset=utf-8"},{"id":"3eaeb8b8-bc7a-5dea-beb4-a4a2f2e4eacd","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/3eaeb8b8-bc7a-5dea-beb4-a4a2f2e4eacd/attachment.md","path":"references/input-validation.md","size":26294,"sha256":"f8384c099d1eefb63bcd1eae2311314d9c8ac7f35b11db6218608b7eba904595","contentType":"text/markdown; charset=utf-8"},{"id":"c80a0d10-e89d-5d6f-8907-dd99321cd54e","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/c80a0d10-e89d-5d6f-8907-dd99321cd54e/attachment.md","path":"references/operational-playbook.md","size":15965,"sha256":"92ea55a9d5691f6f991ef5fd84310176453a2fa93af689705977ee04792bd970","contentType":"text/markdown; charset=utf-8"},{"id":"4d0de2de-5806-599c-bc64-9cd71e2ad965","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/4d0de2de-5806-599c-bc64-9cd71e2ad965/attachment.md","path":"references/owasp-top-10.md","size":19498,"sha256":"92c459d81b2951e0e3f5c5f3b41cbb6a2cd22701f3cfd095736281d46c6a61db","contentType":"text/markdown; charset=utf-8"},{"id":"2f0104d8-04fe-5f09-9435-39d22f5fad82","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/2f0104d8-04fe-5f09-9435-39d22f5fad82/attachment.md","path":"references/secure-design-principles.md","size":15570,"sha256":"11b6c2e930b2fbab8cdf37bc7c287f5408cccff7ca7aa9170394bfa8e99c50bd","contentType":"text/markdown; charset=utf-8"},{"id":"cb3b65a7-d9f0-557a-baba-a516791609d0","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/cb3b65a7-d9f0-557a-baba-a516791609d0/attachment.md","path":"references/security-business-value.md","size":11231,"sha256":"1c59609875b4093f252c327f490a123935243c865a4420128e2050b1b2d0e7ef","contentType":"text/markdown; charset=utf-8"},{"id":"b521a917-223e-5223-bf3b-33cdf5c8d3bf","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b521a917-223e-5223-bf3b-33cdf5c8d3bf/attachment.md","path":"references/smart-contract-security-auditing.md","size":15456,"sha256":"b3921ce0265f10a99cb9b214866ccca2db5aa3b999beffbd0988b6c2009ae0fa","contentType":"text/markdown; charset=utf-8"},{"id":"19082570-bed0-590c-9071-0c47a01ff1b3","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/19082570-bed0-590c-9071-0c47a01ff1b3/attachment.md","path":"references/supply-chain-security.md","size":12794,"sha256":"e7c981b4e351a843df52528a7efc32b7cd73490bed937ba8c5cc99d03a07c0d3","contentType":"text/markdown; charset=utf-8"},{"id":"163ac4ab-21a8-5be0-8636-ce858d6fd99d","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/163ac4ab-21a8-5be0-8636-ce858d6fd99d/attachment.md","path":"references/threat-modeling-guide.md","size":22195,"sha256":"02e37ca1ef8a228f4823f6f6c15a07874ffbeedd80ca6bbcce44e237d338a739","contentType":"text/markdown; charset=utf-8"},{"id":"47c3d044-79c2-5758-9ae3-87a8d0c305ce","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/47c3d044-79c2-5758-9ae3-87a8d0c305ce/attachment.md","path":"references/zero-trust-architecture.md","size":15316,"sha256":"813f9340587b7e5b1ee5cb44c319a2a980135614aced072df9fc6e4c8213233c","contentType":"text/markdown; charset=utf-8"}],"bundle_sha256":"6f15302149902956ea5a52c905afc01664d8182c2b7b6c1bc9d0eb823eeab166","attachment_count":22,"text_attachments":22,"attachment_storage":"skillopedia-attachments-v1","binary_attachments":0,"excluded_attachments":[]},"cluster_size":1,"skill_md_path":"frameworks/shared-skills/skills/software-security-appsec/SKILL.md","import_metadata":{"date":"2026-06-05","author":"@skillopedia","version":"v1","category":"security","category_label":"Security"},"exact_dupes_collapsed_into_this":0},"version":"v1","category":"security","import_tag":"clean-skills-v1","description":"AppSec patterns aligned with OWASP Top 10:2025 and NIST SSDF. Use when implementing auth, input validation, crypto, or reviewing security posture."}},"renderedAt":1782986523464}

Software Security & AppSec — Quick Reference Production-grade security patterns for building secure applications in Jan 2026. Covers OWASP Top 10:2025 (stable) https://owasp.org/Top10/2025/ plus OWASP API Security Top 10 (2023) https://owasp.org/API-Security/ and secure SDLC baselines (NIST SSDF) https://csrc.nist.gov/publications/detail/sp/800-218/final. --- When to Use This Skill Activate this skill when: - Implementing authentication or authorization systems - Handling user input that could lead to injection attacks (SQL, XSS, command injection) - Designing secure APIs or web applications…