import unittest from utils.security import generate_gateway_session_id, hash_gateway_session_id from services.request_context import RequestContextParser class GatewaySecurityTest(unittest.TestCase): def test_generate_gateway_session_id_is_prefixed_and_high_entropy(self): first = generate_gateway_session_id() second = generate_gateway_session_id() self.assertTrue(first.startswith('GWS_')) self.assertTrue(second.startswith('GWS_')) self.assertNotEqual(first, second) self.assertGreaterEqual(len(first), 36) def test_hash_gateway_session_id_does_not_return_plaintext(self): session_id = 'GWS_example_secret_value' digest = hash_gateway_session_id(session_id) self.assertNotIn(session_id, digest) self.assertEqual(digest, hash_gateway_session_id(session_id)) self.assertGreaterEqual(len(digest), 32) class RequestContextParserTest(unittest.TestCase): def test_parse_session_from_x_gateway_session_header(self): context = RequestContextParser().parse({ 'X-Gateway-Session': 'GWS_header_token', }) self.assertEqual('GWS_header_token', context.gateway_session_id) self.assertEqual('header', context.source) def test_parse_session_from_authorization_bearer(self): context = RequestContextParser().parse({ 'Authorization': 'Bearer GWS_bearer_token', }) self.assertEqual('GWS_bearer_token', context.gateway_session_id) self.assertEqual('authorization', context.source) def test_parse_session_from_cookie(self): context = RequestContextParser().parse({ 'Cookie': 'foo=bar; gateway_session_id=GWS_cookie_token; theme=dark', }) self.assertEqual('GWS_cookie_token', context.gateway_session_id) self.assertEqual('cookie', context.source) def test_missing_session_is_not_authenticated(self): context = RequestContextParser().parse({}) self.assertFalse(context.has_session()) self.assertEqual('', context.gateway_session_id) if __name__ == '__main__': unittest.main()