test_keyring.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 New Vector Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import time
  16. from mock import Mock
  17. import canonicaljson
  18. import signedjson.key
  19. import signedjson.sign
  20. from nacl.signing import SigningKey
  21. from signedjson.key import encode_verify_key_base64, get_verify_key
  22. from twisted.internet import defer
  23. from synapse.api.errors import SynapseError
  24. from synapse.crypto import keyring
  25. from synapse.crypto.keyring import (
  26. PerspectivesKeyFetcher,
  27. ServerKeyFetcher,
  28. StoreKeyFetcher,
  29. )
  30. from synapse.logging.context import (
  31. LoggingContext,
  32. PreserveLoggingContext,
  33. make_deferred_yieldable,
  34. )
  35. from synapse.storage.keys import FetchKeyResult
  36. from tests import unittest
  37. class MockPerspectiveServer(object):
  38. def __init__(self):
  39. self.server_name = "mock_server"
  40. self.key = signedjson.key.generate_signing_key(0)
  41. def get_verify_keys(self):
  42. vk = signedjson.key.get_verify_key(self.key)
  43. return {"%s:%s" % (vk.alg, vk.version): encode_verify_key_base64(vk)}
  44. def get_signed_key(self, server_name, verify_key):
  45. key_id = "%s:%s" % (verify_key.alg, verify_key.version)
  46. res = {
  47. "server_name": server_name,
  48. "old_verify_keys": {},
  49. "valid_until_ts": time.time() * 1000 + 3600,
  50. "verify_keys": {key_id: {"key": encode_verify_key_base64(verify_key)}},
  51. }
  52. self.sign_response(res)
  53. return res
  54. def sign_response(self, res):
  55. signedjson.sign.sign_json(res, self.server_name, self.key)
  56. class KeyringTestCase(unittest.HomeserverTestCase):
  57. def make_homeserver(self, reactor, clock):
  58. self.mock_perspective_server = MockPerspectiveServer()
  59. self.http_client = Mock()
  60. config = self.default_config()
  61. config["trusted_key_servers"] = [
  62. {
  63. "server_name": self.mock_perspective_server.server_name,
  64. "verify_keys": self.mock_perspective_server.get_verify_keys(),
  65. }
  66. ]
  67. return self.setup_test_homeserver(
  68. handlers=None, http_client=self.http_client, config=config
  69. )
  70. def check_context(self, _, expected):
  71. self.assertEquals(
  72. getattr(LoggingContext.current_context(), "request", None), expected
  73. )
  74. def test_verify_json_objects_for_server_awaits_previous_requests(self):
  75. key1 = signedjson.key.generate_signing_key(1)
  76. kr = keyring.Keyring(self.hs)
  77. json1 = {}
  78. signedjson.sign.sign_json(json1, "server10", key1)
  79. persp_resp = {
  80. "server_keys": [
  81. self.mock_perspective_server.get_signed_key(
  82. "server10", signedjson.key.get_verify_key(key1)
  83. )
  84. ]
  85. }
  86. persp_deferred = defer.Deferred()
  87. @defer.inlineCallbacks
  88. def get_perspectives(**kwargs):
  89. self.assertEquals(LoggingContext.current_context().request, "11")
  90. with PreserveLoggingContext():
  91. yield persp_deferred
  92. return persp_resp
  93. self.http_client.post_json.side_effect = get_perspectives
  94. # start off a first set of lookups
  95. @defer.inlineCallbacks
  96. def first_lookup():
  97. with LoggingContext("11") as context_11:
  98. context_11.request = "11"
  99. res_deferreds = kr.verify_json_objects_for_server(
  100. [("server10", json1, 0, "test10"), ("server11", {}, 0, "test11")]
  101. )
  102. # the unsigned json should be rejected pretty quickly
  103. self.assertTrue(res_deferreds[1].called)
  104. try:
  105. yield 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. yield make_deferred_yieldable(res_deferreds[0])
  112. # let verify_json_objects_for_server finish its work before we kill the
  113. # logcontext
  114. yield self.clock.sleep(0)
  115. d0 = first_lookup()
  116. # wait a tick for it to send the request to the perspectives server
  117. # (it first tries the datastore)
  118. self.pump()
  119. self.http_client.post_json.assert_called_once()
  120. # a second request for a server with outstanding requests
  121. # should block rather than start a second call
  122. @defer.inlineCallbacks
  123. def second_lookup():
  124. with LoggingContext("12") as context_12:
  125. context_12.request = "12"
  126. self.http_client.post_json.reset_mock()
  127. self.http_client.post_json.return_value = defer.Deferred()
  128. res_deferreds_2 = kr.verify_json_objects_for_server(
  129. [("server10", json1, 0, "test")]
  130. )
  131. res_deferreds_2[0].addBoth(self.check_context, None)
  132. yield make_deferred_yieldable(res_deferreds_2[0])
  133. # let verify_json_objects_for_server finish its work before we kill the
  134. # logcontext
  135. yield self.clock.sleep(0)
  136. d2 = second_lookup()
  137. self.pump()
  138. self.http_client.post_json.assert_not_called()
  139. # complete the first request
  140. persp_deferred.callback(persp_resp)
  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_datastore().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 = _verify_json_for_server(kr, "server9", {}, 0, "test unsigned")
  156. self.failureResultOf(d, SynapseError)
  157. # should suceed on a signed object
  158. d = _verify_json_for_server(kr, "server9", json1, 500, "test signed")
  159. # self.assertFalse(d.called)
  160. self.get_success(d)
  161. def test_verify_json_for_server_with_null_valid_until_ms(self):
  162. """Tests that we correctly handle key requests for keys we've stored
  163. with a null `ts_valid_until_ms`
  164. """
  165. mock_fetcher = keyring.KeyFetcher()
  166. mock_fetcher.get_keys = Mock(return_value=defer.succeed({}))
  167. kr = keyring.Keyring(
  168. self.hs, key_fetchers=(StoreKeyFetcher(self.hs), mock_fetcher)
  169. )
  170. key1 = signedjson.key.generate_signing_key(1)
  171. r = self.hs.get_datastore().store_server_verify_keys(
  172. "server9",
  173. time.time() * 1000,
  174. [("server9", get_key_id(key1), FetchKeyResult(get_verify_key(key1), None))],
  175. )
  176. self.get_success(r)
  177. json1 = {}
  178. signedjson.sign.sign_json(json1, "server9", key1)
  179. # should fail immediately on an unsigned object
  180. d = _verify_json_for_server(kr, "server9", {}, 0, "test unsigned")
  181. self.failureResultOf(d, SynapseError)
  182. # should fail on a signed object with a non-zero minimum_valid_until_ms,
  183. # as it tries to refetch the keys and fails.
  184. d = _verify_json_for_server(
  185. kr, "server9", json1, 500, "test signed non-zero min"
  186. )
  187. self.get_failure(d, SynapseError)
  188. # We expect the keyring tried to refetch the key once.
  189. mock_fetcher.get_keys.assert_called_once_with(
  190. {"server9": {get_key_id(key1): 500}}
  191. )
  192. # should succeed on a signed object with a 0 minimum_valid_until_ms
  193. d = _verify_json_for_server(
  194. kr, "server9", json1, 0, "test signed with zero min"
  195. )
  196. self.get_success(d)
  197. def test_verify_json_dedupes_key_requests(self):
  198. """Two requests for the same key should be deduped."""
  199. key1 = signedjson.key.generate_signing_key(1)
  200. def get_keys(keys_to_fetch):
  201. # there should only be one request object (with the max validity)
  202. self.assertEqual(keys_to_fetch, {"server1": {get_key_id(key1): 1500}})
  203. return defer.succeed(
  204. {
  205. "server1": {
  206. get_key_id(key1): FetchKeyResult(get_verify_key(key1), 1200)
  207. }
  208. }
  209. )
  210. mock_fetcher = keyring.KeyFetcher()
  211. mock_fetcher.get_keys = Mock(side_effect=get_keys)
  212. kr = keyring.Keyring(self.hs, key_fetchers=(mock_fetcher,))
  213. json1 = {}
  214. signedjson.sign.sign_json(json1, "server1", key1)
  215. # the first request should succeed; the second should fail because the key
  216. # has expired
  217. results = kr.verify_json_objects_for_server(
  218. [("server1", json1, 500, "test1"), ("server1", json1, 1500, "test2")]
  219. )
  220. self.assertEqual(len(results), 2)
  221. self.get_success(results[0])
  222. e = self.get_failure(results[1], SynapseError).value
  223. self.assertEqual(e.errcode, "M_UNAUTHORIZED")
  224. self.assertEqual(e.code, 401)
  225. # there should have been a single call to the fetcher
  226. mock_fetcher.get_keys.assert_called_once()
  227. def test_verify_json_falls_back_to_other_fetchers(self):
  228. """If the first fetcher cannot provide a recent enough key, we fall back"""
  229. key1 = signedjson.key.generate_signing_key(1)
  230. def get_keys1(keys_to_fetch):
  231. self.assertEqual(keys_to_fetch, {"server1": {get_key_id(key1): 1500}})
  232. return defer.succeed(
  233. {
  234. "server1": {
  235. get_key_id(key1): FetchKeyResult(get_verify_key(key1), 800)
  236. }
  237. }
  238. )
  239. def get_keys2(keys_to_fetch):
  240. self.assertEqual(keys_to_fetch, {"server1": {get_key_id(key1): 1500}})
  241. return defer.succeed(
  242. {
  243. "server1": {
  244. get_key_id(key1): FetchKeyResult(get_verify_key(key1), 1200)
  245. }
  246. }
  247. )
  248. mock_fetcher1 = keyring.KeyFetcher()
  249. mock_fetcher1.get_keys = Mock(side_effect=get_keys1)
  250. mock_fetcher2 = keyring.KeyFetcher()
  251. mock_fetcher2.get_keys = Mock(side_effect=get_keys2)
  252. kr = keyring.Keyring(self.hs, key_fetchers=(mock_fetcher1, mock_fetcher2))
  253. json1 = {}
  254. signedjson.sign.sign_json(json1, "server1", key1)
  255. results = kr.verify_json_objects_for_server(
  256. [("server1", json1, 1200, "test1"), ("server1", json1, 1500, "test2")]
  257. )
  258. self.assertEqual(len(results), 2)
  259. self.get_success(results[0])
  260. e = self.get_failure(results[1], SynapseError).value
  261. self.assertEqual(e.errcode, "M_UNAUTHORIZED")
  262. self.assertEqual(e.code, 401)
  263. # there should have been a single call to each fetcher
  264. mock_fetcher1.get_keys.assert_called_once()
  265. mock_fetcher2.get_keys.assert_called_once()
  266. class ServerKeyFetcherTestCase(unittest.HomeserverTestCase):
  267. def make_homeserver(self, reactor, clock):
  268. self.http_client = Mock()
  269. hs = self.setup_test_homeserver(handlers=None, http_client=self.http_client)
  270. return hs
  271. def test_get_keys_from_server(self):
  272. # arbitrarily advance the clock a bit
  273. self.reactor.advance(100)
  274. SERVER_NAME = "server2"
  275. fetcher = ServerKeyFetcher(self.hs)
  276. testkey = signedjson.key.generate_signing_key("ver1")
  277. testverifykey = signedjson.key.get_verify_key(testkey)
  278. testverifykey_id = "ed25519:ver1"
  279. VALID_UNTIL_TS = 200 * 1000
  280. # valid response
  281. response = {
  282. "server_name": SERVER_NAME,
  283. "old_verify_keys": {},
  284. "valid_until_ts": VALID_UNTIL_TS,
  285. "verify_keys": {
  286. testverifykey_id: {
  287. "key": signedjson.key.encode_verify_key_base64(testverifykey)
  288. }
  289. },
  290. }
  291. signedjson.sign.sign_json(response, SERVER_NAME, testkey)
  292. def get_json(destination, path, **kwargs):
  293. self.assertEqual(destination, SERVER_NAME)
  294. self.assertEqual(path, "/_matrix/key/v2/server/key1")
  295. return response
  296. self.http_client.get_json.side_effect = get_json
  297. keys_to_fetch = {SERVER_NAME: {"key1": 0}}
  298. keys = self.get_success(fetcher.get_keys(keys_to_fetch))
  299. k = keys[SERVER_NAME][testverifykey_id]
  300. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  301. self.assertEqual(k.verify_key, testverifykey)
  302. self.assertEqual(k.verify_key.alg, "ed25519")
  303. self.assertEqual(k.verify_key.version, "ver1")
  304. # check that the perspectives store is correctly updated
  305. lookup_triplet = (SERVER_NAME, testverifykey_id, None)
  306. key_json = self.get_success(
  307. self.hs.get_datastore().get_server_keys_json([lookup_triplet])
  308. )
  309. res = key_json[lookup_triplet]
  310. self.assertEqual(len(res), 1)
  311. res = res[0]
  312. self.assertEqual(res["key_id"], testverifykey_id)
  313. self.assertEqual(res["from_server"], SERVER_NAME)
  314. self.assertEqual(res["ts_added_ms"], self.reactor.seconds() * 1000)
  315. self.assertEqual(res["ts_valid_until_ms"], VALID_UNTIL_TS)
  316. # we expect it to be encoded as canonical json *before* it hits the db
  317. self.assertEqual(
  318. bytes(res["key_json"]), canonicaljson.encode_canonical_json(response)
  319. )
  320. # change the server name: the result should be ignored
  321. response["server_name"] = "OTHER_SERVER"
  322. keys = self.get_success(fetcher.get_keys(keys_to_fetch))
  323. self.assertEqual(keys, {})
  324. class PerspectivesKeyFetcherTestCase(unittest.HomeserverTestCase):
  325. def make_homeserver(self, reactor, clock):
  326. self.mock_perspective_server = MockPerspectiveServer()
  327. self.http_client = Mock()
  328. config = self.default_config()
  329. config["trusted_key_servers"] = [
  330. {
  331. "server_name": self.mock_perspective_server.server_name,
  332. "verify_keys": self.mock_perspective_server.get_verify_keys(),
  333. }
  334. ]
  335. return self.setup_test_homeserver(
  336. handlers=None, http_client=self.http_client, config=config
  337. )
  338. def build_perspectives_response(
  339. self, server_name: str, signing_key: SigningKey, valid_until_ts: int,
  340. ) -> dict:
  341. """
  342. Build a valid perspectives server response to a request for the given key
  343. """
  344. verify_key = signedjson.key.get_verify_key(signing_key)
  345. verifykey_id = "%s:%s" % (verify_key.alg, verify_key.version)
  346. response = {
  347. "server_name": server_name,
  348. "old_verify_keys": {},
  349. "valid_until_ts": valid_until_ts,
  350. "verify_keys": {
  351. verifykey_id: {
  352. "key": signedjson.key.encode_verify_key_base64(verify_key)
  353. }
  354. },
  355. }
  356. # the response must be signed by both the origin server and the perspectives
  357. # server.
  358. signedjson.sign.sign_json(response, server_name, signing_key)
  359. self.mock_perspective_server.sign_response(response)
  360. return response
  361. def expect_outgoing_key_query(
  362. self, expected_server_name: str, expected_key_id: str, response: dict
  363. ) -> None:
  364. """
  365. Tell the mock http client to expect a perspectives-server key query
  366. """
  367. def post_json(destination, path, data, **kwargs):
  368. self.assertEqual(destination, self.mock_perspective_server.server_name)
  369. self.assertEqual(path, "/_matrix/key/v2/query")
  370. # check that the request is for the expected key
  371. q = data["server_keys"]
  372. self.assertEqual(list(q[expected_server_name].keys()), [expected_key_id])
  373. return {"server_keys": [response]}
  374. self.http_client.post_json.side_effect = post_json
  375. def test_get_keys_from_perspectives(self):
  376. # arbitrarily advance the clock a bit
  377. self.reactor.advance(100)
  378. fetcher = PerspectivesKeyFetcher(self.hs)
  379. SERVER_NAME = "server2"
  380. testkey = signedjson.key.generate_signing_key("ver1")
  381. testverifykey = signedjson.key.get_verify_key(testkey)
  382. testverifykey_id = "ed25519:ver1"
  383. VALID_UNTIL_TS = 200 * 1000
  384. response = self.build_perspectives_response(
  385. SERVER_NAME, testkey, VALID_UNTIL_TS,
  386. )
  387. self.expect_outgoing_key_query(SERVER_NAME, "key1", response)
  388. keys_to_fetch = {SERVER_NAME: {"key1": 0}}
  389. keys = self.get_success(fetcher.get_keys(keys_to_fetch))
  390. self.assertIn(SERVER_NAME, keys)
  391. k = keys[SERVER_NAME][testverifykey_id]
  392. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  393. self.assertEqual(k.verify_key, testverifykey)
  394. self.assertEqual(k.verify_key.alg, "ed25519")
  395. self.assertEqual(k.verify_key.version, "ver1")
  396. # check that the perspectives store is correctly updated
  397. lookup_triplet = (SERVER_NAME, testverifykey_id, None)
  398. key_json = self.get_success(
  399. self.hs.get_datastore().get_server_keys_json([lookup_triplet])
  400. )
  401. res = key_json[lookup_triplet]
  402. self.assertEqual(len(res), 1)
  403. res = res[0]
  404. self.assertEqual(res["key_id"], testverifykey_id)
  405. self.assertEqual(res["from_server"], self.mock_perspective_server.server_name)
  406. self.assertEqual(res["ts_added_ms"], self.reactor.seconds() * 1000)
  407. self.assertEqual(res["ts_valid_until_ms"], VALID_UNTIL_TS)
  408. self.assertEqual(
  409. bytes(res["key_json"]), canonicaljson.encode_canonical_json(response)
  410. )
  411. def test_get_perspectives_own_key(self):
  412. """Check that we can get the perspectives server's own keys
  413. This is slightly complicated by the fact that the perspectives server may
  414. use different keys for signing notary responses.
  415. """
  416. # arbitrarily advance the clock a bit
  417. self.reactor.advance(100)
  418. fetcher = PerspectivesKeyFetcher(self.hs)
  419. SERVER_NAME = self.mock_perspective_server.server_name
  420. testkey = signedjson.key.generate_signing_key("ver1")
  421. testverifykey = signedjson.key.get_verify_key(testkey)
  422. testverifykey_id = "ed25519:ver1"
  423. VALID_UNTIL_TS = 200 * 1000
  424. response = self.build_perspectives_response(
  425. SERVER_NAME, testkey, VALID_UNTIL_TS
  426. )
  427. self.expect_outgoing_key_query(SERVER_NAME, "key1", response)
  428. keys_to_fetch = {SERVER_NAME: {"key1": 0}}
  429. keys = self.get_success(fetcher.get_keys(keys_to_fetch))
  430. self.assertIn(SERVER_NAME, keys)
  431. k = keys[SERVER_NAME][testverifykey_id]
  432. self.assertEqual(k.valid_until_ts, VALID_UNTIL_TS)
  433. self.assertEqual(k.verify_key, testverifykey)
  434. self.assertEqual(k.verify_key.alg, "ed25519")
  435. self.assertEqual(k.verify_key.version, "ver1")
  436. # check that the perspectives store is correctly updated
  437. lookup_triplet = (SERVER_NAME, testverifykey_id, None)
  438. key_json = self.get_success(
  439. self.hs.get_datastore().get_server_keys_json([lookup_triplet])
  440. )
  441. res = key_json[lookup_triplet]
  442. self.assertEqual(len(res), 1)
  443. res = res[0]
  444. self.assertEqual(res["key_id"], testverifykey_id)
  445. self.assertEqual(res["from_server"], self.mock_perspective_server.server_name)
  446. self.assertEqual(res["ts_added_ms"], self.reactor.seconds() * 1000)
  447. self.assertEqual(res["ts_valid_until_ms"], VALID_UNTIL_TS)
  448. self.assertEqual(
  449. bytes(res["key_json"]), canonicaljson.encode_canonical_json(response)
  450. )
  451. def test_invalid_perspectives_responses(self):
  452. """Check that invalid responses from the perspectives server are rejected"""
  453. # arbitrarily advance the clock a bit
  454. self.reactor.advance(100)
  455. SERVER_NAME = "server2"
  456. testkey = signedjson.key.generate_signing_key("ver1")
  457. testverifykey = signedjson.key.get_verify_key(testkey)
  458. testverifykey_id = "ed25519:ver1"
  459. VALID_UNTIL_TS = 200 * 1000
  460. def build_response():
  461. return self.build_perspectives_response(
  462. SERVER_NAME, testkey, VALID_UNTIL_TS
  463. )
  464. def get_key_from_perspectives(response):
  465. fetcher = PerspectivesKeyFetcher(self.hs)
  466. keys_to_fetch = {SERVER_NAME: {"key1": 0}}
  467. self.expect_outgoing_key_query(SERVER_NAME, "key1", response)
  468. return self.get_success(fetcher.get_keys(keys_to_fetch))
  469. # start with a valid response so we can check we are testing the right thing
  470. response = build_response()
  471. keys = get_key_from_perspectives(response)
  472. k = keys[SERVER_NAME][testverifykey_id]
  473. self.assertEqual(k.verify_key, testverifykey)
  474. # remove the perspectives server's signature
  475. response = build_response()
  476. del response["signatures"][self.mock_perspective_server.server_name]
  477. self.http_client.post_json.return_value = {"server_keys": [response]}
  478. keys = get_key_from_perspectives(response)
  479. self.assertEqual(keys, {}, "Expected empty dict with missing persp server sig")
  480. # remove the origin server's signature
  481. response = build_response()
  482. del response["signatures"][SERVER_NAME]
  483. self.http_client.post_json.return_value = {"server_keys": [response]}
  484. keys = get_key_from_perspectives(response)
  485. self.assertEqual(keys, {}, "Expected empty dict with missing origin server sig")
  486. def get_key_id(key):
  487. """Get the matrix ID tag for a given SigningKey or VerifyKey"""
  488. return "%s:%s" % (key.alg, key.version)
  489. @defer.inlineCallbacks
  490. def run_in_context(f, *args, **kwargs):
  491. with LoggingContext("testctx") as ctx:
  492. # we set the "request" prop to make it easier to follow what's going on in the
  493. # logs.
  494. ctx.request = "testctx"
  495. rv = yield f(*args, **kwargs)
  496. return rv
  497. def _verify_json_for_server(kr, *args):
  498. """thin wrapper around verify_json_for_server which makes sure it is wrapped
  499. with the patched defer.inlineCallbacks.
  500. """
  501. @defer.inlineCallbacks
  502. def v():
  503. rv1 = yield kr.verify_json_for_server(*args)
  504. return rv1
  505. return run_in_context(v)