test_pagure_flask_form.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # -*- coding: utf-8 -*-
  2. """
  3. (c) 2016 - Copyright Red Hat Inc
  4. Authors:
  5. Pierre-Yves Chibon <pingou@pingoured.fr>
  6. """
  7. from __future__ import unicode_literals, absolute_import
  8. import datetime
  9. import unittest
  10. import sys
  11. import time
  12. import os
  13. import flask
  14. import flask_wtf
  15. from mock import patch, MagicMock
  16. sys.path.insert(
  17. 0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
  18. )
  19. import pagure.forms
  20. import tests
  21. class PagureFlaskFormTests(tests.SimplePagureTest):
  22. """Tests for forms of the flask application"""
  23. @patch.dict(
  24. "pagure.config.config", {"SERVER_NAME": "localhost.localdomain"}
  25. )
  26. def setUp(self):
  27. super(PagureFlaskFormTests, self).setUp()
  28. def test_csrf_form_no_input(self):
  29. """Test the CSRF validation if not CSRF is specified."""
  30. with self.app.application.test_request_context(method="POST"):
  31. flask.g.session = MagicMock()
  32. form = pagure.forms.ConfirmationForm()
  33. self.assertFalse(form.validate_on_submit())
  34. def test_csrf_form_w_invalid_input(self):
  35. """Test the CSRF validation with an invalid CSRF specified."""
  36. with self.app.application.test_request_context(method="POST"):
  37. flask.g.session = MagicMock()
  38. form = pagure.forms.ConfirmationForm()
  39. form.csrf_token.data = "foobar"
  40. self.assertFalse(form.validate_on_submit())
  41. def test_csrf_form_w_input(self):
  42. """Test the CSRF validation with a valid CSRF specified."""
  43. with self.app.application.test_request_context(method="POST"):
  44. flask.g.session = MagicMock()
  45. form = pagure.forms.ConfirmationForm()
  46. form.csrf_token.data = form.csrf_token.current_token
  47. self.assertTrue(form.validate_on_submit())
  48. def test_csrf_form_w_expired_input(self):
  49. """Test the CSRF validation with an expired CSRF specified."""
  50. with self.app.application.test_request_context(method="POST"):
  51. flask.g.session = MagicMock()
  52. form = pagure.forms.ConfirmationForm()
  53. data = form.csrf_token.current_token
  54. # CSRF token expired
  55. if hasattr(flask_wtf, "__version__"):
  56. flask_wtf_version = tuple(
  57. [int(v) for v in flask_wtf.__version__.split(".")]
  58. )
  59. if flask_wtf_version and (
  60. flask_wtf_version < (0, 10, 0)
  61. or flask_wtf_version >= (0, 14, 0)
  62. ):
  63. expires = time.time() - 1
  64. else:
  65. expires = (
  66. datetime.datetime.now() - datetime.timedelta(minutes=1)
  67. ).strftime("%Y%m%d%H%M%S")
  68. # Change the CSRF format
  69. if hasattr(flask_wtf, "__version__") and tuple(
  70. [int(e) for e in flask_wtf.__version__.split(".")]
  71. ) >= (0, 14, 0):
  72. import itsdangerous
  73. try: # ItsDangerous-1.0
  74. timestamp = itsdangerous.base64_encode(
  75. itsdangerous.encoding.int_to_bytes(int(expires))
  76. )
  77. except AttributeError: # ItsDangerous-0.24
  78. timestamp = itsdangerous.base64_encode(
  79. itsdangerous.int_to_bytes(int(expires))
  80. )
  81. timestamp = timestamp.decode("ascii")
  82. part1, _, part2 = data.split(".", 2)
  83. form.csrf_token.data = ".".join([part1, timestamp, part2])
  84. else:
  85. _, hmac_csrf = data.split("##", 1)
  86. form.csrf_token.data = "%s##%s" % (expires, hmac_csrf)
  87. self.assertFalse(form.validate_on_submit())
  88. def test_csrf_form_w_unexpiring_input(self):
  89. """Test the CSRF validation with a CSRF not expiring."""
  90. pagure.config.config["WTF_CSRF_TIME_LIMIT"] = None
  91. with self.app.application.test_request_context(method="POST"):
  92. flask.g.session = MagicMock()
  93. form = pagure.forms.ConfirmationForm()
  94. data = form.csrf_token.current_token
  95. if hasattr(flask_wtf, "__version__") and tuple(
  96. [int(e) for e in flask_wtf.__version__.split(".")]
  97. ) >= (0, 14, 0):
  98. form.csrf_token.data = data
  99. else:
  100. _, hmac_csrf = data.split("##", 1)
  101. # CSRF can no longer expire, they have no expiration info
  102. form.csrf_token.data = "##%s" % hmac_csrf
  103. self.assertTrue(form.validate_on_submit())
  104. def test_add_user_form(self):
  105. """Test the AddUserForm of pagure.forms"""
  106. with self.app.application.test_request_context(method="POST"):
  107. flask.g.session = MagicMock()
  108. form = pagure.forms.AddUserForm()
  109. form.csrf_token.data = form.csrf_token.current_token
  110. # No user or access given
  111. self.assertFalse(form.validate_on_submit())
  112. # No access given
  113. form.user.data = "foo"
  114. self.assertFalse(form.validate_on_submit())
  115. form.access.data = "admin"
  116. self.assertTrue(form.validate_on_submit())
  117. def test_add_user_to_group_form(self):
  118. """Test the AddUserToGroup form of pagure.forms"""
  119. with self.app.application.test_request_context(method="POST"):
  120. flask.g.session = MagicMock()
  121. form = pagure.forms.AddUserToGroupForm()
  122. form.csrf_token.data = form.csrf_token.current_token
  123. # No user given
  124. self.assertFalse(form.validate_on_submit())
  125. form.user.data = "foo"
  126. # Everything given
  127. self.assertTrue(form.validate_on_submit())
  128. def test_add_group_form(self):
  129. """Test the AddGroupForm form of pagure.forms"""
  130. with self.app.application.test_request_context(method="POST"):
  131. flask.g.session = MagicMock()
  132. form = pagure.forms.AddGroupForm()
  133. form.csrf_token.data = form.csrf_token.current_token
  134. # No group given
  135. self.assertFalse(form.validate_on_submit())
  136. # No access given
  137. form.group.data = "gname"
  138. self.assertFalse(form.validate_on_submit())
  139. form.access.data = "admin"
  140. self.assertTrue(form.validate_on_submit())
  141. if __name__ == "__main__":
  142. unittest.main(verbosity=2)