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.
 
 
 
 
 
 

271 lines
11 KiB

  1. # Copyright 2023 Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. from unittest.mock import Mock
  16. from synapse.config import ConfigError
  17. from synapse.config.homeserver import HomeServerConfig
  18. from synapse.module_api import ModuleApi
  19. from synapse.types import JsonDict
  20. from tests.server import get_clock, setup_test_homeserver
  21. from tests.unittest import TestCase, skip_unless
  22. from tests.utils import HAS_AUTHLIB, default_config
  23. # These are a few constants that are used as config parameters in the tests.
  24. SERVER_NAME = "test"
  25. ISSUER = "https://issuer/"
  26. CLIENT_ID = "test-client-id"
  27. CLIENT_SECRET = "test-client-secret"
  28. BASE_URL = "https://synapse/"
  29. class CustomAuthModule:
  30. """A module which registers a password auth provider."""
  31. @staticmethod
  32. def parse_config(config: JsonDict) -> None:
  33. pass
  34. def __init__(self, config: None, api: ModuleApi):
  35. api.register_password_auth_provider_callbacks(
  36. auth_checkers={("m.login.password", ("password",)): Mock()},
  37. )
  38. @skip_unless(HAS_AUTHLIB, "requires authlib")
  39. class MSC3861OAuthDelegation(TestCase):
  40. """Test that the Homeserver fails to initialize if the config is invalid."""
  41. def setUp(self) -> None:
  42. self.config_dict: JsonDict = {
  43. **default_config("test"),
  44. "public_baseurl": BASE_URL,
  45. "enable_registration": False,
  46. "experimental_features": {
  47. "msc3861": {
  48. "enabled": True,
  49. "issuer": ISSUER,
  50. "client_id": CLIENT_ID,
  51. "client_auth_method": "client_secret_post",
  52. "client_secret": CLIENT_SECRET,
  53. }
  54. },
  55. }
  56. def parse_config(self) -> HomeServerConfig:
  57. config = HomeServerConfig()
  58. config.parse_config_dict(self.config_dict, "", "")
  59. return config
  60. def test_client_secret_post_works(self) -> None:
  61. self.config_dict["experimental_features"]["msc3861"].update(
  62. client_auth_method="client_secret_post",
  63. client_secret=CLIENT_SECRET,
  64. )
  65. self.parse_config()
  66. def test_client_secret_post_requires_client_secret(self) -> None:
  67. self.config_dict["experimental_features"]["msc3861"].update(
  68. client_auth_method="client_secret_post",
  69. client_secret=None,
  70. )
  71. with self.assertRaises(ConfigError):
  72. self.parse_config()
  73. def test_client_secret_basic_works(self) -> None:
  74. self.config_dict["experimental_features"]["msc3861"].update(
  75. client_auth_method="client_secret_basic",
  76. client_secret=CLIENT_SECRET,
  77. )
  78. self.parse_config()
  79. def test_client_secret_basic_requires_client_secret(self) -> None:
  80. self.config_dict["experimental_features"]["msc3861"].update(
  81. client_auth_method="client_secret_basic",
  82. client_secret=None,
  83. )
  84. with self.assertRaises(ConfigError):
  85. self.parse_config()
  86. def test_client_secret_jwt_works(self) -> None:
  87. self.config_dict["experimental_features"]["msc3861"].update(
  88. client_auth_method="client_secret_jwt",
  89. client_secret=CLIENT_SECRET,
  90. )
  91. self.parse_config()
  92. def test_client_secret_jwt_requires_client_secret(self) -> None:
  93. self.config_dict["experimental_features"]["msc3861"].update(
  94. client_auth_method="client_secret_jwt",
  95. client_secret=None,
  96. )
  97. with self.assertRaises(ConfigError):
  98. self.parse_config()
  99. def test_invalid_client_auth_method(self) -> None:
  100. self.config_dict["experimental_features"]["msc3861"].update(
  101. client_auth_method="invalid",
  102. )
  103. with self.assertRaises(ConfigError):
  104. self.parse_config()
  105. def test_private_key_jwt_requires_jwk(self) -> None:
  106. self.config_dict["experimental_features"]["msc3861"].update(
  107. client_auth_method="private_key_jwt",
  108. )
  109. with self.assertRaises(ConfigError):
  110. self.parse_config()
  111. def test_private_key_jwt_works(self) -> None:
  112. self.config_dict["experimental_features"]["msc3861"].update(
  113. client_auth_method="private_key_jwt",
  114. jwk={
  115. "p": "-frVdP_tZ-J_nIR6HNMDq1N7aunwm51nAqNnhqIyuA8ikx7LlQED1tt2LD3YEvYyW8nxE2V95HlCRZXQPMiRJBFOsbmYkzl2t-MpavTaObB_fct_JqcRtdXddg4-_ihdjRDwUOreq_dpWh6MIKsC3UyekfkHmeEJg5YpOTL15j8",
  116. "kty": "RSA",
  117. "q": "oFw-Enr_YozQB1ab-kawn4jY3yHi8B1nSmYT0s8oTCflrmps5BFJfCkHL5ij3iY15z0o2m0N-jjB1oSJ98O4RayEEYNQlHnTNTl0kRIWzpoqblHUIxVcahIpP_xTovBJzwi8XXoLGqHOOMA-r40LSyVgP2Ut8D9qBwV6_UfT0LU",
  118. "d": "WFkDPYo4b4LIS64D_QtQfGGuAObPvc3HFfp9VZXyq3SJR58XZRHE0jqtlEMNHhOTgbMYS3w8nxPQ_qVzY-5hs4fIanwvB64mAoOGl0qMHO65DTD_WsGFwzYClJPBVniavkLE2Hmpu8IGe6lGliN8vREC6_4t69liY-XcN_ECboVtC2behKkLOEASOIMuS7YcKAhTJFJwkl1dqDlliEn5A4u4xy7nuWQz3juB1OFdKlwGA5dfhDNglhoLIwNnkLsUPPFO-WB5ZNEW35xxHOToxj4bShvDuanVA6mJPtTKjz0XibjB36bj_nF_j7EtbE2PdGJ2KevAVgElR4lqS4ISgQ",
  119. "e": "AQAB",
  120. "kid": "test",
  121. "qi": "cPfNk8l8W5exVNNea4d7QZZ8Qr8LgHghypYAxz8PQh1fNa8Ya1SNUDVzC2iHHhszxxA0vB9C7jGze8dBrvnzWYF1XvQcqNIVVgHhD57R1Nm3dj2NoHIKe0Cu4bCUtP8xnZQUN4KX7y4IIcgRcBWG1hT6DEYZ4BxqicnBXXNXAUI",
  122. "dp": "dKlMHvslV1sMBQaKWpNb3gPq0B13TZhqr3-E2_8sPlvJ3fD8P4CmwwnOn50JDuhY3h9jY5L06sBwXjspYISVv8hX-ndMLkEeF3lrJeA5S70D8rgakfZcPIkffm3tlf1Ok3v5OzoxSv3-67Df4osMniyYwDUBCB5Oq1tTx77xpU8",
  123. "dq": "S4ooU1xNYYcjl9FcuJEEMqKsRrAXzzSKq6laPTwIp5dDwt2vXeAm1a4eDHXC-6rUSZGt5PbqVqzV4s-cjnJMI8YYkIdjNg4NSE1Ac_YpeDl3M3Colb5CQlU7yUB7xY2bt0NOOFp9UJZYJrOo09mFMGjy5eorsbitoZEbVqS3SuE",
  124. "n": "nJbYKqFwnURKimaviyDFrNLD3gaKR1JW343Qem25VeZxoMq1665RHVoO8n1oBm4ClZdjIiZiVdpyqzD5-Ow12YQgQEf1ZHP3CCcOQQhU57Rh5XvScTe5IxYVkEW32IW2mp_CJ6WfjYpfeL4azarVk8H3Vr59d1rSrKTVVinVdZer9YLQyC_rWAQNtHafPBMrf6RYiNGV9EiYn72wFIXlLlBYQ9Fx7bfe1PaL6qrQSsZP3_rSpuvVdLh1lqGeCLR0pyclA9uo5m2tMyCXuuGQLbA_QJm5xEc7zd-WFdux2eXF045oxnSZ_kgQt-pdN7AxGWOVvwoTf9am6mSkEdv6iw",
  125. },
  126. )
  127. self.parse_config()
  128. def test_registration_cannot_be_enabled(self) -> None:
  129. self.config_dict["enable_registration"] = True
  130. with self.assertRaises(ConfigError):
  131. self.parse_config()
  132. def test_user_consent_cannot_be_enabled(self) -> None:
  133. tmpdir = self.mktemp()
  134. os.mkdir(tmpdir)
  135. self.config_dict["user_consent"] = {
  136. "require_at_registration": True,
  137. "version": "1",
  138. "template_dir": tmpdir,
  139. "server_notice_content": {
  140. "msgtype": "m.text",
  141. "body": "foo",
  142. },
  143. }
  144. with self.assertRaises(ConfigError):
  145. self.parse_config()
  146. def test_password_config_cannot_be_enabled(self) -> None:
  147. self.config_dict["password_config"] = {"enabled": True}
  148. with self.assertRaises(ConfigError):
  149. self.parse_config()
  150. def test_oidc_sso_cannot_be_enabled(self) -> None:
  151. self.config_dict["oidc_providers"] = [
  152. {
  153. "idp_id": "microsoft",
  154. "idp_name": "Microsoft",
  155. "issuer": "https://login.microsoftonline.com/<tenant id>/v2.0",
  156. "client_id": "<client id>",
  157. "client_secret": "<client secret>",
  158. "scopes": ["openid", "profile"],
  159. "authorization_endpoint": "https://login.microsoftonline.com/<tenant id>/oauth2/v2.0/authorize",
  160. "token_endpoint": "https://login.microsoftonline.com/<tenant id>/oauth2/v2.0/token",
  161. "userinfo_endpoint": "https://graph.microsoft.com/oidc/userinfo",
  162. }
  163. ]
  164. with self.assertRaises(ConfigError):
  165. self.parse_config()
  166. def test_cas_sso_cannot_be_enabled(self) -> None:
  167. self.config_dict["cas_config"] = {
  168. "enabled": True,
  169. "server_url": "https://cas-server.com",
  170. "displayname_attribute": "name",
  171. "required_attributes": {"userGroup": "staff", "department": "None"},
  172. }
  173. with self.assertRaises(ConfigError):
  174. self.parse_config()
  175. def test_auth_providers_cannot_be_enabled(self) -> None:
  176. self.config_dict["modules"] = [
  177. {
  178. "module": f"{__name__}.{CustomAuthModule.__qualname__}",
  179. "config": {},
  180. }
  181. ]
  182. # This requires actually setting up an HS, as the module will be run on setup,
  183. # which should raise as the module tries to register an auth provider
  184. config = self.parse_config()
  185. reactor, clock = get_clock()
  186. with self.assertRaises(ConfigError):
  187. setup_test_homeserver(
  188. self.addCleanup, reactor=reactor, clock=clock, config=config
  189. )
  190. def test_jwt_auth_cannot_be_enabled(self) -> None:
  191. self.config_dict["jwt_config"] = {
  192. "enabled": True,
  193. "secret": "my-secret-token",
  194. "algorithm": "HS256",
  195. }
  196. with self.assertRaises(ConfigError):
  197. self.parse_config()
  198. def test_login_via_existing_session_cannot_be_enabled(self) -> None:
  199. self.config_dict["login_via_existing_session"] = {"enabled": True}
  200. with self.assertRaises(ConfigError):
  201. self.parse_config()
  202. def test_captcha_cannot_be_enabled(self) -> None:
  203. self.config_dict.update(
  204. enable_registration_captcha=True,
  205. recaptcha_public_key="test",
  206. recaptcha_private_key="test",
  207. )
  208. with self.assertRaises(ConfigError):
  209. self.parse_config()
  210. def test_refreshable_tokens_cannot_be_enabled(self) -> None:
  211. self.config_dict.update(
  212. refresh_token_lifetime="24h",
  213. refreshable_access_token_lifetime="10m",
  214. nonrefreshable_access_token_lifetime="24h",
  215. )
  216. with self.assertRaises(ConfigError):
  217. self.parse_config()
  218. def test_session_lifetime_cannot_be_set(self) -> None:
  219. self.config_dict["session_lifetime"] = "24h"
  220. with self.assertRaises(ConfigError):
  221. self.parse_config()
  222. def test_enable_3pid_changes_cannot_be_enabled(self) -> None:
  223. self.config_dict["enable_3pid_changes"] = True
  224. with self.assertRaises(ConfigError):
  225. self.parse_config()