Project-Image-Uploader/AUTHENTICATION.md
matthias.lotz cdb2aa95e6 feat: Add comprehensive test suite and admin API authentication
🧪 Testing Infrastructure (45 tests, 100% passing)
- Implemented Jest + Supertest framework for automated testing
- Unit tests: 5 tests for auth middleware (100% coverage)
- Integration tests: 40 tests covering admin, consent, migration, upload APIs
- Test execution time: ~10 seconds for full suite
- Coverage: 26% statements, 15% branches (realistic start)
- In-memory SQLite database for isolated testing
- Singleton server pattern for fast test execution
- Automatic cleanup and teardown

🔒 Admin API Authentication
- Bearer token authentication for all admin endpoints
- requireAdminAuth middleware with ADMIN_API_KEY validation
- Protected routes: /api/admin/*, /api/system/migration/migrate|rollback
- Complete authentication guide in AUTHENTICATION.md
- HTTP 403 for missing/invalid tokens, 500 if not configured
- Ready for production with token rotation support

📋 API Route Documentation
- Single Source of Truth: backend/src/routes/routeMappings.js
- Comprehensive route overview in backend/src/routes/README.md
- Express routing order documented (specific before generic)
- Frontend integration guide with authentication examples
- OpenAPI auto-generation integrated

🐛 Bug Fixes
- Fixed SQLite connection not properly awaited (caused test hangs)
- Fixed upload validation checking req.files.file before req.files
- Fixed Express route order (consent before admin router)
- Fixed test environment using /tmp for uploads (permission issues)

📚 Documentation Updates
- Updated README.md with testing and authentication features
- Updated README.dev.md with testing section and API development guide
- Updated CHANGELOG.md with complete feature documentation
- Updated FEATURE_PLAN-autogen-openapi.md (status: 100% complete)
- Added frontend/MIGRATION-GUIDE.md for frontend team

🚀 Frontend Impact
Frontend needs to add Bearer token to all /api/admin/* calls.
See frontend/MIGRATION-GUIDE.md for detailed instructions.

Test Status:  45/45 passing (100%)
Backend:  Production ready
Frontend: ⚠️ Migration required (see MIGRATION-GUIDE.md)
2025-11-16 18:08:48 +01:00

200 lines
5.0 KiB
Markdown

# API Authentication Guide
## Übersicht
Die API verwendet **zwei verschiedene Authentifizierungs-Mechanismen** für unterschiedliche Zugriffslevel:
### 1. Admin-Routes (Bearer Token)
- **Zweck**: Geschützte Admin-Funktionen (Deletion Log, Cleanup, Moderation, Statistics)
- **Methode**: Bearer Token im Authorization Header
- **Konfiguration**: `.env``ADMIN_API_KEY`
### 2. Management-Routes (UUID Token)
- **Zweck**: Self-Service Portal für Gruppen-Verwaltung
- **Methode**: UUID v4 Token in URL-Path
- **Quelle**: Automatisch generiert beim Upload, gespeichert in DB
---
## 1. Admin Authentication
### Setup
1. **Sicheren Admin-Key generieren**:
```bash
# Linux/Mac:
openssl rand -hex 32
# Oder Node.js:
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
```
2. **In `.env` eintragen**:
```env
ADMIN_API_KEY=dein-generierter-key-hier
```
3. **Server neu starten**
### Verwendung
Alle Requests an `/api/admin/*` benötigen den Authorization Header:
```bash
curl -H "Authorization: Bearer dein-generierter-key-hier" \
http://localhost:5000/api/admin/deletion-log
```
**Postman/Insomnia**:
- Type: `Bearer Token`
- Token: `dein-generierter-key-hier`
### Geschützte Endpoints
| Endpoint | Method | Beschreibung |
|----------|--------|--------------|
| `/api/admin/deletion-log` | GET | Deletion Log Einträge |
| `/api/admin/deletion-log/csv` | GET | Deletion Log als CSV |
| `/api/admin/cleanup/run` | POST | Cleanup manuell starten |
| `/api/admin/cleanup/status` | GET | Cleanup Status |
| `/api/admin/rate-limiter/stats` | GET | Rate-Limiter Statistiken |
| `/api/admin/management-audit` | GET | Management Audit Log |
| `/api/admin/groups` | GET | Alle Gruppen (Moderation) |
| `/api/admin/groups/:id/approve` | PUT | Gruppe freigeben |
| `/api/admin/groups/:id` | DELETE | Gruppe löschen |
### Error Codes
| Status | Bedeutung |
|--------|-----------|
| `403` | Authorization header fehlt oder ungültig |
| `500` | ADMIN_API_KEY nicht konfiguriert |
---
## 2. Management Authentication
### Setup
**Kein Setup nötig!** Token werden automatisch generiert.
### Funktionsweise
1. **Bei Upload** wird automatisch ein UUID v4 Token generiert
2. **Token wird gespeichert** in DB (Spalte: `management_token`)
3. **Token wird zurückgegeben** in der Upload-Response
4. **Nutzer erhält Link** wie: `https://example.com/manage/{token}`
### Verwendung
Token wird **im URL-Path** übergeben (nicht im Header):
```bash
# Token validieren und Daten laden
GET /api/manage/550e8400-e29b-41d4-a716-446655440000
# Bilder hochladen
POST /api/manage/550e8400-e29b-41d4-a716-446655440000/images
# Gruppe löschen
DELETE /api/manage/550e8400-e29b-41d4-a716-446655440000
```
### Geschützte Endpoints
| Endpoint | Method | Beschreibung |
|----------|--------|--------------|
| `/api/manage/:token` | GET | Gruppen-Daten laden |
| `/api/manage/:token/consents` | PUT | Social Media Consents |
| `/api/manage/:token/metadata` | PUT | Metadaten bearbeiten |
| `/api/manage/:token/images` | POST | Bilder hinzufügen |
| `/api/manage/:token/images/:imageId` | DELETE | Bild löschen |
| `/api/manage/:token` | DELETE | Gruppe löschen |
### Sicherheits-Features
- **Token-Format Validierung**: Nur gültige UUID v4 Tokens
- **Rate Limiting**: Schutz vor Brute-Force
- **Audit Logging**: Alle Aktionen werden geloggt
- **DB-Check**: Token muss in DB existieren
### Error Codes
| Status | Bedeutung |
|--------|-----------|
| `404` | Token nicht gefunden oder Gruppe gelöscht |
| `429` | Rate Limit überschritten |
---
## Testing
### Unit Tests
```bash
npm test -- tests/unit/auth.test.js
```
### Integration Tests
```bash
# Admin Auth testen
npm test -- tests/api/admin-auth.test.js
# Alle API Tests
npm test
```
### Manuelles Testen
**Admin-Route ohne Auth**:
```bash
curl http://localhost:5000/api/admin/deletion-log
# → 403 Forbidden
```
**Admin-Route mit Auth**:
```bash
curl -H "Authorization: Bearer your-key" \
http://localhost:5000/api/admin/deletion-log
# → 200 OK
```
---
## Production Checklist
- [ ] `ADMIN_API_KEY` mit sicherem 64-Zeichen Key setzen
- [ ] `.env` nicht in Git committen (bereits in `.gitignore`)
- [ ] HTTPS verwenden (TLS/SSL)
- [ ] Rate Limiting aktiviert prüfen
- [ ] Audit Logs regelmäßig überprüfen
- [ ] Token-Rotation Policy für Admin-Key implementieren
---
## Sicherheits-Hinweise
### Admin-Key Rotation
Admin-Key regelmäßig erneuern (z.B. alle 90 Tage):
1. Neuen Key generieren
2. `.env` aktualisieren
3. Server neu starten
4. Alte Clients auf neuen Key umstellen
### Management-Token
- Token sind **permanent gültig** bis Gruppe gelöscht wird
- Bei Verdacht auf Leak: Gruppe löschen (löscht auch Token)
- Token-Format (UUID v4) macht Brute-Force unpraktisch
### Best Practices
- Admin-Key **nie** im Code hart-kodieren
- Admin-Key **nie** in Logs/Errors ausgeben
- Requests über HTTPS (kein Plain-HTTP in Production)
- Rate-Limiting für beide Auth-Typen aktiv
- Audit-Logs regelmäßig auf Anomalien prüfen