test_keyring.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  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 AsyncMock, 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_json(
  157. "server9",
  158. get_key_id(key1),
  159. from_server="test",
  160. ts_now_ms=int(time.time() * 1000),
  161. ts_expires_ms=1000,
  162. # The entire response gets signed & stored, just include the bits we
  163. # care about.
  164. key_json_bytes=canonicaljson.encode_canonical_json(
  165. {
  166. "verify_keys": {
  167. get_key_id(key1): {
  168. "key": encode_verify_key_base64(get_verify_key(key1))
  169. }
  170. }
  171. }
  172. ),
  173. )
  174. self.get_success(r)
  175. json1: JsonDict = {}
  176. signedjson.sign.sign_json(json1, "server9", key1)
  177. # should fail immediately on an unsigned object
  178. d = kr.verify_json_for_server("server9", {}, 0)
  179. self.get_failure(d, SynapseError)
  180. # should succeed on a signed object
  181. d = kr.verify_json_for_server("server9", json1, 500)
  182. # self.assertFalse(d.called)
  183. self.get_success(d)
  184. def test_verify_for_local_server(self) -> None:
  185. """Ensure that locally signed JSON can be verified without fetching keys
  186. over federation
  187. """
  188. kr = keyring.Keyring(self.hs)
  189. json1: JsonDict = {}
  190. signedjson.sign.sign_json(json1, self.hs.hostname, self.hs.signing_key)
  191. # Test that verify_json_for_server succeeds on a object signed by ourselves
  192. d = kr.verify_json_for_server(self.hs.hostname, json1, 0)
  193. self.get_success(d)
  194. OLD_KEY = signedjson.key.generate_signing_key("old")
  195. @override_config(
  196. {
  197. "old_signing_keys": {
  198. f"{OLD_KEY.alg}:{OLD_KEY.version}": {
  199. "key": encode_verify_key_base64(
  200. signedjson.key.get_verify_key(OLD_KEY)
  201. ),
  202. "expired_ts": 1000,
  203. }
  204. }
  205. }
  206. )
  207. def test_verify_for_local_server_old_key(self) -> None:
  208. """Can also use keys in old_signing_keys for verification"""
  209. json1: JsonDict = {}
  210. signedjson.sign.sign_json(json1, self.hs.hostname, self.OLD_KEY)
  211. kr = keyring.Keyring(self.hs)
  212. d = kr.verify_json_for_server(self.hs.hostname, json1, 0)
  213. self.get_success(d)
  214. def test_verify_for_local_server_unknown_key(self) -> None:
  215. """Local keys that we no longer have should be fetched via the fetcher"""
  216. # the key we'll sign things with (nb, not known to the Keyring)
  217. key2 = signedjson.key.generate_signing_key("2")
  218. # set up a mock fetcher which will return the key
  219. async def get_keys(
  220. server_name: str, key_ids: List[str], minimum_valid_until_ts: int
  221. ) -> Dict[str, FetchKeyResult]:
  222. self.assertEqual(server_name, self.hs.hostname)
  223. self.assertEqual(key_ids, [get_key_id(key2)])
  224. return {get_key_id(key2): FetchKeyResult(get_verify_key(key2), 1200)}
  225. mock_fetcher = Mock()
  226. mock_fetcher.get_keys = Mock(side_effect=get_keys)
  227. kr = keyring.Keyring(
  228. self.hs, key_fetchers=(StoreKeyFetcher(self.hs), mock_fetcher)
  229. )
  230. # sign the json
  231. json1: JsonDict = {}
  232. signedjson.sign.sign_json(json1, self.hs.hostname, key2)
  233. # ... and check we can verify it.
  234. d = kr.verify_json_for_server(self.hs.hostname, json1, 0)
  235. self.get_success(d)
  236. def test_verify_json_for_server_with_null_valid_until_ms(self) -> None:
  237. """Tests that we correctly handle key requests for keys we've stored
  238. with a null `ts_valid_until_ms`
  239. """
  240. mock_fetcher = Mock()
  241. mock_fetcher.get_keys = AsyncMock(return_value={})
  242. key1 = signedjson.key.generate_signing_key("1")
  243. r = self.hs.get_datastores().main.store_server_signature_keys(
  244. "server9",
  245. int(time.time() * 1000),
  246. # None is not a valid value in FetchKeyResult, but we're abusing this
  247. # API to insert null values into the database. The nulls get converted
  248. # to 0 when fetched in KeyStore.get_server_signature_keys.
  249. {("server9", get_key_id(key1)): FetchKeyResult(get_verify_key(key1), None)}, # type: ignore[arg-type]
  250. )
  251. self.get_success(r)
  252. json1: JsonDict = {}
  253. signedjson.sign.sign_json(json1, "server9", key1)
  254. # should succeed on a signed object with a 0 minimum_valid_until_ms
  255. d = self.hs.get_datastores().main.get_server_signature_keys(
  256. [("server9", get_key_id(key1))]
  257. )
  258. result = self.get_success(d)
  259. self.assertEqual(result[("server9", get_key_id(key1))].valid_until_ts, 0)
  260. def test_verify_json_dedupes_key_requests(self) -> None:
  261. """Two requests for the same key should be deduped."""
  262. key1 = signedjson.key.generate_signing_key("1")
  263. async def get_keys(
  264. server_name: str, key_ids: List[str], minimum_valid_until_ts: int
  265. ) -> Dict[str, FetchKeyResult]:
  266. # there should only be one request object (with the max validity)
  267. self.assertEqual(server_name, "server1")
  268. self.assertEqual(key_ids, [get_key_id(key1)])
  269. self.assertEqual(minimum_valid_until_ts, 1500)
  270. return {get_key_id(key1): FetchKeyResult(get_verify_key(key1), 1200)}
  271. mock_fetcher = Mock()
  272. mock_fetcher.get_keys = Mock(side_effect=get_keys)
  273. kr = keyring.Keyring(self.hs, key_fetchers=(mock_fetcher,))
  274. json1: JsonDict = {}
  275. signedjson.sign.sign_json(json1, "server1", key1)
  276. # the first request should succeed; the second should fail because the key
  277. # has expired
  278. results = kr.verify_json_objects_for_server(
  279. [
  280. (
  281. "server1",
  282. json1,
  283. 500,
  284. ),
  285. ("server1", json1, 1500),
  286. ]
  287. )
  288. self.assertEqual(len(results), 2)
  289. self.get_success(results[0])
  290. e = self.get_failure(results[1], SynapseError).value
  291. self.assertEqual(e.errcode, "M_UNAUTHORIZED")
  292. self.assertEqual(e.code, 401)
  293. # there should have been a single call to the fetcher
  294. mock_fetcher.get_keys.assert_called_once()
  295. def test_verify_json_falls_back_to_other_fetchers(self) -> None:
  296. """If the first fetcher cannot provide a recent enough key, we fall back"""
  297. key1 = signedjson.key.generate_signing_key("1")
  298. async def get_keys1(
  299. server_name: str, key_ids: List[str], minimum_valid_until_ts: int
  300. ) -> Dict[str, FetchKeyResult]:
  301. self.assertEqual(server_name, "server1")
  302. self.assertEqual(key_ids, [get_key_id(key1)])
  303. self.assertEqual(minimum_valid_until_ts, 1500)
  304. return {get_key_id(key1): FetchKeyResult(get_verify_key(key1), 800)}
  305. async def get_keys2(
  306. server_name: str, key_ids: List[str], minimum_valid_until_ts: int
  307. ) -> Dict[str, FetchKeyResult]:
  308. self.assertEqual(server_name, "server1")
  309. self.assertEqual(key_ids, [get_key_id(key1)])
  310. self.assertEqual(minimum_valid_until_ts, 1500)
  311. return {get_key_id(key1): FetchKeyResult(get_verify_key(key1), 1200)}
  312. mock_fetcher1 = Mock()
  313. mock_fetcher1.get_keys = Mock(side_effect=get_keys1)
  314. mock_fetcher2 = Mock()
  315. mock_fetcher2.get_keys = Mock(side_effect=get_keys2)
  316. kr = keyring.Keyring(self.hs, key_fetchers=(mock_fetcher1, mock_fetcher2))
  317. json1: JsonDict = {}
  318. signedjson.sign.sign_json(json1, "server1", key1)
  319. results = kr.verify_json_objects_for_server(
  320. [
  321. (
  322. "server1",
  323. json1,
  324. 1200,
  325. ),
  326. (
  327. "server1",
  328. json1,
  329. 1500,
  330. ),
  331. ]
  332. )
  333. self.assertEqual(len(results), 2)
  334. self.get_success(results[0])
  335. e = self.get_failure(results[1], SynapseError).value
  336. self.assertEqual(e.errcode, "M_UNAUTHORIZED")
  337. self.assertEqual(e.code, 401)
  338. # there should have been a single call to each fetcher
  339. mock_fetcher1.get_keys.assert_called_once()
  340. mock_fetcher2.get_keys.assert_called_once()
  341. @logcontext_clean
  342. class ServerKeyFetcherTestCase(unittest.HomeserverTestCase):
  343. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  344. self.http_client = Mock()
  345. hs = self.setup_test_homeserver(federation_http_client=self.http_client)
  346. return hs
  347. def test_get_keys_from_server(self) -> None:
  348. # arbitrarily advance the clock a bit
  349. self.reactor.advance(100)
  350. SERVER_NAME = "server2"
  351. fetcher = ServerKeyFetcher(self.hs)
  352. testkey = signedjson.key.generate_signing_key("ver1")
  353. testverifykey = signedjson.key.get_verify_key(testkey)
  354. testverifykey_id = "ed25519:ver1"
  355. VALID_UNTIL_TS = 200 * 1000
  356. # valid response
  357. response = {
  358. "server_name": SERVER_NAME,
  359. "old_verify_keys": {},
  360. "valid_until_ts": VALID_UNTIL_TS,
  361. "verify_keys": {
  362. testverifykey_id: {
  363. "key": signedjson.key.encode_verify_key_base64(testverifykey)
  364. }
  365. },
  366. }
  367. signedjson.sign.sign_json(response, SERVER_NAME, testkey)
  368. async def get_json(destination: str, path: str, **kwargs: Any) -> JsonDict:
  369. self.assertEqual(destination, SERVER_NAME)
  370. self.assertEqual(path, "/_matrix/key/v2/server")
  371. return response
  372. self.http_client.get_json.side_effect = get_json
  373. keys = self.get_success(fetcher.get_keys(SERVER_NAME, ["key1"], 0))
  374. k = keys[testverifykey_id]
  375. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  376. self.assertEqual(k.verify_key, testverifykey)
  377. self.assertEqual(k.verify_key.alg, "ed25519")
  378. self.assertEqual(k.verify_key.version, "ver1")
  379. # check that the perspectives store is correctly updated
  380. key_json = self.get_success(
  381. self.hs.get_datastores().main.get_server_keys_json_for_remote(
  382. SERVER_NAME, [testverifykey_id]
  383. )
  384. )
  385. res = key_json[testverifykey_id]
  386. self.assertIsNotNone(res)
  387. assert res is not None
  388. self.assertEqual(res.added_ts, self.reactor.seconds() * 1000)
  389. self.assertEqual(res.valid_until_ts, VALID_UNTIL_TS)
  390. # we expect it to be encoded as canonical json *before* it hits the db
  391. self.assertEqual(res.key_json, canonicaljson.encode_canonical_json(response))
  392. # change the server name: the result should be ignored
  393. response["server_name"] = "OTHER_SERVER"
  394. keys = self.get_success(fetcher.get_keys(SERVER_NAME, ["key1"], 0))
  395. self.assertEqual(keys, {})
  396. class PerspectivesKeyFetcherTestCase(unittest.HomeserverTestCase):
  397. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  398. self.mock_perspective_server = MockPerspectiveServer()
  399. self.http_client = Mock()
  400. config = self.default_config()
  401. config["trusted_key_servers"] = [
  402. {
  403. "server_name": self.mock_perspective_server.server_name,
  404. "verify_keys": self.mock_perspective_server.get_verify_keys(),
  405. }
  406. ]
  407. return self.setup_test_homeserver(
  408. federation_http_client=self.http_client, config=config
  409. )
  410. def build_perspectives_response(
  411. self,
  412. server_name: str,
  413. signing_key: SigningKey,
  414. valid_until_ts: int,
  415. ) -> dict:
  416. """
  417. Build a valid perspectives server response to a request for the given key
  418. """
  419. verify_key = signedjson.key.get_verify_key(signing_key)
  420. verifykey_id = "%s:%s" % (verify_key.alg, verify_key.version)
  421. response = {
  422. "server_name": server_name,
  423. "old_verify_keys": {},
  424. "valid_until_ts": valid_until_ts,
  425. "verify_keys": {
  426. verifykey_id: {
  427. "key": signedjson.key.encode_verify_key_base64(verify_key)
  428. }
  429. },
  430. }
  431. # the response must be signed by both the origin server and the perspectives
  432. # server.
  433. signedjson.sign.sign_json(response, server_name, signing_key)
  434. self.mock_perspective_server.sign_response(response)
  435. return response
  436. def expect_outgoing_key_query(
  437. self, expected_server_name: str, expected_key_id: str, response: dict
  438. ) -> None:
  439. """
  440. Tell the mock http client to expect a perspectives-server key query
  441. """
  442. async def post_json(
  443. destination: str, path: str, data: JsonDict, **kwargs: Any
  444. ) -> JsonDict:
  445. self.assertEqual(destination, self.mock_perspective_server.server_name)
  446. self.assertEqual(path, "/_matrix/key/v2/query")
  447. # check that the request is for the expected key
  448. q = data["server_keys"]
  449. self.assertEqual(list(q[expected_server_name].keys()), [expected_key_id])
  450. return {"server_keys": [response]}
  451. self.http_client.post_json.side_effect = post_json
  452. def test_get_keys_from_perspectives(self) -> None:
  453. # arbitrarily advance the clock a bit
  454. self.reactor.advance(100)
  455. fetcher = PerspectivesKeyFetcher(self.hs)
  456. SERVER_NAME = "server2"
  457. testkey = signedjson.key.generate_signing_key("ver1")
  458. testverifykey = signedjson.key.get_verify_key(testkey)
  459. testverifykey_id = "ed25519:ver1"
  460. VALID_UNTIL_TS = 200 * 1000
  461. response = self.build_perspectives_response(
  462. SERVER_NAME,
  463. testkey,
  464. VALID_UNTIL_TS,
  465. )
  466. self.expect_outgoing_key_query(SERVER_NAME, "key1", response)
  467. keys = self.get_success(fetcher.get_keys(SERVER_NAME, ["key1"], 0))
  468. self.assertIn(testverifykey_id, keys)
  469. k = keys[testverifykey_id]
  470. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  471. self.assertEqual(k.verify_key, testverifykey)
  472. self.assertEqual(k.verify_key.alg, "ed25519")
  473. self.assertEqual(k.verify_key.version, "ver1")
  474. # check that the perspectives store is correctly updated
  475. key_json = self.get_success(
  476. self.hs.get_datastores().main.get_server_keys_json_for_remote(
  477. SERVER_NAME, [testverifykey_id]
  478. )
  479. )
  480. res = key_json[testverifykey_id]
  481. self.assertIsNotNone(res)
  482. assert res is not None
  483. self.assertEqual(res.added_ts, self.reactor.seconds() * 1000)
  484. self.assertEqual(res.valid_until_ts, VALID_UNTIL_TS)
  485. self.assertEqual(res.key_json, canonicaljson.encode_canonical_json(response))
  486. def test_get_multiple_keys_from_perspectives(self) -> None:
  487. """Check that we can correctly request multiple keys for the same server"""
  488. fetcher = PerspectivesKeyFetcher(self.hs)
  489. SERVER_NAME = "server2"
  490. testkey1 = signedjson.key.generate_signing_key("ver1")
  491. testverifykey1 = signedjson.key.get_verify_key(testkey1)
  492. testverifykey1_id = "ed25519:ver1"
  493. testkey2 = signedjson.key.generate_signing_key("ver2")
  494. testverifykey2 = signedjson.key.get_verify_key(testkey2)
  495. testverifykey2_id = "ed25519:ver2"
  496. VALID_UNTIL_TS = 200 * 1000
  497. response1 = self.build_perspectives_response(
  498. SERVER_NAME,
  499. testkey1,
  500. VALID_UNTIL_TS,
  501. )
  502. response2 = self.build_perspectives_response(
  503. SERVER_NAME,
  504. testkey2,
  505. VALID_UNTIL_TS,
  506. )
  507. async def post_json(
  508. destination: str, path: str, data: JsonDict, **kwargs: str
  509. ) -> JsonDict:
  510. self.assertEqual(destination, self.mock_perspective_server.server_name)
  511. self.assertEqual(path, "/_matrix/key/v2/query")
  512. # check that the request is for the expected keys
  513. q = data["server_keys"]
  514. self.assertEqual(
  515. list(q[SERVER_NAME].keys()), [testverifykey1_id, testverifykey2_id]
  516. )
  517. return {"server_keys": [response1, response2]}
  518. self.http_client.post_json.side_effect = post_json
  519. # fire off two separate requests; they should get merged together into a
  520. # single HTTP hit.
  521. request1_d = defer.ensureDeferred(
  522. fetcher.get_keys(SERVER_NAME, [testverifykey1_id], 0)
  523. )
  524. request2_d = defer.ensureDeferred(
  525. fetcher.get_keys(SERVER_NAME, [testverifykey2_id], 0)
  526. )
  527. keys1 = self.get_success(request1_d)
  528. self.assertIn(testverifykey1_id, keys1)
  529. k = keys1[testverifykey1_id]
  530. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  531. self.assertEqual(k.verify_key, testverifykey1)
  532. self.assertEqual(k.verify_key.alg, "ed25519")
  533. self.assertEqual(k.verify_key.version, "ver1")
  534. keys2 = self.get_success(request2_d)
  535. self.assertIn(testverifykey2_id, keys2)
  536. k = keys2[testverifykey2_id]
  537. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  538. self.assertEqual(k.verify_key, testverifykey2)
  539. self.assertEqual(k.verify_key.alg, "ed25519")
  540. self.assertEqual(k.verify_key.version, "ver2")
  541. # finally, ensure that only one request was sent
  542. self.assertEqual(self.http_client.post_json.call_count, 1)
  543. def test_get_perspectives_own_key(self) -> None:
  544. """Check that we can get the perspectives server's own keys
  545. This is slightly complicated by the fact that the perspectives server may
  546. use different keys for signing notary responses.
  547. """
  548. # arbitrarily advance the clock a bit
  549. self.reactor.advance(100)
  550. fetcher = PerspectivesKeyFetcher(self.hs)
  551. SERVER_NAME = self.mock_perspective_server.server_name
  552. testkey = signedjson.key.generate_signing_key("ver1")
  553. testverifykey = signedjson.key.get_verify_key(testkey)
  554. testverifykey_id = "ed25519:ver1"
  555. VALID_UNTIL_TS = 200 * 1000
  556. response = self.build_perspectives_response(
  557. SERVER_NAME, testkey, VALID_UNTIL_TS
  558. )
  559. self.expect_outgoing_key_query(SERVER_NAME, "key1", response)
  560. keys = self.get_success(fetcher.get_keys(SERVER_NAME, ["key1"], 0))
  561. self.assertIn(testverifykey_id, keys)
  562. k = keys[testverifykey_id]
  563. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  564. self.assertEqual(k.verify_key, testverifykey)
  565. self.assertEqual(k.verify_key.alg, "ed25519")
  566. self.assertEqual(k.verify_key.version, "ver1")
  567. # check that the perspectives store is correctly updated
  568. key_json = self.get_success(
  569. self.hs.get_datastores().main.get_server_keys_json_for_remote(
  570. SERVER_NAME, [testverifykey_id]
  571. )
  572. )
  573. res = key_json[testverifykey_id]
  574. self.assertIsNotNone(res)
  575. assert res is not None
  576. self.assertEqual(res.added_ts, self.reactor.seconds() * 1000)
  577. self.assertEqual(res.valid_until_ts, VALID_UNTIL_TS)
  578. self.assertEqual(res.key_json, canonicaljson.encode_canonical_json(response))
  579. def test_invalid_perspectives_responses(self) -> None:
  580. """Check that invalid responses from the perspectives server are rejected"""
  581. # arbitrarily advance the clock a bit
  582. self.reactor.advance(100)
  583. SERVER_NAME = "server2"
  584. testkey = signedjson.key.generate_signing_key("ver1")
  585. testverifykey = signedjson.key.get_verify_key(testkey)
  586. testverifykey_id = "ed25519:ver1"
  587. VALID_UNTIL_TS = 200 * 1000
  588. def build_response() -> dict:
  589. return self.build_perspectives_response(
  590. SERVER_NAME, testkey, VALID_UNTIL_TS
  591. )
  592. def get_key_from_perspectives(response: JsonDict) -> Dict[str, FetchKeyResult]:
  593. fetcher = PerspectivesKeyFetcher(self.hs)
  594. self.expect_outgoing_key_query(SERVER_NAME, "key1", response)
  595. return self.get_success(fetcher.get_keys(SERVER_NAME, ["key1"], 0))
  596. # start with a valid response so we can check we are testing the right thing
  597. response = build_response()
  598. keys = get_key_from_perspectives(response)
  599. k = keys[testverifykey_id]
  600. self.assertEqual(k.verify_key, testverifykey)
  601. # remove the perspectives server's signature
  602. response = build_response()
  603. del response["signatures"][self.mock_perspective_server.server_name]
  604. keys = get_key_from_perspectives(response)
  605. self.assertEqual(keys, {}, "Expected empty dict with missing persp server sig")
  606. # remove the origin server's signature
  607. response = build_response()
  608. del response["signatures"][SERVER_NAME]
  609. keys = get_key_from_perspectives(response)
  610. self.assertEqual(keys, {}, "Expected empty dict with missing origin server sig")
  611. def get_key_id(key: SigningKey) -> str:
  612. """Get the matrix ID tag for a given SigningKey or VerifyKey"""
  613. return "%s:%s" % (key.alg, key.version)