test_public_request_context.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import unittest
  2. from utils.security import generate_gateway_session_id, hash_gateway_session_id
  3. from services.request_context import RequestContextParser
  4. class GatewaySecurityTest(unittest.TestCase):
  5. def test_generate_gateway_session_id_is_prefixed_and_high_entropy(self):
  6. first = generate_gateway_session_id()
  7. second = generate_gateway_session_id()
  8. self.assertTrue(first.startswith('GWS_'))
  9. self.assertTrue(second.startswith('GWS_'))
  10. self.assertNotEqual(first, second)
  11. self.assertGreaterEqual(len(first), 36)
  12. def test_hash_gateway_session_id_does_not_return_plaintext(self):
  13. session_id = 'GWS_example_secret_value'
  14. digest = hash_gateway_session_id(session_id)
  15. self.assertNotIn(session_id, digest)
  16. self.assertEqual(digest, hash_gateway_session_id(session_id))
  17. self.assertGreaterEqual(len(digest), 32)
  18. class RequestContextParserTest(unittest.TestCase):
  19. def test_parse_session_from_x_gateway_session_header(self):
  20. context = RequestContextParser().parse({
  21. 'X-Gateway-Session': 'GWS_header_token',
  22. })
  23. self.assertEqual('GWS_header_token', context.gateway_session_id)
  24. self.assertEqual('header', context.source)
  25. def test_parse_session_from_authorization_bearer(self):
  26. context = RequestContextParser().parse({
  27. 'Authorization': 'Bearer GWS_bearer_token',
  28. })
  29. self.assertEqual('GWS_bearer_token', context.gateway_session_id)
  30. self.assertEqual('authorization', context.source)
  31. def test_parse_session_from_cookie(self):
  32. context = RequestContextParser().parse({
  33. 'Cookie': 'foo=bar; gateway_session_id=GWS_cookie_token; theme=dark',
  34. })
  35. self.assertEqual('GWS_cookie_token', context.gateway_session_id)
  36. self.assertEqual('cookie', context.source)
  37. def test_missing_session_is_not_authenticated(self):
  38. context = RequestContextParser().parse({})
  39. self.assertFalse(context.has_session())
  40. self.assertEqual('', context.gateway_session_id)
  41. if __name__ == '__main__':
  42. unittest.main()