feat: add unified code quality dashboard with multiple validators

- Add validator_type field to scans and violations (architecture,
  security, performance)
- Create security validator with SEC-xxx rules
- Create performance validator with PERF-xxx rules
- Add base validator class for shared functionality
- Add validate_all.py script to run all validators
- Update code quality service with validator type filtering
- Add validator type tabs to dashboard UI
- Add validator type filter to violations list
- Update stats response with per-validator breakdown
- Add security and performance rules documentation
- Add chat-bubble icons to icon library

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2025-12-21 20:57:47 +01:00
parent 6a903e16c6
commit 26b3dc9e3b
27 changed files with 5270 additions and 119 deletions

View File

@@ -0,0 +1,66 @@
# Security Rules Configuration
# ============================
# Security-focused validation rules for the codebase.
# Run with: python scripts/validate_security.py
version: "1.0"
project: "letzshop-product-import"
description: |
Security validation rules to detect common vulnerabilities and ensure
secure coding practices across the application.
principles:
- name: "Defense in Depth"
description: "Multiple layers of security controls"
- name: "Least Privilege"
description: "Minimal access rights for users and processes"
- name: "Secure by Default"
description: "Secure configurations out of the box"
- name: "Fail Securely"
description: "Errors should not compromise security"
- name: "Input Validation"
description: "Never trust user input"
includes:
- authentication.yaml
- injection.yaml
- data_protection.yaml
- api_security.yaml
- cryptography.yaml
- audit.yaml
severity_levels:
error:
description: "Critical security vulnerability that must be fixed"
exit_code: 1
warning:
description: "Security concern that should be addressed"
exit_code: 0
info:
description: "Security best practice recommendation"
exit_code: 0
ignore:
files:
- "**/test_*.py"
- "**/tests/**"
- "**/*_test.py"
- "**/conftest.py"
- "**/migrations/**"
- "**/.venv/**"
- "**/venv/**"
- "**/node_modules/**"
- "**/site/**"
- "**/scripts/**"
- "**/__pycache__/**"
- "**/*.pyc"
patterns:
# Allow test credentials in test files
- file: "**/tests/**"
pattern: "password.*=.*test"
reason: "Test fixtures use dummy credentials"
# Allow example patterns in documentation
- file: "**/docs/**"
pattern: ".*"
reason: "Documentation examples"

View File

@@ -0,0 +1,66 @@
# API Security Rules
# ==================
api_security_rules:
- id: SEC-031
name: CORS origin validation
severity: error
description: >
CORS must not allow all origins in production.
Specify allowed origins explicitly.
- id: SEC-032
name: Rate limiting on sensitive endpoints
severity: warning
description: >
Auth, password reset, and payment endpoints need rate limiting.
- id: SEC-033
name: Security headers
severity: warning
description: >
Configure security headers like X-Content-Type-Options,
X-Frame-Options, Content-Security-Policy.
- id: SEC-034
name: HTTPS enforcement
severity: error
description: >
External URLs must use HTTPS.
HTTP is only acceptable for localhost.
- id: SEC-035
name: Request size limits
severity: warning
description: >
Limit request body size to prevent DoS attacks.
- id: SEC-036
name: Input validation with Pydantic
severity: warning
description: >
All API inputs should be validated using Pydantic models.
- id: SEC-037
name: API versioning
severity: info
description: >
APIs should be versioned for security update isolation.
- id: SEC-038
name: Method restrictions
severity: warning
description: >
Endpoints should only allow necessary HTTP methods.
- id: SEC-039
name: Authentication bypass prevention
severity: error
description: >
Ensure authentication cannot be bypassed.
- id: SEC-040
name: Timeout configuration
severity: warning
description: >
All external calls must have timeouts configured.

131
.security-rules/audit.yaml Normal file
View File

