You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

csrf_test.go 1.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package integration
  4. import (
  5. "net/http"
  6. "strings"
  7. "testing"
  8. "code.gitea.io/gitea/models/unittest"
  9. user_model "code.gitea.io/gitea/models/user"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/tests"
  12. "github.com/stretchr/testify/assert"
  13. )
  14. func TestCsrfProtection(t *testing.T) {
  15. defer tests.PrepareTestEnv(t)()
  16. // test web form csrf via form
  17. user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
  18. session := loginUser(t, user.Name)
  19. req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
  20. "_csrf": "fake_csrf",
  21. })
  22. session.MakeRequest(t, req, http.StatusSeeOther)
  23. resp := session.MakeRequest(t, req, http.StatusSeeOther)
  24. loc := resp.Header().Get("Location")
  25. assert.Equal(t, setting.AppSubURL+"/", loc)
  26. resp = session.MakeRequest(t, NewRequest(t, "GET", loc), http.StatusOK)
  27. htmlDoc := NewHTMLParser(t, resp.Body)
  28. assert.Equal(t, "Bad Request: invalid CSRF token",
  29. strings.TrimSpace(htmlDoc.doc.Find(".ui.message").Text()),
  30. )
  31. // test web form csrf via header. TODO: should use an UI api to test
  32. req = NewRequest(t, "POST", "/user/settings")
  33. req.Header.Add("X-Csrf-Token", "fake_csrf")
  34. session.MakeRequest(t, req, http.StatusSeeOther)
  35. resp = session.MakeRequest(t, req, http.StatusSeeOther)
  36. loc = resp.Header().Get("Location")
  37. assert.Equal(t, setting.AppSubURL+"/", loc)
  38. resp = session.MakeRequest(t, NewRequest(t, "GET", loc), http.StatusOK)
  39. htmlDoc = NewHTMLParser(t, resp.Body)
  40. assert.Equal(t, "Bad Request: invalid CSRF token",
  41. strings.TrimSpace(htmlDoc.doc.Find(".ui.message").Text()),
  42. )
  43. }