Add tests for various Connection edge cases.

This commit is contained in:
joo committed 2018-05-29 01:14:46 +01:00
1 parent d36b652b69
commit d36a4170ed
2 files changed
+216 -45

No files matched your search

+97 -44
View File
@@ -13,6 +13,7 @@ from minecraft.networking.encryption import (
from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
from future.utils import raise_ from future.utils import raise_
from numbers import Integral
import unittest import unittest
import threading import threading
import logging import logging
@@ -39,7 +40,7 @@ class FakeClientDisconnect(Exception):
class FakeServerDisconnect(Exception): class FakeServerDisconnect(Exception):
""" May be raised within 'FakeClientHandler.handle_*' in order to terminate """ May be raised within 'FakeClientHandler.handle_*' in order to terminate
the client's connection. 'message' is provided as an argument to the client's connection. 'message' is provided as an argument to
'handle_play_server_disconnect'. 'handle_play_server_disconnect' or 'handle_login_server_disconnect'.
""" """
def __init__(self, message=None): def __init__(self, message=None):
self.message = message self.message = message
@@ -78,6 +79,26 @@ class FakeClientHandler(object):
self.socket.close() self.socket.close()
self.socket_file.close() self.socket_file.close()
def handle_connection(self):
# Called in the handshake state, just after the client connects,
# before any packets have been exchanged.
pass
def handle_handshake(self, handshake_packet):
# Called in the handshake state, after receiving the client's
# Handshake packet, which is provided as an argument.
pass
def handle_login(self, join_game_packet):
# Called to transition from the login state to the play state, after
# compression and encryption, if applicable, have been set up. The
# client's LoginStartPacket is given as an argument.
self.user_name = join_game_packet.name
self.user_uuid = uuid.UUID(bytes=hashlib.md5(
('OfflinePlayer:%s' % self.user_name).encode('utf8')).digest())
self.write_packet(clientbound.login.LoginSuccessPacket(
UUID=str(self.user_uuid), Username=self.user_name))
def handle_play_start(self): def handle_play_start(self):
# Called upon entering the play state. # Called upon entering the play state.
self.write_packet(clientbound.play.JoinGamePacket( self.write_packet(clientbound.play.JoinGamePacket(
@@ -93,17 +114,45 @@ class FakeClientHandler(object):
'with': [self.username, packet.message], 'with': [self.username, packet.message],
}))) })))
def handle_play_client_disconnect(self): def handle_status(self, request_packet):
# Called when the client cleanly terminates the connection during play. # Called in the first phase of the status state, to send the Response
pass # packet. The client's Request packet is provided as an argument.
packet = clientbound.status.ResponsePacket()
packet.json_response = json.dumps({
'version': {
'name': self.server.minecraft_version,
'protocol': self.server.context.protocol_version},
'players': {
'max': 1,
'online': 0,
'sample': []},
'description': {
'text': 'FakeServer'}})
self.write_packet(packet)
def handle_play_server_disconnect(self, message=None): def handle_ping(self, ping_packet):
# Called when the server cleanly terminates the connection during play, # Called in the second phase of the status state, to respond to a Ping
# i.e. by raising FakeServerDisconnect from a handler. # packet, which is provided as an argument.
packet = clientbound.status.PingResponsePacket(time=ping_packet.time)
self.write_packet(packet)
def handle_login_server_disconnect(self, message):
# Called when the server cleanly terminates the connection during
# login, i.e. by raising FakeServerDisconnect from a handler.
message = 'Connection denied.' if message is None else message
self.write_packet(clientbound.login.DisconnectPacket(
json_data=json.dumps({'text': message})))
def handle_play_server_disconnect(self, message):
# As 'handle_login_server_disconnect', but for the play state.
message = 'Disconnected.' if message is None else message message = 'Disconnected.' if message is None else message
self.write_packet(clientbound.play.DisconnectPacket( self.write_packet(clientbound.play.DisconnectPacket(
json_data=json.dumps({'text': message}))) json_data=json.dumps({'text': message})))
def handle_play_client_disconnect(self):
# Called when the client cleanly terminates the connection during play.
pass
def write_packet(self, packet): def write_packet(self, packet):
# Send and log a clientbound packet. # Send and log a clientbound packet.
packet.context = self.server.context packet.context = self.server.context
@@ -128,30 +177,33 @@ class FakeClientHandler(object):
def _run_handshake(self): def _run_handshake(self):
# Enter the initial (i.e. handshaking) state of the connection. # Enter the initial (i.e. handshaking) state of the connection.
self.packets = self.server.packets_handshake self.packets = self.server.packets_handshake
try:
self.handle_connection()
packet = self.read_packet() packet = self.read_packet()
assert isinstance(packet, serverbound.handshake.HandShakePacket) assert isinstance(packet, serverbound.handshake.HandShakePacket)
self.handle_handshake(packet)
if packet.next_state == 1: if packet.next_state == 1:
self._run_status() self._run_status()
elif packet.next_state == 2: elif packet.next_state == 2:
self._run_handshake_play(packet) self._run_handshake_play(packet)
else: else:
raise AssertionError('Unknown state: %s' % packet.next_state) raise AssertionError('Unknown state: %s' % packet.next_state)
except FakeServerDisconnect:
pass
def _run_handshake_play(self, packet): def _run_handshake_play(self, packet):
# Prepare to transition from handshaking to play state (via login), # Prepare to transition from handshaking to play state (via login),
# using the given serverbound HandShakePacket to perform play-specific # using the given serverbound HandShakePacket to perform play-specific
# processing. # processing.
if packet.protocol_version == self.server.context.protocol_version: if packet.protocol_version == self.server.context.protocol_version:
self._run_login() return self._run_login()
else:
if packet.protocol_version < self.server.context.protocol_version: if packet.protocol_version < self.server.context.protocol_version:
msg = 'Outdated client! Please use %s' \ msg = 'Outdated client! Please use %s' \
% self.server.minecraft_version % self.server.minecraft_version
else: else:
msg = "Outdated server! I'm still on %s" \ msg = "Outdated server! I'm still on %s" \
% self.server.minecraft_version % self.server.minecraft_version
self.write_packet(clientbound.login.DisconnectPacket( self.handle_login_server_disconnect(msg)
json_data=json.dumps({'text': msg})))
def _run_login(self): def _run_login(self):
# Enter the login state of the connection. # Enter the login state of the connection.
@@ -167,12 +219,11 @@ class FakeClientHandler(object):
threshold=self.server.compression_threshold)) threshold=self.server.compression_threshold))
self.compression_enabled = True self.compression_enabled = True
self.user_name = packet.name try:
self.user_uuid = uuid.UUID(bytes=hashlib.md5( self.handle_login(packet)
('OfflinePlayer:%s' % self.user_name).encode('utf8')).digest()) except FakeServerDisconnect as e:
self.write_packet(clientbound.login.LoginSuccessPacket( self.handle_login_server_disconnect(message=e.message)
UUID=str(self.user_uuid), Username=self.user_name)) else:
self._run_playing() self._run_playing()
def _run_login_encryption(self): def _run_login_encryption(self):
@@ -216,28 +267,16 @@ class FakeClientHandler(object):
packet = self.read_packet() packet = self.read_packet()
assert isinstance(packet, serverbound.status.RequestPacket) assert isinstance(packet, serverbound.status.RequestPacket)
try:
packet = clientbound.status.ResponsePacket() self.handle_status(packet)
packet.json_response = json.dumps({
'version': {
'name': self.server.minecraft_version,
'protocol': self.server.context.protocol_version},
'players': {
'max': 1,
'online': 0,
'sample': []},
'description': {
'text': 'FakeServer'}})
self.write_packet(packet)
try: try:
packet = self.read_packet() packet = self.read_packet()
except FakeClientDisconnect: except FakeClientDisconnect:
return return
assert isinstance(packet, serverbound.status.PingPacket) assert isinstance(packet, serverbound.status.PingPacket)
self.write_packet(clientbound.status.PingResponsePacket( self.handle_ping(packet)
time=packet.time)) except FakeServerDisconnect as e:
pass
def _read_packet_buffer(self): def _read_packet_buffer(self):
# Read a serverbound packet in the form of a raw buffer, or raises # Read a serverbound packet in the form of a raw buffer, or raises
@@ -298,16 +337,22 @@ class FakeServer(object):
if minecraft_version is None: if minecraft_version is None:
minecraft_version = VERSIONS[-1][0] minecraft_version = VERSIONS[-1][0]
if isinstance(minecraft_version, Integral):
proto = minecraft_version
minecraft_version = 'FakeVersion%d' % proto
for ver, ver_proto in SUPPORTED_MINECRAFT_VERSIONS.items():
if ver_proto == proto:
minecraft_version = ver
else:
proto = SUPPORTED_MINECRAFT_VERSIONS[minecraft_version]
self.context = connection.ConnectionContext(protocol_version=proto)
self.minecraft_version = minecraft_version self.minecraft_version = minecraft_version
self.compression_threshold = compression_threshold self.compression_threshold = compression_threshold
self.client_handler_type = client_handler_type self.client_handler_type = client_handler_type
self.private_key = private_key self.private_key = private_key
self.public_key_bytes = public_key_bytes self.public_key_bytes = public_key_bytes
protocol_version = SUPPORTED_MINECRAFT_VERSIONS[minecraft_version]
self.context = connection.ConnectionContext(
protocol_version=protocol_version)
self.packets_handshake = { self.packets_handshake = {
p.get_id(self.context): p for p in p.get_id(self.context): p for p in
serverbound.handshake.get_packets(self.context)} serverbound.handshake.get_packets(self.context)}
@@ -385,6 +430,9 @@ class _FakeServerTest(unittest.TestCase):
client_handler_type = FakeClientHandler client_handler_type = FakeClientHandler
# A subclass of FakeClientHandler to be used in tests. # A subclass of FakeClientHandler to be used in tests.
connection_type = connection.Connection
# The constructor of the Connection instance to be used.
compression_threshold = None compression_threshold = None
# The compression threshold that the server will dictate. # The compression threshold that the server will dictate.
# If None, compression is disabled. # If None, compression is disabled.
@@ -416,20 +464,25 @@ class _FakeServerTest(unittest.TestCase):
client.connect() client.connect()
def _test_connect(self, client_versions=None, server_version=None, def _test_connect(self, client_versions=None, server_version=None,
client_handler_type=None, compression_threshold=None, client_handler_type=None, connection_type=None,
private_key=None, public_key_bytes=None): compression_threshold=None, private_key=None,
public_key_bytes=None, ignore_extra_exceptions=None):
if client_versions is None: if client_versions is None:
client_versions = self.client_versions client_versions = self.client_versions
if server_version is None: if server_version is None:
server_version = self.server_version server_version = self.server_version
if compression_threshold is None:
compression_threshold = self.compression_threshold
if client_handler_type is None: if client_handler_type is None:
client_handler_type = self.client_handler_type client_handler_type = self.client_handler_type
if connection_type is None:
connection_type = self.connection_type
if compression_threshold is None:
compression_threshold = self.compression_threshold
if private_key is None: if private_key is None:
private_key = self.private_key private_key = self.private_key
if public_key_bytes is None: if public_key_bytes is None:
public_key_bytes = self.public_key_bytes public_key_bytes = self.public_key_bytes
if ignore_extra_exceptions is None:
ignore_extra_exceptions = self.ignore_extra_exceptions
server = FakeServer(minecraft_version=server_version, server = FakeServer(minecraft_version=server_version,
compression_threshold=compression_threshold, compression_threshold=compression_threshold,
@@ -451,7 +504,7 @@ class _FakeServerTest(unittest.TestCase):
with cond: with cond:
cond.notify_all() cond.notify_all()
client = connection.Connection( client = connection_type(
addr, port, username='TestUser', allowed_versions=client_versions, addr, port, username='TestUser', allowed_versions=client_versions,
handle_exception=handle_client_exception) handle_exception=handle_client_exception)
client.register_packet_listener( client.register_packet_listener(
@@ -503,7 +556,7 @@ class _FakeServerTest(unittest.TestCase):
errors.insert(0, { errors.insert(0, {
'msg': 'Exception in %s:' % thread_name, 'msg': 'Exception in %s:' % thread_name,
'exc_info': exc_info}) 'exc_info': exc_info})
elif self.ignore_extra_exceptions: elif ignore_extra_exceptions:
del errors[:] del errors[:]
break break
if timeout: if timeout:
+119 -1
View File
@@ -1,6 +1,10 @@
from minecraft import SUPPORTED_MINECRAFT_VERSIONS from minecraft import SUPPORTED_MINECRAFT_VERSIONS
from minecraft import SUPPORTED_PROTOCOL_VERSIONS
from minecraft.networking.packets import clientbound, serverbound from minecraft.networking.packets import clientbound, serverbound
from minecraft.networking.connection import IgnorePacket from minecraft.networking.connection import Connection, IgnorePacket
from minecraft.exceptions import (
VersionMismatch, LoginDisconnect, InvalidState
)
from minecraft.compat import unicode from minecraft.compat import unicode
from . import fake_server from . import fake_server
@@ -98,6 +102,38 @@ class AllowedVersionsTest(fake_server._FakeServerTest):
server_version=version, client_versions=client_versions) server_version=version, client_versions=client_versions)
class LoginDisconnectTest(fake_server._FakeServerTest):
def test_login_disconnect(self):
with self.assertRaisesRegexp(LoginDisconnect, r'You are banned'):
self._test_connect()
class client_handler_type(fake_server.FakeClientHandler):
def handle_login(self, login_start_packet):
raise fake_server.FakeServerDisconnect('You are banned.')
class ConnectTwiceTest(fake_server._FakeServerTest):
def test_connect(self):
with self.assertRaisesRegexp(InvalidState, 'existing connection'):
self._test_connect()
class client_handler_type(fake_server.FakeClientHandler):
def handle_play_start(self):
super(ConnectTwiceTest.client_handler_type, self) \
.handle_play_start()
raise fake_server.FakeServerDisconnect('Test complete.')
def _start_client(self, client):
client.connect()
client.connect()
class ConnectStatusTest(ConnectTwiceTest):
def _start_client(self, client):
client.connect()
client.status()
class EarlyPacketListenerTest(ConnectTest): class EarlyPacketListenerTest(ConnectTest):
""" Early packet listeners should be called before ordinary ones, even when """ Early packet listeners should be called before ordinary ones, even when
the early packet listener is registered afterwards. the early packet listener is registered afterwards.
@@ -244,3 +280,85 @@ class HandleExceptionTest(ConnectTest):
client.handle_exception = handle_exception client.handle_exception = handle_exception
client.connect() client.connect()
class VersionNegotiationEdgeCases(fake_server._FakeServerTest):
lowest_version = min(SUPPORTED_PROTOCOL_VERSIONS)
highest_version = max(SUPPORTED_PROTOCOL_VERSIONS)
impossible_version = highest_version + 1
def test_client_protocol_unsupported(self):
self._test_client_protocol(version=self.impossible_version)
def test_client_protocol_unknown(self):
self._test_client_protocol(version='surprise me!')
def test_client_protocol_invalid(self):
self._test_client_protocol(version=object())
def _test_client_protocol(self, version):
with self.assertRaisesRegexp(ValueError, 'Unsupported version'):
self._test_connect(client_versions={version})
def test_server_protocol_unsupported(self, client_versions=None):
with self.assertRaisesRegexp(VersionMismatch, 'not supported'):
self._test_connect(client_versions=client_versions,
server_version=self.impossible_version)
def test_server_protocol_unsupported_direct(self):
self.test_server_protocol_unsupported({self.highest_version})
def test_server_protocol_disallowed(self, client_versions=None):
if client_versions is None:
client_versions = set(SUPPORTED_PROTOCOL_VERSIONS) \
- {self.highest_version}
with self.assertRaisesRegexp(VersionMismatch, 'not allowed'):
self._test_connect(client_versions={self.lowest_version},
server_version=self.highest_version)
def test_server_protocol_disallowed_direct(self):
self.test_server_protocol_disallowed({self.lowest_version})
def test_default_protocol_version(self, status_response=None):
if status_response is None:
status_response = '{"description": {"text": "FakeServer"}}'
class ClientHandler(fake_server.FakeClientHandler):
def _run_status(self):
packet = clientbound.status.ResponsePacket()
packet.json_response = status_response
self.write_packet(packet)
def handle_play_start(self):
super(ClientHandler, self).handle_play_start()
raise fake_server.FakeServerDisconnect('Test complete.')
def make_connection(*args, **kwds):
kwds['initial_version'] = self.lowest_version
return Connection(*args, **kwds)
self._test_connect(server_version=self.lowest_version,
client_handler_type=ClientHandler,
connection_type=make_connection)
def test_default_protocol_version_empty(self):
with self.assertRaisesRegexp(IOError, 'Invalid server status'):
self.test_default_protocol_version(status_response='{}')
def test_default_protocol_version_eof(self):
class ClientHandler(fake_server.FakeClientHandler):
def handle_status(self, request_packet):
raise fake_server.FakeServerDisconnect(
'Refusing to handle status request, for test purposes.')
def handle_play_start(self):
super(ClientHandler, self).handle_play_start()
raise fake_server.FakeServerDisconnect('Test complete.')
def make_connection(*args, **kwds):
kwds['initial_version'] = self.lowest_version
return Connection(*args, **kwds)
self._test_connect(server_version=self.lowest_version,
client_handler_type=ClientHandler,
connection_type=make_connection)