test_sso.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. from http import HTTPStatus
  13. from typing import BinaryIO, Callable, Dict, List, Optional, Tuple
  14. from unittest.mock import Mock
  15. from twisted.test.proto_helpers import MemoryReactor
  16. from twisted.web.http_headers import Headers
  17. from synapse.api.errors import Codes, SynapseError
  18. from synapse.http.client import RawHeaders
  19. from synapse.server import HomeServer
  20. from synapse.util import Clock
  21. from tests import unittest
  22. from tests.test_utils import SMALL_PNG, FakeResponse
  23. class TestSSOHandler(unittest.HomeserverTestCase):
  24. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  25. self.http_client = Mock(spec=["get_file"])
  26. self.http_client.get_file.side_effect = mock_get_file
  27. self.http_client.user_agent = b"Synapse Test"
  28. hs = self.setup_test_homeserver(
  29. proxied_blacklisted_http_client=self.http_client
  30. )
  31. return hs
  32. def test_set_avatar(self) -> None:
  33. """Tests successfully setting the avatar of a newly created user"""
  34. handler = self.hs.get_sso_handler()
  35. # Create a new user to set avatar for
  36. reg_handler = self.hs.get_registration_handler()
  37. user_id = self.get_success(reg_handler.register_user(approved=True))
  38. self.assertTrue(
  39. self.get_success(handler.set_avatar(user_id, "http://my.server/me.png"))
  40. )
  41. # Ensure avatar is set on this newly created user,
  42. # so no need to compare for the exact image
  43. profile_handler = self.hs.get_profile_handler()
  44. profile = self.get_success(profile_handler.get_profile(user_id))
  45. self.assertIsNot(profile["avatar_url"], None)
  46. @unittest.override_config({"max_avatar_size": 1})
  47. def test_set_avatar_too_big_image(self) -> None:
  48. """Tests that saving an avatar fails when it is too big"""
  49. handler = self.hs.get_sso_handler()
  50. # any random user works since image check is supposed to fail
  51. user_id = "@sso-user:test"
  52. self.assertFalse(
  53. self.get_success(handler.set_avatar(user_id, "http://my.server/me.png"))
  54. )
  55. @unittest.override_config({"allowed_avatar_mimetypes": ["image/jpeg"]})
  56. def test_set_avatar_incorrect_mime_type(self) -> None:
  57. """Tests that saving an avatar fails when its mime type is not allowed"""
  58. handler = self.hs.get_sso_handler()
  59. # any random user works since image check is supposed to fail
  60. user_id = "@sso-user:test"
  61. self.assertFalse(
  62. self.get_success(handler.set_avatar(user_id, "http://my.server/me.png"))
  63. )
  64. def test_skip_saving_avatar_when_not_changed(self) -> None:
  65. """Tests whether saving of avatar correctly skips if the avatar hasn't
  66. changed"""
  67. handler = self.hs.get_sso_handler()
  68. # Create a new user to set avatar for
  69. reg_handler = self.hs.get_registration_handler()
  70. user_id = self.get_success(reg_handler.register_user(approved=True))
  71. # set avatar for the first time, should be a success
  72. self.assertTrue(
  73. self.get_success(handler.set_avatar(user_id, "http://my.server/me.png"))
  74. )
  75. # get avatar picture for comparison after another attempt
  76. profile_handler = self.hs.get_profile_handler()
  77. profile = self.get_success(profile_handler.get_profile(user_id))
  78. url_to_match = profile["avatar_url"]
  79. # set same avatar for the second time, should be a success
  80. self.assertTrue(
  81. self.get_success(handler.set_avatar(user_id, "http://my.server/me.png"))
  82. )
  83. # compare avatar picture's url from previous step
  84. profile = self.get_success(profile_handler.get_profile(user_id))
  85. self.assertEqual(profile["avatar_url"], url_to_match)
  86. async def mock_get_file(
  87. url: str,
  88. output_stream: BinaryIO,
  89. max_size: Optional[int] = None,
  90. headers: Optional[RawHeaders] = None,
  91. is_allowed_content_type: Optional[Callable[[str], bool]] = None,
  92. ) -> Tuple[int, Dict[bytes, List[bytes]], str, int]:
  93. fake_response = FakeResponse(code=404)
  94. if url == "http://my.server/me.png":
  95. fake_response = FakeResponse(
  96. code=200,
  97. headers=Headers(
  98. {"Content-Type": ["image/png"], "Content-Length": [str(len(SMALL_PNG))]}
  99. ),
  100. body=SMALL_PNG,
  101. )
  102. if max_size is not None and max_size < len(SMALL_PNG):
  103. raise SynapseError(
  104. HTTPStatus.BAD_GATEWAY,
  105. "Requested file is too large > %r bytes" % (max_size,),
  106. Codes.TOO_LARGE,
  107. )
  108. if is_allowed_content_type and not is_allowed_content_type("image/png"):
  109. raise SynapseError(
  110. HTTPStatus.BAD_GATEWAY,
  111. (
  112. "Requested file's content type not allowed for this operation: %s"
  113. % "image/png"
  114. ),
  115. )
  116. output_stream.write(fake_response.body)
  117. return len(SMALL_PNG), {b"Content-Type": [b"image/png"]}, "", 200