test_remote_user.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. from datetime import datetime, timezone
  2. from django.conf import settings
  3. from django.contrib.auth import aauthenticate, authenticate
  4. from django.contrib.auth.backends import RemoteUserBackend
  5. from django.contrib.auth.middleware import RemoteUserMiddleware
  6. from django.contrib.auth.models import User
  7. from django.middleware.csrf import _get_new_csrf_string, _mask_cipher_secret
  8. from django.test import (
  9. AsyncClient,
  10. Client,
  11. TestCase,
  12. modify_settings,
  13. override_settings,
  14. )
  15. @override_settings(ROOT_URLCONF="auth_tests.urls")
  16. class RemoteUserTest(TestCase):
  17. middleware = "django.contrib.auth.middleware.RemoteUserMiddleware"
  18. backend = "django.contrib.auth.backends.RemoteUserBackend"
  19. header = "REMOTE_USER"
  20. email_header = "REMOTE_EMAIL"
  21. # Usernames to be passed in REMOTE_USER for the test_known_user test case.
  22. known_user = "knownuser"
  23. known_user2 = "knownuser2"
  24. @classmethod
  25. def setUpClass(cls):
  26. cls.enterClassContext(
  27. modify_settings(
  28. AUTHENTICATION_BACKENDS={"append": cls.backend},
  29. MIDDLEWARE={"append": cls.middleware},
  30. )
  31. )
  32. super().setUpClass()
  33. def test_passing_explicit_none(self):
  34. msg = "get_response must be provided."
  35. with self.assertRaisesMessage(ValueError, msg):
  36. RemoteUserMiddleware(None)
  37. def test_no_remote_user(self):
  38. """Users are not created when remote user is not specified."""
  39. num_users = User.objects.count()
  40. response = self.client.get("/remote_user/")
  41. self.assertTrue(response.context["user"].is_anonymous)
  42. self.assertEqual(User.objects.count(), num_users)
  43. response = self.client.get("/remote_user/", **{self.header: None})
  44. self.assertTrue(response.context["user"].is_anonymous)
  45. self.assertEqual(User.objects.count(), num_users)
  46. response = self.client.get("/remote_user/", **{self.header: ""})
  47. self.assertTrue(response.context["user"].is_anonymous)
  48. self.assertEqual(User.objects.count(), num_users)
  49. async def test_no_remote_user_async(self):
  50. """See test_no_remote_user."""
  51. num_users = await User.objects.acount()
  52. response = await self.async_client.get("/remote_user/")
  53. self.assertTrue(response.context["user"].is_anonymous)
  54. self.assertEqual(await User.objects.acount(), num_users)
  55. response = await self.async_client.get("/remote_user/", **{self.header: ""})
  56. self.assertTrue(response.context["user"].is_anonymous)
  57. self.assertEqual(await User.objects.acount(), num_users)
  58. def test_csrf_validation_passes_after_process_request_login(self):
  59. """
  60. CSRF check must access the CSRF token from the session or cookie,
  61. rather than the request, as rotate_token() may have been called by an
  62. authentication middleware during the process_request() phase.
  63. """
  64. csrf_client = Client(enforce_csrf_checks=True)
  65. csrf_secret = _get_new_csrf_string()
  66. csrf_token = _mask_cipher_secret(csrf_secret)
  67. csrf_token_form = _mask_cipher_secret(csrf_secret)
  68. headers = {self.header: "fakeuser"}
  69. data = {"csrfmiddlewaretoken": csrf_token_form}
  70. # Verify that CSRF is configured for the view
  71. csrf_client.cookies.load({settings.CSRF_COOKIE_NAME: csrf_token})
  72. response = csrf_client.post("/remote_user/", **headers)
  73. self.assertEqual(response.status_code, 403)
  74. self.assertIn(b"CSRF verification failed.", response.content)
  75. # This request will call django.contrib.auth.login() which will call
  76. # django.middleware.csrf.rotate_token() thus changing the value of
  77. # request.META['CSRF_COOKIE'] from the user submitted value set by
  78. # CsrfViewMiddleware.process_request() to the new csrftoken value set
  79. # by rotate_token(). Csrf validation should still pass when the view is
  80. # later processed by CsrfViewMiddleware.process_view()
  81. csrf_client.cookies.load({settings.CSRF_COOKIE_NAME: csrf_token})
  82. response = csrf_client.post("/remote_user/", data, **headers)
  83. self.assertEqual(response.status_code, 200)
  84. async def test_csrf_validation_passes_after_process_request_login_async(self):
  85. """See test_csrf_validation_passes_after_process_request_login."""
  86. csrf_client = AsyncClient(enforce_csrf_checks=True)
  87. csrf_secret = _get_new_csrf_string()
  88. csrf_token = _mask_cipher_secret(csrf_secret)
  89. csrf_token_form = _mask_cipher_secret(csrf_secret)
  90. headers = {self.header: "fakeuser"}
  91. data = {"csrfmiddlewaretoken": csrf_token_form}
  92. # Verify that CSRF is configured for the view
  93. csrf_client.cookies.load({settings.CSRF_COOKIE_NAME: csrf_token})
  94. response = await csrf_client.post("/remote_user/", **headers)
  95. self.assertEqual(response.status_code, 403)
  96. self.assertIn(b"CSRF verification failed.", response.content)
  97. # This request will call django.contrib.auth.alogin() which will call
  98. # django.middleware.csrf.rotate_token() thus changing the value of
  99. # request.META['CSRF_COOKIE'] from the user submitted value set by
  100. # CsrfViewMiddleware.process_request() to the new csrftoken value set
  101. # by rotate_token(). Csrf validation should still pass when the view is
  102. # later processed by CsrfViewMiddleware.process_view()
  103. csrf_client.cookies.load({settings.CSRF_COOKIE_NAME: csrf_token})
  104. response = await csrf_client.post("/remote_user/", data, **headers)
  105. self.assertEqual(response.status_code, 200)
  106. def test_unknown_user(self):
  107. """
  108. Tests the case where the username passed in the header does not exist
  109. as a User.
  110. """
  111. num_users = User.objects.count()
  112. response = self.client.get("/remote_user/", **{self.header: "newuser"})
  113. self.assertEqual(response.context["user"].username, "newuser")
  114. self.assertEqual(User.objects.count(), num_users + 1)
  115. User.objects.get(username="newuser")
  116. # Another request with same user should not create any new users.
  117. response = self.client.get("/remote_user/", **{self.header: "newuser"})
  118. self.assertEqual(User.objects.count(), num_users + 1)
  119. async def test_unknown_user_async(self):
  120. """See test_unknown_user."""
  121. num_users = await User.objects.acount()
  122. response = await self.async_client.get(
  123. "/remote_user/", **{self.header: "newuser"}
  124. )
  125. self.assertEqual(response.context["user"].username, "newuser")
  126. self.assertEqual(await User.objects.acount(), num_users + 1)
  127. await User.objects.aget(username="newuser")
  128. # Another request with same user should not create any new users.
  129. response = await self.async_client.get(
  130. "/remote_user/", **{self.header: "newuser"}
  131. )
  132. self.assertEqual(await User.objects.acount(), num_users + 1)
  133. def test_known_user(self):
  134. """
  135. Tests the case where the username passed in the header is a valid User.
  136. """
  137. User.objects.create(username="knownuser")
  138. User.objects.create(username="knownuser2")
  139. num_users = User.objects.count()
  140. response = self.client.get("/remote_user/", **{self.header: self.known_user})
  141. self.assertEqual(response.context["user"].username, "knownuser")
  142. self.assertEqual(User.objects.count(), num_users)
  143. # A different user passed in the headers causes the new user
  144. # to be logged in.
  145. response = self.client.get("/remote_user/", **{self.header: self.known_user2})
  146. self.assertEqual(response.context["user"].username, "knownuser2")
  147. self.assertEqual(User.objects.count(), num_users)
  148. async def test_known_user_async(self):
  149. """See test_known_user."""
  150. await User.objects.acreate(username="knownuser")
  151. await User.objects.acreate(username="knownuser2")
  152. num_users = await User.objects.acount()
  153. response = await self.async_client.get(
  154. "/remote_user/", **{self.header: self.known_user}
  155. )
  156. self.assertEqual(response.context["user"].username, "knownuser")
  157. self.assertEqual(await User.objects.acount(), num_users)
  158. # A different user passed in the headers causes the new user
  159. # to be logged in.
  160. response = await self.async_client.get(
  161. "/remote_user/", **{self.header: self.known_user2}
  162. )
  163. self.assertEqual(response.context["user"].username, "knownuser2")
  164. self.assertEqual(await User.objects.acount(), num_users)
  165. def test_last_login(self):
  166. """
  167. A user's last_login is set the first time they make a
  168. request but not updated in subsequent requests with the same session.
  169. """
  170. user = User.objects.create(username="knownuser")
  171. # Set last_login to something so we can determine if it changes.
  172. default_login = datetime(2000, 1, 1)
  173. if settings.USE_TZ:
  174. default_login = default_login.replace(tzinfo=timezone.utc)
  175. user.last_login = default_login
  176. user.save()
  177. response = self.client.get("/remote_user/", **{self.header: self.known_user})
  178. self.assertNotEqual(default_login, response.context["user"].last_login)
  179. user = User.objects.get(username="knownuser")
  180. user.last_login = default_login
  181. user.save()
  182. response = self.client.get("/remote_user/", **{self.header: self.known_user})
  183. self.assertEqual(default_login, response.context["user"].last_login)
  184. async def test_last_login_async(self):
  185. """See test_last_login."""
  186. user = await User.objects.acreate(username="knownuser")
  187. # Set last_login to something so we can determine if it changes.
  188. default_login = datetime(2000, 1, 1)
  189. if settings.USE_TZ:
  190. default_login = default_login.replace(tzinfo=timezone.utc)
  191. user.last_login = default_login
  192. await user.asave()
  193. response = await self.async_client.get(
  194. "/remote_user/", **{self.header: self.known_user}
  195. )
  196. self.assertNotEqual(default_login, response.context["user"].last_login)
  197. user = await User.objects.aget(username="knownuser")
  198. user.last_login = default_login
  199. await user.asave()
  200. response = await self.async_client.get(
  201. "/remote_user/", **{self.header: self.known_user}
  202. )
  203. self.assertEqual(default_login, response.context["user"].last_login)
  204. def test_header_disappears(self):
  205. """
  206. A logged in user is logged out automatically when
  207. the REMOTE_USER header disappears during the same browser session.
  208. """
  209. User.objects.create(username="knownuser")
  210. # Known user authenticates
  211. response = self.client.get("/remote_user/", **{self.header: self.known_user})
  212. self.assertEqual(response.context["user"].username, "knownuser")
  213. # During the session, the REMOTE_USER header disappears. Should trigger logout.
  214. response = self.client.get("/remote_user/")
  215. self.assertTrue(response.context["user"].is_anonymous)
  216. # verify the remoteuser middleware will not remove a user
  217. # authenticated via another backend
  218. User.objects.create_user(username="modeluser", password="foo")
  219. self.client.login(username="modeluser", password="foo")
  220. authenticate(username="modeluser", password="foo")
  221. response = self.client.get("/remote_user/")
  222. self.assertEqual(response.context["user"].username, "modeluser")
  223. async def test_header_disappears_async(self):
  224. """See test_header_disappears."""
  225. await User.objects.acreate(username="knownuser")
  226. # Known user authenticates
  227. response = await self.async_client.get(
  228. "/remote_user/", **{self.header: self.known_user}
  229. )
  230. self.assertEqual(response.context["user"].username, "knownuser")
  231. # During the session, the REMOTE_USER header disappears. Should trigger logout.
  232. response = await self.async_client.get("/remote_user/")
  233. self.assertTrue(response.context["user"].is_anonymous)
  234. # verify the remoteuser middleware will not remove a user
  235. # authenticated via another backend
  236. await User.objects.acreate_user(username="modeluser", password="foo")
  237. await self.async_client.alogin(username="modeluser", password="foo")
  238. await aauthenticate(username="modeluser", password="foo")
  239. response = await self.async_client.get("/remote_user/")
  240. self.assertEqual(response.context["user"].username, "modeluser")
  241. def test_user_switch_forces_new_login(self):
  242. """
  243. If the username in the header changes between requests
  244. that the original user is logged out
  245. """
  246. User.objects.create(username="knownuser")
  247. # Known user authenticates
  248. response = self.client.get("/remote_user/", **{self.header: self.known_user})
  249. self.assertEqual(response.context["user"].username, "knownuser")
  250. # During the session, the REMOTE_USER changes to a different user.
  251. response = self.client.get("/remote_user/", **{self.header: "newnewuser"})
  252. # The current user is not the prior remote_user.
  253. # In backends that create a new user, username is "newnewuser"
  254. # In backends that do not create new users, it is '' (anonymous user)
  255. self.assertNotEqual(response.context["user"].username, "knownuser")
  256. async def test_user_switch_forces_new_login_async(self):
  257. """See test_user_switch_forces_new_login."""
  258. await User.objects.acreate(username="knownuser")
  259. # Known user authenticates
  260. response = await self.async_client.get(
  261. "/remote_user/", **{self.header: self.known_user}
  262. )
  263. self.assertEqual(response.context["user"].username, "knownuser")
  264. # During the session, the REMOTE_USER changes to a different user.
  265. response = await self.async_client.get(
  266. "/remote_user/", **{self.header: "newnewuser"}
  267. )
  268. # The current user is not the prior remote_user.
  269. # In backends that create a new user, username is "newnewuser"
  270. # In backends that do not create new users, it is '' (anonymous user)
  271. self.assertNotEqual(response.context["user"].username, "knownuser")
  272. def test_inactive_user(self):
  273. User.objects.create(username="knownuser", is_active=False)
  274. response = self.client.get("/remote_user/", **{self.header: "knownuser"})
  275. self.assertTrue(response.context["user"].is_anonymous)
  276. async def test_inactive_user_async(self):
  277. await User.objects.acreate(username="knownuser", is_active=False)
  278. response = await self.async_client.get(
  279. "/remote_user/", **{self.header: "knownuser"}
  280. )
  281. self.assertTrue(response.context["user"].is_anonymous)
  282. class RemoteUserNoCreateBackend(RemoteUserBackend):
  283. """Backend that doesn't create unknown users."""
  284. create_unknown_user = False
  285. class RemoteUserNoCreateTest(RemoteUserTest):
  286. """
  287. Contains the same tests as RemoteUserTest, but using a custom auth backend
  288. class that doesn't create unknown users.
  289. """
  290. backend = "auth_tests.test_remote_user.RemoteUserNoCreateBackend"
  291. def test_unknown_user(self):
  292. num_users = User.objects.count()
  293. response = self.client.get("/remote_user/", **{self.header: "newuser"})
  294. self.assertTrue(response.context["user"].is_anonymous)
  295. self.assertEqual(User.objects.count(), num_users)
  296. async def test_unknown_user_async(self):
  297. num_users = await User.objects.acount()
  298. response = await self.async_client.get(
  299. "/remote_user/", **{self.header: "newuser"}
  300. )
  301. self.assertTrue(response.context["user"].is_anonymous)
  302. self.assertEqual(await User.objects.acount(), num_users)
  303. class AllowAllUsersRemoteUserBackendTest(RemoteUserTest):
  304. """Backend that allows inactive users."""
  305. backend = "django.contrib.auth.backends.AllowAllUsersRemoteUserBackend"
  306. def test_inactive_user(self):
  307. user = User.objects.create(username="knownuser", is_active=False)
  308. response = self.client.get("/remote_user/", **{self.header: self.known_user})
  309. self.assertEqual(response.context["user"].username, user.username)
  310. async def test_inactive_user_async(self):
  311. user = await User.objects.acreate(username="knownuser", is_active=False)
  312. response = await self.async_client.get(
  313. "/remote_user/", **{self.header: self.known_user}
  314. )
  315. self.assertEqual(response.context["user"].username, user.username)
  316. class CustomRemoteUserBackend(RemoteUserBackend):
  317. """
  318. Backend that overrides RemoteUserBackend methods.
  319. """
  320. def clean_username(self, username):
  321. """
  322. Grabs username before the @ character.
  323. """
  324. return username.split("@")[0]
  325. def configure_user(self, request, user, created=True):
  326. """
  327. Sets user's email address using the email specified in an HTTP header.
  328. Sets user's last name for existing users.
  329. """
  330. user.email = request.META.get(RemoteUserTest.email_header, "")
  331. if not created:
  332. user.last_name = user.username
  333. user.save()
  334. return user
  335. class RemoteUserCustomTest(RemoteUserTest):
  336. """
  337. Tests a custom RemoteUserBackend subclass that overrides the clean_username
  338. and configure_user methods.
  339. """
  340. backend = "auth_tests.test_remote_user.CustomRemoteUserBackend"
  341. # REMOTE_USER strings with email addresses for the custom backend to
  342. # clean.
  343. known_user = "knownuser@example.com"
  344. known_user2 = "knownuser2@example.com"
  345. def test_known_user(self):
  346. """
  347. The strings passed in REMOTE_USER should be cleaned and the known users
  348. should not have been configured with an email address.
  349. """
  350. super().test_known_user()
  351. knownuser = User.objects.get(username="knownuser")
  352. knownuser2 = User.objects.get(username="knownuser2")
  353. self.assertEqual(knownuser.email, "")
  354. self.assertEqual(knownuser2.email, "")
  355. self.assertEqual(knownuser.last_name, "knownuser")
  356. self.assertEqual(knownuser2.last_name, "knownuser2")
  357. def test_unknown_user(self):
  358. """
  359. The unknown user created should be configured with an email address
  360. provided in the request header.
  361. """
  362. num_users = User.objects.count()
  363. response = self.client.get(
  364. "/remote_user/",
  365. **{
  366. self.header: "newuser",
  367. self.email_header: "user@example.com",
  368. },
  369. )
  370. self.assertEqual(response.context["user"].username, "newuser")
  371. self.assertEqual(response.context["user"].email, "user@example.com")
  372. self.assertEqual(response.context["user"].last_name, "")
  373. self.assertEqual(User.objects.count(), num_users + 1)
  374. newuser = User.objects.get(username="newuser")
  375. self.assertEqual(newuser.email, "user@example.com")
  376. class CustomHeaderMiddleware(RemoteUserMiddleware):
  377. """
  378. Middleware that overrides custom HTTP auth user header.
  379. """
  380. header = "HTTP_AUTHUSER"
  381. class CustomHeaderRemoteUserTest(RemoteUserTest):
  382. """
  383. Tests a custom RemoteUserMiddleware subclass with custom HTTP auth user
  384. header.
  385. """
  386. middleware = "auth_tests.test_remote_user.CustomHeaderMiddleware"
  387. header = "HTTP_AUTHUSER"
  388. class PersistentRemoteUserTest(RemoteUserTest):
  389. """
  390. PersistentRemoteUserMiddleware keeps the user logged in even if the
  391. subsequent calls do not contain the header value.
  392. """
  393. middleware = "django.contrib.auth.middleware.PersistentRemoteUserMiddleware"
  394. require_header = False
  395. def test_header_disappears(self):
  396. """
  397. A logged in user is kept logged in even if the REMOTE_USER header
  398. disappears during the same browser session.
  399. """
  400. User.objects.create(username="knownuser")
  401. # Known user authenticates
  402. response = self.client.get("/remote_user/", **{self.header: self.known_user})
  403. self.assertEqual(response.context["user"].username, "knownuser")
  404. # Should stay logged in if the REMOTE_USER header disappears.
  405. response = self.client.get("/remote_user/")
  406. self.assertFalse(response.context["user"].is_anonymous)
  407. self.assertEqual(response.context["user"].username, "knownuser")
  408. async def test_header_disappears_async(self):
  409. """See test_header_disappears."""
  410. await User.objects.acreate(username="knownuser")
  411. # Known user authenticates
  412. response = await self.async_client.get(
  413. "/remote_user/", **{self.header: self.known_user}
  414. )
  415. self.assertEqual(response.context["user"].username, "knownuser")
  416. # Should stay logged in if the REMOTE_USER header disappears.
  417. response = await self.async_client.get("/remote_user/")
  418. self.assertFalse(response.context["user"].is_anonymous)
  419. self.assertEqual(response.context["user"].username, "knownuser")