@@ -0,0 +1,131 @@
# Audit & Logging Rules
# =====================
audit_rules:
- id: "SEC-051"
name: "Authentication event logging"
severity: warning
description: |
Log authentication events:
- Successful logins (with user ID, IP)
- Failed login attempts (with IP, reason)
- Logouts
- Password changes
- Password reset requests
file_pattern: "**/auth*.py|**/login*.py"
required_patterns:
- "log"
suggested_patterns:
- 'logger\.(info|warning).*login|auth|password'
- id: "SEC-052"
name: "Admin action audit trail"
severity: warning
description: |
All admin operations should be logged with:
- Admin user ID
- Action performed
- Target resource
- Timestamp
- IP address
file_pattern: "**/admin/**/*.py"
required_patterns:
- "log"
suggested_patterns:
- "logger|audit"
- id: "SEC-053"
name: "Data modification logging"
severity: info
description: |
Log create/update/delete on sensitive data:
- User accounts
- Roles and permissions
- Financial transactions
- Configuration changes
file_pattern: "**/service*.py"
- id: "SEC-054"
name: "Security event logging"
severity: warning
description: |
Log security-relevant events:
- Authorization failures
- Input validation failures
- Rate limit triggers
- Suspicious activity patterns
file_pattern: "**/*.py"
context_patterns:
- "unauthorized|forbidden|rate_limit|suspicious"
suggested_patterns:
- "logger\\.warning|logger\\.error"
- id: "SEC-055"
name: "Log injection prevention"
severity: warning
description: |
Sanitize user input before logging.
Newlines and control characters can corrupt logs.
file_pattern: "**/*.py"
anti_patterns:
- 'logger\.[a-z]+\(.*request\..*\)'
suggested_patterns:
- "sanitize|escape|repr\\("
example_bad: |
logger.info(f"User search: {request.query}")
example_good: |
logger.info(f"User search: {request.query!r}") # repr escapes
- id: "SEC-056"
name: "Centralized logging"
severity: info
description: |
Use centralized logging for:
- Correlation across services
- Tamper-evident storage
- Retention management
- Alerting capabilities
- id: "SEC-057"
name: "Log level appropriateness"
severity: info
description: |
Use appropriate log levels:
- ERROR: Security failures requiring attention
- WARNING: Suspicious activity, failed auth
- INFO: Successful security events
- DEBUG: Never log sensitive data even at debug
- id: "SEC-058"
name: "Structured logging format"
severity: info
description: |
Use structured logging (JSON) for:
- Easy parsing
- Consistent fields
- Searchability
suggested_patterns:
- "structlog|json_formatter|extra={"
- id: "SEC-059"
name: "Audit log integrity"
severity: info
description: |
Protect audit logs from tampering:
- Append-only storage
- Cryptographic chaining
- Separate access controls
- id: "SEC-060"
name: "Privacy-aware logging"
severity: warning
description: |
Comply with data protection regulations:
- No PII in logs without consent
- Log retention limits
- Right to deletion support
file_pattern: "**/*.py"
anti_patterns:
- 'log.*email(?!.*@.*sanitized)'
- 'log.*phone'
- 'log.*address(?!.*ip)'

View File

@@ -0,0 +1,70 @@
# Authentication Security Rules
# =============================
authentication_rules:
- id: SEC-001
name: No hardcoded credentials
severity: error
description: >
Credentials must never be hardcoded in source code.
Use environment variables or secret management.
- id: SEC-002
name: JWT expiry enforcement
severity: error
description: >
All JWT tokens must have expiration claims.
Access tokens should expire in 15-60 minutes.
- id: SEC-003
name: Password hashing required
severity: error
description: >
Passwords must be hashed using bcrypt, argon2, or scrypt.
Never store or compare passwords in plain text.
- id: SEC-004
name: Session regeneration after auth
severity: warning
description: >
Session IDs should be regenerated after authentication
to prevent session fixation attacks.
- id: SEC-005
name: Brute force protection
severity: warning
description: >
Login endpoints should implement rate limiting
or account lockout after failed attempts.
- id: SEC-006
name: Secure password reset
severity: warning
description: >
Password reset tokens must be cryptographically random,
expire within 1 hour, and be single-use.
- id: SEC-007
name: Authentication on sensitive endpoints
severity: error
description: >
All endpoints except public ones must require authentication.
- id: SEC-008
name: Token in Authorization header
severity: warning
description: >
JWT tokens should be sent in Authorization header,
not in URL parameters.
- id: SEC-009
name: Logout invalidates tokens
severity: warning
description: >
Logout should invalidate or blacklist tokens.
- id: SEC-010
name: Multi-factor authentication support
severity: info
description: >
Consider implementing MFA for sensitive operations.

View File

