1
0

test_oauth_delegation.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. from unittest.mock import Mock
  15. from synapse.config import ConfigError
  16. from synapse.config.homeserver import HomeServerConfig
  17. from synapse.module_api import ModuleApi
  18. from synapse.types import JsonDict
  19. from tests.server import get_clock, setup_test_homeserver
  20. from tests.unittest import TestCase, skip_unless
  21. from tests.utils import default_config
  22. try:
  23. import authlib # noqa: F401
  24. HAS_AUTHLIB = True
  25. except ImportError:
  26. HAS_AUTHLIB = False
  27. # These are a few constants that are used as config parameters in the tests.
  28. SERVER_NAME = "test"
  29. ISSUER = "https://issuer/"
  30. CLIENT_ID = "test-client-id"
  31. CLIENT_SECRET = "test-client-secret"
  32. BASE_URL = "https://synapse/"
  33. class CustomAuthModule:
  34. """A module which registers a password auth provider."""
  35. @staticmethod
  36. def parse_config(config: JsonDict) -> None:
  37. pass
  38. def __init__(self, config: None, api: ModuleApi):
  39. api.register_password_auth_provider_callbacks(
  40. auth_checkers={("m.login.password", ("password",)): Mock()},
  41. )
  42. @skip_unless(HAS_AUTHLIB, "requires authlib")
  43. class MSC3861OAuthDelegation(TestCase):
  44. """Test that the Homeserver fails to initialize if the config is invalid."""
  45. def setUp(self) -> None:
  46. self.config_dict: JsonDict = {
  47. **default_config("test"),
  48. "public_baseurl": BASE_URL,
  49. "enable_registration": False,
  50. "experimental_features": {
  51. "msc3861": {
  52. "enabled": True,
  53. "issuer": ISSUER,
  54. "client_id": CLIENT_ID,
  55. "client_auth_method": "client_secret_post",
  56. "client_secret": CLIENT_SECRET,
  57. }
  58. },
  59. }
  60. def parse_config(self) -> HomeServerConfig:
  61. config = HomeServerConfig()
  62. config.parse_config_dict(self.config_dict, "", "")
  63. return config
  64. def test_client_secret_post_works(self) -> None:
  65. self.config_dict["experimental_features"]["msc3861"].update(
  66. client_auth_method="client_secret_post",
  67. client_secret=CLIENT_SECRET,
  68. )
  69. self.parse_config()
  70. def test_client_secret_post_requires_client_secret(self) -> None:
  71. self.config_dict["experimental_features"]["msc3861"].update(
  72. client_auth_method="client_secret_post",
  73. client_secret=None,
  74. )
  75. with self.assertRaises(ConfigError):
  76. self.parse_config()
  77. def test_client_secret_basic_works(self) -> None:
  78. self.config_dict["experimental_features"]["msc3861"].update(
  79. client_auth_method="client_secret_basic",
  80. client_secret=CLIENT_SECRET,
  81. )
  82. self.parse_config()
  83. def test_client_secret_basic_requires_client_secret(self) -> None:
  84. self.config_dict["experimental_features"]["msc3861"].update(
  85. client_auth_method="client_secret_basic",
  86. client_secret=None,
  87. )
  88. with self.assertRaises(ConfigError):
  89. self.parse_config()
  90. def test_client_secret_jwt_works(self) -> None:
  91. self.config_dict["experimental_features"]["msc3861"].update(
  92. client_auth_method="client_secret_jwt",
  93. client_secret=CLIENT_SECRET,
  94. )
  95. self.parse_config()
  96. def test_client_secret_jwt_requires_client_secret(self) -> None:
  97. self.config_dict["experimental_features"]["msc3861"].update(
  98. client_auth_method="client_secret_jwt",
  99. client_secret=None,
  100. )
  101. with self.assertRaises(ConfigError):
  102. self.parse_config()
  103. def test_invalid_client_auth_method(self) -> None:
  104. self.config_dict["experimental_features"]["msc3861"].update(
  105. client_auth_method="invalid",
  106. )
  107. with self.assertRaises(ConfigError):
  108. self.parse_config()
  109. def test_private_key_jwt_requires_jwk(self) -> None:
  110. self.config_dict["experimental_features"]["msc3861"].update(
  111. client_auth_method="private_key_jwt",
  112. )
  113. with self.assertRaises(ConfigError):
  114. self.parse_config()
  115. def test_private_key_jwt_works(self) -> None:
  116. self.config_dict["experimental_features"]["msc3861"].update(
  117. client_auth_method="private_key_jwt",
  118. jwk={
  119. "p": "-frVdP_tZ-J_nIR6HNMDq1N7aunwm51nAqNnhqIyuA8ikx7LlQED1tt2LD3YEvYyW8nxE2V95HlCRZXQPMiRJBFOsbmYkzl2t-MpavTaObB_fct_JqcRtdXddg4-_ihdjRDwUOreq_dpWh6MIKsC3UyekfkHmeEJg5YpOTL15j8",
  120. "kty": "RSA",
  121. "q": "oFw-Enr_YozQB1ab-kawn4jY3yHi8B1nSmYT0s8oTCflrmps5BFJfCkHL5ij3iY15z0o2m0N-jjB1oSJ98O4RayEEYNQlHnTNTl0kRIWzpoqblHUIxVcahIpP_xTovBJzwi8XXoLGqHOOMA-r40LSyVgP2Ut8D9qBwV6_UfT0LU",
  122. "d": "WFkDPYo4b4LIS64D_QtQfGGuAObPvc3HFfp9VZXyq3SJR58XZRHE0jqtlEMNHhOTgbMYS3w8nxPQ_qVzY-5hs4fIanwvB64mAoOGl0qMHO65DTD_WsGFwzYClJPBVniavkLE2Hmpu8IGe6lGliN8vREC6_4t69liY-XcN_ECboVtC2behKkLOEASOIMuS7YcKAhTJFJwkl1dqDlliEn5A4u4xy7nuWQz3juB1OFdKlwGA5dfhDNglhoLIwNnkLsUPPFO-WB5ZNEW35xxHOToxj4bShvDuanVA6mJPtTKjz0XibjB36bj_nF_j7EtbE2PdGJ2KevAVgElR4lqS4ISgQ",
  123. "e": "AQAB",
  124. "kid": "test",
  125. "qi": "cPfNk8l8W5exVNNea4d7QZZ8Qr8LgHghypYAxz8PQh1fNa8Ya1SNUDVzC2iHHhszxxA0vB9C7jGze8dBrvnzWYF1XvQcqNIVVgHhD57R1Nm3dj2NoHIKe0Cu4bCUtP8xnZQUN4KX7y4IIcgRcBWG1hT6DEYZ4BxqicnBXXNXAUI",
  126. "dp": "dKlMHvslV1sMBQaKWpNb3gPq0B13TZhqr3-E2_8sPlvJ3fD8P4CmwwnOn50JDuhY3h9jY5L06sBwXjspYISVv8hX-ndMLkEeF3lrJeA5S70D8rgakfZcPIkffm3tlf1Ok3v5OzoxSv3-67Df4osMniyYwDUBCB5Oq1tTx77xpU8",
  127. "dq": "S4ooU1xNYYcjl9FcuJEEMqKsRrAXzzSKq6laPTwIp5dDwt2vXeAm1a4eDHXC-6rUSZGt5PbqVqzV4s-cjnJMI8YYkIdjNg4NSE1Ac_YpeDl3M3Colb5CQlU7yUB7xY2bt0NOOFp9UJZYJrOo09mFMGjy5eorsbitoZEbVqS3SuE",
  128. "n": "nJbYKqFwnURKimaviyDFrNLD3gaKR1JW343Qem25VeZxoMq1665RHVoO8n1oBm4ClZdjIiZiVdpyqzD5-Ow12YQgQEf1ZHP3CCcOQQhU57Rh5XvScTe5IxYVkEW32IW2mp_CJ6WfjYpfeL4azarVk8H3Vr59d1rSrKTVVinVdZer9YLQyC_rWAQNtHafPBMrf6RYiNGV9EiYn72wFIXlLlBYQ9Fx7bfe1PaL6qrQSsZP3_rSpuvVdLh1lqGeCLR0pyclA9uo5m2tMyCXuuGQLbA_QJm5xEc7zd-WFdux2eXF045oxnSZ_kgQt-pdN7AxGWOVvwoTf9am6mSkEdv6iw",
  129. },
  130. )
  131. self.parse_config()
  132. def test_registration_cannot_be_enabled(self) -> None:
  133. self.config_dict["enable_registration"] = True
  134. with self.assertRaises(ConfigError):
  135. self.parse_config()
  136. def test_password_config_cannot_be_enabled(self) -> None:
  137. self.config_dict["password_config"] = {"enabled": True}
  138. with self.assertRaises(ConfigError):
  139. self.parse_config()
  140. def test_oidc_sso_cannot_be_enabled(self) -> None:
  141. self.config_dict["oidc_providers"] = [
  142. {
  143. "idp_id": "microsoft",
  144. "idp_name": "Microsoft",
  145. "issuer": "https://login.microsoftonline.com/<tenant id>/v2.0",
  146. "client_id": "<client id>",
  147. "client_secret": "<client secret>",
  148. "scopes": ["openid", "profile"],
  149. "authorization_endpoint": "https://login.microsoftonline.com/<tenant id>/oauth2/v2.0/authorize",
  150. "token_endpoint": "https://login.microsoftonline.com/<tenant id>/oauth2/v2.0/token",
  151. "userinfo_endpoint": "https://graph.microsoft.com/oidc/userinfo",
  152. }
  153. ]
  154. with self.assertRaises(ConfigError):
  155. self.parse_config()
  156. def test_cas_sso_cannot_be_enabled(self) -> None:
  157. self.config_dict["cas_config"] = {
  158. "enabled": True,
  159. "server_url": "https://cas-server.com",
  160. "displayname_attribute": "name",
  161. "required_attributes": {"userGroup": "staff", "department": "None"},
  162. }
  163. with self.assertRaises(ConfigError):
  164. self.parse_config()
  165. def test_auth_providers_cannot_be_enabled(self) -> None:
  166. self.config_dict["modules"] = [
  167. {
  168. "module": f"{__name__}.{CustomAuthModule.__qualname__}",
  169. "config": {},
  170. }
  171. ]
  172. # This requires actually setting up an HS, as the module will be run on setup,
  173. # which should raise as the module tries to register an auth provider
  174. config = self.parse_config()
  175. reactor, clock = get_clock()
  176. with self.assertRaises(ConfigError):
  177. setup_test_homeserver(
  178. self.addCleanup, reactor=reactor, clock=clock, config=config
  179. )
  180. def test_jwt_auth_cannot_be_enabled(self) -> None:
  181. self.config_dict["jwt_config"] = {
  182. "enabled": True,
  183. "secret": "my-secret-token",
  184. "algorithm": "HS256",
  185. }
  186. with self.assertRaises(ConfigError):
  187. self.parse_config()
  188. def test_login_via_existing_session_cannot_be_enabled(self) -> None:
  189. self.config_dict["login_via_existing_session"] = {"enabled": True}
  190. with self.assertRaises(ConfigError):
  191. self.parse_config()
  192. def test_captcha_cannot_be_enabled(self) -> None:
  193. self.config_dict.update(
  194. enable_registration_captcha=True,
  195. recaptcha_public_key="test",
  196. recaptcha_private_key="test",
  197. )
  198. with self.assertRaises(ConfigError):
  199. self.parse_config()
  200. def test_refreshable_tokens_cannot_be_enabled(self) -> None:
  201. self.config_dict.update(
  202. refresh_token_lifetime="24h",
  203. refreshable_access_token_lifetime="10m",
  204. nonrefreshable_access_token_lifetime="24h",
  205. )
  206. with self.assertRaises(ConfigError):
  207. self.parse_config()
  208. def test_session_lifetime_cannot_be_set(self) -> None:
  209. self.config_dict["session_lifetime"] = "24h"
  210. with self.assertRaises(ConfigError):
  211. self.parse_config()