Security Implementation Guide
Step-by-step instructions for deploying IDPFlare in a security-conscious manner that aligns with ISO 27001 and SOC 2 requirements.
Target Audience: Security engineers, DevOps engineers, and compliance officers
deploying IDPFlare.
Prerequisites
- Cloudflare account with Workers enabled
- wrangler CLI installed
- Domain configured for IDPFlare (e.g.,
auth.yourcompany.com) - SSL certificate configured (Cloudflare managed certificates)
Phase 1: Initial Secure Configuration
1.1 Generate Secure Keys
# Navigate to idpflare-core directory
cd idpflare-core
# Generate RSA key pair for JWT signing
node scripts/generate-keys.js
# Generate encryption key for MFA secrets
node -e "console.log(crypto.randomBytes(32).toString('hex'))"
# Generate SAML certificate (if using SAML)
openssl req -x509 -newkey rsa:2048 -keyout saml.key -out saml.crt -days 365 -nodes
1.2 Create Cloudflare Resources
# Create D1 database
wrangler d1 create idpflare-db
# Note database_id
# Create KV namespace for sessions
wrangler kv namespace create SESSIONS
# Note namespace id
# Create KV namespace for rate limiting
wrangler kv namespace create RATE_LIMIT
# Note namespace id
1.3 Update wrangler.toml
[[d1_databases]]
binding = "DB"
database_name = "idpflare-db"
database_id = "<YOUR_D1_DATABASE_ID>"
[[kv_namespaces]]
binding = "SESSIONS"
id = "<YOUR_SESSIONS_KV_ID>"
[[kv_namespaces]]
binding = "RATE_LIMIT"
id = "<YOUR_RATE_LIMIT_KV_ID>"
1.4 Set Security-Critical Secrets
# JWT signing keys
wrangler secret put JWT_PRIVATE_KEY < jwt-private.pem
wrangler secret put JWT_PUBLIC_KEY < jwt-public.pem
# Encryption key (32-byte hex)
wrangler secret put ENCRYPTION_KEY
# Email provider (choose one)
wrangler secret put RESEND_API_KEY
1.5 Configure Environment Variables for Security
[vars]
# Base URL (use HTTPS)
BASE_URL = "https://auth.yourcompany.com"
ISSUER = "https://auth.yourcompany.com"
# Session Configuration (ISO/SOC: token lifetime)
SESSION_DURATION_SECONDS = "28800" # 8 hours
REFRESH_TOKEN_DURATION_SECONDS = "604800" # 7 days
ACCESS_TOKEN_DURATION_SECONDS = "3600" # 1 hour
AUTH_CODE_DURATION_SECONDS = "600" # 10 minutes
# Security Settings
PASSWORD_MIN_LENGTH = "12"
REQUIRE_EMAIL_VERIFICATION = "true"
ALLOW_REGISTRATION = "false" # Closed registration
# Rate Limiting (SOC 2 CC3.1.2f)
RATE_LIMIT_LOGIN_ATTEMPTS = "5"
RATE_LIMIT_WINDOW_SECONDS = "900" # 15 minutes
# MFA Configuration (SOC 2 CC3.1.2, ISO 8.2.9)
MFA_MODE = "required" # Require MFA
MFA_METHODS_ENABLED = "totp"
Encryption at Rest
Application-Level: MFA TOTP secrets: AES-GCM-256 encryption
Platform-Level:
• D1 Database: "All objects stored in D1 are encrypted at rest"
Source: https://developers.cloudflare.com/d1/reference/data-security/
• KV Storage: "All values stored in KV are encrypted at rest with 256-bit AES-GCM"
Source: https://developers.cloudflare.com/kv/reference/data-security/
For compliance audits, bookmark these documentation URLs as evidence.
Application-Level: MFA TOTP secrets: AES-GCM-256 encryption
Platform-Level:
• D1 Database: "All objects stored in D1 are encrypted at rest"
Source: https://developers.cloudflare.com/d1/reference/data-security/
• KV Storage: "All values stored in KV are encrypted at rest with 256-bit AES-GCM"
Source: https://developers.cloudflare.com/kv/reference/data-security/
For compliance audits, bookmark these documentation URLs as evidence.
Phase 2: Deploy and Initialize
2.1 Run Database Migrations
# Development/Testing
npm run db:migrate:dev
# Production
npm run db:migrate:prod
2.2 Initial Deployment
npm run deploy
2.3 Create Initial Admin User
# Using wrangler d1
wrangler d1 execute idpflare-db --command="
INSERT INTO users (id, email, password_hash, email_verified, is_active, created_at, updated_at)
VALUES ('admin-001', '[email protected]', '<HASH>', 1, 1, $(date +%s)000, $(date +%s)000);
"
2.4 Verify Security Headers
curl -I https://auth.yourcompany.com
Expected headers:
Strict-Transport-Security: max-age=31536000; includeSubDomainsX-Content-Type-Options: nosniffX-Frame-Options: DENY(orSAMEORIGIN)
Phase 3: Monitoring and Logging (Critical for SOC 2)
3.1 Set Up Cloudflare Analytics
- Go to Cloudflare Dashboard → Workers & Pages
- Select your IDPFlare worker
- Enable Analytics
- Configure retention (minimum 90 days for SOC 2)
3.2 Export Audit Logs to SIEM
Option A: Cloudflare Logpush
Cloudflare Dashboard → Logs → Logpush
Option B: Scheduled Export
#!/bin/bash
# export-audit-logs.sh
# Query recent audit logs
wrangler d1 execute idpflare-db --command="
SELECT * FROM audit_log
WHERE created_at > $(($(date +%s) * 1000 - 86400000))
ORDER BY created_at DESC
" > audit-export-$(date +%Y%m%d).json
# Send to SIEM (example with curl)
curl -X POST https://your-siem.com/logs \
-H "Content-Type: application/json" \
-d @audit-export-$(date +%Y%m%d).json
3.3 Configure Security Alerts
| Event | Alert Condition | Response |
|---|---|---|
| Failed login threshold | >10 failures from same IP in 5 min | Investigate, potential block |
| Account lockout | Any account locked | Notify user, verify activity |
| MFA failure | >3 consecutive failures | Alert security team |
| Rate limit exceeded | Any rate limit event | Investigate potential attack |
Phase 4: Backup and Recovery (Critical for ISO 8.3.6, SOC 2 CC3.1.6c)
4.1 Automated Database Backup
#!/bin/bash
# backup-d1.sh
BACKUP_DIR="/backups/idpflare"
DATABASE_ID="<your-database-id>"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
mkdir -p $BACKUP_DIR
# Export database
wrangler d1 exports $DATABASE_ID > $BACKUP_DIR/idpflare-$TIMESTAMP.sql
# Verify backup
if [ -s $BACKUP_DIR/idpflare-$TIMESTAMP.sql ]; then
echo "Backup successful: idpflare-$TIMESTAMP.sql"
# Optional: Upload to secure storage
aws s3 cp $BACKUP_DIR/idpflare-$TIMESTAMP.sql s3://secure-backups/
else
echo "Backup failed!"
exit 1
fi
# Clean old backups (retain 30 days)
find $BACKUP_DIR -name "idpflare-*.sql" -mtime +30 -delete
Schedule with cron (daily at 2 AM):
0 2 * * * /path/to/backup-d1.sh
4.2 Restoration Testing
Conduct quarterly restoration tests:
# Test restoration procedure
wrangler d1 execute <DATABASE_ID> --file=idpflare-test-backup.sql
# Verify data integrity
wrangler d1 execute <DATABASE_ID> --command="SELECT COUNT(*) FROM users"
Document results for SOC 2 evidence.
Phase 5: Access Management (SOC 2 CC3.1.2c)
5.1 Define Access Levels
| Role | Access | Approval Required |
|---|---|---|
| Administrator | Full access to IDPFlare management API | CTO/VP Engineering |
| Security Auditor | Read-only audit log access | CISO |
| Support | Limited user account access (no deletion) | IT Manager |
| Developer | No production access (dev/staging only) | N/A |
5.2 Implement Quarterly Access Reviews
- Generate Access Report - Query all users with admin role
- Review Access - Document justification for each admin
- Process Decisions - Save completed reviews, process revocations within 7 days
Phase 6: Change Management (SOC 2 CC3.1.5)
6.1 Change Process
- Request - Create change ticket with description
- Assessment - Security/Operations review
- Approval - Based on risk level
- Testing - Test in staging environment
- Deployment - Deploy during approved window
- Verification - Confirm successful deployment
- Documentation - Update change log
- Post-Review - Conduct within 7 days
6.2 Change Categories
| Category | Examples | Approval Required |
|---|---|---|
| Normal | Configuration updates, feature changes | Manager approval |
| Emergency | Critical security fix, service restoration | Post-approval + documentation |
| Standard | Pre-approved changes (e.g., log rotation) | Pre-authorized |
Phase 7: Incident Response (SOC 2 CC3.1.14)
7.1 Incident Severity Levels
| Severity | Definition | Response Time |
|---|---|---|
| P0 | Complete service outage, confirmed breach | 1 hour |
| P1 | Significant degradation, suspected breach | 4 hours |
| P2 | Minor issues, potential security event | 1 business day |
| P3 | Informational, no immediate impact | 1 week |
7.2 Incident Response Steps
- Detection - Alert triggered, initial triage
- Containment - Isolate affected systems, preserve evidence
- Eradication - Identify root cause, remove threat, patch vulnerabilities
- Recovery - Restore from backup if needed, verify integrity
- Post-Incident Activity - Document incident, conduct root cause analysis
Phase 8: Vulnerability Management (ISO 8.5.9, SOC 2 CC3.1.6)
8.1 Dependency Scanning
Set up automated dependency scanning using GitHub Dependabot or Snyk.
8.2 Monthly Security Review
- Review dependency alerts
- Evaluate update risk/benefit
- Test updates in staging
- Deploy critical updates within 7 days
- Document review
8.3 Annual Penetration Test
For SOC 2 compliance, schedule annual:
- External penetration test
- Web application security assessment
- Network security review
Phase 9: Compliance Documentation
9.1 Required Policies
- Information Security Policy
- Access Control Policy
- Change Management Policy
- Incident Response Policy
- Data Retention Policy
- Acceptable Use Policy
- Password Policy
- Vendor Management Policy
9.2 Required Procedures
- User Onboarding
- User Offboarding
- Access Review
- Backup Procedures
- Change Procedures
- Incident Procedures
- Monitoring Procedures
- Vulnerability Management
Pre-Assessment Checklist
Before scheduling your formal audit:
- ✔ All security policies written and approved
- ✔ All procedures documented and communicated
- ✔ Monitoring and alerting configured and tested
- ✔ Backup procedures implemented and tested
- ✔ At least one successful restoration test completed
- ✔ Access reviews conducted and documented
- ✔ Incident response plan created and tabletop exercise conducted
- ✔ Change management process defined and followed
- ✔ Vulnerability scanning operational
- ✔ Annual penetration test scheduled or completed
- ✔ Data retention policy implemented
- ✔ Employee security training completed
- ✔ Vendor risk assessments completed
- ✔ Evidence collection system established