1
0

test_keyring.py 27 KB

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