test_keyring.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. # Copyright 2017-2021 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 time
  15. from typing import Dict, List
  16. from unittest.mock import Mock
  17. import attr
  18. import canonicaljson
  19. import signedjson.key
  20. import signedjson.sign
  21. from signedjson.key import encode_verify_key_base64, get_verify_key
  22. from signedjson.types import SigningKey
  23. from twisted.internet import defer
  24. from twisted.internet.defer import Deferred, ensureDeferred
  25. from synapse.api.errors import SynapseError
  26. from synapse.crypto import keyring
  27. from synapse.crypto.keyring import (
  28. PerspectivesKeyFetcher,
  29. ServerKeyFetcher,
  30. StoreKeyFetcher,
  31. )
  32. from synapse.logging.context import (
  33. LoggingContext,
  34. current_context,
  35. make_deferred_yieldable,
  36. )
  37. from synapse.storage.keys import FetchKeyResult
  38. from tests import unittest
  39. from tests.test_utils import make_awaitable
  40. from tests.unittest import logcontext_clean, override_config
  41. class MockPerspectiveServer:
  42. def __init__(self):
  43. self.server_name = "mock_server"
  44. self.key = signedjson.key.generate_signing_key(0)
  45. def get_verify_keys(self):
  46. vk = signedjson.key.get_verify_key(self.key)
  47. return {"%s:%s" % (vk.alg, vk.version): encode_verify_key_base64(vk)}
  48. def get_signed_key(self, server_name, verify_key):
  49. key_id = "%s:%s" % (verify_key.alg, verify_key.version)
  50. res = {
  51. "server_name": server_name,
  52. "old_verify_keys": {},
  53. "valid_until_ts": time.time() * 1000 + 3600,
  54. "verify_keys": {key_id: {"key": encode_verify_key_base64(verify_key)}},
  55. }
  56. self.sign_response(res)
  57. return res
  58. def sign_response(self, res):
  59. signedjson.sign.sign_json(res, self.server_name, self.key)
  60. @attr.s(slots=True)
  61. class FakeRequest:
  62. id = attr.ib()
  63. @logcontext_clean
  64. class KeyringTestCase(unittest.HomeserverTestCase):
  65. def check_context(self, val, expected):
  66. self.assertEqual(getattr(current_context(), "request", None), expected)
  67. return val
  68. def test_verify_json_objects_for_server_awaits_previous_requests(self):
  69. mock_fetcher = Mock()
  70. mock_fetcher.get_keys = Mock()
  71. kr = keyring.Keyring(self.hs, key_fetchers=(mock_fetcher,))
  72. # a signed object that we are going to try to validate
  73. key1 = signedjson.key.generate_signing_key(1)
  74. json1 = {}
  75. signedjson.sign.sign_json(json1, "server10", key1)
  76. # start off a first set of lookups. We make the mock fetcher block until this
  77. # deferred completes.
  78. first_lookup_deferred = Deferred()
  79. async def first_lookup_fetch(
  80. server_name: str, key_ids: List[str], minimum_valid_until_ts: int
  81. ) -> Dict[str, FetchKeyResult]:
  82. # self.assertEqual(current_context().request.id, "context_11")
  83. self.assertEqual(server_name, "server10")
  84. self.assertEqual(key_ids, [get_key_id(key1)])
  85. self.assertEqual(minimum_valid_until_ts, 0)
  86. await make_deferred_yieldable(first_lookup_deferred)
  87. return {get_key_id(key1): FetchKeyResult(get_verify_key(key1), 100)}
  88. mock_fetcher.get_keys.side_effect = first_lookup_fetch
  89. async def first_lookup():
  90. with LoggingContext("context_11", request=FakeRequest("context_11")):
  91. res_deferreds = kr.verify_json_objects_for_server(
  92. [("server10", json1, 0), ("server11", {}, 0)]
  93. )
  94. # the unsigned json should be rejected pretty quickly
  95. self.assertTrue(res_deferreds[1].called)
  96. try:
  97. await res_deferreds[1]
  98. self.assertFalse("unsigned json didn't cause a failure")
  99. except SynapseError:
  100. pass
  101. self.assertFalse(res_deferreds[0].called)
  102. res_deferreds[0].addBoth(self.check_context, None)
  103. await make_deferred_yieldable(res_deferreds[0])
  104. d0 = ensureDeferred(first_lookup())
  105. self.pump()
  106. mock_fetcher.get_keys.assert_called_once()
  107. # a second request for a server with outstanding requests
  108. # should block rather than start a second call
  109. async def second_lookup_fetch(
  110. server_name: str, key_ids: List[str], minimum_valid_until_ts: int
  111. ) -> Dict[str, FetchKeyResult]:
  112. # self.assertEqual(current_context().request.id, "context_12")
  113. return {get_key_id(key1): FetchKeyResult(get_verify_key(key1), 100)}
  114. mock_fetcher.get_keys.reset_mock()
  115. mock_fetcher.get_keys.side_effect = second_lookup_fetch
  116. second_lookup_state = [0]
  117. async def second_lookup():
  118. with LoggingContext("context_12", request=FakeRequest("context_12")):
  119. res_deferreds_2 = kr.verify_json_objects_for_server(
  120. [
  121. (
  122. "server10",
  123. json1,
  124. 0,
  125. )
  126. ]
  127. )
  128. res_deferreds_2[0].addBoth(self.check_context, None)
  129. second_lookup_state[0] = 1
  130. await make_deferred_yieldable(res_deferreds_2[0])
  131. second_lookup_state[0] = 2
  132. d2 = ensureDeferred(second_lookup())
  133. self.pump()
  134. # the second request should be pending, but the fetcher should not yet have been
  135. # called
  136. self.assertEqual(second_lookup_state[0], 1)
  137. mock_fetcher.get_keys.assert_not_called()
  138. # complete the first request
  139. first_lookup_deferred.callback(None)
  140. # and now both verifications should succeed.
  141. self.get_success(d0)
  142. self.get_success(d2)
  143. def test_verify_json_for_server(self):
  144. kr = keyring.Keyring(self.hs)
  145. key1 = signedjson.key.generate_signing_key(1)
  146. r = self.hs.get_datastores().main.store_server_verify_keys(
  147. "server9",
  148. time.time() * 1000,
  149. [("server9", get_key_id(key1), FetchKeyResult(get_verify_key(key1), 1000))],
  150. )
  151. self.get_success(r)
  152. json1 = {}
  153. signedjson.sign.sign_json(json1, "server9", key1)
  154. # should fail immediately on an unsigned object
  155. d = kr.verify_json_for_server("server9", {}, 0)
  156. self.get_failure(d, SynapseError)
  157. # should succeed on a signed object
  158. d = kr.verify_json_for_server("server9", json1, 500)
  159. # self.assertFalse(d.called)
  160. self.get_success(d)
  161. def test_verify_for_local_server(self):
  162. """Ensure that locally signed JSON can be verified without fetching keys
  163. over federation
  164. """
  165. kr = keyring.Keyring(self.hs)
  166. json1 = {}
  167. signedjson.sign.sign_json(json1, self.hs.hostname, self.hs.signing_key)
  168. # Test that verify_json_for_server succeeds on a object signed by ourselves
  169. d = kr.verify_json_for_server(self.hs.hostname, json1, 0)
  170. self.get_success(d)
  171. OLD_KEY = signedjson.key.generate_signing_key("old")
  172. @override_config(
  173. {
  174. "old_signing_keys": {
  175. f"{OLD_KEY.alg}:{OLD_KEY.version}": {
  176. "key": encode_verify_key_base64(OLD_KEY.verify_key),
  177. "expired_ts": 1000,
  178. }
  179. }
  180. }
  181. )
  182. def test_verify_for_local_server_old_key(self):
  183. """Can also use keys in old_signing_keys for verification"""
  184. json1 = {}
  185. signedjson.sign.sign_json(json1, self.hs.hostname, self.OLD_KEY)
  186. kr = keyring.Keyring(self.hs)
  187. d = kr.verify_json_for_server(self.hs.hostname, json1, 0)
  188. self.get_success(d)
  189. def test_verify_for_local_server_unknown_key(self):
  190. """Local keys that we no longer have should be fetched via the fetcher"""
  191. # the key we'll sign things with (nb, not known to the Keyring)
  192. key2 = signedjson.key.generate_signing_key("2")
  193. # set up a mock fetcher which will return the key
  194. async def get_keys(
  195. server_name: str, key_ids: List[str], minimum_valid_until_ts: int
  196. ) -> Dict[str, FetchKeyResult]:
  197. self.assertEqual(server_name, self.hs.hostname)
  198. self.assertEqual(key_ids, [get_key_id(key2)])
  199. return {get_key_id(key2): FetchKeyResult(get_verify_key(key2), 1200)}
  200. mock_fetcher = Mock()
  201. mock_fetcher.get_keys = Mock(side_effect=get_keys)
  202. kr = keyring.Keyring(
  203. self.hs, key_fetchers=(StoreKeyFetcher(self.hs), mock_fetcher)
  204. )
  205. # sign the json
  206. json1 = {}
  207. signedjson.sign.sign_json(json1, self.hs.hostname, key2)
  208. # ... and check we can verify it.
  209. d = kr.verify_json_for_server(self.hs.hostname, json1, 0)
  210. self.get_success(d)
  211. def test_verify_json_for_server_with_null_valid_until_ms(self):
  212. """Tests that we correctly handle key requests for keys we've stored
  213. with a null `ts_valid_until_ms`
  214. """
  215. mock_fetcher = Mock()
  216. mock_fetcher.get_keys = Mock(return_value=make_awaitable({}))
  217. kr = keyring.Keyring(
  218. self.hs, key_fetchers=(StoreKeyFetcher(self.hs), mock_fetcher)
  219. )
  220. key1 = signedjson.key.generate_signing_key(1)
  221. r = self.hs.get_datastores().main.store_server_verify_keys(
  222. "server9",
  223. time.time() * 1000,
  224. [("server9", get_key_id(key1), FetchKeyResult(get_verify_key(key1), None))],
  225. )
  226. self.get_success(r)
  227. json1 = {}
  228. signedjson.sign.sign_json(json1, "server9", key1)
  229. # should fail immediately on an unsigned object
  230. d = kr.verify_json_for_server("server9", {}, 0)
  231. self.get_failure(d, SynapseError)
  232. # should fail on a signed object with a non-zero minimum_valid_until_ms,
  233. # as it tries to refetch the keys and fails.
  234. d = kr.verify_json_for_server("server9", json1, 500)
  235. self.get_failure(d, SynapseError)
  236. # We expect the keyring tried to refetch the key once.
  237. mock_fetcher.get_keys.assert_called_once_with(
  238. "server9", [get_key_id(key1)], 500
  239. )
  240. # should succeed on a signed object with a 0 minimum_valid_until_ms
  241. d = kr.verify_json_for_server(
  242. "server9",
  243. json1,
  244. 0,
  245. )
  246. self.get_success(d)
  247. def test_verify_json_dedupes_key_requests(self):
  248. """Two requests for the same key should be deduped."""
  249. key1 = signedjson.key.generate_signing_key(1)
  250. async def get_keys(
  251. server_name: str, key_ids: List[str], minimum_valid_until_ts: int
  252. ) -> Dict[str, FetchKeyResult]:
  253. # there should only be one request object (with the max validity)
  254. self.assertEqual(server_name, "server1")
  255. self.assertEqual(key_ids, [get_key_id(key1)])
  256. self.assertEqual(minimum_valid_until_ts, 1500)
  257. return {get_key_id(key1): FetchKeyResult(get_verify_key(key1), 1200)}
  258. mock_fetcher = Mock()
  259. mock_fetcher.get_keys = Mock(side_effect=get_keys)
  260. kr = keyring.Keyring(self.hs, key_fetchers=(mock_fetcher,))
  261. json1 = {}
  262. signedjson.sign.sign_json(json1, "server1", key1)
  263. # the first request should succeed; the second should fail because the key
  264. # has expired
  265. results = kr.verify_json_objects_for_server(
  266. [
  267. (
  268. "server1",
  269. json1,
  270. 500,
  271. ),
  272. ("server1", json1, 1500),
  273. ]
  274. )
  275. self.assertEqual(len(results), 2)
  276. self.get_success(results[0])
  277. e = self.get_failure(results[1], SynapseError).value
  278. self.assertEqual(e.errcode, "M_UNAUTHORIZED")
  279. self.assertEqual(e.code, 401)
  280. # there should have been a single call to the fetcher
  281. mock_fetcher.get_keys.assert_called_once()
  282. def test_verify_json_falls_back_to_other_fetchers(self):
  283. """If the first fetcher cannot provide a recent enough key, we fall back"""
  284. key1 = signedjson.key.generate_signing_key(1)
  285. async def get_keys1(
  286. server_name: str, key_ids: List[str], minimum_valid_until_ts: int
  287. ) -> Dict[str, FetchKeyResult]:
  288. self.assertEqual(server_name, "server1")
  289. self.assertEqual(key_ids, [get_key_id(key1)])
  290. self.assertEqual(minimum_valid_until_ts, 1500)
  291. return {get_key_id(key1): FetchKeyResult(get_verify_key(key1), 800)}
  292. async def get_keys2(
  293. server_name: str, key_ids: List[str], minimum_valid_until_ts: int
  294. ) -> Dict[str, FetchKeyResult]:
  295. self.assertEqual(server_name, "server1")
  296. self.assertEqual(key_ids, [get_key_id(key1)])
  297. self.assertEqual(minimum_valid_until_ts, 1500)
  298. return {get_key_id(key1): FetchKeyResult(get_verify_key(key1), 1200)}
  299. mock_fetcher1 = Mock()
  300. mock_fetcher1.get_keys = Mock(side_effect=get_keys1)
  301. mock_fetcher2 = Mock()
  302. mock_fetcher2.get_keys = Mock(side_effect=get_keys2)
  303. kr = keyring.Keyring(self.hs, key_fetchers=(mock_fetcher1, mock_fetcher2))
  304. json1 = {}
  305. signedjson.sign.sign_json(json1, "server1", key1)
  306. results = kr.verify_json_objects_for_server(
  307. [
  308. (
  309. "server1",
  310. json1,
  311. 1200,
  312. ),
  313. (
  314. "server1",
  315. json1,
  316. 1500,
  317. ),
  318. ]
  319. )
  320. self.assertEqual(len(results), 2)
  321. self.get_success(results[0])
  322. e = self.get_failure(results[1], SynapseError).value
  323. self.assertEqual(e.errcode, "M_UNAUTHORIZED")
  324. self.assertEqual(e.code, 401)
  325. # there should have been a single call to each fetcher
  326. mock_fetcher1.get_keys.assert_called_once()
  327. mock_fetcher2.get_keys.assert_called_once()
  328. @logcontext_clean
  329. class ServerKeyFetcherTestCase(unittest.HomeserverTestCase):
  330. def make_homeserver(self, reactor, clock):
  331. self.http_client = Mock()
  332. hs = self.setup_test_homeserver(federation_http_client=self.http_client)
  333. return hs
  334. def test_get_keys_from_server(self):
  335. # arbitrarily advance the clock a bit
  336. self.reactor.advance(100)
  337. SERVER_NAME = "server2"
  338. fetcher = ServerKeyFetcher(self.hs)
  339. testkey = signedjson.key.generate_signing_key("ver1")
  340. testverifykey = signedjson.key.get_verify_key(testkey)
  341. testverifykey_id = "ed25519:ver1"
  342. VALID_UNTIL_TS = 200 * 1000
  343. # valid response
  344. response = {
  345. "server_name": SERVER_NAME,
  346. "old_verify_keys": {},
  347. "valid_until_ts": VALID_UNTIL_TS,
  348. "verify_keys": {
  349. testverifykey_id: {
  350. "key": signedjson.key.encode_verify_key_base64(testverifykey)
  351. }
  352. },
  353. }
  354. signedjson.sign.sign_json(response, SERVER_NAME, testkey)
  355. async def get_json(destination, path, **kwargs):
  356. self.assertEqual(destination, SERVER_NAME)
  357. self.assertEqual(path, "/_matrix/key/v2/server")
  358. return response
  359. self.http_client.get_json.side_effect = get_json
  360. keys = self.get_success(fetcher.get_keys(SERVER_NAME, ["key1"], 0))
  361. k = keys[testverifykey_id]
  362. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  363. self.assertEqual(k.verify_key, testverifykey)
  364. self.assertEqual(k.verify_key.alg, "ed25519")
  365. self.assertEqual(k.verify_key.version, "ver1")
  366. # check that the perspectives store is correctly updated
  367. lookup_triplet = (SERVER_NAME, testverifykey_id, None)
  368. key_json = self.get_success(
  369. self.hs.get_datastores().main.get_server_keys_json([lookup_triplet])
  370. )
  371. res = key_json[lookup_triplet]
  372. self.assertEqual(len(res), 1)
  373. res = res[0]
  374. self.assertEqual(res["key_id"], testverifykey_id)
  375. self.assertEqual(res["from_server"], SERVER_NAME)
  376. self.assertEqual(res["ts_added_ms"], self.reactor.seconds() * 1000)
  377. self.assertEqual(res["ts_valid_until_ms"], VALID_UNTIL_TS)
  378. # we expect it to be encoded as canonical json *before* it hits the db
  379. self.assertEqual(
  380. bytes(res["key_json"]), canonicaljson.encode_canonical_json(response)
  381. )
  382. # change the server name: the result should be ignored
  383. response["server_name"] = "OTHER_SERVER"
  384. keys = self.get_success(fetcher.get_keys(SERVER_NAME, ["key1"], 0))
  385. self.assertEqual(keys, {})
  386. class PerspectivesKeyFetcherTestCase(unittest.HomeserverTestCase):
  387. def make_homeserver(self, reactor, clock):
  388. self.mock_perspective_server = MockPerspectiveServer()
  389. self.http_client = Mock()
  390. config = self.default_config()
  391. config["trusted_key_servers"] = [
  392. {
  393. "server_name": self.mock_perspective_server.server_name,
  394. "verify_keys": self.mock_perspective_server.get_verify_keys(),
  395. }
  396. ]
  397. return self.setup_test_homeserver(
  398. federation_http_client=self.http_client, config=config
  399. )
  400. def build_perspectives_response(
  401. self,
  402. server_name: str,
  403. signing_key: SigningKey,
  404. valid_until_ts: int,
  405. ) -> dict:
  406. """
  407. Build a valid perspectives server response to a request for the given key
  408. """
  409. verify_key = signedjson.key.get_verify_key(signing_key)
  410. verifykey_id = "%s:%s" % (verify_key.alg, verify_key.version)
  411. response = {
  412. "server_name": server_name,
  413. "old_verify_keys": {},
  414. "valid_until_ts": valid_until_ts,
  415. "verify_keys": {
  416. verifykey_id: {
  417. "key": signedjson.key.encode_verify_key_base64(verify_key)
  418. }
  419. },
  420. }
  421. # the response must be signed by both the origin server and the perspectives
  422. # server.
  423. signedjson.sign.sign_json(response, server_name, signing_key)
  424. self.mock_perspective_server.sign_response(response)
  425. return response
  426. def expect_outgoing_key_query(
  427. self, expected_server_name: str, expected_key_id: str, response: dict
  428. ) -> None:
  429. """
  430. Tell the mock http client to expect a perspectives-server key query
  431. """
  432. async def post_json(destination, path, data, **kwargs):
  433. self.assertEqual(destination, self.mock_perspective_server.server_name)
  434. self.assertEqual(path, "/_matrix/key/v2/query")
  435. # check that the request is for the expected key
  436. q = data["server_keys"]
  437. self.assertEqual(list(q[expected_server_name].keys()), [expected_key_id])
  438. return {"server_keys": [response]}
  439. self.http_client.post_json.side_effect = post_json
  440. def test_get_keys_from_perspectives(self):
  441. # arbitrarily advance the clock a bit
  442. self.reactor.advance(100)
  443. fetcher = PerspectivesKeyFetcher(self.hs)
  444. SERVER_NAME = "server2"
  445. testkey = signedjson.key.generate_signing_key("ver1")
  446. testverifykey = signedjson.key.get_verify_key(testkey)
  447. testverifykey_id = "ed25519:ver1"
  448. VALID_UNTIL_TS = 200 * 1000
  449. response = self.build_perspectives_response(
  450. SERVER_NAME,
  451. testkey,
  452. VALID_UNTIL_TS,
  453. )
  454. self.expect_outgoing_key_query(SERVER_NAME, "key1", response)
  455. keys = self.get_success(fetcher.get_keys(SERVER_NAME, ["key1"], 0))
  456. self.assertIn(testverifykey_id, keys)
  457. k = keys[testverifykey_id]
  458. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  459. self.assertEqual(k.verify_key, testverifykey)
  460. self.assertEqual(k.verify_key.alg, "ed25519")
  461. self.assertEqual(k.verify_key.version, "ver1")
  462. # check that the perspectives store is correctly updated
  463. lookup_triplet = (SERVER_NAME, testverifykey_id, None)
  464. key_json = self.get_success(
  465. self.hs.get_datastores().main.get_server_keys_json([lookup_triplet])
  466. )
  467. res = key_json[lookup_triplet]
  468. self.assertEqual(len(res), 1)
  469. res = res[0]
  470. self.assertEqual(res["key_id"], testverifykey_id)
  471. self.assertEqual(res["from_server"], self.mock_perspective_server.server_name)
  472. self.assertEqual(res["ts_added_ms"], self.reactor.seconds() * 1000)
  473. self.assertEqual(res["ts_valid_until_ms"], VALID_UNTIL_TS)
  474. self.assertEqual(
  475. bytes(res["key_json"]), canonicaljson.encode_canonical_json(response)
  476. )
  477. def test_get_multiple_keys_from_perspectives(self):
  478. """Check that we can correctly request multiple keys for the same server"""
  479. fetcher = PerspectivesKeyFetcher(self.hs)
  480. SERVER_NAME = "server2"
  481. testkey1 = signedjson.key.generate_signing_key("ver1")
  482. testverifykey1 = signedjson.key.get_verify_key(testkey1)
  483. testverifykey1_id = "ed25519:ver1"
  484. testkey2 = signedjson.key.generate_signing_key("ver2")
  485. testverifykey2 = signedjson.key.get_verify_key(testkey2)
  486. testverifykey2_id = "ed25519:ver2"
  487. VALID_UNTIL_TS = 200 * 1000
  488. response1 = self.build_perspectives_response(
  489. SERVER_NAME,
  490. testkey1,
  491. VALID_UNTIL_TS,
  492. )
  493. response2 = self.build_perspectives_response(
  494. SERVER_NAME,
  495. testkey2,
  496. VALID_UNTIL_TS,
  497. )
  498. async def post_json(destination, path, data, **kwargs):
  499. self.assertEqual(destination, self.mock_perspective_server.server_name)
  500. self.assertEqual(path, "/_matrix/key/v2/query")
  501. # check that the request is for the expected keys
  502. q = data["server_keys"]
  503. self.assertEqual(
  504. list(q[SERVER_NAME].keys()), [testverifykey1_id, testverifykey2_id]
  505. )
  506. return {"server_keys": [response1, response2]}
  507. self.http_client.post_json.side_effect = post_json
  508. # fire off two separate requests; they should get merged together into a
  509. # single HTTP hit.
  510. request1_d = defer.ensureDeferred(
  511. fetcher.get_keys(SERVER_NAME, [testverifykey1_id], 0)
  512. )
  513. request2_d = defer.ensureDeferred(
  514. fetcher.get_keys(SERVER_NAME, [testverifykey2_id], 0)
  515. )
  516. keys1 = self.get_success(request1_d)
  517. self.assertIn(testverifykey1_id, keys1)
  518. k = keys1[testverifykey1_id]
  519. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  520. self.assertEqual(k.verify_key, testverifykey1)
  521. self.assertEqual(k.verify_key.alg, "ed25519")
  522. self.assertEqual(k.verify_key.version, "ver1")
  523. keys2 = self.get_success(request2_d)
  524. self.assertIn(testverifykey2_id, keys2)
  525. k = keys2[testverifykey2_id]
  526. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  527. self.assertEqual(k.verify_key, testverifykey2)
  528. self.assertEqual(k.verify_key.alg, "ed25519")
  529. self.assertEqual(k.verify_key.version, "ver2")
  530. # finally, ensure that only one request was sent
  531. self.assertEqual(self.http_client.post_json.call_count, 1)
  532. def test_get_perspectives_own_key(self):
  533. """Check that we can get the perspectives server's own keys
  534. This is slightly complicated by the fact that the perspectives server may
  535. use different keys for signing notary responses.
  536. """
  537. # arbitrarily advance the clock a bit
  538. self.reactor.advance(100)
  539. fetcher = PerspectivesKeyFetcher(self.hs)
  540. SERVER_NAME = self.mock_perspective_server.server_name
  541. testkey = signedjson.key.generate_signing_key("ver1")
  542. testverifykey = signedjson.key.get_verify_key(testkey)
  543. testverifykey_id = "ed25519:ver1"
  544. VALID_UNTIL_TS = 200 * 1000
  545. response = self.build_perspectives_response(
  546. SERVER_NAME, testkey, VALID_UNTIL_TS
  547. )
  548. self.expect_outgoing_key_query(SERVER_NAME, "key1", response)
  549. keys = self.get_success(fetcher.get_keys(SERVER_NAME, ["key1"], 0))
  550. self.assertIn(testverifykey_id, keys)
  551. k = keys[testverifykey_id]
  552. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  553. self.assertEqual(k.verify_key, testverifykey)
  554. self.assertEqual(k.verify_key.alg, "ed25519")
  555. self.assertEqual(k.verify_key.version, "ver1")
  556. # check that the perspectives store is correctly updated
  557. lookup_triplet = (SERVER_NAME, testverifykey_id, None)
  558. key_json = self.get_success(
  559. self.hs.get_datastores().main.get_server_keys_json([lookup_triplet])
  560. )
  561. res = key_json[lookup_triplet]
  562. self.assertEqual(len(res), 1)
  563. res = res[0]
  564. self.assertEqual(res["key_id"], testverifykey_id)
  565. self.assertEqual(res["from_server"], self.mock_perspective_server.server_name)
  566. self.assertEqual(res["ts_added_ms"], self.reactor.seconds() * 1000)
  567. self.assertEqual(res["ts_valid_until_ms"], VALID_UNTIL_TS)
  568. self.assertEqual(
  569. bytes(res["key_json"]), canonicaljson.encode_canonical_json(response)
  570. )
  571. def test_invalid_perspectives_responses(self):
  572. """Check that invalid responses from the perspectives server are rejected"""
  573. # arbitrarily advance the clock a bit
  574. self.reactor.advance(100)
  575. SERVER_NAME = "server2"
  576. testkey = signedjson.key.generate_signing_key("ver1")
  577. testverifykey = signedjson.key.get_verify_key(testkey)
  578. testverifykey_id = "ed25519:ver1"
  579. VALID_UNTIL_TS = 200 * 1000
  580. def build_response():
  581. return self.build_perspectives_response(
  582. SERVER_NAME, testkey, VALID_UNTIL_TS
  583. )
  584. def get_key_from_perspectives(response):
  585. fetcher = PerspectivesKeyFetcher(self.hs)
  586. self.expect_outgoing_key_query(SERVER_NAME, "key1", response)
  587. return self.get_success(fetcher.get_keys(SERVER_NAME, ["key1"], 0))
  588. # start with a valid response so we can check we are testing the right thing
  589. response = build_response()
  590. keys = get_key_from_perspectives(response)
  591. k = keys[testverifykey_id]
  592. self.assertEqual(k.verify_key, testverifykey)
  593. # remove the perspectives server's signature
  594. response = build_response()
  595. del response["signatures"][self.mock_perspective_server.server_name]
  596. keys = get_key_from_perspectives(response)
  597. self.assertEqual(keys, {}, "Expected empty dict with missing persp server sig")
  598. # remove the origin server's signature
  599. response = build_response()
  600. del response["signatures"][SERVER_NAME]
  601. keys = get_key_from_perspectives(response)
  602. self.assertEqual(keys, {}, "Expected empty dict with missing origin server sig")
  603. def get_key_id(key):
  604. """Get the matrix ID tag for a given SigningKey or VerifyKey"""
  605. return "%s:%s" % (key.alg, key.version)