morz-infoboard/server/backend/internal/httpapi/ratelimit.go
Jesko Anschütz dd3ec070f7 Security-Review + Phase 6: CSRF, Rate-Limiting, Tenant-Isolation, Screenshot, Ansible
### Security-Fixes (K1–K6, W1–W4, W7, N1, N5–N6, V1, V5–V7)
- K1: CSRF-Schutz via Double-Submit-Cookie (httpapi/csrf.go + csrf_helpers.go)
- K2: requireScreenAccess() in allen manage-Handlern (Tenant-Isolation)
- K3: Tenant-Check bei DELETE /api/v1/media/{id}
- K4: requirePlaylistAccess() + GetByItemID() für JSON-API Playlist-Routen
- K5: Admin-Passwort nur noch als [gesetzt] geloggt
- K6: POST /api/v1/screens/register mit Pre-Shared-Secret (MORZ_INFOBOARD_REGISTER_SECRET)
- W1: Race Condition bei order_index behoben (atomare Subquery in AddItem)
- W2: Graceful Shutdown mit 15s Timeout auf SIGTERM/SIGINT
- W3: http.MaxBytesReader (512 MB) in allen Upload-Handlern
- W4: err.Error() nicht mehr an den Client
- W7: Template-Execution via bytes.Buffer (kein partial write bei Fehler)
- N1: Rate-Limiting auf /login (5 Versuche/Minute pro IP, httpapi/ratelimit.go)
- N5: Directory-Listing auf /uploads/ deaktiviert (neuteredFileSystem)
- N6: Uploads nach Tenant getrennt (uploads/{tenantSlug}/)
- V1: Upload-Logik konsolidiert in internal/fileutil/fileutil.go
- V5: Cookie-Name als Konstante reqcontext.SessionCookieName
- V6: Strukturiertes Logging mit log/slog + JSON-Handler
- V7: DB-Pool wird im Graceful-Shutdown geschlossen

### Phase 6: Screenshot-Erzeugung
- player/agent/internal/screenshot/screenshot.go erstellt
- Integration in app.go mit MORZ_INFOBOARD_SCREENSHOT_EVERY Config

### UX: PDF.js Integration
- pdf.min.js + pdf.worker.min.js als lokale Assets eingebettet
- Automatisches Seitendurchblättern im Player

### Ansible: Neue Rollen
- signage_base, signage_server, signage_provision erstellt
- inventory.yml und site.yml erweitert

### Konzept-Docs
- GRUPPEN-KONZEPT.md, KAMPAGNEN-AKTIVIERUNG.md, MONITORING-KONZEPT.md
- PROVISION-KONZEPT.md, TEMPLATE-EDITOR.md, WATCHDOG-KONZEPT.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-23 21:06:35 +01:00

91 lines
2.2 KiB
Go

package httpapi
// ratelimit.go — Einfaches In-Memory-Rate-Limiting für POST /login (N1).
//
// Implementierung: Sliding-Window-Counter pro IP-Adresse.
// Erlaubt maximal loginMaxAttempts Versuche pro loginWindow.
// Ältere Einträge werden periodisch aus der Map bereinigt.
import (
"net"
"net/http"
"sync"
"time"
)
const (
loginMaxAttempts = 5
loginWindow = 1 * time.Minute
cleanupInterval = 5 * time.Minute
)
type loginAttempt struct {
count int
windowEnd time.Time
}
type loginRateLimiter struct {
mu sync.Mutex
entries map[string]*loginAttempt
}
func newLoginRateLimiter() *loginRateLimiter {
rl := &loginRateLimiter{
entries: make(map[string]*loginAttempt),
}
go rl.cleanup()
return rl
}
// Allow returns true if the IP is within the rate limit, false if it should be blocked.
func (rl *loginRateLimiter) Allow(ip string) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
e, ok := rl.entries[ip]
if !ok || now.After(e.windowEnd) {
// Neues Fenster.
rl.entries[ip] = &loginAttempt{count: 1, windowEnd: now.Add(loginWindow)}
return true
}
e.count++
return e.count <= loginMaxAttempts
}
// cleanup bereinigt abgelaufene Einträge periodisch.
func (rl *loginRateLimiter) cleanup() {
ticker := time.NewTicker(cleanupInterval)
defer ticker.Stop()
for range ticker.C {
rl.mu.Lock()
now := time.Now()
for ip, e := range rl.entries {
if now.After(e.windowEnd) {
delete(rl.entries, ip)
}
}
rl.mu.Unlock()
}
}
// LoginRateLimit ist eine globale Instanz des Rate-Limiters (package-level Singleton).
var LoginRateLimit = newLoginRateLimiter()
// RateLimitLogin ist Middleware, die Brute-Force-Angriffe auf den Login-Endpoint verhindert.
// Bei Überschreitung wird 429 Too Many Requests zurückgegeben.
func RateLimitLogin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// IP-Adresse extrahieren (berücksichtigt X-Forwarded-For nicht, um Spoofing zu vermeiden).
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
ip = r.RemoteAddr
}
if !LoginRateLimit.Allow(ip) {
http.Error(w, "Zu viele Anmeldeversuche. Bitte warte eine Minute.", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}