@@ -0,0 +1,72 @@
# Cryptography Rules
# ==================
cryptography_rules:
- id: SEC-041
name: Strong hashing algorithms
severity: error
description: >
Use bcrypt, argon2, scrypt for passwords.
Use SHA-256 or stronger for general hashing.
Never use MD5 or SHA1.
- id: SEC-042
name: Secure random generation
severity: error
description: >
Use the secrets module for security-sensitive randomness.
Never use random module for tokens or keys.
- id: SEC-043
name: No hardcoded encryption keys
severity: error
description: >
Encryption keys must come from environment variables
or secret management services.
- id: SEC-044
name: Strong encryption algorithms
severity: error
description: >
Use AES-256 or ChaCha20. Never use DES, 3DES, or RC4.
- id: SEC-045
name: Proper IV/nonce usage
severity: error
description: >
Encryption IVs and nonces must be randomly generated
and unique per encryption.
- id: SEC-046
name: TLS version requirements
severity: warning
description: >
Enforce TLS 1.2 or higher.
Disable SSLv2, SSLv3, TLS 1.0, TLS 1.1.
- id: SEC-047
name: Certificate verification
severity: error
description: >
Always verify SSL certificates.
Never disable verification in production.
- id: SEC-048
name: Key derivation for passwords
severity: warning
description: >
When deriving encryption keys from passwords,
use PBKDF2 with 100K+ iterations, Argon2, or scrypt.
- id: SEC-049
name: Secure key storage
severity: info
description: >
Encryption keys should be stored in environment variables,
secret management, or HSMs.
- id: SEC-050
name: Key rotation support
severity: info
description: >
Implement key rotation with multiple key versions.

View File

@@ -0,0 +1,67 @@
# Data Protection Rules
# =====================
data_protection_rules:
- id: SEC-021
name: PII logging prevention
severity: error
description: >
Never log passwords, tokens, credit cards, or sensitive PII.
- id: SEC-022
name: Sensitive data in URLs
severity: error
description: >
Sensitive data should not appear in URL query parameters.
Use POST body or headers instead.
- id: SEC-023
name: Mass assignment prevention
severity: warning
description: >
Use explicit field assignment, not **kwargs from user input.
- id: SEC-024
name: Error message information leakage
severity: error
description: >
Error messages should not reveal internal details.
No stack traces to users.
- id: SEC-025
name: Secure cookie settings
severity: error
description: >
Cookies must have Secure, HttpOnly, SameSite attributes.
- id: SEC-026
name: Encryption for sensitive data at rest
severity: info
description: >
Consider encrypting sensitive data stored in the database.
- id: SEC-027
name: Data retention limits
severity: info
description: >
Implement data retention policies.
- id: SEC-028
name: Response data filtering
severity: warning
description: >
API responses should not include sensitive internal fields.
Use Pydantic response models.
- id: SEC-029
name: File upload validation
severity: error
description: >
Validate uploaded files by extension AND content type.
Limit file size.
- id: SEC-030
name: Backup encryption
severity: info
description: >
Database backups should be encrypted.

View File

@@ -0,0 +1,70 @@
# Injection Prevention Rules
# ==========================
injection_rules:
- id: SEC-011
name: No raw SQL queries
severity: error
description: >
Use SQLAlchemy ORM or parameterized queries only.
Never concatenate user input into SQL strings.
- id: SEC-012
name: No shell command injection
severity: error
description: >
Never use shell=True with subprocess.
Use subprocess with list arguments.
- id: SEC-013
name: No code execution
severity: error
description: >
Never use eval() or exec() with user input.
- id: SEC-014
name: Path traversal prevention
severity: error
description: >
Validate file paths to prevent directory traversal.
Use secure_filename() for uploads.
- id: SEC-015
name: XSS prevention in templates
severity: error
description: >
Use safe output methods in templates.
Prefer x-text over x-html.
- id: SEC-016
name: LDAP injection prevention
severity: error
description: >
Escape special characters in LDAP queries.
- id: SEC-017
name: XML external entity prevention
severity: error
description: >
Disable external entities when parsing XML.
Use defusedxml.
- id: SEC-018
name: Template injection prevention
severity: error
description: >
Never render user input as template code.
- id: SEC-019
name: SSRF prevention
severity: warning
description: >
Validate URLs before making external requests.
Whitelist allowed domains.
- id: SEC-020
name: Deserialization safety
severity: error
description: >
Never deserialize untrusted data with pickle.
Use yaml.safe_load() instead of yaml.load().