mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2025-01-18 15:20:42 +01:00
Move and Rename TelegramDecryptionError to telegram.error.PassportDecryptionError (#2621)
This commit is contained in:
parent
92cb6f3ae8
commit
4a329aa4da
7 changed files with 33 additions and 34 deletions
|
@ -57,7 +57,7 @@ from .replymarkup import ReplyMarkup
|
|||
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
|
||||
|
@ -160,7 +160,6 @@ from .passport.credentials import (
|
|||
SecureData,
|
||||
SecureValue,
|
||||
FileCredentials,
|
||||
TelegramDecryptionError,
|
||||
)
|
||||
from .botcommandscope import (
|
||||
BotCommandScope,
|
||||
|
@ -310,7 +309,7 @@ __all__ = ( # Keep this alphabetically ordered
|
|||
'Sticker',
|
||||
'StickerSet',
|
||||
'SuccessfulPayment',
|
||||
'TelegramDecryptionError',
|
||||
'PassportDecryptionError',
|
||||
'TelegramError',
|
||||
'TelegramObject',
|
||||
'Update',
|
||||
|
|
|
@ -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:
|
||||
|
@ -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,)
|
||||
|
|
|
@ -23,7 +23,7 @@ except ImportError:
|
|||
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
|
||||
|
@ -41,26 +41,13 @@ except ImportError:
|
|||
|
||||
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):
|
||||
"""
|
||||
|
@ -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.
|
||||
|
@ -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] :]
|
||||
|
||||
|
@ -173,7 +160,7 @@ class EncryptedCredentials(TelegramObject):
|
|||
: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:
|
||||
|
@ -195,7 +182,7 @@ class EncryptedCredentials(TelegramObject):
|
|||
)
|
||||
except ValueError as exception:
|
||||
# If decryption fails raise exception
|
||||
raise TelegramDecryptionError(exception) from exception
|
||||
raise PassportDecryptionError(exception) from exception
|
||||
return self._decrypted_secret
|
||||
|
||||
@property
|
||||
|
@ -206,7 +193,7 @@ class EncryptedCredentials(TelegramObject):
|
|||
`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:
|
||||
|
|
|
@ -95,7 +95,7 @@ class PassportData(TelegramObject):
|
|||
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:
|
||||
|
@ -115,7 +115,7 @@ class PassportData(TelegramObject):
|
|||
`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
|
||||
|
|
|
@ -21,7 +21,7 @@ from collections import defaultdict
|
|||
|
||||
import pytest
|
||||
|
||||
from telegram import TelegramError, TelegramDecryptionError
|
||||
from telegram import TelegramError, PassportDecryptionError
|
||||
from telegram.error import (
|
||||
Unauthorized,
|
||||
InvalidToken,
|
||||
|
@ -112,7 +112,7 @@ class TestErrors:
|
|||
(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']),
|
||||
],
|
||||
)
|
||||
|
@ -147,7 +147,7 @@ class TestErrors:
|
|||
ChatMigrated,
|
||||
RetryAfter,
|
||||
Conflict,
|
||||
TelegramDecryptionError,
|
||||
PassportDecryptionError,
|
||||
InvalidCallbackData,
|
||||
},
|
||||
NetworkError: {BadRequest, TimedOut},
|
||||
|
|
|
@ -28,7 +28,7 @@ from telegram import (
|
|||
PassportElementErrorSelfie,
|
||||
PassportElementErrorDataField,
|
||||
Credentials,
|
||||
TelegramDecryptionError,
|
||||
PassportDecryptionError,
|
||||
)
|
||||
|
||||
|
||||
|
@ -412,20 +412,20 @@ class TestPassport:
|
|||
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++157X6UqWFl54LOE9MeHZnoW7rZ+DxLKhk6NwAHTxXPnvw4CZlvUPC3OFxg3\r\nhEmNen6ojSM4sl4kYUIa7F+Q5uMEYaboxoBen9mbj4zzMGsG4aY/xBOb2ewrXQyL\r\nRh//tk1Px4ago+lUPisAvQVecz7/6KU4Xj4Lpv2z20f3cHlZX6bb7HlE1vixCMOf\r\nxvfC5SkWEGZMR/ZoWQUsoDkrDSITF/S3GtLfg083TgtCKaOF3mCT27sJ1og77npP\r\n0cH/qdlbdoFtdrRj3PvBpaj/TtXRhmdGcJBxAgMBAAECggEAYSq1Sp6XHo8dkV8B\r\nK2/QSURNu8y5zvIH8aUrgqo8Shb7OH9bryekrB3vJtgNwR5JYHdu2wHttcL3S4SO\r\nftJQxbyHgmxAjHUVNGqOM6yPA0o7cR70J7FnMoKVgdO3q68pVY7ll50IET9/T0X9\r\nD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Iu+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):
|
||||
|
|
|
@ -30,7 +30,7 @@ excluded = {
|
|||
'DispatcherHandlerStop',
|
||||
'Days',
|
||||
'telegram.deprecate',
|
||||
'TelegramDecryptionError',
|
||||
'PassportDecryptionError',
|
||||
'ContextTypes',
|
||||
'CallbackDataCache',
|
||||
'InvalidCallbackData',
|
||||
|
|
Loading…
Reference in a new issue