Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue/#444 localize authentication_failed message #505

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 17 additions & 42 deletions server/lobbyconnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ def __init__(self, message, recoverable=True, *args, **kwargs):


class AuthenticationError(Exception):
def __init__(self, message, *args, **kwargs):
super().__init__(*args, **kwargs)
self.message = message
def __init__(self, context, **attrs):
self.context = context
self.attrs = attrs


@with_logger
Expand Down Expand Up @@ -158,7 +158,8 @@ async def on_message_received(self, message):
except AuthenticationError as ex:
await self.send({
'command': 'authentication_failed',
'text': ex.message
'context': ex.context,
**ex.attrs
})
except ClientError as ex:
self._logger.warning("Client error: %s", ex.message)
Expand Down Expand Up @@ -391,11 +392,10 @@ async def check_user_login(self, conn, username, password):
.order_by(lobby_ban.c.expires_at.desc())
)

auth_error_message = "Login not found or password incorrect. They are case sensitive."
row = await result.fetchone()
if not row:
metrics.user_logins.labels("failure").inc()
raise AuthenticationError(auth_error_message)
raise AuthenticationError("denied")

player_id = row[t_login.c.id]
real_username = row[t_login.c.login]
Expand All @@ -407,7 +407,7 @@ async def check_user_login(self, conn, username, password):

if dbPassword != password:
metrics.user_logins.labels("failure").inc()
raise AuthenticationError(auth_error_message)
raise AuthenticationError("denied")

now = datetime.now()
if ban_reason is not None and now < ban_expiry:
Expand All @@ -420,9 +420,7 @@ async def check_user_login(self, conn, username, password):

if config.FORCE_STEAM_LINK and not steamid and create_time.timestamp() > config.FORCE_STEAM_LINK_AFTER_DATE:
self._logger.debug('Rejected login from new user: %s, %s, %s', player_id, username, self.session)
raise ClientError(
"Unfortunately, you must currently link your account to Steam in order to play Forged Alliance Forever. You can do so on <a href='{steamlink_url}'>{steamlink_url}</a>.".format(steamlink_url=config.WWW_URL + '/account/link'),
recoverable=False)
raise AuthenticationError("steam_link")

self._logger.debug("Login from: %s, %s, %s", player_id, username, self.session)

