csrf_middleware.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package ui // import "miniflux.app/v2/internal/ui"
  4. import (
  5. "errors"
  6. "log/slog"
  7. "net/http"
  8. "miniflux.app/v2/internal/crypto"
  9. "miniflux.app/v2/internal/http/request"
  10. "miniflux.app/v2/internal/http/response"
  11. )
  12. type csrfMiddleware struct {
  13. basePath string
  14. }
  15. func newCSRFMiddleware(basePath string) *csrfMiddleware {
  16. return &csrfMiddleware{basePath: basePath}
  17. }
  18. // handle validates the CSRF token on state-changing requests. It must be
  19. // chained inside handleWebSession so that the session is already present
  20. // in the request context.
  21. func (m *csrfMiddleware) handle(next http.Handler) http.Handler {
  22. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  23. if r.Method == http.MethodPost && !m.validate(w, r) {
  24. return
  25. }
  26. next.ServeHTTP(w, r)
  27. })
  28. }
  29. func (m *csrfMiddleware) validate(w http.ResponseWriter, r *http.Request) bool {
  30. csrfToken := request.WebSession(r).CSRF()
  31. formValue := r.FormValue("csrf")
  32. headerValue := r.Header.Get("X-Csrf-Token")
  33. if crypto.ConstantTimeCmp(csrfToken, formValue) || crypto.ConstantTimeCmp(csrfToken, headerValue) {
  34. return true
  35. }
  36. slog.Warn("Invalid or missing CSRF token",
  37. slog.String("url", r.RequestURI),
  38. )
  39. if r.URL.Path == "/login" {
  40. response.HTMLRedirect(w, r, m.basePath+"/")
  41. } else {
  42. response.HTMLBadRequest(w, r, errors.New("invalid or missing CSRF"))
  43. }
  44. return false
  45. }