1
0

test_api.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. # Copyright 2022 The 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 typing import Any, List, Mapping, Sequence, Union
  15. from unittest.mock import Mock
  16. from twisted.test.proto_helpers import MemoryReactor
  17. from synapse.api.errors import HttpResponseException
  18. from synapse.appservice import ApplicationService
  19. from synapse.server import HomeServer
  20. from synapse.types import JsonDict
  21. from synapse.util import Clock
  22. from tests import unittest
  23. PROTOCOL = "myproto"
  24. TOKEN = "myastoken"
  25. URL = "http://mytestservice"
  26. class ApplicationServiceApiTestCase(unittest.HomeserverTestCase):
  27. def prepare(self, reactor: MemoryReactor, clock: Clock, hs: HomeServer) -> None:
  28. self.api = hs.get_application_service_api()
  29. self.service = ApplicationService(
  30. id="unique_identifier",
  31. sender="@as:test",
  32. url=URL,
  33. token="unused",
  34. hs_token=TOKEN,
  35. )
  36. def test_query_3pe_authenticates_token(self) -> None:
  37. """
  38. Tests that 3pe queries to the appservice are authenticated
  39. with the appservice's token.
  40. """
  41. SUCCESS_RESULT_USER = [
  42. {
  43. "protocol": PROTOCOL,
  44. "userid": "@a:user",
  45. "fields": {
  46. "more": "fields",
  47. },
  48. }
  49. ]
  50. SUCCESS_RESULT_LOCATION = [
  51. {
  52. "protocol": PROTOCOL,
  53. "alias": "#a:room",
  54. "fields": {
  55. "more": "fields",
  56. },
  57. }
  58. ]
  59. URL_USER = f"{URL}/_matrix/app/v1/thirdparty/user/{PROTOCOL}"
  60. URL_LOCATION = f"{URL}/_matrix/app/v1/thirdparty/location/{PROTOCOL}"
  61. self.request_url = None
  62. async def get_json(
  63. url: str,
  64. args: Mapping[Any, Any],
  65. headers: Mapping[Union[str, bytes], Sequence[Union[str, bytes]]],
  66. ) -> List[JsonDict]:
  67. # Ensure the access token is passed as both a header and query arg.
  68. if not headers.get("Authorization") or not args.get(b"access_token"):
  69. raise RuntimeError("Access token not provided")
  70. self.assertEqual(headers.get("Authorization"), [f"Bearer {TOKEN}"])
  71. self.assertEqual(args.get(b"access_token"), TOKEN)
  72. self.request_url = url
  73. if url == URL_USER:
  74. return SUCCESS_RESULT_USER
  75. elif url == URL_LOCATION:
  76. return SUCCESS_RESULT_LOCATION
  77. else:
  78. raise RuntimeError(
  79. "URL provided was invalid. This should never be seen."
  80. )
  81. # We assign to a method, which mypy doesn't like.
  82. self.api.get_json = Mock(side_effect=get_json) # type: ignore[assignment]
  83. result = self.get_success(
  84. self.api.query_3pe(self.service, "user", PROTOCOL, {b"some": [b"field"]})
  85. )
  86. self.assertEqual(self.request_url, URL_USER)
  87. self.assertEqual(result, SUCCESS_RESULT_USER)
  88. result = self.get_success(
  89. self.api.query_3pe(
  90. self.service, "location", PROTOCOL, {b"some": [b"field"]}
  91. )
  92. )
  93. self.assertEqual(self.request_url, URL_LOCATION)
  94. self.assertEqual(result, SUCCESS_RESULT_LOCATION)
  95. def test_fallback(self) -> None:
  96. """
  97. Tests that the fallback to legacy URLs works.
  98. """
  99. SUCCESS_RESULT_USER = [
  100. {
  101. "protocol": PROTOCOL,
  102. "userid": "@a:user",
  103. "fields": {
  104. "more": "fields",
  105. },
  106. }
  107. ]
  108. URL_USER = f"{URL}/_matrix/app/v1/thirdparty/user/{PROTOCOL}"
  109. FALLBACK_URL_USER = f"{URL}/_matrix/app/unstable/thirdparty/user/{PROTOCOL}"
  110. self.request_url = None
  111. self.v1_seen = False
  112. async def get_json(
  113. url: str,
  114. args: Mapping[Any, Any],
  115. headers: Mapping[Union[str, bytes], Sequence[Union[str, bytes]]],
  116. ) -> List[JsonDict]:
  117. # Ensure the access token is passed as both a header and query arg.
  118. if not headers.get("Authorization") or not args.get(b"access_token"):
  119. raise RuntimeError("Access token not provided")
  120. self.assertEqual(headers.get("Authorization"), [f"Bearer {TOKEN}"])
  121. self.assertEqual(args.get(b"access_token"), TOKEN)
  122. self.request_url = url
  123. if url == URL_USER:
  124. self.v1_seen = True
  125. raise HttpResponseException(404, "NOT_FOUND", b"NOT_FOUND")
  126. elif url == FALLBACK_URL_USER:
  127. return SUCCESS_RESULT_USER
  128. else:
  129. raise RuntimeError(
  130. "URL provided was invalid. This should never be seen."
  131. )
  132. # We assign to a method, which mypy doesn't like.
  133. self.api.get_json = Mock(side_effect=get_json) # type: ignore[assignment]
  134. result = self.get_success(
  135. self.api.query_3pe(self.service, "user", PROTOCOL, {b"some": [b"field"]})
  136. )
  137. self.assertTrue(self.v1_seen)
  138. self.assertEqual(self.request_url, FALLBACK_URL_USER)
  139. self.assertEqual(result, SUCCESS_RESULT_USER)
  140. def test_claim_keys(self) -> None:
  141. """
  142. Tests that the /keys/claim response is properly parsed for missing
  143. keys.
  144. """
  145. RESPONSE: JsonDict = {
  146. "@alice:example.org": {
  147. "DEVICE_1": {
  148. "signed_curve25519:AAAAHg": {
  149. # We don't really care about the content of the keys,
  150. # they get passed back transparently.
  151. },
  152. "signed_curve25519:BBBBHg": {},
  153. },
  154. "DEVICE_2": {"signed_curve25519:CCCCHg": {}},
  155. },
  156. }
  157. async def post_json_get_json(
  158. uri: str,
  159. post_json: Any,
  160. headers: Mapping[Union[str, bytes], Sequence[Union[str, bytes]]],
  161. ) -> JsonDict:
  162. # Ensure the access token is passed as both a header and query arg.
  163. if not headers.get("Authorization"):
  164. raise RuntimeError("Access token not provided")
  165. self.assertEqual(headers.get("Authorization"), [f"Bearer {TOKEN}"])
  166. return RESPONSE
  167. # We assign to a method, which mypy doesn't like.
  168. self.api.post_json_get_json = Mock(side_effect=post_json_get_json) # type: ignore[assignment]
  169. MISSING_KEYS = [
  170. # Known user, known device, missing algorithm.
  171. ("@alice:example.org", "DEVICE_2", "xyz", 1),
  172. # Known user, missing device.
  173. ("@alice:example.org", "DEVICE_3", "signed_curve25519", 1),
  174. # Unknown user.
  175. ("@bob:example.org", "DEVICE_4", "signed_curve25519", 1),
  176. ]
  177. claimed_keys, missing = self.get_success(
  178. self.api.claim_client_keys(
  179. self.service,
  180. [
  181. # Found devices
  182. ("@alice:example.org", "DEVICE_1", "signed_curve25519", 1),
  183. ("@alice:example.org", "DEVICE_2", "signed_curve25519", 1),
  184. ]
  185. + MISSING_KEYS,
  186. )
  187. )
  188. self.assertEqual(claimed_keys, RESPONSE)
  189. self.assertEqual(missing, MISSING_KEYS)