test_oidc.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. # Copyright 2020 Quentin Gliech
  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 os
  15. from typing import Any, Dict, Tuple
  16. from unittest.mock import ANY, Mock, patch
  17. from urllib.parse import parse_qs, urlparse
  18. import pymacaroons
  19. from twisted.test.proto_helpers import MemoryReactor
  20. from synapse.handlers.sso import MappingException
  21. from synapse.http.site import SynapseRequest
  22. from synapse.server import HomeServer
  23. from synapse.types import UserID
  24. from synapse.util import Clock
  25. from synapse.util.macaroons import get_value_from_macaroon
  26. from synapse.util.stringutils import random_string
  27. from tests.test_utils import FakeResponse, get_awaitable_result, simple_async_mock
  28. from tests.test_utils.oidc import FakeAuthorizationGrant, FakeOidcServer
  29. from tests.unittest import HomeserverTestCase, override_config
  30. try:
  31. import authlib # noqa: F401
  32. HAS_OIDC = True
  33. except ImportError:
  34. HAS_OIDC = False
  35. # These are a few constants that are used as config parameters in the tests.
  36. ISSUER = "https://issuer/"
  37. CLIENT_ID = "test-client-id"
  38. CLIENT_SECRET = "test-client-secret"
  39. BASE_URL = "https://synapse/"
  40. CALLBACK_URL = BASE_URL + "_synapse/client/oidc/callback"
  41. SCOPES = ["openid"]
  42. # config for common cases
  43. DEFAULT_CONFIG = {
  44. "enabled": True,
  45. "client_id": CLIENT_ID,
  46. "client_secret": CLIENT_SECRET,
  47. "issuer": ISSUER,
  48. "scopes": SCOPES,
  49. "user_mapping_provider": {"module": __name__ + ".TestMappingProvider"},
  50. }
  51. # extends the default config with explicit OAuth2 endpoints instead of using discovery
  52. EXPLICIT_ENDPOINT_CONFIG = {
  53. **DEFAULT_CONFIG,
  54. "discover": False,
  55. "authorization_endpoint": ISSUER + "authorize",
  56. "token_endpoint": ISSUER + "token",
  57. "jwks_uri": ISSUER + "jwks",
  58. }
  59. class TestMappingProvider:
  60. @staticmethod
  61. def parse_config(config):
  62. return
  63. def __init__(self, config):
  64. pass
  65. def get_remote_user_id(self, userinfo):
  66. return userinfo["sub"]
  67. async def map_user_attributes(self, userinfo, token):
  68. return {"localpart": userinfo["username"], "display_name": None}
  69. # Do not include get_extra_attributes to test backwards compatibility paths.
  70. class TestMappingProviderExtra(TestMappingProvider):
  71. async def get_extra_attributes(self, userinfo, token):
  72. return {"phone": userinfo["phone"]}
  73. class TestMappingProviderFailures(TestMappingProvider):
  74. async def map_user_attributes(self, userinfo, token, failures):
  75. return {
  76. "localpart": userinfo["username"] + (str(failures) if failures else ""),
  77. "display_name": None,
  78. }
  79. def _key_file_path() -> str:
  80. """path to a file containing the private half of a test key"""
  81. # this key was generated with:
  82. # openssl ecparam -name prime256v1 -genkey -noout |
  83. # openssl pkcs8 -topk8 -nocrypt -out oidc_test_key.p8
  84. #
  85. # we use PKCS8 rather than SEC-1 (which is what openssl ecparam spits out), because
  86. # that's what Apple use, and we want to be sure that we work with Apple's keys.
  87. #
  88. # (For the record: both PKCS8 and SEC-1 specify (different) ways of representing
  89. # keys using ASN.1. Both are then typically formatted using PEM, which says: use the
  90. # base64-encoded DER encoding of ASN.1, with headers and footers. But we don't
  91. # really need to care about any of that.)
  92. return os.path.join(os.path.dirname(__file__), "oidc_test_key.p8")
  93. def _public_key_file_path() -> str:
  94. """path to a file containing the public half of a test key"""
  95. # this was generated with:
  96. # openssl ec -in oidc_test_key.p8 -pubout -out oidc_test_key.pub.pem
  97. #
  98. # See above about where oidc_test_key.p8 came from
  99. return os.path.join(os.path.dirname(__file__), "oidc_test_key.pub.pem")
  100. class OidcHandlerTestCase(HomeserverTestCase):
  101. if not HAS_OIDC:
  102. skip = "requires OIDC"
  103. def default_config(self) -> Dict[str, Any]:
  104. config = super().default_config()
  105. config["public_baseurl"] = BASE_URL
  106. return config
  107. def make_homeserver(self, reactor: MemoryReactor, clock: Clock) -> HomeServer:
  108. self.fake_server = FakeOidcServer(clock=clock, issuer=ISSUER)
  109. hs = self.setup_test_homeserver()
  110. self.hs_patcher = self.fake_server.patch_homeserver(hs=hs)
  111. self.hs_patcher.start()
  112. self.handler = hs.get_oidc_handler()
  113. self.provider = self.handler._providers["oidc"]
  114. sso_handler = hs.get_sso_handler()
  115. # Mock the render error method.
  116. self.render_error = Mock(return_value=None)
  117. sso_handler.render_error = self.render_error # type: ignore[assignment]
  118. # Reduce the number of attempts when generating MXIDs.
  119. sso_handler._MAP_USERNAME_RETRIES = 3
  120. auth_handler = hs.get_auth_handler()
  121. # Mock the complete SSO login method.
  122. self.complete_sso_login = simple_async_mock()
  123. auth_handler.complete_sso_login = self.complete_sso_login # type: ignore[assignment]
  124. return hs
  125. def tearDown(self) -> None:
  126. self.hs_patcher.stop()
  127. return super().tearDown()
  128. def reset_mocks(self):
  129. """Reset all the Mocks."""
  130. self.fake_server.reset_mocks()
  131. self.render_error.reset_mock()
  132. self.complete_sso_login.reset_mock()
  133. def metadata_edit(self, values):
  134. """Modify the result that will be returned by the well-known query"""
  135. metadata = self.fake_server.get_metadata()
  136. metadata.update(values)
  137. return patch.object(self.fake_server, "get_metadata", return_value=metadata)
  138. def start_authorization(
  139. self,
  140. userinfo: dict,
  141. client_redirect_url: str = "http://client/redirect",
  142. scope: str = "openid",
  143. with_sid: bool = False,
  144. ) -> Tuple[SynapseRequest, FakeAuthorizationGrant]:
  145. """Start an authorization request, and get the callback request back."""
  146. nonce = random_string(10)
  147. state = random_string(10)
  148. code, grant = self.fake_server.start_authorization(
  149. userinfo=userinfo,
  150. scope=scope,
  151. client_id=self.provider._client_auth.client_id,
  152. redirect_uri=self.provider._callback_url,
  153. nonce=nonce,
  154. with_sid=with_sid,
  155. )
  156. session = self._generate_oidc_session_token(state, nonce, client_redirect_url)
  157. return _build_callback_request(code, state, session), grant
  158. def assertRenderedError(self, error, error_description=None):
  159. self.render_error.assert_called_once()
  160. args = self.render_error.call_args[0]
  161. self.assertEqual(args[1], error)
  162. if error_description is not None:
  163. self.assertEqual(args[2], error_description)
  164. # Reset the render_error mock
  165. self.render_error.reset_mock()
  166. return args
  167. @override_config({"oidc_config": DEFAULT_CONFIG})
  168. def test_config(self) -> None:
  169. """Basic config correctly sets up the callback URL and client auth correctly."""
  170. self.assertEqual(self.provider._callback_url, CALLBACK_URL)
  171. self.assertEqual(self.provider._client_auth.client_id, CLIENT_ID)
  172. self.assertEqual(self.provider._client_auth.client_secret, CLIENT_SECRET)
  173. @override_config({"oidc_config": {**DEFAULT_CONFIG, "discover": True}})
  174. def test_discovery(self) -> None:
  175. """The handler should discover the endpoints from OIDC discovery document."""
  176. # This would throw if some metadata were invalid
  177. metadata = self.get_success(self.provider.load_metadata())
  178. self.fake_server.get_metadata_handler.assert_called_once()
  179. self.assertEqual(metadata.issuer, self.fake_server.issuer)
  180. self.assertEqual(
  181. metadata.authorization_endpoint,
  182. self.fake_server.authorization_endpoint,
  183. )
  184. self.assertEqual(metadata.token_endpoint, self.fake_server.token_endpoint)
  185. self.assertEqual(metadata.jwks_uri, self.fake_server.jwks_uri)
  186. # It seems like authlib does not have that defined in its metadata models
  187. self.assertEqual(
  188. metadata.get("userinfo_endpoint"),
  189. self.fake_server.userinfo_endpoint,
  190. )
  191. # subsequent calls should be cached
  192. self.reset_mocks()
  193. self.get_success(self.provider.load_metadata())
  194. self.fake_server.get_metadata_handler.assert_not_called()
  195. @override_config({"oidc_config": EXPLICIT_ENDPOINT_CONFIG})
  196. def test_no_discovery(self) -> None:
  197. """When discovery is disabled, it should not try to load from discovery document."""
  198. self.get_success(self.provider.load_metadata())
  199. self.fake_server.get_metadata_handler.assert_not_called()
  200. @override_config({"oidc_config": DEFAULT_CONFIG})
  201. def test_load_jwks(self) -> None:
  202. """JWKS loading is done once (then cached) if used."""
  203. jwks = self.get_success(self.provider.load_jwks())
  204. self.fake_server.get_jwks_handler.assert_called_once()
  205. self.assertEqual(jwks, self.fake_server.get_jwks())
  206. # subsequent calls should be cached…
  207. self.reset_mocks()
  208. self.get_success(self.provider.load_jwks())
  209. self.fake_server.get_jwks_handler.assert_not_called()
  210. # …unless forced
  211. self.reset_mocks()
  212. self.get_success(self.provider.load_jwks(force=True))
  213. self.fake_server.get_jwks_handler.assert_called_once()
  214. with self.metadata_edit({"jwks_uri": None}):
  215. # If we don't do this, the load_metadata call will throw because of the
  216. # missing jwks_uri
  217. self.provider._user_profile_method = "userinfo_endpoint"
  218. self.get_success(self.provider.load_metadata(force=True))
  219. self.get_failure(self.provider.load_jwks(force=True), RuntimeError)
  220. @override_config({"oidc_config": DEFAULT_CONFIG})
  221. def test_validate_config(self) -> None:
  222. """Provider metadatas are extensively validated."""
  223. h = self.provider
  224. def force_load_metadata():
  225. async def force_load():
  226. return await h.load_metadata(force=True)
  227. return get_awaitable_result(force_load())
  228. # Default test config does not throw
  229. force_load_metadata()
  230. with self.metadata_edit({"issuer": None}):
  231. self.assertRaisesRegex(ValueError, "issuer", force_load_metadata)
  232. with self.metadata_edit({"issuer": "http://insecure/"}):
  233. self.assertRaisesRegex(ValueError, "issuer", force_load_metadata)
  234. with self.metadata_edit({"issuer": "https://invalid/?because=query"}):
  235. self.assertRaisesRegex(ValueError, "issuer", force_load_metadata)
  236. with self.metadata_edit({"authorization_endpoint": None}):
  237. self.assertRaisesRegex(
  238. ValueError, "authorization_endpoint", force_load_metadata
  239. )
  240. with self.metadata_edit({"authorization_endpoint": "http://insecure/auth"}):
  241. self.assertRaisesRegex(
  242. ValueError, "authorization_endpoint", force_load_metadata
  243. )
  244. with self.metadata_edit({"token_endpoint": None}):
  245. self.assertRaisesRegex(ValueError, "token_endpoint", force_load_metadata)
  246. with self.metadata_edit({"token_endpoint": "http://insecure/token"}):
  247. self.assertRaisesRegex(ValueError, "token_endpoint", force_load_metadata)
  248. with self.metadata_edit({"jwks_uri": None}):
  249. self.assertRaisesRegex(ValueError, "jwks_uri", force_load_metadata)
  250. with self.metadata_edit({"jwks_uri": "http://insecure/jwks.json"}):
  251. self.assertRaisesRegex(ValueError, "jwks_uri", force_load_metadata)
  252. with self.metadata_edit({"response_types_supported": ["id_token"]}):
  253. self.assertRaisesRegex(
  254. ValueError, "response_types_supported", force_load_metadata
  255. )
  256. with self.metadata_edit(
  257. {"token_endpoint_auth_methods_supported": ["client_secret_basic"]}
  258. ):
  259. # should not throw, as client_secret_basic is the default auth method
  260. force_load_metadata()
  261. with self.metadata_edit(
  262. {"token_endpoint_auth_methods_supported": ["client_secret_post"]}
  263. ):
  264. self.assertRaisesRegex(
  265. ValueError,
  266. "token_endpoint_auth_methods_supported",
  267. force_load_metadata,
  268. )
  269. # Tests for configs that require the userinfo endpoint
  270. self.assertFalse(h._uses_userinfo)
  271. self.assertEqual(h._user_profile_method, "auto")
  272. h._user_profile_method = "userinfo_endpoint"
  273. self.assertTrue(h._uses_userinfo)
  274. # Revert the profile method and do not request the "openid" scope: this should
  275. # mean that we check for a userinfo endpoint
  276. h._user_profile_method = "auto"
  277. h._scopes = []
  278. self.assertTrue(h._uses_userinfo)
  279. with self.metadata_edit({"userinfo_endpoint": None}):
  280. self.assertRaisesRegex(ValueError, "userinfo_endpoint", force_load_metadata)
  281. with self.metadata_edit({"jwks_uri": None}):
  282. # Shouldn't raise with a valid userinfo, even without jwks
  283. force_load_metadata()
  284. @override_config({"oidc_config": {**DEFAULT_CONFIG, "skip_verification": True}})
  285. def test_skip_verification(self) -> None:
  286. """Provider metadata validation can be disabled by config."""
  287. with self.metadata_edit({"issuer": "http://insecure"}):
  288. # This should not throw
  289. get_awaitable_result(self.provider.load_metadata())
  290. @override_config({"oidc_config": DEFAULT_CONFIG})
  291. def test_redirect_request(self) -> None:
  292. """The redirect request has the right arguments & generates a valid session cookie."""
  293. req = Mock(spec=["cookies"])
  294. req.cookies = []
  295. url = urlparse(
  296. self.get_success(
  297. self.provider.handle_redirect_request(req, b"http://client/redirect")
  298. )
  299. )
  300. auth_endpoint = urlparse(self.fake_server.authorization_endpoint)
  301. self.assertEqual(url.scheme, auth_endpoint.scheme)
  302. self.assertEqual(url.netloc, auth_endpoint.netloc)
  303. self.assertEqual(url.path, auth_endpoint.path)
  304. params = parse_qs(url.query)
  305. self.assertEqual(params["redirect_uri"], [CALLBACK_URL])
  306. self.assertEqual(params["response_type"], ["code"])
  307. self.assertEqual(params["scope"], [" ".join(SCOPES)])
  308. self.assertEqual(params["client_id"], [CLIENT_ID])
  309. self.assertEqual(len(params["state"]), 1)
  310. self.assertEqual(len(params["nonce"]), 1)
  311. # Check what is in the cookies
  312. self.assertEqual(len(req.cookies), 2) # two cookies
  313. cookie_header = req.cookies[0]
  314. # The cookie name and path don't really matter, just that it has to be coherent
  315. # between the callback & redirect handlers.
  316. parts = [p.strip() for p in cookie_header.split(b";")]
  317. self.assertIn(b"Path=/_synapse/client/oidc", parts)
  318. name, cookie = parts[0].split(b"=")
  319. self.assertEqual(name, b"oidc_session")
  320. macaroon = pymacaroons.Macaroon.deserialize(cookie)
  321. state = get_value_from_macaroon(macaroon, "state")
  322. nonce = get_value_from_macaroon(macaroon, "nonce")
  323. redirect = get_value_from_macaroon(macaroon, "client_redirect_url")
  324. self.assertEqual(params["state"], [state])
  325. self.assertEqual(params["nonce"], [nonce])
  326. self.assertEqual(redirect, "http://client/redirect")
  327. @override_config({"oidc_config": DEFAULT_CONFIG})
  328. def test_callback_error(self) -> None:
  329. """Errors from the provider returned in the callback are displayed."""
  330. request = Mock(args={})
  331. request.args[b"error"] = [b"invalid_client"]
  332. self.get_success(self.handler.handle_oidc_callback(request))
  333. self.assertRenderedError("invalid_client", "")
  334. request.args[b"error_description"] = [b"some description"]
  335. self.get_success(self.handler.handle_oidc_callback(request))
  336. self.assertRenderedError("invalid_client", "some description")
  337. @override_config({"oidc_config": DEFAULT_CONFIG})
  338. def test_callback(self) -> None:
  339. """Code callback works and display errors if something went wrong.
  340. A lot of scenarios are tested here:
  341. - when the callback works, with userinfo from ID token
  342. - when the user mapping fails
  343. - when ID token verification fails
  344. - when the callback works, with userinfo fetched from the userinfo endpoint
  345. - when the userinfo fetching fails
  346. - when the code exchange fails
  347. """
  348. # ensure that we are correctly testing the fallback when "get_extra_attributes"
  349. # is not implemented.
  350. mapping_provider = self.provider._user_mapping_provider
  351. with self.assertRaises(AttributeError):
  352. _ = mapping_provider.get_extra_attributes
  353. username = "bar"
  354. userinfo = {
  355. "sub": "foo",
  356. "username": username,
  357. }
  358. expected_user_id = "@%s:%s" % (username, self.hs.hostname)
  359. client_redirect_url = "http://client/redirect"
  360. request, _ = self.start_authorization(
  361. userinfo, client_redirect_url=client_redirect_url
  362. )
  363. self.get_success(self.handler.handle_oidc_callback(request))
  364. self.complete_sso_login.assert_called_once_with(
  365. expected_user_id,
  366. self.provider.idp_id,
  367. request,
  368. client_redirect_url,
  369. None,
  370. new_user=True,
  371. auth_provider_session_id=None,
  372. )
  373. self.fake_server.post_token_handler.assert_called_once()
  374. self.fake_server.get_userinfo_handler.assert_not_called()
  375. self.render_error.assert_not_called()
  376. # Handle mapping errors
  377. request, _ = self.start_authorization(userinfo)
  378. with patch.object(
  379. self.provider,
  380. "_remote_id_from_userinfo",
  381. new=Mock(side_effect=MappingException()),
  382. ):
  383. self.get_success(self.handler.handle_oidc_callback(request))
  384. self.assertRenderedError("mapping_error")
  385. # Handle ID token errors
  386. request, _ = self.start_authorization(userinfo)
  387. with self.fake_server.id_token_override({"iss": "https://bad.issuer/"}):
  388. self.get_success(self.handler.handle_oidc_callback(request))
  389. self.assertRenderedError("invalid_token")
  390. self.reset_mocks()
  391. # With userinfo fetching
  392. self.provider._user_profile_method = "userinfo_endpoint"
  393. # Without the "openid" scope, the FakeProvider does not generate an id_token
  394. request, _ = self.start_authorization(userinfo, scope="")
  395. self.get_success(self.handler.handle_oidc_callback(request))
  396. self.complete_sso_login.assert_called_once_with(
  397. expected_user_id,
  398. self.provider.idp_id,
  399. request,
  400. ANY,
  401. None,
  402. new_user=False,
  403. auth_provider_session_id=None,
  404. )
  405. self.fake_server.post_token_handler.assert_called_once()
  406. self.fake_server.get_userinfo_handler.assert_called_once()
  407. self.render_error.assert_not_called()
  408. self.reset_mocks()
  409. # With an ID token, userinfo fetching and sid in the ID token
  410. self.provider._user_profile_method = "userinfo_endpoint"
  411. request, grant = self.start_authorization(userinfo, with_sid=True)
  412. self.assertIsNotNone(grant.sid)
  413. self.get_success(self.handler.handle_oidc_callback(request))
  414. self.complete_sso_login.assert_called_once_with(
  415. expected_user_id,
  416. self.provider.idp_id,
  417. request,
  418. ANY,
  419. None,
  420. new_user=False,
  421. auth_provider_session_id=grant.sid,
  422. )
  423. self.fake_server.post_token_handler.assert_called_once()
  424. self.fake_server.get_userinfo_handler.assert_called_once()
  425. self.render_error.assert_not_called()
  426. # Handle userinfo fetching error
  427. request, _ = self.start_authorization(userinfo)
  428. with self.fake_server.buggy_endpoint(userinfo=True):
  429. self.get_success(self.handler.handle_oidc_callback(request))
  430. self.assertRenderedError("fetch_error")
  431. request, _ = self.start_authorization(userinfo)
  432. with self.fake_server.buggy_endpoint(token=True):
  433. self.get_success(self.handler.handle_oidc_callback(request))
  434. self.assertRenderedError("server_error")
  435. @override_config({"oidc_config": DEFAULT_CONFIG})
  436. def test_callback_session(self) -> None:
  437. """The callback verifies the session presence and validity"""
  438. request = Mock(spec=["args", "getCookie", "cookies"])
  439. # Missing cookie
  440. request.args = {}
  441. request.getCookie.return_value = None
  442. self.get_success(self.handler.handle_oidc_callback(request))
  443. self.assertRenderedError("missing_session", "No session cookie found")
  444. # Missing session parameter
  445. request.args = {}
  446. request.getCookie.return_value = "session"
  447. self.get_success(self.handler.handle_oidc_callback(request))
  448. self.assertRenderedError("invalid_request", "State parameter is missing")
  449. # Invalid cookie
  450. request.args = {}
  451. request.args[b"state"] = [b"state"]
  452. request.getCookie.return_value = "session"
  453. self.get_success(self.handler.handle_oidc_callback(request))
  454. self.assertRenderedError("invalid_session")
  455. # Mismatching session
  456. session = self._generate_oidc_session_token(
  457. state="state",
  458. nonce="nonce",
  459. client_redirect_url="http://client/redirect",
  460. )
  461. request.args = {}
  462. request.args[b"state"] = [b"mismatching state"]
  463. request.getCookie.return_value = session
  464. self.get_success(self.handler.handle_oidc_callback(request))
  465. self.assertRenderedError("mismatching_session")
  466. # Valid session
  467. request.args = {}
  468. request.args[b"state"] = [b"state"]
  469. request.getCookie.return_value = session
  470. self.get_success(self.handler.handle_oidc_callback(request))
  471. self.assertRenderedError("invalid_request")
  472. @override_config(
  473. {"oidc_config": {**DEFAULT_CONFIG, "client_auth_method": "client_secret_post"}}
  474. )
  475. def test_exchange_code(self) -> None:
  476. """Code exchange behaves correctly and handles various error scenarios."""
  477. token = {
  478. "type": "Bearer",
  479. "access_token": "aabbcc",
  480. }
  481. self.fake_server.post_token_handler.side_effect = None
  482. self.fake_server.post_token_handler.return_value = FakeResponse.json(
  483. payload=token
  484. )
  485. code = "code"
  486. ret = self.get_success(self.provider._exchange_code(code))
  487. kwargs = self.fake_server.request.call_args[1]
  488. self.assertEqual(ret, token)
  489. self.assertEqual(kwargs["method"], "POST")
  490. self.assertEqual(kwargs["uri"], self.fake_server.token_endpoint)
  491. args = parse_qs(kwargs["data"].decode("utf-8"))
  492. self.assertEqual(args["grant_type"], ["authorization_code"])
  493. self.assertEqual(args["code"], [code])
  494. self.assertEqual(args["client_id"], [CLIENT_ID])
  495. self.assertEqual(args["client_secret"], [CLIENT_SECRET])
  496. self.assertEqual(args["redirect_uri"], [CALLBACK_URL])
  497. # Test error handling
  498. self.fake_server.post_token_handler.return_value = FakeResponse.json(
  499. code=400, payload={"error": "foo", "error_description": "bar"}
  500. )
  501. from synapse.handlers.oidc import OidcError
  502. exc = self.get_failure(self.provider._exchange_code(code), OidcError)
  503. self.assertEqual(exc.value.error, "foo")
  504. self.assertEqual(exc.value.error_description, "bar")
  505. # Internal server error with no JSON body
  506. self.fake_server.post_token_handler.return_value = FakeResponse(
  507. code=500, body=b"Not JSON"
  508. )
  509. exc = self.get_failure(self.provider._exchange_code(code), OidcError)
  510. self.assertEqual(exc.value.error, "server_error")
  511. # Internal server error with JSON body
  512. self.fake_server.post_token_handler.return_value = FakeResponse.json(
  513. code=500, payload={"error": "internal_server_error"}
  514. )
  515. exc = self.get_failure(self.provider._exchange_code(code), OidcError)
  516. self.assertEqual(exc.value.error, "internal_server_error")
  517. # 4xx error without "error" field
  518. self.fake_server.post_token_handler.return_value = FakeResponse.json(
  519. code=400, payload={}
  520. )
  521. exc = self.get_failure(self.provider._exchange_code(code), OidcError)
  522. self.assertEqual(exc.value.error, "server_error")
  523. # 2xx error with "error" field
  524. self.fake_server.post_token_handler.return_value = FakeResponse.json(
  525. code=200, payload={"error": "some_error"}
  526. )
  527. exc = self.get_failure(self.provider._exchange_code(code), OidcError)
  528. self.assertEqual(exc.value.error, "some_error")
  529. @override_config(
  530. {
  531. "oidc_config": {
  532. "enabled": True,
  533. "client_id": CLIENT_ID,
  534. "issuer": ISSUER,
  535. "client_auth_method": "client_secret_post",
  536. "client_secret_jwt_key": {
  537. "key_file": _key_file_path(),
  538. "jwt_header": {"alg": "ES256", "kid": "ABC789"},
  539. "jwt_payload": {"iss": "DEFGHI"},
  540. },
  541. }
  542. }
  543. )
  544. def test_exchange_code_jwt_key(self) -> None:
  545. """Test that code exchange works with a JWK client secret."""
  546. from authlib.jose import jwt
  547. token = {
  548. "type": "Bearer",
  549. "access_token": "aabbcc",
  550. }
  551. self.fake_server.post_token_handler.side_effect = None
  552. self.fake_server.post_token_handler.return_value = FakeResponse.json(
  553. payload=token
  554. )
  555. code = "code"
  556. # advance the clock a bit before we start, so we aren't working with zero
  557. # timestamps.
  558. self.reactor.advance(1000)
  559. start_time = self.reactor.seconds()
  560. ret = self.get_success(self.provider._exchange_code(code))
  561. self.assertEqual(ret, token)
  562. # the request should have hit the token endpoint
  563. kwargs = self.fake_server.request.call_args[1]
  564. self.assertEqual(kwargs["method"], "POST")
  565. self.assertEqual(kwargs["uri"], self.fake_server.token_endpoint)
  566. # the client secret provided to the should be a jwt which can be checked with
  567. # the public key
  568. args = parse_qs(kwargs["data"].decode("utf-8"))
  569. secret = args["client_secret"][0]
  570. with open(_public_key_file_path()) as f:
  571. key = f.read()
  572. claims = jwt.decode(secret, key)
  573. self.assertEqual(claims.header["kid"], "ABC789")
  574. self.assertEqual(claims["aud"], ISSUER)
  575. self.assertEqual(claims["iss"], "DEFGHI")
  576. self.assertEqual(claims["sub"], CLIENT_ID)
  577. self.assertEqual(claims["iat"], start_time)
  578. self.assertGreater(claims["exp"], start_time)
  579. # check the rest of the POSTed data
  580. self.assertEqual(args["grant_type"], ["authorization_code"])
  581. self.assertEqual(args["code"], [code])
  582. self.assertEqual(args["client_id"], [CLIENT_ID])
  583. self.assertEqual(args["redirect_uri"], [CALLBACK_URL])
  584. @override_config(
  585. {
  586. "oidc_config": {
  587. "enabled": True,
  588. "client_id": CLIENT_ID,
  589. "issuer": ISSUER,
  590. "client_auth_method": "none",
  591. }
  592. }
  593. )
  594. def test_exchange_code_no_auth(self) -> None:
  595. """Test that code exchange works with no client secret."""
  596. token = {
  597. "type": "Bearer",
  598. "access_token": "aabbcc",
  599. }
  600. self.fake_server.post_token_handler.side_effect = None
  601. self.fake_server.post_token_handler.return_value = FakeResponse.json(
  602. payload=token
  603. )
  604. code = "code"
  605. ret = self.get_success(self.provider._exchange_code(code))
  606. self.assertEqual(ret, token)
  607. # the request should have hit the token endpoint
  608. kwargs = self.fake_server.request.call_args[1]
  609. self.assertEqual(kwargs["method"], "POST")
  610. self.assertEqual(kwargs["uri"], self.fake_server.token_endpoint)
  611. # check the POSTed data
  612. args = parse_qs(kwargs["data"].decode("utf-8"))
  613. self.assertEqual(args["grant_type"], ["authorization_code"])
  614. self.assertEqual(args["code"], [code])
  615. self.assertEqual(args["client_id"], [CLIENT_ID])
  616. self.assertEqual(args["redirect_uri"], [CALLBACK_URL])
  617. @override_config(
  618. {
  619. "oidc_config": {
  620. **DEFAULT_CONFIG,
  621. "user_mapping_provider": {
  622. "module": __name__ + ".TestMappingProviderExtra"
  623. },
  624. }
  625. }
  626. )
  627. def test_extra_attributes(self) -> None:
  628. """
  629. Login while using a mapping provider that implements get_extra_attributes.
  630. """
  631. userinfo = {
  632. "sub": "foo",
  633. "username": "foo",
  634. "phone": "1234567",
  635. }
  636. request, _ = self.start_authorization(userinfo)
  637. self.get_success(self.handler.handle_oidc_callback(request))
  638. self.complete_sso_login.assert_called_once_with(
  639. "@foo:test",
  640. self.provider.idp_id,
  641. request,
  642. ANY,
  643. {"phone": "1234567"},
  644. new_user=True,
  645. auth_provider_session_id=None,
  646. )
  647. @override_config({"oidc_config": DEFAULT_CONFIG})
  648. def test_map_userinfo_to_user(self) -> None:
  649. """Ensure that mapping the userinfo returned from a provider to an MXID works properly."""
  650. userinfo: dict = {
  651. "sub": "test_user",
  652. "username": "test_user",
  653. }
  654. request, _ = self.start_authorization(userinfo)
  655. self.get_success(self.handler.handle_oidc_callback(request))
  656. self.complete_sso_login.assert_called_once_with(
  657. "@test_user:test",
  658. self.provider.idp_id,
  659. request,
  660. ANY,
  661. None,
  662. new_user=True,
  663. auth_provider_session_id=None,
  664. )
  665. self.reset_mocks()
  666. # Some providers return an integer ID.
  667. userinfo = {
  668. "sub": 1234,
  669. "username": "test_user_2",
  670. }
  671. request, _ = self.start_authorization(userinfo)
  672. self.get_success(self.handler.handle_oidc_callback(request))
  673. self.complete_sso_login.assert_called_once_with(
  674. "@test_user_2:test",
  675. self.provider.idp_id,
  676. request,
  677. ANY,
  678. None,
  679. new_user=True,
  680. auth_provider_session_id=None,
  681. )
  682. self.reset_mocks()
  683. # Test if the mxid is already taken
  684. store = self.hs.get_datastores().main
  685. user3 = UserID.from_string("@test_user_3:test")
  686. self.get_success(
  687. store.register_user(user_id=user3.to_string(), password_hash=None)
  688. )
  689. userinfo = {"sub": "test3", "username": "test_user_3"}
  690. request, _ = self.start_authorization(userinfo)
  691. self.get_success(self.handler.handle_oidc_callback(request))
  692. self.complete_sso_login.assert_not_called()
  693. self.assertRenderedError(
  694. "mapping_error",
  695. "Mapping provider does not support de-duplicating Matrix IDs",
  696. )
  697. @override_config({"oidc_config": {**DEFAULT_CONFIG, "allow_existing_users": True}})
  698. def test_map_userinfo_to_existing_user(self) -> None:
  699. """Existing users can log in with OpenID Connect when allow_existing_users is True."""
  700. store = self.hs.get_datastores().main
  701. user = UserID.from_string("@test_user:test")
  702. self.get_success(
  703. store.register_user(user_id=user.to_string(), password_hash=None)
  704. )
  705. # Map a user via SSO.
  706. userinfo = {
  707. "sub": "test",
  708. "username": "test_user",
  709. }
  710. request, _ = self.start_authorization(userinfo)
  711. self.get_success(self.handler.handle_oidc_callback(request))
  712. self.complete_sso_login.assert_called_once_with(
  713. user.to_string(),
  714. self.provider.idp_id,
  715. request,
  716. ANY,
  717. None,
  718. new_user=False,
  719. auth_provider_session_id=None,
  720. )
  721. self.reset_mocks()
  722. # Subsequent calls should map to the same mxid.
  723. request, _ = self.start_authorization(userinfo)
  724. self.get_success(self.handler.handle_oidc_callback(request))
  725. self.complete_sso_login.assert_called_once_with(
  726. user.to_string(),
  727. self.provider.idp_id,
  728. request,
  729. ANY,
  730. None,
  731. new_user=False,
  732. auth_provider_session_id=None,
  733. )
  734. self.reset_mocks()
  735. # Note that a second SSO user can be mapped to the same Matrix ID. (This
  736. # requires a unique sub, but something that maps to the same matrix ID,
  737. # in this case we'll just use the same username. A more realistic example
  738. # would be subs which are email addresses, and mapping from the localpart
  739. # of the email, e.g. bob@foo.com and bob@bar.com -> @bob:test.)
  740. userinfo = {
  741. "sub": "test1",
  742. "username": "test_user",
  743. }
  744. request, _ = self.start_authorization(userinfo)
  745. self.get_success(self.handler.handle_oidc_callback(request))
  746. self.complete_sso_login.assert_called_once_with(
  747. user.to_string(),
  748. self.provider.idp_id,
  749. request,
  750. ANY,
  751. None,
  752. new_user=False,
  753. auth_provider_session_id=None,
  754. )
  755. self.reset_mocks()
  756. # Register some non-exact matching cases.
  757. user2 = UserID.from_string("@TEST_user_2:test")
  758. self.get_success(
  759. store.register_user(user_id=user2.to_string(), password_hash=None)
  760. )
  761. user2_caps = UserID.from_string("@test_USER_2:test")
  762. self.get_success(
  763. store.register_user(user_id=user2_caps.to_string(), password_hash=None)
  764. )
  765. # Attempting to login without matching a name exactly is an error.
  766. userinfo = {
  767. "sub": "test2",
  768. "username": "TEST_USER_2",
  769. }
  770. request, _ = self.start_authorization(userinfo)
  771. self.get_success(self.handler.handle_oidc_callback(request))
  772. self.complete_sso_login.assert_not_called()
  773. args = self.assertRenderedError("mapping_error")
  774. self.assertTrue(
  775. args[2].startswith(
  776. "Attempted to login as '@TEST_USER_2:test' but it matches more than one user inexactly:"
  777. )
  778. )
  779. # Logging in when matching a name exactly should work.
  780. user2 = UserID.from_string("@TEST_USER_2:test")
  781. self.get_success(
  782. store.register_user(user_id=user2.to_string(), password_hash=None)
  783. )
  784. request, _ = self.start_authorization(userinfo)
  785. self.get_success(self.handler.handle_oidc_callback(request))
  786. self.complete_sso_login.assert_called_once_with(
  787. "@TEST_USER_2:test",
  788. self.provider.idp_id,
  789. request,
  790. ANY,
  791. None,
  792. new_user=False,
  793. auth_provider_session_id=None,
  794. )
  795. @override_config({"oidc_config": DEFAULT_CONFIG})
  796. def test_map_userinfo_to_invalid_localpart(self) -> None:
  797. """If the mapping provider generates an invalid localpart it should be rejected."""
  798. userinfo = {"sub": "test2", "username": "föö"}
  799. request, _ = self.start_authorization(userinfo)
  800. self.get_success(self.handler.handle_oidc_callback(request))
  801. self.assertRenderedError("mapping_error", "localpart is invalid: föö")
  802. @override_config(
  803. {
  804. "oidc_config": {
  805. **DEFAULT_CONFIG,
  806. "user_mapping_provider": {
  807. "module": __name__ + ".TestMappingProviderFailures"
  808. },
  809. }
  810. }
  811. )
  812. def test_map_userinfo_to_user_retries(self) -> None:
  813. """The mapping provider can retry generating an MXID if the MXID is already in use."""
  814. store = self.hs.get_datastores().main
  815. self.get_success(
  816. store.register_user(user_id="@test_user:test", password_hash=None)
  817. )
  818. userinfo = {
  819. "sub": "test",
  820. "username": "test_user",
  821. }
  822. request, _ = self.start_authorization(userinfo)
  823. self.get_success(self.handler.handle_oidc_callback(request))
  824. # test_user is already taken, so test_user1 gets registered instead.
  825. self.complete_sso_login.assert_called_once_with(
  826. "@test_user1:test",
  827. self.provider.idp_id,
  828. request,
  829. ANY,
  830. None,
  831. new_user=True,
  832. auth_provider_session_id=None,
  833. )
  834. self.reset_mocks()
  835. # Register all of the potential mxids for a particular OIDC username.
  836. self.get_success(
  837. store.register_user(user_id="@tester:test", password_hash=None)
  838. )
  839. for i in range(1, 3):
  840. self.get_success(
  841. store.register_user(user_id="@tester%d:test" % i, password_hash=None)
  842. )
  843. # Now attempt to map to a username, this will fail since all potential usernames are taken.
  844. userinfo = {
  845. "sub": "tester",
  846. "username": "tester",
  847. }
  848. request, _ = self.start_authorization(userinfo)
  849. self.get_success(self.handler.handle_oidc_callback(request))
  850. self.complete_sso_login.assert_not_called()
  851. self.assertRenderedError(
  852. "mapping_error", "Unable to generate a Matrix ID from the SSO response"
  853. )
  854. @override_config({"oidc_config": DEFAULT_CONFIG})
  855. def test_empty_localpart(self) -> None:
  856. """Attempts to map onto an empty localpart should be rejected."""
  857. userinfo = {
  858. "sub": "tester",
  859. "username": "",
  860. }
  861. request, _ = self.start_authorization(userinfo)
  862. self.get_success(self.handler.handle_oidc_callback(request))
  863. self.assertRenderedError("mapping_error", "localpart is invalid: ")
  864. @override_config(
  865. {
  866. "oidc_config": {
  867. **DEFAULT_CONFIG,
  868. "user_mapping_provider": {
  869. "config": {"localpart_template": "{{ user.username }}"}
  870. },
  871. }
  872. }
  873. )
  874. def test_null_localpart(self) -> None:
  875. """Mapping onto a null localpart via an empty OIDC attribute should be rejected"""
  876. userinfo = {
  877. "sub": "tester",
  878. "username": None,
  879. }
  880. request, _ = self.start_authorization(userinfo)
  881. self.get_success(self.handler.handle_oidc_callback(request))
  882. self.assertRenderedError("mapping_error", "localpart is invalid: ")
  883. @override_config(
  884. {
  885. "oidc_config": {
  886. **DEFAULT_CONFIG,
  887. "attribute_requirements": [{"attribute": "test", "value": "foobar"}],
  888. }
  889. }
  890. )
  891. def test_attribute_requirements(self) -> None:
  892. """The required attributes must be met from the OIDC userinfo response."""
  893. # userinfo lacking "test": "foobar" attribute should fail.
  894. userinfo = {
  895. "sub": "tester",
  896. "username": "tester",
  897. }
  898. request, _ = self.start_authorization(userinfo)
  899. self.get_success(self.handler.handle_oidc_callback(request))
  900. self.complete_sso_login.assert_not_called()
  901. # userinfo with "test": "foobar" attribute should succeed.
  902. userinfo = {
  903. "sub": "tester",
  904. "username": "tester",
  905. "test": "foobar",
  906. }
  907. request, _ = self.start_authorization(userinfo)
  908. self.get_success(self.handler.handle_oidc_callback(request))
  909. # check that the auth handler got called as expected
  910. self.complete_sso_login.assert_called_once_with(
  911. "@tester:test",
  912. self.provider.idp_id,
  913. request,
  914. ANY,
  915. None,
  916. new_user=True,
  917. auth_provider_session_id=None,
  918. )
  919. @override_config(
  920. {
  921. "oidc_config": {
  922. **DEFAULT_CONFIG,
  923. "attribute_requirements": [{"attribute": "test", "value": "foobar"}],
  924. }
  925. }
  926. )
  927. def test_attribute_requirements_contains(self) -> None:
  928. """Test that auth succeeds if userinfo attribute CONTAINS required value"""
  929. # userinfo with "test": ["foobar", "foo", "bar"] attribute should succeed.
  930. userinfo = {
  931. "sub": "tester",
  932. "username": "tester",
  933. "test": ["foobar", "foo", "bar"],
  934. }
  935. request, _ = self.start_authorization(userinfo)
  936. self.get_success(self.handler.handle_oidc_callback(request))
  937. # check that the auth handler got called as expected
  938. self.complete_sso_login.assert_called_once_with(
  939. "@tester:test",
  940. self.provider.idp_id,
  941. request,
  942. ANY,
  943. None,
  944. new_user=True,
  945. auth_provider_session_id=None,
  946. )
  947. @override_config(
  948. {
  949. "oidc_config": {
  950. **DEFAULT_CONFIG,
  951. "attribute_requirements": [{"attribute": "test", "value": "foobar"}],
  952. }
  953. }
  954. )
  955. def test_attribute_requirements_mismatch(self) -> None:
  956. """
  957. Test that auth fails if attributes exist but don't match,
  958. or are non-string values.
  959. """
  960. # userinfo with "test": "not_foobar" attribute should fail
  961. userinfo: dict = {
  962. "sub": "tester",
  963. "username": "tester",
  964. "test": "not_foobar",
  965. }
  966. request, _ = self.start_authorization(userinfo)
  967. self.get_success(self.handler.handle_oidc_callback(request))
  968. self.complete_sso_login.assert_not_called()
  969. # userinfo with "test": ["foo", "bar"] attribute should fail
  970. userinfo = {
  971. "sub": "tester",
  972. "username": "tester",
  973. "test": ["foo", "bar"],
  974. }
  975. request, _ = self.start_authorization(userinfo)
  976. self.get_success(self.handler.handle_oidc_callback(request))
  977. self.complete_sso_login.assert_not_called()
  978. # userinfo with "test": False attribute should fail
  979. # this is largely just to ensure we don't crash here
  980. userinfo = {
  981. "sub": "tester",
  982. "username": "tester",
  983. "test": False,
  984. }
  985. request, _ = self.start_authorization(userinfo)
  986. self.get_success(self.handler.handle_oidc_callback(request))
  987. self.complete_sso_login.assert_not_called()
  988. # userinfo with "test": None attribute should fail
  989. # a value of None breaks the OIDC spec, but it's important to not crash here
  990. userinfo = {
  991. "sub": "tester",
  992. "username": "tester",
  993. "test": None,
  994. }
  995. request, _ = self.start_authorization(userinfo)
  996. self.get_success(self.handler.handle_oidc_callback(request))
  997. self.complete_sso_login.assert_not_called()
  998. # userinfo with "test": 1 attribute should fail
  999. # this is largely just to ensure we don't crash here
  1000. userinfo = {
  1001. "sub": "tester",
  1002. "username": "tester",
  1003. "test": 1,
  1004. }
  1005. request, _ = self.start_authorization(userinfo)
  1006. self.get_success(self.handler.handle_oidc_callback(request))
  1007. self.complete_sso_login.assert_not_called()
  1008. # userinfo with "test": 3.14 attribute should fail
  1009. # this is largely just to ensure we don't crash here
  1010. userinfo = {
  1011. "sub": "tester",
  1012. "username": "tester",
  1013. "test": 3.14,
  1014. }
  1015. request, _ = self.start_authorization(userinfo)
  1016. self.get_success(self.handler.handle_oidc_callback(request))
  1017. self.complete_sso_login.assert_not_called()
  1018. def _generate_oidc_session_token(
  1019. self,
  1020. state: str,
  1021. nonce: str,
  1022. client_redirect_url: str,
  1023. ui_auth_session_id: str = "",
  1024. ) -> str:
  1025. from synapse.handlers.oidc import OidcSessionData
  1026. return self.handler._macaroon_generator.generate_oidc_session_token(
  1027. state=state,
  1028. session_data=OidcSessionData(
  1029. idp_id=self.provider.idp_id,
  1030. nonce=nonce,
  1031. client_redirect_url=client_redirect_url,
  1032. ui_auth_session_id=ui_auth_session_id,
  1033. ),
  1034. )
  1035. def _build_callback_request(
  1036. code: str,
  1037. state: str,
  1038. session: str,
  1039. ip_address: str = "10.0.0.1",
  1040. ):
  1041. """Builds a fake SynapseRequest to mock the browser callback
  1042. Returns a Mock object which looks like the SynapseRequest we get from a browser
  1043. after SSO (before we return to the client)
  1044. Args:
  1045. code: the authorization code which would have been returned by the OIDC
  1046. provider
  1047. state: the "state" param which would have been passed around in the
  1048. query param. Should be the same as was embedded in the session in
  1049. _build_oidc_session.
  1050. session: the "session" which would have been passed around in the cookie.
  1051. ip_address: the IP address to pretend the request came from
  1052. """
  1053. request = Mock(
  1054. spec=[
  1055. "args",
  1056. "getCookie",
  1057. "cookies",
  1058. "requestHeaders",
  1059. "getClientAddress",
  1060. "getHeader",
  1061. ]
  1062. )
  1063. request.cookies = []
  1064. request.getCookie.return_value = session
  1065. request.args = {}
  1066. request.args[b"code"] = [code.encode("utf-8")]
  1067. request.args[b"state"] = [state.encode("utf-8")]
  1068. request.getClientAddress.return_value.host = ip_address
  1069. return request