test_oauth_delegation.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. # Copyright 2022 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 http import HTTPStatus
  15. from typing import Any, Dict, Union
  16. from unittest.mock import ANY, AsyncMock, Mock
  17. from urllib.parse import parse_qs
  18. from signedjson.key import (
  19. encode_verify_key_base64,
  20. generate_signing_key,
  21. get_verify_key,
  22. )
  23. from signedjson.sign import sign_json
  24. from twisted.test.proto_helpers import MemoryReactor
  25. from synapse.api.errors import (
  26. AuthError,
  27. Codes,
  28. InvalidClientTokenError,
  29. OAuthInsufficientScopeError,
  30. SynapseError,
  31. )
  32. from synapse.rest import admin
  33. from synapse.rest.client import account, devices, keys, login, logout, register
  34. from synapse.server import HomeServer
  35. from synapse.types import JsonDict
  36. from synapse.util import Clock
  37. from tests.test_utils import FakeResponse, get_awaitable_result
  38. from tests.unittest import HomeserverTestCase, skip_unless
  39. from tests.utils import mock_getRawHeaders
  40. try:
  41. import authlib # noqa: F401
  42. HAS_AUTHLIB = True
  43. except ImportError:
  44. HAS_AUTHLIB = False
  45. # These are a few constants that are used as config parameters in the tests.
  46. SERVER_NAME = "test"
  47. ISSUER = "https://issuer/"
  48. CLIENT_ID = "test-client-id"
  49. CLIENT_SECRET = "test-client-secret"
  50. BASE_URL = "https://synapse/"
  51. SCOPES = ["openid"]
  52. AUTHORIZATION_ENDPOINT = ISSUER + "authorize"
  53. TOKEN_ENDPOINT = ISSUER + "token"
  54. USERINFO_ENDPOINT = ISSUER + "userinfo"
  55. WELL_KNOWN = ISSUER + ".well-known/openid-configuration"
  56. JWKS_URI = ISSUER + ".well-known/jwks.json"
  57. INTROSPECTION_ENDPOINT = ISSUER + "introspect"
  58. SYNAPSE_ADMIN_SCOPE = "urn:synapse:admin:*"
  59. MATRIX_USER_SCOPE = "urn:matrix:org.matrix.msc2967.client:api:*"
  60. MATRIX_GUEST_SCOPE = "urn:matrix:org.matrix.msc2967.client:api:guest"
  61. MATRIX_DEVICE_SCOPE_PREFIX = "urn:matrix:org.matrix.msc2967.client:device:"
  62. DEVICE = "AABBCCDD"
  63. MATRIX_DEVICE_SCOPE = MATRIX_DEVICE_SCOPE_PREFIX + DEVICE
  64. SUBJECT = "abc-def-ghi"
  65. USERNAME = "test-user"
  66. USER_ID = "@" + USERNAME + ":" + SERVER_NAME
  67. async def get_json(url: str) -> JsonDict:
  68. # Mock get_json calls to handle jwks & oidc discovery endpoints
  69. if url == WELL_KNOWN:
  70. # Minimal discovery document, as defined in OpenID.Discovery
  71. # https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata
  72. return {
  73. "issuer": ISSUER,
  74. "authorization_endpoint": AUTHORIZATION_ENDPOINT,
  75. "token_endpoint": TOKEN_ENDPOINT,
  76. "jwks_uri": JWKS_URI,
  77. "userinfo_endpoint": USERINFO_ENDPOINT,
  78. "introspection_endpoint": INTROSPECTION_ENDPOINT,
  79. "response_types_supported": ["code"],
  80. "subject_types_supported": ["public"],
  81. "id_token_signing_alg_values_supported": ["RS256"],
  82. }
  83. elif url == JWKS_URI:
  84. return {"keys": []}
  85. return {}
  86. @skip_unless(HAS_AUTHLIB, "requires authlib")
  87. class MSC3861OAuthDelegation(HomeserverTestCase):
  88. servlets = [
  89. account.register_servlets,
  90. devices.register_servlets,
  91. keys.register_servlets,
  92. register.register_servlets,
  93. login.register_servlets,
  94. logout.register_servlets,
  95. admin.register_servlets,
  96. ]
  97. def default_config(self) -> Dict[str, Any]:
  98. config = super().default_config()
  99. config["public_baseurl"] = BASE_URL
  100. config["disable_registration"] = True
  101. config["experimental_features"] = {
  102. "msc3861": {
  103. "enabled": True,
  104. "issuer": ISSUER,
  105. "client_id": CLIENT_ID,
  106. "client_auth_method": "client_secret_post",
  107. "client_secret": CLIENT_SECRET,
  108. "admin_token": "admin_token_value",
  109. }
  110. }
  111. return config
  112. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  113. self.http_client = Mock(spec=["get_json"])
  114. self.http_client.get_json.side_effect = get_json
  115. self.http_client.user_agent = b"Synapse Test"
  116. hs = self.setup_test_homeserver(proxied_http_client=self.http_client)
  117. self.auth = hs.get_auth()
  118. return hs
  119. def _assertParams(self) -> None:
  120. """Assert that the request parameters are correct."""
  121. params = parse_qs(self.http_client.request.call_args[1]["data"].decode("utf-8"))
  122. self.assertEqual(params["token"], ["mockAccessToken"])
  123. self.assertEqual(params["client_id"], [CLIENT_ID])
  124. self.assertEqual(params["client_secret"], [CLIENT_SECRET])
  125. def test_inactive_token(self) -> None:
  126. """The handler should return a 403 where the token is inactive."""
  127. self.http_client.request = AsyncMock(
  128. return_value=FakeResponse.json(
  129. code=200,
  130. payload={"active": False},
  131. )
  132. )
  133. request = Mock(args={})
  134. request.args[b"access_token"] = [b"mockAccessToken"]
  135. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  136. self.get_failure(self.auth.get_user_by_req(request), InvalidClientTokenError)
  137. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  138. self.http_client.request.assert_called_once_with(
  139. method="POST", uri=INTROSPECTION_ENDPOINT, data=ANY, headers=ANY
  140. )
  141. self._assertParams()
  142. def test_active_no_scope(self) -> None:
  143. """The handler should return a 403 where no scope is given."""
  144. self.http_client.request = AsyncMock(
  145. return_value=FakeResponse.json(
  146. code=200,
  147. payload={"active": True},
  148. )
  149. )
  150. request = Mock(args={})
  151. request.args[b"access_token"] = [b"mockAccessToken"]
  152. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  153. self.get_failure(self.auth.get_user_by_req(request), InvalidClientTokenError)
  154. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  155. self.http_client.request.assert_called_once_with(
  156. method="POST", uri=INTROSPECTION_ENDPOINT, data=ANY, headers=ANY
  157. )
  158. self._assertParams()
  159. def test_active_user_no_subject(self) -> None:
  160. """The handler should return a 500 when no subject is present."""
  161. self.http_client.request = AsyncMock(
  162. return_value=FakeResponse.json(
  163. code=200,
  164. payload={"active": True, "scope": " ".join([MATRIX_USER_SCOPE])},
  165. )
  166. )
  167. request = Mock(args={})
  168. request.args[b"access_token"] = [b"mockAccessToken"]
  169. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  170. self.get_failure(self.auth.get_user_by_req(request), InvalidClientTokenError)
  171. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  172. self.http_client.request.assert_called_once_with(
  173. method="POST", uri=INTROSPECTION_ENDPOINT, data=ANY, headers=ANY
  174. )
  175. self._assertParams()
  176. def test_active_no_user_scope(self) -> None:
  177. """The handler should return a 500 when no subject is present."""
  178. self.http_client.request = AsyncMock(
  179. return_value=FakeResponse.json(
  180. code=200,
  181. payload={
  182. "active": True,
  183. "sub": SUBJECT,
  184. "scope": " ".join([MATRIX_DEVICE_SCOPE]),
  185. },
  186. )
  187. )
  188. request = Mock(args={})
  189. request.args[b"access_token"] = [b"mockAccessToken"]
  190. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  191. self.get_failure(self.auth.get_user_by_req(request), InvalidClientTokenError)
  192. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  193. self.http_client.request.assert_called_once_with(
  194. method="POST", uri=INTROSPECTION_ENDPOINT, data=ANY, headers=ANY
  195. )
  196. self._assertParams()
  197. def test_active_admin_not_user(self) -> None:
  198. """The handler should raise when the scope has admin right but not user."""
  199. self.http_client.request = AsyncMock(
  200. return_value=FakeResponse.json(
  201. code=200,
  202. payload={
  203. "active": True,
  204. "sub": SUBJECT,
  205. "scope": " ".join([SYNAPSE_ADMIN_SCOPE]),
  206. "username": USERNAME,
  207. },
  208. )
  209. )
  210. request = Mock(args={})
  211. request.args[b"access_token"] = [b"mockAccessToken"]
  212. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  213. self.get_failure(self.auth.get_user_by_req(request), InvalidClientTokenError)
  214. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  215. self.http_client.request.assert_called_once_with(
  216. method="POST", uri=INTROSPECTION_ENDPOINT, data=ANY, headers=ANY
  217. )
  218. self._assertParams()
  219. def test_active_admin(self) -> None:
  220. """The handler should return a requester with admin rights."""
  221. self.http_client.request = AsyncMock(
  222. return_value=FakeResponse.json(
  223. code=200,
  224. payload={
  225. "active": True,
  226. "sub": SUBJECT,
  227. "scope": " ".join([SYNAPSE_ADMIN_SCOPE, MATRIX_USER_SCOPE]),
  228. "username": USERNAME,
  229. },
  230. )
  231. )
  232. request = Mock(args={})
  233. request.args[b"access_token"] = [b"mockAccessToken"]
  234. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  235. requester = self.get_success(self.auth.get_user_by_req(request))
  236. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  237. self.http_client.request.assert_called_once_with(
  238. method="POST", uri=INTROSPECTION_ENDPOINT, data=ANY, headers=ANY
  239. )
  240. self._assertParams()
  241. self.assertEqual(requester.user.to_string(), "@%s:%s" % (USERNAME, SERVER_NAME))
  242. self.assertEqual(requester.is_guest, False)
  243. self.assertEqual(requester.device_id, None)
  244. self.assertEqual(
  245. get_awaitable_result(self.auth.is_server_admin(requester)), True
  246. )
  247. def test_active_admin_highest_privilege(self) -> None:
  248. """The handler should resolve to the most permissive scope."""
  249. self.http_client.request = AsyncMock(
  250. return_value=FakeResponse.json(
  251. code=200,
  252. payload={
  253. "active": True,
  254. "sub": SUBJECT,
  255. "scope": " ".join(
  256. [SYNAPSE_ADMIN_SCOPE, MATRIX_USER_SCOPE, MATRIX_GUEST_SCOPE]
  257. ),
  258. "username": USERNAME,
  259. },
  260. )
  261. )
  262. request = Mock(args={})
  263. request.args[b"access_token"] = [b"mockAccessToken"]
  264. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  265. requester = self.get_success(self.auth.get_user_by_req(request))
  266. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  267. self.http_client.request.assert_called_once_with(
  268. method="POST", uri=INTROSPECTION_ENDPOINT, data=ANY, headers=ANY
  269. )
  270. self._assertParams()
  271. self.assertEqual(requester.user.to_string(), "@%s:%s" % (USERNAME, SERVER_NAME))
  272. self.assertEqual(requester.is_guest, False)
  273. self.assertEqual(requester.device_id, None)
  274. self.assertEqual(
  275. get_awaitable_result(self.auth.is_server_admin(requester)), True
  276. )
  277. def test_active_user(self) -> None:
  278. """The handler should return a requester with normal user rights."""
  279. self.http_client.request = AsyncMock(
  280. return_value=FakeResponse.json(
  281. code=200,
  282. payload={
  283. "active": True,
  284. "sub": SUBJECT,
  285. "scope": " ".join([MATRIX_USER_SCOPE]),
  286. "username": USERNAME,
  287. },
  288. )
  289. )
  290. request = Mock(args={})
  291. request.args[b"access_token"] = [b"mockAccessToken"]
  292. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  293. requester = self.get_success(self.auth.get_user_by_req(request))
  294. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  295. self.http_client.request.assert_called_once_with(
  296. method="POST", uri=INTROSPECTION_ENDPOINT, data=ANY, headers=ANY
  297. )
  298. self._assertParams()
  299. self.assertEqual(requester.user.to_string(), "@%s:%s" % (USERNAME, SERVER_NAME))
  300. self.assertEqual(requester.is_guest, False)
  301. self.assertEqual(requester.device_id, None)
  302. self.assertEqual(
  303. get_awaitable_result(self.auth.is_server_admin(requester)), False
  304. )
  305. def test_active_user_with_device(self) -> None:
  306. """The handler should return a requester with normal user rights and a device ID."""
  307. self.http_client.request = AsyncMock(
  308. return_value=FakeResponse.json(
  309. code=200,
  310. payload={
  311. "active": True,
  312. "sub": SUBJECT,
  313. "scope": " ".join([MATRIX_USER_SCOPE, MATRIX_DEVICE_SCOPE]),
  314. "username": USERNAME,
  315. },
  316. )
  317. )
  318. request = Mock(args={})
  319. request.args[b"access_token"] = [b"mockAccessToken"]
  320. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  321. requester = self.get_success(self.auth.get_user_by_req(request))
  322. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  323. self.http_client.request.assert_called_once_with(
  324. method="POST", uri=INTROSPECTION_ENDPOINT, data=ANY, headers=ANY
  325. )
  326. self._assertParams()
  327. self.assertEqual(requester.user.to_string(), "@%s:%s" % (USERNAME, SERVER_NAME))
  328. self.assertEqual(requester.is_guest, False)
  329. self.assertEqual(
  330. get_awaitable_result(self.auth.is_server_admin(requester)), False
  331. )
  332. self.assertEqual(requester.device_id, DEVICE)
  333. def test_multiple_devices(self) -> None:
  334. """The handler should raise an error if multiple devices are found in the scope."""
  335. self.http_client.request = AsyncMock(
  336. return_value=FakeResponse.json(
  337. code=200,
  338. payload={
  339. "active": True,
  340. "sub": SUBJECT,
  341. "scope": " ".join(
  342. [
  343. MATRIX_USER_SCOPE,
  344. f"{MATRIX_DEVICE_SCOPE_PREFIX}AABBCC",
  345. f"{MATRIX_DEVICE_SCOPE_PREFIX}DDEEFF",
  346. ]
  347. ),
  348. "username": USERNAME,
  349. },
  350. )
  351. )
  352. request = Mock(args={})
  353. request.args[b"access_token"] = [b"mockAccessToken"]
  354. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  355. self.get_failure(self.auth.get_user_by_req(request), AuthError)
  356. def test_active_guest_not_allowed(self) -> None:
  357. """The handler should return an insufficient scope error."""
  358. self.http_client.request = AsyncMock(
  359. return_value=FakeResponse.json(
  360. code=200,
  361. payload={
  362. "active": True,
  363. "sub": SUBJECT,
  364. "scope": " ".join([MATRIX_GUEST_SCOPE, MATRIX_DEVICE_SCOPE]),
  365. "username": USERNAME,
  366. },
  367. )
  368. )
  369. request = Mock(args={})
  370. request.args[b"access_token"] = [b"mockAccessToken"]
  371. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  372. error = self.get_failure(
  373. self.auth.get_user_by_req(request), OAuthInsufficientScopeError
  374. )
  375. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  376. self.http_client.request.assert_called_once_with(
  377. method="POST", uri=INTROSPECTION_ENDPOINT, data=ANY, headers=ANY
  378. )
  379. self._assertParams()
  380. self.assertEqual(
  381. getattr(error.value, "headers", {})["WWW-Authenticate"],
  382. 'Bearer error="insufficient_scope", scope="urn:matrix:org.matrix.msc2967.client:api:*"',
  383. )
  384. def test_active_guest_allowed(self) -> None:
  385. """The handler should return a requester with guest user rights and a device ID."""
  386. self.http_client.request = AsyncMock(
  387. return_value=FakeResponse.json(
  388. code=200,
  389. payload={
  390. "active": True,
  391. "sub": SUBJECT,
  392. "scope": " ".join([MATRIX_GUEST_SCOPE, MATRIX_DEVICE_SCOPE]),
  393. "username": USERNAME,
  394. },
  395. )
  396. )
  397. request = Mock(args={})
  398. request.args[b"access_token"] = [b"mockAccessToken"]
  399. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  400. requester = self.get_success(
  401. self.auth.get_user_by_req(request, allow_guest=True)
  402. )
  403. self.http_client.get_json.assert_called_once_with(WELL_KNOWN)
  404. self.http_client.request.assert_called_once_with(
  405. method="POST", uri=INTROSPECTION_ENDPOINT, data=ANY, headers=ANY
  406. )
  407. self._assertParams()
  408. self.assertEqual(requester.user.to_string(), "@%s:%s" % (USERNAME, SERVER_NAME))
  409. self.assertEqual(requester.is_guest, True)
  410. self.assertEqual(
  411. get_awaitable_result(self.auth.is_server_admin(requester)), False
  412. )
  413. self.assertEqual(requester.device_id, DEVICE)
  414. def test_unavailable_introspection_endpoint(self) -> None:
  415. """The handler should return an internal server error."""
  416. request = Mock(args={})
  417. request.args[b"access_token"] = [b"mockAccessToken"]
  418. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  419. # The introspection endpoint is returning an error.
  420. self.http_client.request = AsyncMock(
  421. return_value=FakeResponse(code=500, body=b"Internal Server Error")
  422. )
  423. error = self.get_failure(self.auth.get_user_by_req(request), SynapseError)
  424. self.assertEqual(error.value.code, 503)
  425. # The introspection endpoint request fails.
  426. self.http_client.request = AsyncMock(side_effect=Exception())
  427. error = self.get_failure(self.auth.get_user_by_req(request), SynapseError)
  428. self.assertEqual(error.value.code, 503)
  429. # The introspection endpoint does not return a JSON object.
  430. self.http_client.request = AsyncMock(
  431. return_value=FakeResponse.json(
  432. code=200, payload=["this is an array", "not an object"]
  433. )
  434. )
  435. error = self.get_failure(self.auth.get_user_by_req(request), SynapseError)
  436. self.assertEqual(error.value.code, 503)
  437. # The introspection endpoint does not return valid JSON.
  438. self.http_client.request = AsyncMock(
  439. return_value=FakeResponse(code=200, body=b"this is not valid JSON")
  440. )
  441. error = self.get_failure(self.auth.get_user_by_req(request), SynapseError)
  442. self.assertEqual(error.value.code, 503)
  443. def make_device_keys(self, user_id: str, device_id: str) -> JsonDict:
  444. # We only generate a master key to simplify the test.
  445. master_signing_key = generate_signing_key(device_id)
  446. master_verify_key = encode_verify_key_base64(get_verify_key(master_signing_key))
  447. return {
  448. "master_key": sign_json(
  449. {
  450. "user_id": user_id,
  451. "usage": ["master"],
  452. "keys": {"ed25519:" + master_verify_key: master_verify_key},
  453. },
  454. user_id,
  455. master_signing_key,
  456. ),
  457. }
  458. def test_cross_signing(self) -> None:
  459. """Try uploading device keys with OAuth delegation enabled."""
  460. self.http_client.request = AsyncMock(
  461. return_value=FakeResponse.json(
  462. code=200,
  463. payload={
  464. "active": True,
  465. "sub": SUBJECT,
  466. "scope": " ".join([MATRIX_USER_SCOPE, MATRIX_DEVICE_SCOPE]),
  467. "username": USERNAME,
  468. },
  469. )
  470. )
  471. keys_upload_body = self.make_device_keys(USER_ID, DEVICE)
  472. channel = self.make_request(
  473. "POST",
  474. "/_matrix/client/v3/keys/device_signing/upload",
  475. keys_upload_body,
  476. access_token="mockAccessToken",
  477. )
  478. self.assertEqual(channel.code, 200, channel.json_body)
  479. channel = self.make_request(
  480. "POST",
  481. "/_matrix/client/v3/keys/device_signing/upload",
  482. keys_upload_body,
  483. access_token="mockAccessToken",
  484. )
  485. self.assertEqual(channel.code, HTTPStatus.NOT_IMPLEMENTED, channel.json_body)
  486. def expect_unauthorized(
  487. self, method: str, path: str, content: Union[bytes, str, JsonDict] = ""
  488. ) -> None:
  489. channel = self.make_request(method, path, content, shorthand=False)
  490. self.assertEqual(channel.code, 401, channel.json_body)
  491. def expect_unrecognized(
  492. self, method: str, path: str, content: Union[bytes, str, JsonDict] = ""
  493. ) -> None:
  494. channel = self.make_request(method, path, content)
  495. self.assertEqual(channel.code, 404, channel.json_body)
  496. self.assertEqual(
  497. channel.json_body["errcode"], Codes.UNRECOGNIZED, channel.json_body
  498. )
  499. def test_uia_endpoints(self) -> None:
  500. """Test that endpoints that were removed in MSC2964 are no longer available."""
  501. # This is just an endpoint that should remain visible (but requires auth):
  502. self.expect_unauthorized("GET", "/_matrix/client/v3/devices")
  503. # This remains usable, but will require a uia scope:
  504. self.expect_unauthorized(
  505. "POST", "/_matrix/client/v3/keys/device_signing/upload"
  506. )
  507. def test_3pid_endpoints(self) -> None:
  508. """Test that 3pid account management endpoints that were removed in MSC2964 are no longer available."""
  509. # Remains and requires auth:
  510. self.expect_unauthorized("GET", "/_matrix/client/v3/account/3pid")
  511. self.expect_unauthorized(
  512. "POST",
  513. "/_matrix/client/v3/account/3pid/bind",
  514. {
  515. "client_secret": "foo",
  516. "id_access_token": "bar",
  517. "id_server": "foo",
  518. "sid": "bar",
  519. },
  520. )
  521. self.expect_unauthorized("POST", "/_matrix/client/v3/account/3pid/unbind", {})
  522. # These are gone:
  523. self.expect_unrecognized(
  524. "POST", "/_matrix/client/v3/account/3pid"
  525. ) # deprecated
  526. self.expect_unrecognized("POST", "/_matrix/client/v3/account/3pid/add")
  527. self.expect_unrecognized("POST", "/_matrix/client/v3/account/3pid/delete")
  528. self.expect_unrecognized(
  529. "POST", "/_matrix/client/v3/account/3pid/email/requestToken"
  530. )
  531. self.expect_unrecognized(
  532. "POST", "/_matrix/client/v3/account/3pid/msisdn/requestToken"
  533. )
  534. def test_account_management_endpoints_removed(self) -> None:
  535. """Test that account management endpoints that were removed in MSC2964 are no longer available."""
  536. self.expect_unrecognized("POST", "/_matrix/client/v3/account/deactivate")
  537. self.expect_unrecognized("POST", "/_matrix/client/v3/account/password")
  538. self.expect_unrecognized(
  539. "POST", "/_matrix/client/v3/account/password/email/requestToken"
  540. )
  541. self.expect_unrecognized(
  542. "POST", "/_matrix/client/v3/account/password/msisdn/requestToken"
  543. )
  544. def test_registration_endpoints_removed(self) -> None:
  545. """Test that registration endpoints that were removed in MSC2964 are no longer available."""
  546. self.expect_unrecognized(
  547. "GET", "/_matrix/client/v1/register/m.login.registration_token/validity"
  548. )
  549. # This is still available for AS registrations
  550. # self.expect_unrecognized("POST", "/_matrix/client/v3/register")
  551. self.expect_unrecognized("GET", "/_matrix/client/v3/register/available")
  552. self.expect_unrecognized(
  553. "POST", "/_matrix/client/v3/register/email/requestToken"
  554. )
  555. self.expect_unrecognized(
  556. "POST", "/_matrix/client/v3/register/msisdn/requestToken"
  557. )
  558. def test_session_management_endpoints_removed(self) -> None:
  559. """Test that session management endpoints that were removed in MSC2964 are no longer available."""
  560. self.expect_unrecognized("GET", "/_matrix/client/v3/login")
  561. self.expect_unrecognized("POST", "/_matrix/client/v3/login")
  562. self.expect_unrecognized("GET", "/_matrix/client/v3/login/sso/redirect")
  563. self.expect_unrecognized("POST", "/_matrix/client/v3/logout")
  564. self.expect_unrecognized("POST", "/_matrix/client/v3/logout/all")
  565. self.expect_unrecognized("POST", "/_matrix/client/v3/refresh")
  566. self.expect_unrecognized("GET", "/_matrix/static/client/login")
  567. def test_device_management_endpoints_removed(self) -> None:
  568. """Test that device management endpoints that were removed in MSC2964 are no longer available."""
  569. self.expect_unrecognized("POST", "/_matrix/client/v3/delete_devices")
  570. self.expect_unrecognized("DELETE", "/_matrix/client/v3/devices/{DEVICE}")
  571. def test_openid_endpoints_removed(self) -> None:
  572. """Test that OpenID id_token endpoints that were removed in MSC2964 are no longer available."""
  573. self.expect_unrecognized(
  574. "POST", "/_matrix/client/v3/user/{USERNAME}/openid/request_token"
  575. )
  576. def test_admin_api_endpoints_removed(self) -> None:
  577. """Test that admin API endpoints that were removed in MSC2964 are no longer available."""
  578. self.expect_unrecognized("GET", "/_synapse/admin/v1/registration_tokens")
  579. self.expect_unrecognized("POST", "/_synapse/admin/v1/registration_tokens/new")
  580. self.expect_unrecognized("GET", "/_synapse/admin/v1/registration_tokens/abcd")
  581. self.expect_unrecognized("PUT", "/_synapse/admin/v1/registration_tokens/abcd")
  582. self.expect_unrecognized(
  583. "DELETE", "/_synapse/admin/v1/registration_tokens/abcd"
  584. )
  585. self.expect_unrecognized("POST", "/_synapse/admin/v1/reset_password/foo")
  586. self.expect_unrecognized("POST", "/_synapse/admin/v1/users/foo/login")
  587. self.expect_unrecognized("GET", "/_synapse/admin/v1/register")
  588. self.expect_unrecognized("POST", "/_synapse/admin/v1/register")
  589. self.expect_unrecognized("GET", "/_synapse/admin/v1/users/foo/admin")
  590. self.expect_unrecognized("PUT", "/_synapse/admin/v1/users/foo/admin")
  591. self.expect_unrecognized("POST", "/_synapse/admin/v1/account_validity/validity")
  592. def test_admin_token(self) -> None:
  593. """The handler should return a requester with admin rights when admin_token is used."""
  594. self.http_client.request = AsyncMock(
  595. return_value=FakeResponse.json(code=200, payload={"active": False}),
  596. )
  597. request = Mock(args={})
  598. request.args[b"access_token"] = [b"admin_token_value"]
  599. request.requestHeaders.getRawHeaders = mock_getRawHeaders()
  600. requester = self.get_success(self.auth.get_user_by_req(request))
  601. self.assertEqual(
  602. requester.user.to_string(), "@%s:%s" % ("__oidc_admin", SERVER_NAME)
  603. )
  604. self.assertEqual(requester.is_guest, False)
  605. self.assertEqual(requester.device_id, None)
  606. self.assertEqual(
  607. get_awaitable_result(self.auth.is_server_admin(requester)), True
  608. )
  609. # There should be no call to the introspection endpoint
  610. self.http_client.request.assert_not_called()