test_navigation.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. import unittest
  2. from unittest.mock import patch, MagicMock
  3. from urllib.parse import parse_qs, urlencode, urlsplit
  4. from fastapi import FastAPI
  5. from fastapi.testclient import TestClient
  6. from types import SimpleNamespace
  7. from datetime import date
  8. from app.db import get_session
  9. from app.routes import router
  10. from app.config import settings
  11. from app.ldap import DirectoryUser
  12. from app.main import app
  13. from app.navigation import LIST_PATH, list_return_url, normalize_page_url
  14. from app.permissions import Entitlement
  15. class NavigationUrlTests(unittest.TestCase):
  16. def test_return_url_preserves_filters_and_replaces_transport_and_focus(self):
  17. value = LIST_PATH + '?Filiale=10&Kunde=A%26B&page=3&limit=100&scope=debtor&focus=2_OTHER'
  18. result = list_return_url(value, '1_R1')
  19. self.assertEqual(parse_qs(urlsplit(result).query), {'Filiale': ['10'], 'Kunde': ['A&B'], 'focus': ['1_R1']})
  20. def test_invalid_return_destinations_fall_back_to_filtered_page_type(self):
  21. for value in ['https://evil.test/', '//evil.test', '/\\evil', '/%2f%2fevil', '/select', '/app/forderungen/liste\n']:
  22. with self.subTest(value=value):
  23. self.assertEqual(list_return_url(value, '1_R1'), LIST_PATH + '?focus=1_R1')
  24. def test_fragment_recovery_uses_only_matching_invoice_context(self):
  25. return_to = LIST_PATH + '?Filiale=10&focus=1_R1'
  26. current = 'https://external-proxy.test/app/forderungen/details/1_R1?' + urlencode({'return_to': return_to})
  27. for fragment in ['kommentare', 'buchungen']:
  28. result = normalize_page_url('/app/forderungen/details/1_R1/' + fragment + '?scope=debtor', current_url=current)
  29. self.assertEqual(result, '/app/forderungen/details/1_R1?' + urlencode({'return_to': return_to}))
  30. self.assertEqual(normalize_page_url('/app/forderungen/details/2_R1/kommentare', current_url=current),
  31. '/app/forderungen/details/2_R1')
  32. def test_external_current_url_never_becomes_redirect_origin(self):
  33. result = normalize_page_url('/app/forderungen/details/1_R1/buchungen',
  34. current_url='https://evil.test/app/forderungen/details/1_R1?return_to=https://evil.test')
  35. self.assertTrue(result.startswith('/app/forderungen/details/1_R1?'))
  36. self.assertNotIn('evil', result)
  37. class LoginRecoveryTests(unittest.TestCase):
  38. def setUp(self):
  39. config = patch.multiple(settings, DEBUG_AUTH=False, TRUSTED_PROXY_IPS=[], COOKIE_SECURE=False)
  40. config.start()
  41. self.addCleanup(config.stop)
  42. session = patch('app.auth.SessionLocal', return_value=MagicMock())
  43. session.start()
  44. self.addCleanup(session.stop)
  45. self.client = TestClient(app)
  46. self.addCleanup(self.client.close)
  47. def login_target(self, response):
  48. self.assertEqual(response.status_code, 200)
  49. login = response.headers['HX-Redirect']
  50. self.assertTrue(login.startswith('/login?next='))
  51. return parse_qs(urlsplit(login).query)['next'][0]
  52. def test_expired_list_paging_resumes_full_filtered_page(self):
  53. response = self.client.get(LIST_PATH + '?page=3&limit=100&Filiale=10', headers={
  54. 'HX-Request': 'true', 'HX-Current-URL': 'http://testserver' + LIST_PATH + '?Filiale=10&focus=1_R120',
  55. }, follow_redirects=False)
  56. self.assertEqual(self.login_target(response), LIST_PATH + '?Filiale=10&focus=1_R120')
  57. def test_fragment_and_save_expiry_resume_detail_without_replaying_post(self):
  58. return_to = LIST_PATH + '?Filiale=10&Kunde=Muster&focus=1_R1'
  59. current = 'http://testserver/app/forderungen/details/1_R1?' + urlencode({'return_to': return_to})
  60. headers = {'HX-Request': 'true', 'HX-Current-URL': current}
  61. for suffix in ['/kommentare?scope=debtor', '/buchungen?scope=open', '']:
  62. with self.subTest(suffix=suffix):
  63. if suffix:
  64. response = self.client.get('/app/forderungen/details/1_R1' + suffix, headers=headers)
  65. else:
  66. response = self.client.post('/app/forderungen/details/1_R1', headers=headers,
  67. data={'source': 'details', 'return_to': return_to})
  68. self.assertEqual(self.login_target(response), current.removeprefix('http://testserver'))
  69. def test_login_post_normalizes_fragment_next_to_full_get(self):
  70. self.client.get('/login')
  71. csrf = self.client.cookies[settings.LOGIN_CSRF_COOKIE_NAME]
  72. user = DirectoryUser('tester', 'CN=tester', 'Tester', '')
  73. rights = (Entitlement('1', '10', 'SC', 'Mitarbeiter', 100),)
  74. with patch('app.routes.ldap_authenticate', return_value=user), patch('app.routes.load_entitlements', return_value=rights):
  75. response = self.client.post('/login', data={
  76. 'username': 'tester', 'password': 'test', '_csrf': csrf,
  77. 'next': '/app/forderungen/details/1_R1/kommentare?scope=debtor',
  78. }, follow_redirects=False)
  79. self.assertEqual(response.status_code, 303)
  80. self.assertEqual(response.headers['location'], '/app/forderungen/details/1_R1')
  81. def test_native_page_request_uses_full_page_redirect(self):
  82. response = self.client.get(LIST_PATH + '?Filiale=10', follow_redirects=False)
  83. self.assertEqual(response.status_code, 303)
  84. self.assertEqual(parse_qs(urlsplit(response.headers['location']).query)['next'], [LIST_PATH + '?Filiale=10'])
  85. class DetailReturnTests(unittest.TestCase):
  86. def setUp(self):
  87. self.db = MagicMock()
  88. self.db.execute.return_value.first.return_value = (1,)
  89. application = FastAPI()
  90. application.include_router(router)
  91. application.dependency_overrides[get_session] = lambda: self.db
  92. @application.middleware('http')
  93. async def identity(request, call_next):
  94. request.state.principal = SimpleNamespace(username='tester', name='Tester', role='Mitarbeiter', csrf='csrf')
  95. return await call_next(request)
  96. self.client = TestClient(application, raise_server_exceptions=False)
  97. self.addCleanup(self.client.close)
  98. self.row = dict(Client_DB='1', Beleg_Nr='R1', Beleg_Text='Rechnung R1', Beleg_offen=10,
  99. Kunde_offen_gesamt=20, Beleg_Datum=date(2026, 10, 1),
  100. Fahrzeug_Erstzulassung=None, Fahrzeug_Kaufdatum=None, Wiedervorlage=date(2026, 11, 1),
  101. Mwst_Betrag=0, Mwst_Betrag_berechnet=1.9)
  102. context = dict(forderungen_details=[self.row], forderungen_kommentare=[], forderungen_buchungen=[],
  103. auftraege_positionen=[], versicherungen=[], files=[], detail_url='/app/forderungen/details/1_R1',
  104. kommentare_scope='invoice', buchungen_scope='invoice', vehicle_missing=False, summary=False)
  105. fixture = patch('app.routes.get_template_context', side_effect=lambda *args: dict(context))
  106. fixture.start()
  107. self.addCleanup(fixture.stop)
  108. self.return_url = LIST_PATH + '?Filiale=10&Kunde=Muster&focus=1_R1'
  109. def test_detail_and_saved_form_keep_explicit_return_context(self):
  110. response = self.client.get('/app/forderungen/details/1_R1?' + urlencode({'return_to': self.return_url}))
  111. self.assertEqual(response.status_code, 200)
  112. self.assertIn('Filiale=10&Kunde=Muster&focus=1_R1', response.text)
  113. response = self.client.post('/app/forderungen/details/1_R1', data={
  114. 'source': 'details', 'return_to': self.return_url,
  115. }, headers={'HX-Request': 'true', 'Referer': 'http://testserver/app/forderungen/details/1_R1'})
  116. self.assertEqual(response.status_code, 200)
  117. self.assertIn('name="return_to" value="/app/forderungen/liste?Filiale=10&Kunde=Muster&focus=1_R1"', response.text)
  118. self.assertEqual(self.db.commit.call_count, 1)
  119. def test_save_and_back_redirects_after_commit_to_full_list(self):
  120. response = self.client.post('/app/forderungen/details/1_R1', data={
  121. 'source': 'details', 'return_to': self.return_url, 'redirect': 'list',
  122. }, headers={'HX-Request': 'true'})
  123. self.assertEqual(response.status_code, 200)
  124. self.assertEqual(response.headers['HX-Redirect'], self.return_url)
  125. self.db.commit.assert_called_once()
  126. native = self.client.post('/app/forderungen/details/1_R1', data={
  127. 'source': 'details', 'return_to': self.return_url, 'redirect': 'list',
  128. }, follow_redirects=False)
  129. self.assertEqual(native.status_code, 303)
  130. self.assertEqual(native.headers['location'], self.return_url)
  131. def test_failed_save_does_not_return_and_external_target_is_ignored(self):
  132. self.db.commit.side_effect = RuntimeError('test database unavailable')
  133. response = self.client.post('/app/forderungen/details/1_R1', data={
  134. 'source': 'details', 'return_to': self.return_url, 'redirect': 'list',
  135. }, headers={'HX-Request': 'true'})
  136. self.assertEqual(response.status_code, 500)
  137. self.assertNotIn('HX-Redirect', response.headers)
  138. self.db.commit.side_effect = None
  139. response = self.client.post('/app/forderungen/details/1_R1', data={
  140. 'source': 'details', 'redirect': 'https://evil.test',
  141. }, headers={'HX-Request': 'true'})
  142. self.assertEqual(response.headers['HX-Redirect'], LIST_PATH + '?focus=1_R1')