csrf_middleware_test.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. "bytes"
  6. "context"
  7. "mime/multipart"
  8. "net/http"
  9. "net/http/httptest"
  10. "net/url"
  11. "os"
  12. "strings"
  13. "testing"
  14. "miniflux.app/v2/internal/http/request"
  15. "miniflux.app/v2/internal/model"
  16. )
  17. func newCSRFTestSession(authenticated bool) *model.WebSession {
  18. session, _ := model.NewWebSession("test", "127.0.0.1")
  19. if authenticated {
  20. session.SetUser(&model.User{ID: 1})
  21. }
  22. return session
  23. }
  24. func withCSRFTestSession(r *http.Request, session *model.WebSession) *http.Request {
  25. return r.WithContext(context.WithValue(r.Context(), request.WebSessionContextKey, session))
  26. }
  27. func newMultipartBody(t *testing.T, fields map[string]string, fileContent []byte) (*bytes.Buffer, string) {
  28. t.Helper()
  29. body := &bytes.Buffer{}
  30. writer := multipart.NewWriter(body)
  31. for name, value := range fields {
  32. if err := writer.WriteField(name, value); err != nil {
  33. t.Fatal(err)
  34. }
  35. }
  36. if fileContent != nil {
  37. part, err := writer.CreateFormFile("file", "feeds.opml")
  38. if err != nil {
  39. t.Fatal(err)
  40. }
  41. if _, err := part.Write(fileContent); err != nil {
  42. t.Fatal(err)
  43. }
  44. }
  45. if err := writer.Close(); err != nil {
  46. t.Fatal(err)
  47. }
  48. return body, writer.FormDataContentType()
  49. }
  50. func TestCSRFMiddlewareIgnoresMultipartBodyWithoutAuthentication(t *testing.T) {
  51. session := newCSRFTestSession(false)
  52. body, contentType := newMultipartBody(t, map[string]string{"csrf": session.CSRF()}, []byte("<opml/>"))
  53. r := httptest.NewRequest(http.MethodPost, "/login", body)
  54. r.Header.Set("Content-Type", contentType)
  55. r = withCSRFTestSession(r, session)
  56. handler := newCSRFMiddleware("/base").handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  57. t.Fatal(`The next handler should not be called`)
  58. }))
  59. w := httptest.NewRecorder()
  60. handler.ServeHTTP(w, r)
  61. if w.Code != http.StatusFound {
  62. t.Fatalf(`Unexpected status code, got: %d`, w.Code)
  63. }
  64. if location := w.Header().Get("Location"); location != "/base/" {
  65. t.Fatalf(`Unexpected redirect location, got: %q`, location)
  66. }
  67. if r.MultipartForm != nil {
  68. t.Fatal(`The multipart form should not be parsed before authentication`)
  69. }
  70. }
  71. func TestCSRFMiddlewareAcceptsURLEncodedFormWithoutAuthentication(t *testing.T) {
  72. session := newCSRFTestSession(false)
  73. form := url.Values{"csrf": {session.CSRF()}, "username": {"admin"}}
  74. r := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(form.Encode()))
  75. r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  76. r = withCSRFTestSession(r, session)
  77. called := false
  78. handler := newCSRFMiddleware("").handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  79. called = true
  80. if username := r.FormValue("username"); username != "admin" {
  81. t.Fatalf(`Unexpected username, got: %q`, username)
  82. }
  83. }))
  84. handler.ServeHTTP(httptest.NewRecorder(), r)
  85. if !called {
  86. t.Fatal(`The next handler should be called`)
  87. }
  88. }
  89. func TestCSRFMiddlewareAcceptsHeaderWithoutParsingBody(t *testing.T) {
  90. session := newCSRFTestSession(false)
  91. r := httptest.NewRequest(http.MethodPost, "/webauthn/login/finish", strings.NewReader(`{}`))
  92. r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  93. r.Header.Set("X-Csrf-Token", session.CSRF())
  94. r = withCSRFTestSession(r, session)
  95. called := false
  96. handler := newCSRFMiddleware("").handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  97. called = true
  98. }))
  99. handler.ServeHTTP(httptest.NewRecorder(), r)
  100. if !called {
  101. t.Fatal(`The next handler should be called`)
  102. }
  103. if r.Form != nil {
  104. t.Fatal(`The request body should not be parsed when the header token is valid`)
  105. }
  106. }
  107. func TestCSRFMiddlewareAcceptsMultipartFormWhenAuthenticated(t *testing.T) {
  108. session := newCSRFTestSession(true)
  109. body, contentType := newMultipartBody(t, map[string]string{"csrf": session.CSRF()}, []byte("<opml/>"))
  110. r := httptest.NewRequest(http.MethodPost, "/upload", body)
  111. r.Header.Set("Content-Type", contentType)
  112. r = withCSRFTestSession(r, session)
  113. called := false
  114. handler := newCSRFMiddleware("").handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  115. called = true
  116. file, _, err := r.FormFile("file")
  117. if err != nil {
  118. t.Fatalf(`Unable to read the uploaded file: %v`, err)
  119. }
  120. file.Close()
  121. }))
  122. handler.ServeHTTP(httptest.NewRecorder(), r)
  123. if !called {
  124. t.Fatal(`The next handler should be called`)
  125. }
  126. }
  127. func TestCSRFMiddlewareRejectsQueryStringToken(t *testing.T) {
  128. session := newCSRFTestSession(true)
  129. r := httptest.NewRequest(http.MethodPost, "/feeds/refresh?csrf="+url.QueryEscape(session.CSRF()), nil)
  130. r = withCSRFTestSession(r, session)
  131. handler := newCSRFMiddleware("").handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  132. t.Fatal(`The next handler should not be called`)
  133. }))
  134. w := httptest.NewRecorder()
  135. handler.ServeHTTP(w, r)
  136. if w.Code != http.StatusBadRequest {
  137. t.Fatalf(`Unexpected status code, got: %d`, w.Code)
  138. }
  139. }
  140. func TestCSRFMiddlewareRemovesMultipartTemporaryFiles(t *testing.T) {
  141. // os.TempDir reads TMPDIR on Unix and TMP on Windows.
  142. tempDir := t.TempDir()
  143. t.Setenv("TMPDIR", tempDir)
  144. t.Setenv("TMP", tempDir)
  145. session := newCSRFTestSession(true)
  146. body, contentType := newMultipartBody(t, nil, bytes.Repeat([]byte("a"), 4096))
  147. r := httptest.NewRequest(http.MethodPost, "/upload", body)
  148. r.Header.Set("Content-Type", contentType)
  149. r.Header.Set("X-Csrf-Token", session.CSRF())
  150. r = withCSRFTestSession(r, session)
  151. handler := newCSRFMiddleware("").handle(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  152. // A tiny memory limit forces the file part to be written to disk.
  153. if err := r.ParseMultipartForm(1); err != nil {
  154. t.Fatalf(`Unable to parse the multipart form: %v`, err)
  155. }
  156. entries, err := os.ReadDir(tempDir)
  157. if err != nil {
  158. t.Fatal(err)
  159. }
  160. if len(entries) == 0 {
  161. t.Fatal(`Expected the file part to be stored in a temporary file`)
  162. }
  163. }))
  164. handler.ServeHTTP(httptest.NewRecorder(), r)
  165. entries, err := os.ReadDir(tempDir)
  166. if err != nil {
  167. t.Fatal(err)
  168. }
  169. if len(entries) != 0 {
  170. t.Fatalf(`Expected temporary files to be removed, found %d`, len(entries))
  171. }
  172. }