test_keyring.py 29 KB

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