"""Test encryption logic.""" import time from unittest.mock import Mock import rsa from auth import config from auth.logic import encryption from auth.models import rsa_key def test_create_encryption_key(monkeypatch): """Test the creation of an encryption key.""" spy = Mock() def put_item(data): spy() return data monkeypatch.setattr(rsa_key.RsaKey.table.table, 'put_item', put_item) response = encryption.create() assert response.success assert response.public_key assert response.token assert not response.message.get('private_key') assert spy.called def test_decrypting_password_from_key(monkeypatch): """Test decrypting the password from a key. This part is a little more complex because we need to capture the data of the token that is being created (the private key is not returned by the create method for security reasons). """ response = encryption.create() # Create the password password = b'random-password' public_key = rsa.PublicKey.load_pkcs1_openssl_pem(response.public_key) encrypted_password = rsa.encrypt(password, public_key) assert not encrypted_password == password time.sleep(5) response = encryption.decode(response.token, encrypted_password) assert response.message == password def test_decrypting_password_from_key_expired_key(monkeypatch): """Test decrypting the password from an expired key.""" token = {} def put_item(data): token.update(data) return data monkeypatch.setattr(rsa_key.RsaKey.table.table, 'put_item', put_item) response = encryption.create() token.update(date=token.get('date') - (config.RSA_EXPIRATION * 2)) def get_item(**keys): if keys.get('token') == token.get('token'): return token monkeypatch.setattr( rsa_key.RsaKey.table.table, 'get_item', get_item) response = encryption.decode(response.token, b'someencrypted') assert not response.success assert response.errors.get('token')