6.5 KiB
Keys for All - Security Model
Overview
The Keys for All system implements defense-in-depth security with multiple layers of protection for key generation, validation, and distribution.
Key Security
Key Generation
-
Cryptographically Secure Random Number Generator (CSPRNG)
const crypto = require('crypto'); function generateSecureKey() { const bytes = crypto.randomBytes(12); // 96 bits of entropy const key = base32Encode(bytes); // Base32 for readability return formatKey(key); // XXXX-XXXX-XXXX-XXXX } -
Key Format
- 16 characters in 4 groups
- Base32 alphabet (no ambiguous characters)
- 96 bits of entropy (2^96 possible keys)
- Built-in checksum validation
-
Collision Prevention
- Database unique constraint
- Retry on collision (extremely rare)
- Monitoring for collision attempts
Key Validation
-
Format Validation
- Regex pattern matching
- Checksum verification
- Character set validation
-
Business Logic Validation
- Key exists in database
- Key not expired
- Key not revoked
- App ID matches
API Security
Authentication
-
API Key Requirements
- 256-bit randomly generated keys
- Stored as hashed values (bcrypt)
- Rotatable on demand
- Per-app isolation
-
Request Signing (Optional High Security)
X-Signature: HMAC-SHA256(request_body + timestamp, api_secret) X-Timestamp: 1674567890
Rate Limiting
-
Tiered Limits
const rateLimits = { '/keys/validate': { window: '1m', max: 100 }, '/keys/generate': { window: '1m', max: 10 }, '/community/request': { window: '1h', max: 1 }, 'default': { window: '1h', max: 1000 } }; -
Implementation
- Redis-based sliding window
- Per API key and per IP
- Exponential backoff for violations
Input Validation
-
Request Validation
- JSON schema validation (AJV)
- SQL injection prevention (parameterized queries)
- XSS prevention (output encoding)
-
Data Sanitization
const sanitize = require('mongo-sanitize'); const validator = require('validator'); // Clean all user input const cleanInput = (data) => { return sanitize(data); };
Data Security
Encryption at Rest
-
Database Encryption
- PostgreSQL Transparent Data Encryption (TDE)
- Encrypted backups
- Encrypted file systems
-
Sensitive Data
- Purchase receipts encrypted with AES-256
- Email addresses hashed for lookups
- No credit card data stored
Encryption in Transit
-
TLS Requirements
- TLS 1.2 minimum
- Strong cipher suites only
- HSTS enabled
- Certificate pinning for mobile apps
-
API Communication
ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384'; ssl_prefer_server_ciphers on; add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
Access Control
Role-Based Access Control (RBAC)
const roles = {
'app': ['read:own_keys', 'create:keys', 'validate:keys'],
'admin': ['read:all_keys', 'create:keys', 'revoke:keys', 'read:analytics'],
'support': ['read:keys', 'read:users', 'create:community_keys']
};
Principle of Least Privilege
-
Database Access
- Apps can only access their own keys
- Read-only replicas for analytics
- Separate credentials per service
-
API Scopes
- Granular permissions per endpoint
- OAuth 2.0 style scopes
- Audit trail for all actions
Audit and Monitoring
Logging
-
Security Events
const securityEvents = [ 'key.generated', 'key.validated', 'key.activation_failed', 'api.authentication_failed', 'rate_limit.exceeded', 'suspicious.pattern_detected' ]; -
Log Storage
- Centralized logging (ELK stack)
- Immutable audit trail
- 90-day retention minimum
- Real-time alerting
Anomaly Detection
-
Patterns to Detect
- Unusual validation patterns
- Key farming attempts
- Brute force attacks
- Geographic anomalies
-
Response Actions
- Automatic rate limit increases
- API key suspension
- Admin notifications
- Incident response triggers
Privacy Protection
Data Minimization
-
No Personal Data Required
- Keys are anonymous
- No user accounts needed
- Optional email for community requests
-
Data Retention
- Analytics aggregated after 30 days
- Logs pruned after 90 days
- Inactive keys archived
GDPR Compliance
-
User Rights
- Right to erasure (key revocation)
- Data portability (key export)
- Transparency (clear policies)
-
Data Processing
// Anonymize IP addresses const anonymizeIP = (ip) => { const parts = ip.split('.'); if (parts.length === 4) { parts[3] = '0'; // IPv4 } return parts.join('.'); };
Incident Response
Security Incident Procedure
-
Detection
- Automated alerts
- Manual reports
- Regular audits
-
Response Plan
1. Isolate affected systems 2. Assess impact and scope 3. Contain the incident 4. Eradicate the threat 5. Recover normal operations 6. Post-incident review -
Communication
- Notify affected apps within 24 hours
- Public disclosure if widespread
- Transparent incident reports
Best Practices for App Developers
Secure Integration
-
Store API Keys Securely
// iOS Keychain let keychain = Keychain(service: "com.app.keysforall") keychain["api_key"] = apiKey -
Validate Keys Locally First
func isValidKeyFormat(_ key: String) -> Bool { let pattern = "^[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$" return key.range(of: pattern, options: .regularExpression) != nil } -
Handle Errors Gracefully
- Don't expose error details to users
- Log errors for debugging
- Implement retry logic
Security Checklist
- API keys stored in secure storage
- HTTPS certificate pinning implemented
- Input validation before API calls
- Rate limiting handled gracefully
- Error messages don't leak information
- Regular security updates applied
- Audit logs for key operations
Security Contact
Report security vulnerabilities to: security@keysforall.com
We follow responsible disclosure with:
- 90-day disclosure timeline
- Bug bounty program available
- CVE assignment for valid issues