test_remote_key_resource.py 9.7 KB

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