Skip to content

move telegramdecryptionerror to error.py #2621

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

Merged
merged 2 commits into from
Aug 11, 2021
Merged
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
5 changes: 2 additions & 3 deletions telegram/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@
from .replykeyboardmarkup import ReplyKeyboardMarkup
from .replykeyboardremove import ReplyKeyboardRemove
from .forcereply import ForceReply
from .error import TelegramError
from .error import TelegramError, PassportDecryptionError
from .files.inputfile import InputFile
from .files.file import File
from .parsemode import ParseMode
Expand Down Expand Up @@ -159,7 +159,6 @@
SecureData,
SecureValue,
FileCredentials,
TelegramDecryptionError,
)
from .botcommandscope import (
BotCommandScope,
Expand Down Expand Up @@ -308,7 +307,7 @@
'Sticker',
'StickerSet',
'SuccessfulPayment',
'TelegramDecryptionError',
'PassportDecryptionError',
'TelegramError',
'TelegramObject',
'Update',
Expand Down
15 changes: 14 additions & 1 deletion telegram/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
# along with this program. If not, see [http://www.gnu.org/licenses/].
# pylint: disable=C0115
"""This module contains an object that represents Telegram errors."""
from typing import Tuple
from typing import Tuple, Union


def _lstrip_str(in_s: str, lstr: str) -> str:
Expand Down Expand Up @@ -149,3 +149,16 @@ class Conflict(TelegramError):

def __reduce__(self) -> Tuple[type, Tuple[str]]:
return self.__class__, (self.message,)


class PassportDecryptionError(TelegramError):
"""Something went wrong with decryption."""

__slots__ = ('_msg',)

def __init__(self, message: Union[str, Exception]):
super().__init__(f"PassportDecryptionError: {message}")
self._msg = str(message)

def __reduce__(self) -> Tuple[type, Tuple[str]]:
return self.__class__, (self._msg,)
27 changes: 7 additions & 20 deletions telegram/passport/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
import json # type: ignore[no-redef]

from base64 import b64decode
from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union, no_type_check
from typing import TYPE_CHECKING, Any, List, Optional, no_type_check

try:
from cryptography.hazmat.backends import default_backend
Expand All @@ -41,26 +41,13 @@

CRYPTO_INSTALLED = False

from telegram import TelegramError, TelegramObject
from telegram import TelegramObject, PassportDecryptionError
from telegram.utils.types import JSONDict

if TYPE_CHECKING:
from telegram import Bot


class TelegramDecryptionError(TelegramError):
"""Something went wrong with decryption."""

__slots__ = ('_msg',)

def __init__(self, message: Union[str, Exception]):
super().__init__(f"TelegramDecryptionError: {message}")
self._msg = str(message)

def __reduce__(self) -> Tuple[type, Tuple[str]]:
return self.__class__, (self._msg,)


@no_type_check
def decrypt(secret, hash, data):
"""
Expand All @@ -77,7 +64,7 @@ def decrypt(secret, hash, data):
b64decode it.

Raises:
:class:`TelegramDecryptionError`: Given hash does not match hash of decrypted data.
:class:`PassportDecryptionError`: Given hash does not match hash of decrypted data.

Returns:
:obj:`bytes`: The decrypted data as bytes.
Expand Down Expand Up @@ -105,7 +92,7 @@ def decrypt(secret, hash, data):
# If the newly calculated hash did not match the one telegram gave us
if data_hash != hash:
# Raise a error that is caught inside telegram.PassportData and transformed into a warning
raise TelegramDecryptionError(f"Hashes are not equal! {data_hash} != {hash}")
raise PassportDecryptionError(f"Hashes are not equal! {data_hash} != {hash}")
# Return data without padding
return data[data[0] :]

Expand Down Expand Up @@ -173,7 +160,7 @@ def decrypted_secret(self) -> str:
:obj:`str`: Lazily decrypt and return secret.

Raises:
telegram.TelegramDecryptionError: Decryption failed. Usually due to bad
telegram.PassportDecryptionError: Decryption failed. Usually due to bad
private/public key but can also suggest malformed/tampered data.
"""
if self._decrypted_secret is None:
Expand All @@ -195,7 +182,7 @@ def decrypted_secret(self) -> str:
)
except ValueError as exception:
# If decryption fails raise exception
raise TelegramDecryptionError(exception) from exception
raise PassportDecryptionError(exception) from exception
return self._decrypted_secret

@property
Expand All @@ -206,7 +193,7 @@ def decrypted_data(self) -> 'Credentials':
`decrypted_data.nonce`.

Raises:
telegram.TelegramDecryptionError: Decryption failed. Usually due to bad
telegram.PassportDecryptionError: Decryption failed. Usually due to bad
private/public key but can also suggest malformed/tampered data.
"""
if self._decrypted_data is None:
Expand Down
4 changes: 2 additions & 2 deletions telegram/passport/passportdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def decrypted_data(self) -> List[EncryptedPassportElement]:
about documents and other Telegram Passport elements which were shared with the bot.

Raises:
telegram.TelegramDecryptionError: Decryption failed. Usually due to bad
telegram.PassportDecryptionError: Decryption failed. Usually due to bad
private/public key but can also suggest malformed/tampered data.
"""
if self._decrypted_data is None:
Expand All @@ -115,7 +115,7 @@ def decrypted_credentials(self) -> 'Credentials':
`decrypted_data.payload`.

