diff --git a/matemat/webserver/httpd.py b/matemat/webserver/httpd.py index 2f3f3cb..5c75520 100644 --- a/matemat/webserver/httpd.py +++ b/matemat/webserver/httpd.py @@ -175,12 +175,13 @@ class HttpHandler(BaseHTTPRequestHandler): :param args: Arguments sent with the request. This includes GET and POST arguments, where the POST arguments take precedence. """ - # Start or resume a session; report an error on session timeout + # Start or resume a session; redirect to / on session timeout try: session_id, timeout = self._start_session() except TimeoutError: - self.send_error(599, 'Session Timed Out', 'Session Timed Out.') + self.send_response(302) self.send_header('Set-Cookie', 'matemat_session_id=; expires=Thu, 01 Jan 1970 00:00:00 GMT') + self.send_header('Location', '/') self.end_headers() return self.session_id: str = session_id diff --git a/matemat/webserver/test/abstract_httpd_test.py b/matemat/webserver/test/abstract_httpd_test.py index a931628..eda18dd 100644 --- a/matemat/webserver/test/abstract_httpd_test.py +++ b/matemat/webserver/test/abstract_httpd_test.py @@ -39,7 +39,7 @@ class HttpResponse: def __finalize(self): self.parse_phase = 'done' - self.pagelet = self.headers['X-Test-Pagelet'] + self.pagelet = self.headers.get('X-Test-Pagelet', None) def parse(self, fragment: bytes) -> None: """ diff --git a/matemat/webserver/test/test_session.py b/matemat/webserver/test/test_session.py index 6697da3..b8e21cf 100644 --- a/matemat/webserver/test/test_session.py +++ b/matemat/webserver/test/test_session.py @@ -68,7 +68,7 @@ class TestSession(AbstractHttpdTest): # Send a mock GET request for '/just/testing/sessions' with a matemat session cookie self.client_sock.set_request( - f'GET /just/testing/sessions HTTP/1.1\r\nCookie: matemat_session_id={session_id}\r\n'.encode('utf-8')) + f'GET /just/testing/sessions HTTP/1.1\r\nCookie: matemat_session_id={session_id}\r\n\r\n'.encode('utf-8')) # Trigger request handling handler = HttpHandler(self.client_sock, ('::1', 45678), self.server) # Fetch the parsed response @@ -98,3 +98,63 @@ class TestSession(AbstractHttpdTest): # Make sure the session exists on the server self.assertIn('test', handler.session_vars) self.assertEqual('hello, world!', handler.session_vars['test']) + + def test_unknown_session_id(self): + # Unknown session ID + session_id: str = 'theserverdoesnotknowthisid' + refdate: datetime = datetime.utcnow() + timedelta(seconds=3500) + # Send a mock GET request for '/just/testing/sessions' with a session cookie not known to the server + self.client_sock.set_request( + f'GET /just/testing/sessions HTTP/1.1\r\nCookie: matemat_session_id={session_id}\r\n\r\n'.encode('utf-8')) + # Trigger request handling + handler = HttpHandler(self.client_sock, ('::1', 45678), self.server) + # Fetch the parsed response + packet = self.client_sock.get_response() + # Make sure a full HTTP response was parsed + self.assertEqual('done', packet.parse_phase) + # Make sure the request was served by the test pagelet + self.assertEqual('session_test_pagelet', packet.pagelet) + self.assertEqual(200, packet.statuscode) + + server_session_id: str = list(handler.server.session_vars.keys())[0] + self.assertNotEqual(session_id, server_session_id) + # Make sure a cookie was set - assuming that only one was set + self.assertIn('Set-Cookie', packet.headers) + # Split into the cookie itself + cookie, expiry = packet.headers['Set-Cookie'].split(';') + cookie: str = cookie.strip() + expiry: str = expiry.strip() + # Make sure the 'matemat_session_id' cookie was set to the session ID string + self.assertEqual(f'matemat_session_id={server_session_id}', cookie) + # Make sure the session expires in about one hour + self.assertTrue(expiry.startswith('expires=')) + _, expdatestr = expiry.split('=', 1) + expdate = datetime.strptime(expdatestr, '%a, %d %b %Y %H:%M:%S GMT') + self.assertTrue(expdate > refdate) + # Make sure the session exists on the server + self.assertIn('test', handler.session_vars) + self.assertEqual('hello, world!', handler.session_vars['test']) + + def test_session_expired(self): + # Test session expiry date + refdate: datetime = datetime.utcnow() - timedelta(hours=1) + # Session ID for testing + session_id: str = 'testsessionid' + # Insert test session + self.server.session_vars[session_id] = refdate, {'test': 'bar'} + + # Send a mock GET request for '/just/testing/sessions' with a matemat session cookie + self.client_sock.set_request( + f'GET /just/testing/sessions HTTP/1.1\r\nCookie: matemat_session_id={session_id}\r\n\r\n'.encode('utf-8')) + # Trigger request handling + handler = HttpHandler(self.client_sock, ('::1', 45678), self.server) + # Fetch the parsed response + packet = self.client_sock.get_response() + # Make sure a full HTTP response was parsed + self.assertEqual('done', packet.parse_phase) + # Make sure the server redirects to / + self.assertEqual(302, packet.statuscode) + self.assertIn('Location', packet.headers) + self.assertEqual('/', packet.headers['Location']) + # Make sure the session was terminated + self.assertNotIn(session_id, self.server.session_vars)