From ab3db0ab0d3e6344f06a792cf3ea8b8eafc8046a Mon Sep 17 00:00:00 2001 From: UserIsMH Date: Wed, 18 Jun 2025 21:22:12 +0200 Subject: [PATCH] Todo LIZENZSERVER.md --- LIZENZSERVER.md | 642 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 642 insertions(+) create mode 100644 LIZENZSERVER.md diff --git a/LIZENZSERVER.md b/LIZENZSERVER.md new file mode 100644 index 0000000..e24c966 --- /dev/null +++ b/LIZENZSERVER.md @@ -0,0 +1,642 @@ +# Lizenzserver - Architektur & Implementierungsplan + +## Übersicht +Der Lizenzserver ist das zentrale Herzstück des v2-Docker Systems, das für die Validierung, Verwaltung und Überwachung aller Lizenzen verantwortlich ist. Diese Dokumentation beschreibt eine zukunftssichere Architektur, die von Anfang an auf Skalierbarkeit, Wartbarkeit und Erweiterbarkeit ausgelegt ist. + +## Architektur-Prinzipien (Kein Refactoring nötig!) + +### 1. **Klare Trennung von Anfang an** +- **API Layer**: Strikte Trennung zwischen Public API (Clients) und Admin API +- **Business Logic**: Zentral in Service-Klassen, nicht in Routes +- **Data Access**: Repository Pattern für alle DB-Zugriffe +- **No Spaghetti Code**: Keine Vermischung von Präsentation und Logik + +### 2. **Konsistente Namenskonventionen** +```python +# Datenbank-Felder (snake_case, eindeutig) +is_active # NICHT: active +hardware_id # NICHT: device_id +created_at # NICHT: created +updated_at # NICHT: updated +is_test # NICHT: test + +# API Responses (camelCase für JSON) +{ + "licenseId": "uuid", + "isActive": true, + "hardwareId": "hash", + "createdAt": "2025-01-18T10:00:00Z" +} + +# Python (snake_case) +def validate_license(license_key: str, hardware_id: str) -> dict: + pass +``` + +### 3. **Modulare Service-Architektur** +```python +# services/license_service.py +class LicenseService: + def __init__(self, db_repo, cache_repo, event_bus): + self.db = db_repo + self.cache = cache_repo + self.events = event_bus + + def validate_license(self, key, hw_id): + # Business Logic hier, NICHT in Routes! + pass + +# routes/api_routes.py +@api.route('/validate') +def validate(): + # NUR Request handling, keine Business Logic + data = request.get_json() + result = license_service.validate_license( + data['licenseKey'], + data['hardwareId'] + ) + return jsonify(result) +``` + +### 4. **Event-Driven Architecture** +```python +# Lose Kopplung durch Events +class EventBus: + def publish(self, event_type, data): + # Analytics Service hört zu + # Audit Service hört zu + # Email Service hört zu + pass + +# Neue Features = Neue Listener, kein Code ändern! +``` + +### 5. **Klare API-Struktur** +``` +/api/license/validate # Einheitliche API ohne Versionierung +/api/license/activate # Konsistente Endpoints +/api/admin/license/status # Klare Trennung Admin vs. Public +``` + +### 6. **Feature Flags von Anfang an** +```python +if feature_flags.is_enabled('anomaly_detection'): + anomaly_service.check(license_id) +# Neue Features ohne Deployment aktivieren +``` + +### 7. **Dependency Injection** +```python +# Keine harten Dependencies! +def create_app(config): + db = Database(config.db_url) + cache = Redis(config.redis_url) + + # Services bekommen Dependencies injiziert + license_service = LicenseService(db, cache) + + # Routes bekommen Services injiziert + api_blueprint = create_api_routes(license_service) + + app.register_blueprint(api_blueprint) + return app +``` + +### 8. **Klare Verzeichnisstruktur** +``` +lizenzserver/ +├── api/ +│ ├── v1/ +│ │ ├── routes/ +│ │ ├── schemas/ # Validation schemas +│ │ └── middleware/ +│ └── v2/ +├── services/ # Business Logic +│ ├── license_service.py +│ ├── analytics_service.py +│ └── anomaly_service.py +├── repositories/ # Data Access +│ ├── license_repo.py +│ └── cache_repo.py +├── models/ # Domain Models +├── events/ # Event System +├── utils/ # Helpers +└── tests/ # Umfassende Tests! +``` + +### 9. **Database Migrations von Anfang an** +```python +# Alembic/Flyway für versioned migrations +# NIEMALS manuelle SQL changes! +alembic revision -m "add_anomaly_detection_table" +alembic upgrade head +``` + +### 10. **Dokumentation als Code** +```python +# OpenAPI/Swagger von Anfang an +from flask_restx import Api, Resource, fields + +api = Api(doc='/docs') + +@api.route('/license/validate') +class LicenseValidation(Resource): + @api.doc('validate_license') + @api.expect(license_model) + @api.marshal_with(validation_result) + def post(self): + """Validate a license key with hardware ID""" + pass +``` + +## Kernfunktionen + +### 1. Lizenzvalidierung +- **Online-Validierung**: Echtzeit-Prüfung von Lizenzen +- **Offline-Grace-Period**: 72h Offline-Betrieb mit gecachten Tokens +- **Hardware-Binding**: Geräte-spezifische Lizenzierung +- **Multi-Device-Support**: Verwaltung mehrerer Geräte pro Lizenz + +### 2. Aktivierungsmanagement +- **Erste Aktivierung**: Hardware-ID Registrierung +- **Re-Aktivierung**: Bei Hardware-Wechsel +- **Deaktivierung**: Manuell oder automatisch +- **Transfer**: Lizenz auf neues Gerät übertragen + +### 3. Nutzungsüberwachung +- **Heartbeat-System**: Regelmäßige Lebenszeichen +- **Usage-Tracking**: Detaillierte Nutzungsstatistiken +- **Anomalie-Erkennung**: Verdächtige Aktivitäten +- **Concurrent-Use-Prevention**: Mehrfachnutzung verhindern + +## Architektur-Design + +### Microservices-Ansatz +``` +┌─────────────────────────────────────────────────────────┐ +│ Load Balancer │ +│ (HAProxy/Nginx) │ +└────────────┬────────────────┬────────────────┬─────────┘ + │ │ │ + ┌───────▼──────┐ ┌──────▼──────┐ ┌──────▼──────┐ + │ Auth Service │ │License API │ │ Analytics │ + │ (JWT) │ │ Service │ │ Service │ + └───────┬──────┘ └──────┬──────┘ └──────┬──────┘ + │ │ │ + ┌───────▼────────────────▼────────────────▼──────┐ + │ Message Queue (RabbitMQ) │ + └─────────────────────┬───────────────────────────┘ + │ + ┌─────────────────────▼───────────────────────────┐ + │ Database Cluster (PostgreSQL) │ + │ Master-Slave Replication │ + └─────────────────────────────────────────────────┘ +``` + +### Service-Trennung + +#### 1. **Auth Service** (Port 5001) +- JWT Token Generation/Validation +- API Key Management +- Rate Limiting +- IP Whitelisting + +#### 2. **License API Service** (Port 5002) +- License Validation Endpoints +- Activation/Deactivation +- Device Management +- License Status Queries + +#### 3. **Analytics Service** (Port 5003) +- Usage Statistics +- Performance Metrics +- Anomaly Detection +- Report Generation + +#### 4. **Admin API Service** (Port 5004) +- CRUD Operations +- Batch Processing +- System Configuration +- Audit Logging + +## Datenbankschema (Erweiterung) + +### Neue Tabellen + +```sql +-- Lizenz-Token für Offline-Validierung +CREATE TABLE license_tokens ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + license_id UUID REFERENCES licenses(id) ON DELETE CASCADE, + token VARCHAR(512) NOT NULL UNIQUE, + hardware_id VARCHAR(255) NOT NULL, + valid_until TIMESTAMP NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + last_validated TIMESTAMP, + validation_count INTEGER DEFAULT 0, + INDEX idx_token (token), + INDEX idx_hardware (hardware_id), + INDEX idx_valid_until (valid_until) +); + +-- Heartbeat-Tracking +CREATE TABLE license_heartbeats ( + id BIGSERIAL PRIMARY KEY, + license_id UUID REFERENCES licenses(id) ON DELETE CASCADE, + hardware_id VARCHAR(255) NOT NULL, + ip_address INET, + user_agent VARCHAR(500), + app_version VARCHAR(50), + timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + session_data JSONB, + INDEX idx_license_time (license_id, timestamp DESC), + INDEX idx_hardware_time (hardware_id, timestamp DESC) +) PARTITION BY RANGE (timestamp); + +-- Aktivierungs-Events +CREATE TABLE activation_events ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + license_id UUID REFERENCES licenses(id) ON DELETE CASCADE, + event_type VARCHAR(50) NOT NULL, -- 'activation', 'deactivation', 'reactivation', 'transfer' + hardware_id VARCHAR(255), + previous_hardware_id VARCHAR(255), + ip_address INET, + user_agent VARCHAR(500), + success BOOLEAN DEFAULT true, + error_message TEXT, + metadata JSONB, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + INDEX idx_license_events (license_id, created_at DESC), + INDEX idx_event_type (event_type, created_at DESC) +); + +-- API Rate Limiting +CREATE TABLE api_rate_limits ( + id SERIAL PRIMARY KEY, + api_key VARCHAR(255) NOT NULL UNIQUE, + requests_per_minute INTEGER DEFAULT 60, + requests_per_hour INTEGER DEFAULT 1000, + requests_per_day INTEGER DEFAULT 10000, + burst_size INTEGER DEFAULT 100, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP +); + +-- Anomalie-Erkennung +CREATE TABLE anomaly_detections ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + license_id UUID REFERENCES licenses(id), + anomaly_type VARCHAR(100) NOT NULL, -- 'multiple_ips', 'rapid_hardware_change', 'suspicious_pattern' + severity VARCHAR(20) NOT NULL, -- 'low', 'medium', 'high', 'critical' + details JSONB NOT NULL, + detected_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + resolved BOOLEAN DEFAULT false, + resolved_at TIMESTAMP, + resolved_by VARCHAR(255), + action_taken TEXT, + INDEX idx_unresolved (resolved, severity, detected_at DESC), + INDEX idx_license_anomalies (license_id, detected_at DESC) +); +``` + +## API-Endpunkte + +### Public API (Client-Software) + +```yaml +# Lizenz-Validierung +POST /api/v1/license/validate + Headers: + X-API-Key: {client_api_key} + Body: + license_key: string + hardware_id: string + app_version: string + +# Aktivierung +POST /api/v1/license/activate + Headers: + X-API-Key: {client_api_key} + Body: + license_key: string + hardware_id: string + device_name: string + os_info: object + +# Heartbeat +POST /api/v1/license/heartbeat + Headers: + Authorization: Bearer {token} + Body: + session_data: object + +# Offline-Token anfordern +POST /api/v1/license/offline-token + Headers: + Authorization: Bearer {token} + Body: + duration_hours: number (max: 72) +``` + +### Admin API (Admin Panel) + +```yaml +# Lizenz-Details mit Echtzeit-Status +GET /api/v1/admin/license/{id}/status + Response: + license_info: object + active_devices: array + recent_activity: array + anomalies: array + +# Geräte-Management +DELETE /api/v1/admin/license/{id}/device/{hardware_id} +POST /api/v1/admin/license/{id}/transfer + Body: + from_hardware_id: string + to_hardware_id: string + +# Anomalie-Management +GET /api/v1/admin/anomalies +PATCH /api/v1/admin/anomaly/{id}/resolve +``` + +## Sicherheitskonzepte + +### 1. **Token-Strategie** +```python +# JWT Token Struktur +{ + "sub": "license_id", + "hwid": "hardware_id", + "exp": timestamp, + "iat": timestamp, + "features": ["feature1", "feature2"], + "limits": { + "api_calls": 1000, + "concurrent_sessions": 1 + } +} +``` + +### 2. **Rate Limiting** +- Per API Key +- Per License +- Per IP Address +- Sliding Window Algorithm + +### 3. **Encryption** +- License Keys: AES-256-GCM +- API Communication: TLS 1.3 +- Database: Transparent Data Encryption +- Backups: GPG Encryption + +## Monitoring & Observability + +### Metriken (Prometheus) +```yaml +# Business Metrics +license_validations_total +license_activations_total +active_licenses_gauge +license_revenue_total + +# Technical Metrics +api_request_duration_seconds +database_query_duration_seconds +cache_hit_ratio +error_rate +``` + +### Logging (ELK Stack) +```json +{ + "timestamp": "2025-01-18T10:00:00Z", + "level": "INFO", + "service": "license-api", + "trace_id": "uuid", + "event": "license_validation", + "license_id": "uuid", + "hardware_id": "hash", + "result": "success", + "duration_ms": 23 +} +``` + +### Alerting +- License-Abuse Detection +- System Health Checks +- Performance Degradation +- Security Incidents + +## Skalierungsstrategien + +### Horizontal Scaling +1. **Stateless Services**: Alle Services zustandslos +2. **Load Balancing**: Round-Robin mit Health Checks +3. **Auto-Scaling**: CPU/Memory basiert +4. **Database Read Replicas**: Für Read-Heavy Operations + +### Caching-Strategie +```yaml +Cache-Layer: + - Redis Cluster + - TTL: 5 Minuten für Validierungen + - Invalidation: Event-basiert + +Cache-Keys: + - license:{id}:status + - license:{id}:devices + - hardware:{id}:licenses + - token:{token}:valid +``` + +### Queue-basierte Verarbeitung +- Heartbeat Processing +- Email Notifications +- Report Generation +- Batch Operations + +## Implementierungs-Roadmap + +### Phase 1: Foundation (Woche 1-2) +- [ ] Docker-Setup für alle Services +- [ ] Basis-Datenbankschema +- [ ] JWT Authentication +- [ ] Basis API-Endpoints + +### Phase 2: Core Features (Woche 3-4) +- [ ] License Validation Logic +- [ ] Device Management +- [ ] Heartbeat System +- [ ] Admin API + +### Phase 3: Advanced Features (Woche 5-6) +- [ ] Offline Token System +- [ ] Anomaly Detection +- [ ] Analytics Service +- [ ] Monitoring Setup + +### Phase 4: Optimization (Woche 7-8) +- [ ] Caching Layer +- [ ] Performance Tuning +- [ ] Load Testing +- [ ] Documentation + +## Testing-Strategie + +### Unit Tests +- Service Logic +- Validation Rules +- Token Generation + +### Integration Tests +- API Endpoints +- Database Operations +- Cache Integration + +### Load Tests +- 10k concurrent validations +- 100k active licenses +- Sustained load scenarios + +### Security Tests +- Penetration Testing +- Token Manipulation +- Rate Limit Bypass + +## Deployment + +### Docker Compose (Development) +```yaml +services: + license-auth: + build: ./services/auth + environment: + - JWT_SECRET=${JWT_SECRET} + ports: + - "5001:5001" + + license-api: + build: ./services/api + depends_on: + - postgres + - redis + ports: + - "5002:5002" + + license-analytics: + build: ./services/analytics + depends_on: + - postgres + - rabbitmq + ports: + - "5003:5003" +``` + +### Kubernetes (Production) +- Helm Charts +- ConfigMaps für Konfiguration +- Secrets für Credentials +- HPA für Auto-Scaling + +## Wartung & Updates + +### Zero-Downtime Deployments +1. Blue-Green Deployment +2. Database Migrations mit Flyway +3. Feature Flags für schrittweise Rollouts + +### Backup-Strategie +- Stündliche Snapshots +- Tägliche Full Backups +- Geo-Redundante Speicherung +- Point-in-Time Recovery + +## Admin Panel Integration + +### Dashboard-Erweiterungen +Das bestehende Admin Panel wird um folgende Lizenzserver-Funktionen erweitert: + +#### 1. **Lizenzserver Status Dashboard** +- Echtzeit-Übersicht aller aktiven Validierungen +- Heartbeat-Monitor mit Karte der aktiven Geräte +- Performance-Metriken (Response Times, Success Rate) +- Anomalie-Warnungen mit Quick Actions + +#### 2. **Lizenz-Detailansicht (Erweitert)** +``` +Bestehende Ansicht + neue Tabs: +- [Basis Info] [Geräte] [Aktivität] [Anomalien] [Logs] + +Aktivität-Tab: +- Timeline der letzten 100 Validierungen +- Heartbeat-Grafik (24h, 7d, 30d) +- IP-Adressen und Locations +- API-Nutzungsstatistiken + +Anomalien-Tab: +- Verdächtige Aktivitäten +- Automatische Warnungen +- Manuelle Actions (Block, Warn, etc.) +``` + +#### 3. **Neue Menüpunkte im Admin Panel** +``` +📊 Lizenzserver + ├── 🔍 Live Monitor + ├── 📈 Analytics + ├── ⚠️ Anomalien + ├── 🔧 Konfiguration + └── 📝 API Logs +``` + +#### 4. **Live Monitor Features** +- WebSocket-basierte Echtzeit-Updates +- Aktive Sessions Counter +- Validierungen pro Minute Graph +- Top 10 aktivste Lizenzen +- Geografische Verteilung + +#### 5. **Analytics Dashboard** +- Nutzungsstatistiken pro Kunde/Lizenz +- Revenue Impact Analysis +- Churn Prediction +- Usage Patterns + +### Integration in bestehende Views + +#### Kunden & Lizenzen Übersicht +```html + +💚 Online (2 Geräte) +⏱️ Vor 5 Min +🔴 2 Warnungen +``` + +#### Audit Log Erweiterung +Neue Event-Typen: +- `license.validation.success` +- `license.validation.failed` +- `license.anomaly.detected` +- `license.device.blocked` +- `license.transfer.completed` + +### Admin Panel Routes (Neue) +```python +# Lizenzserver Monitoring +@app.route('/lizenzserver/monitor') +@app.route('/lizenzserver/analytics') +@app.route('/lizenzserver/anomalies') +@app.route('/lizenzserver/config') + +# API für Live-Updates +@app.route('/api/admin/lizenzserver/live-stats') +@app.websocket('/ws/lizenzserver/updates') +``` + +## Fazit + +Diese Architektur ist darauf ausgelegt, von Anfang an skalierbar und wartbar zu sein. Durch die Microservices-Architektur, Event-Driven Design und sorgfältige Planung der Datenbankstruktur wird sichergestellt, dass zukünftige Erweiterungen ohne größere Refactorings möglich sind. + +**Wichtig**: Alle Lizenzserver-Funktionen sind vollständig im Admin Panel integriert und bieten eine einheitliche Oberfläche für die Verwaltung. Die Implementierung sollte schrittweise erfolgen, wobei jede Phase vollständig getestet wird, bevor zur nächsten übergegangen wird. Besonderes Augenmerk sollte auf Security, Performance und Monitoring gelegt werden, da diese Aspekte für einen Lizenzserver kritisch sind. \ No newline at end of file