"""Own functional tests: contract edges carried from lab 1 plus lab 2 auth. Every test creates unique synthetic users, so the file is safe to re-run against the same stand (the API has no delete endpoint by design). """ from __future__ import annotations import unittest import uuid from datetime import datetime, timezone import common def timestamp(value: str) -> datetime: return datetime.fromisoformat(value[:-1] + "+00:00") class Base(unittest.TestCase): @classmethod def setUpClass(cls) -> None: again = common.request("POST", "/api/v1/users", body=common.new_registration()) if again.status != 201: raise AssertionError("stand is not serving: %r" % (again.json,)) cls.alice = common.actor("alice") cls.bob = common.actor("bob") cls.eve = common.actor("eve") cls.chat = common.create_chat( cls.alice.token, [cls.alice.id, cls.bob.id], "Контрактный чат" ) class HealthAndEnvelope(Base): def test_health_endpoints_and_request_id(self) -> None: live = common.request("GET", "/health/live") self.assertEqual(live.status, 200) self.assertEqual(live.json, {"status": "ok"}) self.assertTrue(live.header("X-Request-Id")) ready = common.request("GET", "/health/ready") self.assertEqual(ready.status, 200) self.assertEqual(ready.json, {"status": "ok"}) def test_unknown_route_uses_same_error_envelope(self) -> None: common.expect_error(self, common.request("GET", "/api/v1/nope"), 404, "not_found") def test_query_parameters_rejected_where_not_supported(self) -> None: response = common.request( "GET", "/api/v1/users/me?verbose=1", token=self.alice.token ) common.expect_error(self, response, 400, "invalid_request") class Registration(Base): def test_response_has_no_secret_fields(self) -> None: response = common.register(common.new_registration()) self.assertEqual(response.status, 201) self.assertEqual( set(response.json), {"id", "username", "display_name", "created_at"} ) self.assertNotIn("password", response.json) self.assertNotIn("password_hash", response.json) def test_duplicate_username_conflict(self) -> None: registration = common.new_registration() self.assertEqual(common.register(registration).status, 201) common.expect_error(self, common.register(registration), 409, "conflict") def test_username_rules(self) -> None: for username in ("UPPER_case", "ab", "with-dash", "with space"): body = common.new_registration() body["username"] = username common.expect_error(self, common.register(body), 400, "invalid_request") def test_password_rules(self) -> None: short = common.new_registration(password="x" * 11) common.expect_error(self, common.register(short), 400, "invalid_request") long_password = common.new_registration(password="x" * 129) common.expect_error(self, common.register(long_password), 400, "invalid_request") # 12 Unicode code points are enough, even when they are multi-byte. unicode_password = common.new_registration(password="😀" * 12) self.assertEqual(common.register(unicode_password).status, 201) def test_malformed_json_extra_fields_and_wrong_types(self) -> None: common.expect_error( self, common.request( "POST", "/api/v1/users", raw=b'{"username": ', content_type="application/json" ), 400, "invalid_request", ) body = common.new_registration() body["is_admin"] = True common.expect_error(self, common.register(body), 400, "invalid_request") body = common.new_registration() body["display_name"] = 42 common.expect_error(self, common.register(body), 400, "invalid_request") def test_unsupported_media_type(self) -> None: response = common.request( "POST", "/api/v1/users", raw=b"username=alice", content_type="application/x-www-form-urlencoded", ) common.expect_error(self, response, 415, "unsupported_media_type") class Chats(Base): def test_membership_validation(self) -> None: cases = [ [self.bob.id], # caller is missing [self.alice.id, self.alice.id], # duplicate member [self.alice.id, str(uuid.uuid4())], # unknown member [], # no members ] for member_ids in cases: response = common.request( "POST", "/api/v1/chats", body={"title": "Плохой чат", "member_ids": member_ids}, token=self.alice.token, ) common.expect_error(self, response, 400, "invalid_request") def test_foreign_chat_is_hidden_everywhere(self) -> None: chat_id = self.chat["id"] common.expect_error( self, common.request("GET", "/api/v1/chats/" + chat_id, token=self.eve.token), 404, "not_found", ) common.expect_error( self, common.request( "GET", "/api/v1/chats/" + chat_id + "/messages", token=self.eve.token ), 404, "not_found", ) common.expect_error( self, common.request( "POST", "/api/v1/chats/" + chat_id + "/messages", body={"text": "чужое"}, token=self.eve.token, ), 404, "not_found", ) listed = common.request("GET", "/api/v1/chats?limit=100", token=self.eve.token) self.assertEqual(listed.status, 200) self.assertNotIn(chat_id, [item["id"] for item in listed.json["items"]]) def test_messages_are_validated_and_unicode_preserved(self) -> None: chat = common.create_chat(self.alice.token, [self.alice.id, self.bob.id]) for text in ("", " \n\t ", "x" * 4001): response = common.request( "POST", "/api/v1/chats/" + chat["id"] + "/messages", body={"text": text}, token=self.alice.token, ) common.expect_error(self, response, 400, "invalid_request") prefix = "Привет 👋 世界 " text = prefix + "x" * (4000 - len(prefix)) # exactly the contract maximum message = common.send(self.alice.token, chat["id"], text) self.assertEqual(message["text"], text) self.assertEqual(message["sender_id"], self.alice.id) injected = common.request( "POST", "/api/v1/chats/" + chat["id"] + "/messages", body={"text": "подмена", "sender_id": self.bob.id}, token=self.alice.token, ) common.expect_error(self, injected, 400, "invalid_request") class Pagination(Base): def test_walks_every_page_without_loss_or_duplicates(self) -> None: chat = common.create_chat(self.alice.token, [self.alice.id, self.bob.id]) sent = [ common.send(self.alice.token if index % 2 else self.bob.token, chat["id"], "msg-%d" % index) for index in range(7) ] collected: list[dict] = [] cursor = None pages = 0 while True: path = "/api/v1/chats/" + chat["id"] + "/messages?limit=2" if cursor is not None: path += "&cursor=" + cursor page = common.request("GET", path, token=self.alice.token) self.assertEqual(page.status, 200) collected.extend(page.json["items"]) pages += 1 cursor = page.json["next_cursor"] if cursor is None: break self.assertLess(pages, 10, "pagination did not terminate") self.assertEqual(pages, 4) self.assertEqual([item["id"] for item in collected], [item["id"] for item in sent]) self.assertEqual( collected, sorted(collected, key=lambda item: (timestamp(item["created_at"]), item["id"])), ) def test_cursor_is_bound_to_its_chat(self) -> None: other = common.create_chat(self.alice.token, [self.alice.id]) common.send(self.alice.token, other["id"], "a") common.send(self.alice.token, other["id"], "b") first = common.request( "GET", "/api/v1/chats/" + other["id"] + "/messages?limit=1", token=self.alice.token ) cursor = first.json["next_cursor"] self.assertIsNotNone(cursor) response = common.request( "GET", "/api/v1/chats/" + self.chat["id"] + "/messages" + "?limit=1&cursor=" + cursor, token=self.alice.token, ) common.expect_error(self, response, 400, "invalid_request") def test_limit_and_cursor_validation(self) -> None: base = "/api/v1/chats/" + self.chat["id"] + "/messages" for query in ("?limit=0", "?limit=101", "?limit=abc", "?cursor=", "?cursor=not-a-cursor", "?limit=1&limit=2", "?unknown=1"): common.expect_error( self, common.request("GET", base + query, token=self.alice.token), 400, "invalid_request", ) class Authentication(Base): def test_basic_is_not_accepted_outside_session_creation(self) -> None: response = common.request( "GET", "/api/v1/users/me", headers=common.basic(self.alice.username, self.alice.password) ) common.expect_error(self, response, 401, "unauthorized") self.assertTrue(response.header("WWW-Authenticate").lower().startswith("bearer")) def test_missing_and_unknown_tokens(self) -> None: for headers in ({}, {"Authorization": "Bearer not-a-real-token"}): response = common.request("GET", "/api/v1/users/me", headers=headers) common.expect_error(self, response, 401, "unauthorized") self.assertTrue(response.header("WWW-Authenticate").lower().startswith("bearer")) def test_x_user_id_is_ignored(self) -> None: response = common.request("GET", "/api/v1/users/me", headers={"X-User-Id": self.alice.id}) common.expect_error(self, response, 401, "unauthorized") overridden = common.request( "GET", "/api/v1/users/me", token=self.alice.token, headers={"X-User-Id": self.eve.id}, ) self.assertEqual(overridden.status, 200) self.assertEqual(overridden.json["id"], self.alice.id) def test_session_payload_and_expiry(self) -> None: response = common.login(self.alice.username, self.alice.password) self.assertEqual(response.status, 201) session = response.json self.assertEqual(set(session), {"token", "token_type", "expires_at", "user"}) self.assertEqual(session["token_type"], "Bearer") self.assertGreaterEqual(len(session["token"]), 43) self.assertNotIn(self.alice.username, session["token"]) self.assertNotEqual(session["token"], self.alice.id) self.assertEqual(session["user"], self.alice.user) self.assertGreater(timestamp(session["expires_at"]), datetime.now(timezone.utc)) me = common.request("GET", "/api/v1/users/me", token=session["token"]) self.assertEqual(me.status, 200) self.assertEqual(me.json, self.alice.user) def test_wrong_password_and_unknown_user_are_indistinguishable(self) -> None: wrong = common.login(self.alice.username, "definitely-wrong-password") unknown = common.login("nobody_here_" + uuid.uuid4().hex[:8], "definitely-wrong-password") messages = [] for response in (wrong, unknown): error = common.expect_error(self, response, 401, "unauthorized") self.assertTrue( response.header("WWW-Authenticate").lower().startswith("basic") ) messages.append(error["message"]) # Same message and challenge: a client cannot tell the accounts apart. self.assertEqual(messages[0], messages[1]) def test_logout_revokes_only_that_session(self) -> None: first = common.login(self.alice.username, self.alice.password).json["token"] second = common.login(self.alice.username, self.alice.password).json["token"] revoked = common.request("DELETE", "/api/v1/auth/sessions/current", token=first) self.assertEqual(revoked.status, 204) self.assertEqual(revoked.data, b"") common.expect_error( self, common.request("GET", "/api/v1/users/me", token=first), 401, "unauthorized", ) common.expect_error( self, common.request("DELETE", "/api/v1/auth/sessions/current", token=first), 401, "unauthorized", ) still_valid = common.request("GET", "/api/v1/users/me", token=second) self.assertEqual(still_valid.status, 200) def test_session_endpoint_rejects_json_body_and_bad_basic(self) -> None: response = common.request( "POST", "/api/v1/auth/sessions", body={"username": self.alice.username, "password": self.alice.password}, ) common.expect_error(self, response, 401, "unauthorized") response = common.request( "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic !!!not-base64!!!"} ) common.expect_error(self, response, 401, "unauthorized") self.assertTrue(response.header("WWW-Authenticate").lower().startswith("basic")) if __name__ == "__main__": unittest.main()