File: test_password.py

package info (click to toggle)
python-sqlalchemy-utils 0.41.2-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 1,252 kB
  • sloc: python: 13,566; makefile: 141
file content (279 lines) | stat: -rw-r--r-- 7,825 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import unittest.mock as mock

import pytest
import sqlalchemy as sa
import sqlalchemy.dialects.mysql
import sqlalchemy.dialects.oracle
import sqlalchemy.dialects.postgresql
import sqlalchemy.dialects.sqlite
from sqlalchemy import inspect

from sqlalchemy_utils import Password, PasswordType, types  # noqa
from sqlalchemy_utils.compat import _select_args


@pytest.fixture
def extra_kwargs():
    """PasswordType extra keyword arguments."""
    return {}


@pytest.fixture
def User(Base, extra_kwargs):
    class User(Base):
        __tablename__ = 'user'
        id = sa.Column(sa.Integer, primary_key=True)
        password = sa.Column(PasswordType(
            schemes=[
                'pbkdf2_sha512',
                'pbkdf2_sha256',
                'md5_crypt',
                'hex_md5'
            ],
            deprecated=['md5_crypt', 'hex_md5'],
            **extra_kwargs
        ))

        def __repr__(self):
            return 'User(%r)' % self.id
    return User


@pytest.fixture
def init_models(User):
    pass


def onload_callback(schemes, deprecated):
    """
    Get onload callback that takes the PasswordType arguments from the config.
    """
    def onload(**kwargs):
        kwargs['schemes'] = schemes
        kwargs['deprecated'] = deprecated
        return kwargs
    return onload


@pytest.mark.skipif('types.password.passlib is None')
class TestPasswordType:
    @pytest.mark.parametrize('dialect_module,impl', [
        (sqlalchemy.dialects.sqlite, sa.dialects.sqlite.BLOB),
        (sqlalchemy.dialects.postgresql, sa.dialects.postgresql.BYTEA),
        (sqlalchemy.dialects.oracle, sa.dialects.oracle.RAW),
        (sqlalchemy.dialects.mysql, sa.VARBINARY),
    ])
    def test_load_dialect_impl(self, dialect_module, impl):
        """
        Should produce the same impl type as Alembic would expect after
        inspecing a database
        """
        password_type = PasswordType()
        assert isinstance(
            password_type.load_dialect_impl(dialect_module.dialect()),
            impl
        )

    def test_encrypt(self, User):
        """Should encrypt the password on setting the attribute."""
        obj = User()
        obj.password = b'b'

        assert obj.password.hash != 'b'
        assert obj.password.hash.startswith(b'$pbkdf2-sha512$')

    def test_check(self, session, User):
        """
        Should be able to compare the plaintext against the
        encrypted form.
        """
        obj = User()
        obj.password = 'b'

        assert obj.password == 'b'
        assert obj.password != 'a'

        session.add(obj)
        session.commit()

        try:
            obj = session.get(User, obj.id)
        except AttributeError:
            # sqlalchemy 1.3
            obj = session.query(User).get(obj.id)

        assert obj.password == b'b'
        assert obj.password != 'a'

    def test_check_and_update(self, User):
        """
        Should be able to compare the plaintext against a deprecated
        encrypted form and have it auto-update to the preferred version.
        """

        from passlib.hash import md5_crypt

        obj = User()
        obj.password = Password(md5_crypt.hash('b'))

        assert obj.password.hash.decode('utf8').startswith('$1$')
        assert obj.password == 'b'
        assert obj.password.hash.decode('utf8').startswith('$pbkdf2-sha512$')

    def test_auto_column_length(self, User):
        """Should derive the correct column length from the specified schemes.
        """

        from passlib.hash import pbkdf2_sha512

        kind = inspect(User).c.password.type

        # name + rounds + salt + hash + ($ * 4) of largest hash
        expected_length = len(pbkdf2_sha512.name)
        expected_length += len(str(pbkdf2_sha512.max_rounds))
        expected_length += pbkdf2_sha512.max_salt_size
        expected_length += pbkdf2_sha512.encoded_checksum_size
        expected_length += 4

        assert kind.length == expected_length

    def test_without_schemes(self):
        assert PasswordType(schemes=[]).length == 1024

    def test_compare(self, User):
        from passlib.hash import md5_crypt

        obj = User()
        obj.password = Password(md5_crypt.hash('b'))

        other = User()
        other.password = Password(md5_crypt.hash('b'))

        # Not sure what to assert here; the test raised an error before.
        assert obj.password != other.password

    def test_set_none(self, session, User):

        obj = User()
        obj.password = None

        assert obj.password is None

        session.add(obj)
        session.commit()

        try:
            obj = session.get(User, obj.id)
        except AttributeError:
            # sqlalchemy 1.3
            obj = session.query(User).get(obj.id)

        assert obj.password is None

    def test_update_none(self, session, User):
        """
        Should be able to change a password from ``None`` to a valid
        password.
        """

        obj = User()
        obj.password = None

        session.add(obj)
        session.commit()

        try:
            obj = session.get(User, obj.id)
        except AttributeError:
            # sqlalchemy 1.3
            obj = session.query(User).get(obj.id)
        obj.password = 'b'

        session.commit()

    def test_compare_none(self, User):
        """
        Should be able to compare a password of ``None``.
        """

        obj = User()
        obj.password = None

        assert obj.password is None
        assert obj.password == None  # noqa

        obj.password = 'b'

        assert obj.password is not None
        assert obj.password != None  # noqa

    def test_check_and_update_persist(self, session, User):
        """
        When a password is compared, the hash should update if needed to
        change the algorithm; and, commit to the database.
        """

        from passlib.hash import md5_crypt

        obj = User()
        obj.password = Password(md5_crypt.hash('b'))

        session.add(obj)
        session.commit()

        assert obj.password.hash.decode('utf8').startswith('$1$')
        assert obj.password == 'b'

        session.commit()

        try:
            obj = session.get(User, obj.id)
        except AttributeError:
            # sqlalchemy 1.3
            obj = session.query(User).get(obj.id)

        assert obj.password.hash.decode('utf8').startswith('$pbkdf2-sha512$')
        assert obj.password == 'b'

    @pytest.mark.parametrize(
        'extra_kwargs',
        [
            dict(
                onload=onload_callback(
                    schemes=['pbkdf2_sha256'],
                    deprecated=[],
                )
            )
        ]
    )
    def test_lazy_configuration(self, User):
        """
        Field should be able to read the passlib attributes lazily from the
        config (e.g. Flask config).
        """
        schemes = User.password.type.context.schemes()
        assert tuple(schemes) == ('pbkdf2_sha256',)
        obj = User()
        obj.password = b'b'
        assert obj.password.hash.decode('utf8').startswith('$pbkdf2-sha256$')

    @pytest.mark.parametrize('max_length', [1, 103])
    def test_constant_length(self, max_length):
        """
        Test that constant max_length is applied.
        """
        typ = PasswordType(max_length=max_length)
        assert typ.length == max_length

    def test_context_is_lazy(self):
        """
        Make sure the init doesn't evaluate the lazy context.
        """
        onload = mock.Mock(return_value={})
        PasswordType(onload=onload)
        assert not onload.called

    def test_compilation(self, User, session):
        query = sa.select(*_select_args(User.password))
        # the type should be cacheable and not throw exception
        session.execute(query)