Expand Down Expand Up @@ -497,39 +495,16 @@ async def check_policy_conformity(self, player_id, uid_hash, session, ignore_res
if ignore_result:
return True

if response.get('result', '') == 'vm':
self._logger.debug("Using VM: %d: %s", player_id, uid_hash)
await self.send({
"command": "notice",
"style": "error",
"text": (
"You need to link your account to Steam in order to use "
"FAF in a virtual machine. Please contact an admin or "
"moderator on the forums if you feel this is a false "
"positive."
)
})
await self.send_warning("Your computer seems to be a virtual machine.<br><br>In order to "
"log in from a VM, you have to link your account to Steam: <a href='" +
config.WWW_URL + "/account/link'>" +
config.WWW_URL + "/account/link</a>.<br>If you need an exception, please contact an "
"admin or moderator on the forums", fatal=True)
result = response.get('result', '')

if response.get('result', '') == 'already_associated':
if result == 'vm':
self._logger.debug("Using VM: %d: %s", player_id, uid_hash)
raise AuthenticationError("policy", result=result)
elif result == 'already_associated':
self._logger.warning("UID hit: %d: %s", player_id, uid_hash)
await self.send_warning("Your computer is already associated with another FAF account.<br><br>In order to "
"log in with an additional account, you have to link it to Steam: <a href='" +
config.WWW_URL + "/account/link'>" +
config.WWW_URL + "/account/link</a>.<br>If you need an exception, please contact an "
"admin or moderator on the forums", fatal=True)
return False

if response.get('result', '') == 'fraudulent':
raise AuthenticationError("policy", result=result)
elif result == 'fraudulent':
self._logger.info("Banning player %s for fraudulent looking login.", player_id)
await self.send_warning("Fraudulent login attempt detected. As a precautionary measure, your account has been "
"banned permanently. Please contact an admin or moderator on the forums if you feel this is "
"a false positive.",
fatal=True)

async with self._db.acquire() as conn:
try:
Expand All @@ -539,9 +514,9 @@ async def check_policy_conformity(self, player_id, uid_hash, session, ignore_res
except pymysql.MySQLError as e:
raise ClientError('Banning failed: {}'.format(e))

return False
raise AuthenticationError("policy", result=result)

return response.get('result', '') == 'honest'
return result == 'honest'

async def command_hello(self, message):
login = message['login'].strip()
Expand Down
22 changes: 21 additions & 1 deletion tests/integration_tests/test_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ async def test_server_invalid_login(lobby_server):
await perform_login(proto, ('Cat', 'epic'))
auth_failed_msg = {
'command': 'authentication_failed',
'text': 'Login not found or password incorrect. They are case sensitive.'
'context': 'denied'
}
msg = await proto.read_message()
assert msg == auth_failed_msg
Expand All @@ -27,6 +27,26 @@ async def test_server_invalid_login(lobby_server):
proto.close()


@pytest.mark.parametrize("user", [
("test", "test_password"),
("Rhiza", "puff_the_magic_dragon"),
("ban_revoked", "ban_revoked")
])
async def test_server_steam_link(lobby_server, mocker, user):
mocker.patch("server.lobbyconnection.config.FORCE_STEAM_LINK", True)
mocker.patch("server.lobbyconnection.config.FORCE_STEAM_LINK_AFTER_DATE", 0)

proto = await connect_client(lobby_server)

await perform_login(proto, user)
auth_failed_msg = {
'command': 'authentication_failed',
'context': 'steam_link'
}
msg = await proto.read_message()
assert msg == auth_failed_msg


@pytest.mark.parametrize("user", [
("Dostya", "vodka"),
("ban_long_time", "ban_long_time")
Expand Down
25 changes: 11 additions & 14 deletions tests/unit_tests/test_lobbyconnection.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@
from server.geoip_service import GeoIpService
from server.ice_servers.nts import TwilioNTS
from server.ladder_service import LadderService
from server.lobbyconnection import ClientError, LobbyConnection
from server.lobbyconnection import (
AuthenticationError, ClientError, LobbyConnection
)
from server.player_service import PlayerService
from server.players import Player, PlayerState
from server.protocol import DisconnectedError, QDataStreamProtocol
Expand Down Expand Up @@ -999,8 +1001,8 @@ async def test_check_policy_conformity(lobbyconnection, policy_server):
'server.lobbyconnection.FAF_POLICY_SERVER_BASE_URL',
f'http://{host}:{port}'
):
honest = await lobbyconnection.check_policy_conformity(1, "honest", session=100)
assert honest is True
# Should not raise an exception
await lobbyconnection.check_policy_conformity(1, "honest", session=100)


async def test_check_policy_conformity_fraudulent(lobbyconnection, policy_server, database):
Expand All @@ -1010,15 +1012,12 @@ async def test_check_policy_conformity_fraudulent(lobbyconnection, policy_server
f'http://{host}:{port}'
):
# 42 is not a valid player ID which should cause a SQL constraint error
lobbyconnection.abort = CoroutineMock()
with pytest.raises(ClientError):
await lobbyconnection.check_policy_conformity(42, "fraudulent", session=100)

lobbyconnection.abort = CoroutineMock()
player_id = 200
honest = await lobbyconnection.check_policy_conformity(player_id, "fraudulent", session=100)
assert honest is False
lobbyconnection.abort.assert_called_once()
with pytest.raises(AuthenticationError):
await lobbyconnection.check_policy_conformity(player_id, "fraudulent", session=100)

# Check that the user has a ban entry in the database
async with database.acquire() as conn:
Expand All @@ -1030,14 +1029,12 @@ async def test_check_policy_conformity_fraudulent(lobbyconnection, policy_server
assert rows[-1][ban.c.reason] == "Auto-banned because of fraudulent login attempt"


async def test_check_policy_conformity_fatal(lobbyconnection, policy_server):
@pytest.mark.parametrize("result", ('vm', 'already_associated', 'fraudulent'))
async def test_check_policy_conformity_fatal(lobbyconnection, policy_server, result):
host, port = policy_server
with mock.patch(
'server.lobbyconnection.FAF_POLICY_SERVER_BASE_URL',
f'http://{host}:{port}'
):
for result in ('vm', 'already_associated', 'fraudulent'):
lobbyconnection.abort = CoroutineMock()
honest = await lobbyconnection.check_policy_conformity(1, result, session=100)
assert honest is False
lobbyconnection.abort.assert_called_once()
with pytest.raises(AuthenticationError):
await lobbyconnection.check_policy_conformity(1, result, session=100)