test_remote_key_resource.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. # Copyright 2020 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. import urllib.parse
  15. from io import BytesIO, StringIO
  16. from unittest.mock import Mock
  17. import signedjson.key
  18. from canonicaljson import encode_canonical_json
  19. from nacl.signing import SigningKey
  20. from signedjson.sign import sign_json
  21. from twisted.web.resource import NoResource
  22. from synapse.crypto.keyring import PerspectivesKeyFetcher
  23. from synapse.http.site import SynapseRequest
  24. from synapse.rest.key.v2 import KeyApiV2Resource
  25. from synapse.storage.keys import FetchKeyResult
  26. from synapse.util.httpresourcetree import create_resource_tree
  27. from synapse.util.stringutils import random_string
  28. from tests import unittest
  29. from tests.server import FakeChannel
  30. from tests.utils import default_config
  31. class BaseRemoteKeyResourceTestCase(unittest.HomeserverTestCase):
  32. def make_homeserver(self, reactor, clock):
  33. self.http_client = Mock()
  34. return self.setup_test_homeserver(federation_http_client=self.http_client)
  35. def create_test_resource(self):
  36. return create_resource_tree(
  37. {"/_matrix/key/v2": KeyApiV2Resource(self.hs)}, root_resource=NoResource()
  38. )
  39. def expect_outgoing_key_request(
  40. self, server_name: str, signing_key: SigningKey
  41. ) -> None:
  42. """
  43. Tell the mock http client to expect an outgoing GET request for the given key
  44. """
  45. async def get_json(destination, path, ignore_backoff=False, **kwargs):
  46. self.assertTrue(ignore_backoff)
  47. self.assertEqual(destination, server_name)
  48. key_id = "%s:%s" % (signing_key.alg, signing_key.version)
  49. self.assertEqual(
  50. path, "/_matrix/key/v2/server/%s" % (urllib.parse.quote(key_id),)
  51. )
  52. response = {
  53. "server_name": server_name,
  54. "old_verify_keys": {},
  55. "valid_until_ts": 200 * 1000,
  56. "verify_keys": {
  57. key_id: {
  58. "key": signedjson.key.encode_verify_key_base64(
  59. signing_key.verify_key
  60. )
  61. }
  62. },
  63. }
  64. sign_json(response, server_name, signing_key)
  65. return response
  66. self.http_client.get_json.side_effect = get_json
  67. class RemoteKeyResourceTestCase(BaseRemoteKeyResourceTestCase):
  68. def make_notary_request(self, server_name: str, key_id: str) -> dict:
  69. """Send a GET request to the test server requesting the given key.
  70. Checks that the response is a 200 and returns the decoded json body.
  71. """
  72. channel = FakeChannel(self.site, self.reactor)
  73. req = SynapseRequest(channel)
  74. req.content = BytesIO(b"")
  75. req.requestReceived(
  76. b"GET",
  77. b"/_matrix/key/v2/query/%s/%s"
  78. % (server_name.encode("utf-8"), key_id.encode("utf-8")),
  79. b"1.1",
  80. )
  81. channel.await_result()
  82. self.assertEqual(channel.code, 200)
  83. resp = channel.json_body
  84. return resp
  85. def test_get_key(self):
  86. """Fetch a remote key"""
  87. SERVER_NAME = "remote.server"
  88. testkey = signedjson.key.generate_signing_key("ver1")
  89. self.expect_outgoing_key_request(SERVER_NAME, testkey)
  90. resp = self.make_notary_request(SERVER_NAME, "ed25519:ver1")
  91. keys = resp["server_keys"]
  92. self.assertEqual(len(keys), 1)
  93. self.assertIn("ed25519:ver1", keys[0]["verify_keys"])
  94. self.assertEqual(len(keys[0]["verify_keys"]), 1)
  95. # it should be signed by both the origin server and the notary
  96. self.assertIn(SERVER_NAME, keys[0]["signatures"])
  97. self.assertIn(self.hs.hostname, keys[0]["signatures"])
  98. def test_get_own_key(self):
  99. """Fetch our own key"""
  100. testkey = signedjson.key.generate_signing_key("ver1")
  101. self.expect_outgoing_key_request(self.hs.hostname, testkey)
  102. resp = self.make_notary_request(self.hs.hostname, "ed25519:ver1")
  103. keys = resp["server_keys"]
  104. self.assertEqual(len(keys), 1)
  105. # it should be signed by both itself, and the notary signing key
  106. sigs = keys[0]["signatures"]
  107. self.assertEqual(len(sigs), 1)
  108. self.assertIn(self.hs.hostname, sigs)
  109. oursigs = sigs[self.hs.hostname]
  110. self.assertEqual(len(oursigs), 2)
  111. # the requested key should be present in the verify_keys section
  112. self.assertIn("ed25519:ver1", keys[0]["verify_keys"])
  113. class EndToEndPerspectivesTests(BaseRemoteKeyResourceTestCase):
  114. """End-to-end tests of the perspectives fetch case
  115. The idea here is to actually wire up a PerspectivesKeyFetcher to the notary
  116. endpoint, to check that the two implementations are compatible.
  117. """
  118. def default_config(self):
  119. config = super().default_config()
  120. # replace the signing key with our own
  121. self.hs_signing_key = signedjson.key.generate_signing_key("kssk")
  122. strm = StringIO()
  123. signedjson.key.write_signing_keys(strm, [self.hs_signing_key])
  124. config["signing_key"] = strm.getvalue()
  125. return config
  126. def prepare(self, reactor, clock, homeserver):
  127. # make a second homeserver, configured to use the first one as a key notary
  128. self.http_client2 = Mock()
  129. config = default_config(name="keyclient")
  130. config["trusted_key_servers"] = [
  131. {
  132. "server_name": self.hs.hostname,
  133. "verify_keys": {
  134. "ed25519:%s"
  135. % (
  136. self.hs_signing_key.version,
  137. ): signedjson.key.encode_verify_key_base64(
  138. self.hs_signing_key.verify_key
  139. )
  140. },
  141. }
  142. ]
  143. self.hs2 = self.setup_test_homeserver(
  144. federation_http_client=self.http_client2, config=config
  145. )
  146. # wire up outbound POST /key/v2/query requests from hs2 so that they
  147. # will be forwarded to hs1
  148. async def post_json(destination, path, data):
  149. self.assertEqual(destination, self.hs.hostname)
  150. self.assertEqual(
  151. path,
  152. "/_matrix/key/v2/query",
  153. )
  154. channel = FakeChannel(self.site, self.reactor)
  155. req = SynapseRequest(channel)
  156. req.content = BytesIO(encode_canonical_json(data))
  157. req.requestReceived(
  158. b"POST",
  159. path.encode("utf-8"),
  160. b"1.1",
  161. )
  162. channel.await_result()
  163. self.assertEqual(channel.code, 200)
  164. resp = channel.json_body
  165. return resp
  166. self.http_client2.post_json.side_effect = post_json
  167. def test_get_key(self):
  168. """Fetch a key belonging to a random server"""
  169. # make up a key to be fetched.
  170. testkey = signedjson.key.generate_signing_key("abc")
  171. # we expect hs1 to make a regular key request to the target server
  172. self.expect_outgoing_key_request("targetserver", testkey)
  173. keyid = "ed25519:%s" % (testkey.version,)
  174. fetcher = PerspectivesKeyFetcher(self.hs2)
  175. d = fetcher.get_keys("targetserver", [keyid], 1000)
  176. res = self.get_success(d)
  177. self.assertIn(keyid, res)
  178. keyres = res[keyid]
  179. assert isinstance(keyres, FetchKeyResult)
  180. self.assertEqual(
  181. signedjson.key.encode_verify_key_base64(keyres.verify_key),
  182. signedjson.key.encode_verify_key_base64(testkey.verify_key),
  183. )
  184. def test_get_notary_key(self):
  185. """Fetch a key belonging to the notary server"""
  186. # make up a key to be fetched. We randomise the keyid to try to get it to
  187. # appear before the key server signing key sometimes (otherwise we bail out
  188. # before fetching its signature)
  189. testkey = signedjson.key.generate_signing_key(random_string(5))
  190. # we expect hs1 to make a regular key request to itself
  191. self.expect_outgoing_key_request(self.hs.hostname, testkey)
  192. keyid = "ed25519:%s" % (testkey.version,)
  193. fetcher = PerspectivesKeyFetcher(self.hs2)
  194. d = fetcher.get_keys(self.hs.hostname, [keyid], 1000)
  195. res = self.get_success(d)
  196. self.assertIn(keyid, res)
  197. keyres = res[keyid]
  198. assert isinstance(keyres, FetchKeyResult)
  199. self.assertEqual(
  200. signedjson.key.encode_verify_key_base64(keyres.verify_key),
  201. signedjson.key.encode_verify_key_base64(testkey.verify_key),
  202. )
  203. def test_get_notary_keyserver_key(self):
  204. """Fetch the notary's keyserver key"""
  205. # we expect hs1 to make a regular key request to itself
  206. self.expect_outgoing_key_request(self.hs.hostname, self.hs_signing_key)
  207. keyid = "ed25519:%s" % (self.hs_signing_key.version,)
  208. fetcher = PerspectivesKeyFetcher(self.hs2)
  209. d = fetcher.get_keys(self.hs.hostname, [keyid], 1000)
  210. res = self.get_success(d)
  211. self.assertIn(keyid, res)
  212. keyres = res[keyid]
  213. assert isinstance(keyres, FetchKeyResult)
  214. self.assertEqual(
  215. signedjson.key.encode_verify_key_base64(keyres.verify_key),
  216. signedjson.key.encode_verify_key_base64(self.hs_signing_key.verify_key),
  217. )