morz-infoboard/server/backend/internal/httpapi/manage/auth.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

180 lines
5.7 KiB
Go

package manage
import (
"html/template"
"net/http"
"net/url"
"strings"
"time"
"git.az-it.net/az/morz-infoboard/server/backend/internal/config"
"git.az-it.net/az/morz-infoboard/server/backend/internal/reqcontext"
"git.az-it.net/az/morz-infoboard/server/backend/internal/store"
"golang.org/x/crypto/bcrypt"
)
const sessionTTL = 8 * time.Hour
// sessionCookieName ist ein Alias auf die zentrale Konstante (V5).
const sessionCookieName = reqcontext.SessionCookieName
// loginData is the template data for the login page.
type loginData struct {
Error string
Next string
CSRFToken string
}
// HandleLoginUI renders the login form (GET /login).
// If a valid session cookie is already present, the user is redirected to /admin
// (or the tenant dashboard once tenants are wired up in Phase 3).
func HandleLoginUI(authStore *store.AuthStore, cfg config.Config) http.HandlerFunc {
tmpl := template.Must(template.New("login").Parse(loginTmpl))
return func(w http.ResponseWriter, r *http.Request) {
// Redirect if already logged in.
if cookie, err := r.Cookie(sessionCookieName); err == nil {
if u, err := authStore.GetSessionUser(r.Context(), cookie.Value); err == nil {
if u.Role == "admin" {
http.Redirect(w, r, "/admin", http.StatusSeeOther)
} else if u.TenantSlug != "" {
http.Redirect(w, r, "/manage/"+u.TenantSlug, http.StatusSeeOther)
} else {
http.Redirect(w, r, "/admin", http.StatusSeeOther)
}
return
}
}
// K1: CSRF-Token für das Login-Formular setzen/erneuern.
csrfToken := setCSRFCookie(w, r, cfg.DevMode)
next := r.URL.Query().Get("next")
data := loginData{Next: sanitizeNext(next), CSRFToken: csrfToken}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = tmpl.Execute(w, data)
}
}
// HandleLoginPost handles form submission (POST /login).
// It validates credentials, creates a session, sets the session cookie and
// redirects the user based on their role or the ?next= parameter.
func HandleLoginPost(authStore *store.AuthStore, cfg config.Config) http.HandlerFunc {
tmpl := template.Must(template.New("login").Parse(loginTmpl))
renderError := func(w http.ResponseWriter, next, msg string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusUnauthorized)
_ = tmpl.Execute(w, loginData{Error: msg, Next: next})
}
return func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
renderError(w, "", "Ungültige Anfrage.")
return
}
username := strings.TrimSpace(r.FormValue("username"))
password := r.FormValue("password")
next := sanitizeNext(r.FormValue("next"))
if username == "" || password == "" {
renderError(w, next, "Bitte Benutzername und Passwort eingeben.")
return
}
user, err := authStore.GetUserByUsername(r.Context(), username)
if err != nil {
// Mitigate user-enumeration timing leak: run a dummy bcrypt
// comparison so that unknown-user and wrong-password responses
// take approximately the same time. The dummy hash is a
// pre-computed bcrypt hash of "dummy" (cost 12).
const dummyHash = "$2a$12$44H3KPmJUDdgNss7JB7Qneg9GWEl2OgxWwSqVpXRaQdki8T3U9ED2"
_ = bcrypt.CompareHashAndPassword([]byte(dummyHash), []byte(password))
renderError(w, next, "Benutzername oder Passwort falsch.")
return
}
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(password)); err != nil {
renderError(w, next, "Benutzername oder Passwort falsch.")
return
}
session, err := authStore.CreateSession(r.Context(), user.ID, sessionTTL)
if err != nil {
renderError(w, next, "Interner Fehler beim Erstellen der Sitzung.")
return
}
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: session.ID,
Path: "/",
MaxAge: int(sessionTTL.Seconds()),
HttpOnly: true,
Secure: !cfg.DevMode,
SameSite: http.SameSiteLaxMode,
})
// Redirect: honour ?next= for relative paths, otherwise role-based default.
if next != "" {
http.Redirect(w, r, next, http.StatusSeeOther)
return
}
switch user.Role {
case "admin":
http.Redirect(w, r, "/admin", http.StatusSeeOther)
default:
if user.TenantSlug != "" {
http.Redirect(w, r, "/manage/"+user.TenantSlug, http.StatusSeeOther)
} else {
http.Redirect(w, r, "/admin", http.StatusSeeOther)
}
}
}
}
// HandleLogoutPost deletes the session and clears the cookie (POST /logout).
func HandleLogoutPost(authStore *store.AuthStore, cfg config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if cookie, err := r.Cookie(sessionCookieName); err == nil {
_ = authStore.DeleteSession(r.Context(), cookie.Value)
}
// Expire the cookie immediately.
// Secure must match the flag used when the cookie was set so that
// browsers on HTTPS connections honour the expiry directive.
http.SetCookie(w, &http.Cookie{
Name: sessionCookieName,
Value: "",
Path: "/",
MaxAge: -1,
HttpOnly: true,
Secure: !cfg.DevMode,
SameSite: http.SameSiteLaxMode,
})
http.Redirect(w, r, "/login", http.StatusSeeOther)
}
}
// sanitizeNext ensures the redirect target is a safe relative path.
// Only paths starting with "/" and not containing "//" or a scheme are allowed.
func sanitizeNext(next string) string {
if next == "" {
return ""
}
// Reject absolute URLs (contain scheme or authority).
if strings.Contains(next, "://") || strings.Contains(next, "//") {
return ""
}
// Must start with a slash.
if !strings.HasPrefix(next, "/") {
return ""
}
// Validate via url.Parse — rejects anything with a host component.
u, err := url.ParseRequestURI(next)
if err != nil || u.Host != "" || u.Scheme != "" {
return ""
}
return next
}