Self hosted FLOSS fitness/workout, nutrition and weight tracker
Add tests for the brute force protection, diary API and email queue
Roland Geiderb69870ad1bfa
diff --git a/wger/core/tests/test_axes.py b/wger/core/tests/test_axes.pynew file mode 100644index 000000000..59da5d0e3--- /dev/null+++ b/wger/core/tests/test_axes.py@@ -0,0 +1,138 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++# Standard Library+import json++# Django+from django.conf import settings+from django.test import override_settings+from django.urls import reverse++# Third Party+from axes.models import AccessAttempt+from axes.utils import reset++# wger+from wger.core.tests.base_testcase import WgerTestCase+++FAILURE_LIMIT = 3+++@override_settings(AXES_ENABLED=True, AXES_FAILURE_LIMIT=FAILURE_LIMIT)+class AxesLockoutTestCase(WgerTestCase):+ """+ Tests the brute force protection++ allauth's own login rate limit is switched off (see settings_global), so+ django-axes is the only thing standing between an attacker and unlimited+ password guessing.+ """++ def setUp(self):+ super().setUp()++ # The shared base class switches axes off for every test, undo that+ settings.AXES_ENABLED = True+ reset()++ def tearDown(self):+ reset()+ super().tearDown()++ def web_login(self, password: str):+ return self.client.post(+ reverse('core:user:login'),+ {'login': 'test', 'password': password},+ )++ def api_login(self, password: str):+ return self.client.post(+ reverse('headless:app:account:login'),+ data=json.dumps({'username': 'test', 'password': password}),+ content_type='application/json',+ )++ def assert_logged_in(self, response):+ self.assertTrue(response.wsgi_request.user.is_authenticated)++ def test_failed_attempts_are_recorded(self):+ self.web_login('wrong password')++ self.assertEqual(AccessAttempt.objects.count(), 1)++ def test_lockout_after_the_failure_limit(self):+ for _ in range(FAILURE_LIMIT):+ response = self.web_login('wrong password')+ self.assertFalse(response.wsgi_request.user.is_authenticated)++ # Even the correct password is now refused+ response = self.web_login('testtest')+ self.assertFalse(response.wsgi_request.user.is_authenticated)++ def test_login_works_below_the_limit(self):+ for _ in range(FAILURE_LIMIT - 1):+ self.web_login('wrong password')++ self.assert_logged_in(self.web_login('testtest'))++ def test_reset_unlocks_the_account(self):+ for _ in range(FAILURE_LIMIT):+ self.web_login('wrong password')++ reset()++ self.assert_logged_in(self.web_login('testtest'))++ def test_api_login_is_covered(self):+ """+ The API login endpoint has to be protected too, it is the reason+ allauth's own rate limiting was switched off+ """+ for _ in range(FAILURE_LIMIT):+ self.api_login('wrong password')++ response = self.api_login('testtest')+ self.assertNotEqual(response.status_code, 200, response.content)++ def test_api_and_web_share_the_same_counter(self):+ """+ Switching endpoints must not give an attacker a fresh budget+ """+ for _ in range(FAILURE_LIMIT):+ self.api_login('wrong password')++ response = self.web_login('testtest')+ self.assertFalse(response.wsgi_request.user.is_authenticated)+++class AxesDisabledInTestsTestCase(WgerTestCase):+ """+ The shared base test case switches axes off so the other tests can log in+ as many users as they need+ """++ def test_repeated_failures_do_not_lock_out(self):+ for _ in range(15):+ self.client.post(+ reverse('core:user:login'),+ {'login': 'test', 'password': 'wrong password'},+ )++ response = self.client.post(+ reverse('core:user:login'),+ {'login': 'test', 'password': 'testtest'},+ )+ self.assertTrue(response.wsgi_request.user.is_authenticated)diff --git a/wger/mailer/tests/test_send_mass_emails.py b/wger/mailer/tests/test_send_mass_emails.pynew file mode 100644index 000000000..9c6a8e979--- /dev/null+++ b/wger/mailer/tests/test_send_mass_emails.py@@ -0,0 +1,101 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License++# Django+from django.conf import settings+from django.contrib.auth.models import User+from django.core import mail+from django.core.management import call_command++# wger+from wger.core.tests.base_testcase import WgerTestCase+from wger.gym.models import Gym+from wger.mailer.models import (+ CronEntry,+ Log,+)+++class SendMassEmailsTestCase(WgerTestCase):+ """+ Tests the command that works off the email queue+ """++ BATCH_SIZE = 100+ """The number of entries the command processes per run"""++ def setUp(self):+ super().setUp()+ self.log = Log(+ user=User.objects.get(username='admin'),+ gym=Gym.objects.get(pk=1),+ subject='Test subject',+ body='Test body',+ )+ self.log.save()++ def queue_entries(self, count: int):+ CronEntry.objects.bulk_create(+ [CronEntry(log=self.log, email=f'member{i}@example.com') for i in range(count)]+ )++ def test_empty_queue(self):+ call_command('send-mass-emails')++ self.assertEqual(len(mail.outbox), 0)++ def test_entries_are_sent_and_removed(self):+ self.queue_entries(3)++ call_command('send-mass-emails')++ self.assertEqual(len(mail.outbox), 3)+ self.assertEqual(CronEntry.objects.count(), 0)++ def test_email_content_comes_from_the_log(self):+ self.queue_entries(1)++ call_command('send-mass-emails')++ message = mail.outbox[0]+ self.assertEqual(message.subject, 'Test subject')+ self.assertEqual(message.body, 'Test body')+ self.assertEqual(message.to, ['[email protected]'])+ self.assertEqual(message.from_email, settings.WGER_SETTINGS['EMAIL_FROM'])++ def test_only_one_batch_per_run(self):+ """+ Larger queues are worked off over several runs+ """+ self.queue_entries(self.BATCH_SIZE + 20)++ call_command('send-mass-emails')++ self.assertEqual(len(mail.outbox), self.BATCH_SIZE)+ self.assertEqual(CronEntry.objects.count(), 20)++ call_command('send-mass-emails')++ self.assertEqual(len(mail.outbox), self.BATCH_SIZE + 20)+ self.assertEqual(CronEntry.objects.count(), 0)++ def test_the_log_entry_is_kept(self):+ """+ Only the queue entries are consumed, the log stays for the overview+ """+ self.queue_entries(2)++ call_command('send-mass-emails')++ self.assertTrue(Log.objects.filter(pk=self.log.pk).exists())diff --git a/wger/nutrition/fixtures/test-nutrition-diary.json b/wger/nutrition/fixtures/test-nutrition-diary.jsonindex fe76a46c1..c66e8f8c3 100644--- a/wger/nutrition/fixtures/test-nutrition-diary.json+++ b/wger/nutrition/fixtures/test-nutrition-diary.json@@ -56,7 +56,7 @@"amount": "75","weight_unit": null},- "pk": "44444444-4444-4444-4444-000000000004",+ "pk": "44444444-4444-4444-4444-000000000005","model": "nutrition.logitem"}]diff --git a/wger/nutrition/tests/test_log_item_api.py b/wger/nutrition/tests/test_log_item_api.pynew file mode 100644index 000000000..f5cdee63b--- /dev/null+++ b/wger/nutrition/tests/test_log_item_api.py@@ -0,0 +1,163 @@+# This file is part of wger Workout Manager.+#+# wger Workout Manager is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+#+# wger Workout Manager is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU Affero General Public License+# along with Workout Manager. If not, see <http://www.gnu.org/licenses/>.++# Third Party+from rest_framework import status++# wger+from wger.core.tests.api_base_test import ApiBaseTestCase+from wger.core.tests.base_testcase import BaseTestCase+from wger.nutrition.models import LogItem+++PLAN_OWNED = 'cc000000-0000-0000-0000-000000000001'+"""Belongs to user 'test', has four diary entries"""++PLAN_OTHER = 'cc000000-0000-0000-0000-000000000002'+"""Belongs to user 'admin', has one diary entry"""++LOG_OWNED = 'ee000000-0000-0000-0000-000000000001'+LOG_OTHER = '44444444-4444-4444-4444-000000000005'+++class LogItemApiTestCase(BaseTestCase, ApiBaseTestCase):+ """+ Tests the nutrition diary endpoint++ The diary of user 'test' has three entries on 2016-05-15 and one on+ 2016-05-14.+ """++ url = '/api/v2/nutritiondiary/'++ def get_ids(self, response) -> list:+ return [entry['id'] for entry in response.json()['results']]++ def test_anonymous(self):+ response = self.client.get(self.url)+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ def test_list_is_scoped_to_the_owner(self):+ self.authenticate('test')+ response = self.client.get(self.url)++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(len(self.get_ids(response)), 4)+ self.assertNotIn(LOG_OTHER, self.get_ids(response))++ def test_detail_other_user(self):+ self.authenticate('test')+ response = self.client.get(f'{self.url}{LOG_OTHER}/')+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ def test_filter_by_date(self):+ """The date filter uses the local date of the entry's timestamp"""+ self.authenticate('test')++ response = self.client.get(self.url, {'datetime__date': '2016-05-15'})+ self.assertEqual(len(self.get_ids(response)), 3)++ response = self.client.get(self.url, {'datetime__date': '2016-05-14'})+ self.assertEqual(len(self.get_ids(response)), 1)++ response = self.client.get(self.url, {'datetime__date': '2016-05-16'})+ self.assertEqual(self.get_ids(response), [])++ def test_filter_by_datetime_range(self):+ self.authenticate('test')++ response = self.client.get(self.url, {'datetime__gte': '2016-05-15T00:00:00Z'})+ self.assertEqual(len(self.get_ids(response)), 3)++ response = self.client.get(self.url, {'datetime__lt': '2016-05-15T00:00:00Z'})+ self.assertEqual(len(self.get_ids(response)), 1)++ def test_filter_by_plan_cannot_leak(self):+ """Filtering by a foreign plan returns nothing, not that plan's entries"""+ self.authenticate('test')+ response = self.client.get(self.url, {'plan': PLAN_OTHER})++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(self.get_ids(response), [])++ def test_post_to_own_plan(self):+ self.authenticate('test')+ count_before = LogItem.objects.count()++ response = self.client.post(+ self.url,+ data={+ 'plan': PLAN_OWNED,+ 'ingredient': 1,+ 'amount': 100,+ 'datetime': '2016-05-16T10:00:00Z',+ },+ )++ self.assertEqual(response.status_code, status.HTTP_201_CREATED)+ self.assertEqual(LogItem.objects.count(), count_before + 1)+ self.assertEqual(str(LogItem.objects.get(pk=response.json()['id']).plan_id), PLAN_OWNED)++ def test_post_to_other_users_plan(self):+ """A diary entry cannot be written into somebody else's plan"""+ self.authenticate('test')+ count_before = LogItem.objects.count()++ response = self.client.post(+ self.url,+ data={+ 'plan': PLAN_OTHER,+ 'ingredient': 1,+ 'amount': 100,+ 'datetime': '2016-05-16T10:00:00Z',+ },+ )++ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(LogItem.objects.count(), count_before)++ def test_patch_other_user_entry(self):+ self.authenticate('test')+ response = self.client.patch(f'{self.url}{LOG_OTHER}/', data={'amount': 1})++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertEqual(LogItem.objects.get(pk=LOG_OTHER).amount, 75)++ def test_delete_other_user_entry(self):+ self.authenticate('test')+ response = self.client.delete(f'{self.url}{LOG_OTHER}/')++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)+ self.assertTrue(LogItem.objects.filter(pk=LOG_OTHER).exists())++ def test_delete_own_entry(self):+ self.authenticate('test')+ response = self.client.delete(f'{self.url}{LOG_OWNED}/')++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertFalse(LogItem.objects.filter(pk=LOG_OWNED).exists())++ def test_nutritional_values_action(self):+ self.authenticate('test')+ response = self.client.get(f'{self.url}{LOG_OWNED}/nutritional_values/')++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertIn('energy', response.json())++ def test_nutritional_values_action_other_user(self):+ self.authenticate('test')+ response = self.client.get(f'{self.url}{LOG_OTHER}/nutritional_values/')++ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)