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

99 lines
3.3 KiB
Go

package httpapi
import (
"context"
"net/http"
"net/url"
"git.az-it.net/az/morz-infoboard/server/backend/internal/reqcontext"
"git.az-it.net/az/morz-infoboard/server/backend/internal/store"
)
// UserFromContext returns the authenticated *store.User stored in ctx,
// or nil if none is present.
// It delegates to reqcontext so that sub-packages (e.g. manage) can share
// the same context key without creating an import cycle.
func UserFromContext(ctx context.Context) *store.User {
return reqcontext.UserFromContext(ctx)
}
// RequireAuth returns middleware that validates the morz_session cookie.
// On success it stores the *store.User in the request context and calls next.
// On failure it redirects to /login?next=<current-path>.
func RequireAuth(authStore *store.AuthStore) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(reqcontext.SessionCookieName)
if err != nil {
redirectToLogin(w, r)
return
}
user, err := authStore.GetSessionUser(r.Context(), cookie.Value)
if err != nil {
redirectToLogin(w, r)
return
}
ctx := reqcontext.WithUser(r.Context(), user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// RequireAdmin is middleware that allows only users with role "admin".
// It must be chained after RequireAuth (so a user is present in context).
// On failure it responds with 403 Forbidden.
func RequireAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil || user.Role != "admin" {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
// RequireTenantAccess is middleware that allows access only when the
// authenticated user belongs to the tenant identified by the {tenantSlug}
// path value, or when the user has role "admin" (admins can access everything).
// It must be chained after RequireAuth.
func RequireTenantAccess(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
// Admins bypass tenant isolation.
if user.Role == "admin" {
next.ServeHTTP(w, r)
return
}
tenantSlug := r.PathValue("tenantSlug")
// An empty tenantSlug means the route was registered without a
// {tenantSlug} parameter — that is a configuration error. Deny
// access rather than silently granting it to every logged-in user.
if tenantSlug == "" || user.TenantSlug != tenantSlug {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
// chain applies a list of middleware to a handler, wrapping outermost first.
// chain(m1, m2, m3)(h) == m1(m2(m3(h)))
func chain(h http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler {
for i := len(middlewares) - 1; i >= 0; i-- {
h = middlewares[i](h)
}
return h
}
// redirectToLogin issues a 303 redirect to /login with the current path as ?next=.
func redirectToLogin(w http.ResponseWriter, r *http.Request) {
target := "/login?next=" + url.QueryEscape(r.URL.RequestURI())
http.Redirect(w, r, target, http.StatusSeeOther)
}