Raises:
telegram.TelegramDecryptionError: Decryption failed. Usually due to bad
telegram.PassportDecryptionError: Decryption failed. Usually due to bad
private/public key but can also suggest malformed/tampered data.
"""
return self.credentials.decrypted_data
6 changes: 3 additions & 3 deletions tests/test_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

import pytest

from telegram import TelegramError, TelegramDecryptionError
from telegram import TelegramError, PassportDecryptionError
from telegram.error import (
Unauthorized,
InvalidToken,
Expand Down Expand Up @@ -112,7 +112,7 @@ def test_conflict(self):
(ChatMigrated(1234), ["message", "new_chat_id"]),
(RetryAfter(12), ["message", "retry_after"]),
(Conflict("test message"), ["message"]),
(TelegramDecryptionError("test message"), ["message"]),
(PassportDecryptionError("test message"), ["message"]),
(InvalidCallbackData('test data'), ['callback_data']),
],
)
Expand Down Expand Up @@ -147,7 +147,7 @@ def make_assertion(cls):
ChatMigrated,
RetryAfter,
Conflict,
TelegramDecryptionError,
PassportDecryptionError,
InvalidCallbackData,
},
NetworkError: {BadRequest, TimedOut},
Expand Down
8 changes: 4 additions & 4 deletions tests/test_passport.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
PassportElementErrorSelfie,
PassportElementErrorDataField,
Credentials,
TelegramDecryptionError,
PassportDecryptionError,
)


Expand Down Expand Up @@ -412,20 +412,20 @@ def test_wrong_hash(self, bot):
data = deepcopy(RAW_PASSPORT_DATA)
data['credentials']['hash'] = 'bm90Y29ycmVjdGhhc2g=' # Not correct hash
passport_data = PassportData.de_json(data, bot=bot)
with pytest.raises(TelegramDecryptionError):
with pytest.raises(PassportDecryptionError):
assert passport_data.decrypted_data

def test_wrong_key(self, bot):
short_key = b"-----BEGIN RSA PRIVATE KEY-----\r\nMIIBOQIBAAJBAKU+OZ2jJm7sCA/ec4gngNZhXYPu+DZ/TAwSMl0W7vAPXAsLplBk\r\nO8l6IBHx8N0ZC4Bc65mO3b2G8YAzqndyqH8CAwEAAQJAWOx3jQFzeVXDsOaBPdAk\r\nYTncXVeIc6tlfUl9mOLyinSbRNCy1XicOiOZFgH1rRKOGIC1235QmqxFvdecySoY\r\nwQIhAOFeGgeX9CrEPuSsd9+kqUcA2avCwqdQgSdy2qggRFyJAiEAu7QHT8JQSkHU\r\nDELfzrzc24AhjyG0z1DpGZArM8COascCIDK42SboXj3Z2UXiQ0CEcMzYNiVgOisq\r\nBUd5pBi+2mPxAiAM5Z7G/Sv1HjbKrOGh29o0/sXPhtpckEuj5QMC6E0gywIgFY6S\r\nNjwrAA+cMmsgY0O2fAzEKkDc5YiFsiXaGaSS4eA=\r\n-----END RSA PRIVATE KEY-----"
b = Bot(bot.token, private_key=short_key)
passport_data = PassportData.de_json(RAW_PASSPORT_DATA, bot=b)
with pytest.raises(TelegramDecryptionError):
with pytest.raises(PassportDecryptionError):
assert passport_data.decrypted_data

wrong_key = b"-----BEGIN RSA PRIVATE KEY-----\r\nMIIEogIBAAKCAQB4qCFltuvHakZze86TUweU7E/SB3VLGEHAe7GJlBmrou9SSWsL\r\nH7E++157X6UqWFl54LOE9M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t/8AUeKBz7PtCU+38roI/vXF0MBVmGky+HwxREQLpcdl1TVCERpIT\r\nUFXThI9OLUwOGI1IcTZf9tby+1LtKvM++8n4wGdjp9qAv6ylQV9u09pAzZItMwCd\r\nUx5SL6wlaQ2y60tIKk0lfQKBgBJS+56YmA6JGzY11qz+I5FUhfcnpauDNGOTdGLT\r\n9IqRPR2fu7RCdgpva4+KkZHLOTLReoRNUojRPb4WubGfEk93AJju5pWXR7c6k3Bt\r\novS2mrJk8GQLvXVksQxjDxBH44sLDkKMEM3j7uYJqDaZNKbyoCWT7TCwikAau5qx\r\naRevAoGAAKZV705dvrpJuyoHFZ66luANlrAwG/vNf6Q4mBEXB7guqMkokCsSkjqR\r\nhsD79E6q06zA0QzkLCavbCn5kMmDS/AbA80+B7El92iIN6d3jRdiNZiewkhlWhEG\r\nm4N0gQRfIu+rUjsS/4xk8UuQUT/Ossjn/hExi7ejpKdCc7N++bc=\r\n-----END RSA PRIVATE KEY-----"
b = Bot(bot.token, private_key=wrong_key)
passport_data = PassportData.de_json(RAW_PASSPORT_DATA, bot=b)
with pytest.raises(TelegramDecryptionError):
with pytest.raises(PassportDecryptionError):
assert passport_data.decrypted_data

def test_mocked_download_passport_file(self, passport_data, monkeypatch):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_slots.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
'DispatcherHandlerStop',
'Days',
'telegram.deprecate',
'TelegramDecryptionError',
'PassportDecryptionError',
'ContextTypes',
'CallbackDataCache',
'InvalidCallbackData',
Expand Down