File: test_credentials.py

package info (click to toggle)
python-redis 6.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 9,432 kB
  • sloc: python: 60,318; sh: 179; makefile: 128
file content (679 lines) | stat: -rw-r--r-- 22,851 bytes parent folder | download
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
import functools
import random
import string
import threading
from time import sleep
from typing import Optional, Tuple, Union

import pytest
import redis
from mock.mock import Mock, call
from redis import AuthenticationError, DataError, Redis, ResponseError
from redis.auth.err import RequestTokenErr
from redis.backoff import NoBackoff
from redis.connection import ConnectionInterface, ConnectionPool
from redis.credentials import CredentialProvider, UsernamePasswordCredentialProvider
from redis.exceptions import ConnectionError, RedisError
from redis.retry import Retry
from redis.utils import str_if_bytes
from tests.conftest import (
    _get_client,
    get_credential_provider,
    get_endpoint,
    skip_if_redis_enterprise,
)
from enum import Enum
class AuthType(Enum):
    MANAGED_IDENTITY = "managed_identity"
    SERVICE_PRINCIPAL = "service_principal"
    DEFAULT_AZURE_CREDENTIAL = "default_azure_credential"

try:
    from redis_entraid.cred_provider import EntraIdCredentialsProvider
except ImportError:
    EntraIdCredentialsProvider = None


@pytest.fixture()
def endpoint(request):
    endpoint_name = request.config.getoption("--endpoint-name")

    try:
        return get_endpoint(endpoint_name)
    except FileNotFoundError as e:
        pytest.skip(
            f"Skipping scenario test because endpoints file is missing: {str(e)}"
        )


@pytest.fixture()
def r_entra(request, endpoint):
    credential_provider = request.param.get("cred_provider_class", None)
    single_connection = request.param.get("single_connection_client", False)

    if credential_provider is not None:
        credential_provider = get_credential_provider(request)

    with _get_client(
        redis.Redis,
        request,
        credential_provider=credential_provider,
        single_connection_client=single_connection,
        from_url=endpoint,
    ) as client:
        yield client


class NoPassCredProvider(CredentialProvider):
    def get_credentials(self) -> Union[Tuple[str], Tuple[str, str]]:
        return "username", ""


class RandomAuthCredProvider(CredentialProvider):
    def __init__(self, user: Optional[str], endpoint: str):
        self.user = user
        self.endpoint = endpoint

    @functools.lru_cache(maxsize=10)
    def get_credentials(self) -> Union[Tuple[str, str], Tuple[str]]:
        def get_random_string(length):
            letters = string.ascii_lowercase
            result_str = "".join(random.choice(letters) for i in range(length))
            return result_str

        if self.user:
            auth_token: str = get_random_string(5) + self.user + "_" + self.endpoint
            return self.user, auth_token
        else:
            auth_token: str = get_random_string(5) + self.endpoint
            return (auth_token,)


def init_acl_user(r, request, username, password):
    # reset the user
    r.acl_deluser(username)
    if password:
        assert (
            r.acl_setuser(
                username,
                enabled=True,
                passwords=["+" + password],
                keys="~*",
                commands=[
                    "+ping",
                    "+command",
                    "+info",
                    "+select",
                    "+flushdb",
                    "+cluster",
                ],
            )
            is True
        )
    else:
        assert (
            r.acl_setuser(
                username,
                enabled=True,
                keys="~*",
                commands=[
                    "+ping",
                    "+command",
                    "+info",
                    "+select",
                    "+flushdb",
                    "+cluster",
                ],
                nopass=True,
            )
            is True
        )

    if request is not None:

        def teardown():
            r.acl_deluser(username)

        request.addfinalizer(teardown)


def init_required_pass(r, request, password):
    r.config_set("requirepass", password)

    def teardown():
        try:
            r.auth(password)
        except (ResponseError, AuthenticationError):
            r.auth("default", "")
        r.config_set("requirepass", "")

    request.addfinalizer(teardown)


class TestCredentialsProvider:
    @skip_if_redis_enterprise()
    def test_only_pass_without_creds_provider(self, r, request):
        # test for default user (`username` is supposed to be optional)
        password = "password"
        init_required_pass(r, request, password)
        assert r.auth(password) is True

        r2 = _get_client(redis.Redis, request, flushdb=False, password=password)

        assert r2.ping() is True

    @skip_if_redis_enterprise()
    def test_user_and_pass_without_creds_provider(self, r, request):
        """
        Test backward compatibility with username and password
        """
        # test for other users
        username = "username"
        password = "password"

        init_acl_user(r, request, username, password)
        r2 = _get_client(
            redis.Redis, request, flushdb=False, username=username, password=password
        )

        assert r2.ping() is True

    @pytest.mark.parametrize("username", ["username", None])
    @skip_if_redis_enterprise()
    @pytest.mark.onlynoncluster
    def test_credential_provider_with_supplier(self, r, request, username):
        creds_provider = RandomAuthCredProvider(
            user=username,
            endpoint="localhost",
        )

        password = creds_provider.get_credentials()[-1]

        if username:
            init_acl_user(r, request, username, password)
        else:
            init_required_pass(r, request, password)

        r2 = _get_client(
            redis.Redis, request, flushdb=False, credential_provider=creds_provider
        )

        assert r2.ping() is True

    def test_credential_provider_no_password_success(self, r, request):
        init_acl_user(r, request, "username", "")
        r2 = _get_client(
            redis.Redis,
            request,
            flushdb=False,
            credential_provider=NoPassCredProvider(),
        )
        assert r2.ping() is True

    @pytest.mark.onlynoncluster
    def test_credential_provider_no_password_error(self, r, request):
        init_acl_user(r, request, "username", "password")
        with pytest.raises(AuthenticationError) as e:
            _get_client(
                redis.Redis,
                request,
                flushdb=False,
                credential_provider=NoPassCredProvider(),
            )
        assert e.match("invalid username-password")

    @pytest.mark.onlynoncluster
    def test_password_and_username_together_with_cred_provider_raise_error(
        self, r, request
    ):
        init_acl_user(r, request, "username", "password")
        cred_provider = UsernamePasswordCredentialProvider(
            username="username", password="password"
        )
        with pytest.raises(DataError) as e:
            _get_client(
                redis.Redis,
                request,
                flushdb=False,
                username="username",
                password="password",
                credential_provider=cred_provider,
            )
        assert e.match(
            "'username' and 'password' cannot be passed along with "
            "'credential_provider'."
        )

    @pytest.mark.onlynoncluster
    def test_change_username_password_on_existing_connection(self, r, request):
        username = "origin_username"
        password = "origin_password"
        new_username = "new_username"
        new_password = "new_password"

        def teardown():
            r.acl_deluser(new_username)

        request.addfinalizer(teardown)

        init_acl_user(r, request, username, password)
        r2 = _get_client(
            redis.Redis, request, flushdb=False, username=username, password=password
        )
        assert r2.ping() is True
        conn = r2.connection_pool.get_connection()
        conn.send_command("PING")
        assert str_if_bytes(conn.read_response()) == "PONG"
        assert conn.username == username
        assert conn.password == password
        init_acl_user(r, request, new_username, new_password)
        conn.password = new_password
        conn.username = new_username
        conn.send_command("PING")
        assert str_if_bytes(conn.read_response()) == "PONG"


class TestUsernamePasswordCredentialProvider:
    def test_user_pass_credential_provider_acl_user_and_pass(self, r, request):
        username = "username"
        password = "password"
        provider = UsernamePasswordCredentialProvider(username, password)
        assert provider.username == username
        assert provider.password == password
        assert provider.get_credentials() == (username, password)
        init_acl_user(r, request, provider.username, provider.password)
        r2 = _get_client(
            redis.Redis, request, flushdb=False, credential_provider=provider
        )
        assert r2.ping() is True

    def test_user_pass_provider_only_password(self, r, request):
        password = "password"
        provider = UsernamePasswordCredentialProvider(password=password)
        assert provider.username == ""
        assert provider.password == password
        assert provider.get_credentials() == (password,)

        init_required_pass(r, request, password)

        r2 = _get_client(
            redis.Redis, request, flushdb=False, credential_provider=provider
        )
        assert r2.auth(provider.password) is True
        assert r2.ping() is True


@pytest.mark.onlynoncluster
@pytest.mark.skipif(not EntraIdCredentialsProvider, reason="requires redis-entraid")
class TestStreamingCredentialProvider:
    @pytest.mark.parametrize(
        "credential_provider",
        [
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "cred_provider_kwargs": {"expiration_refresh_ratio": 0.00005},
                "mock_idp": True,
            }
        ],
        indirect=True,
    )
    def test_re_auth_all_connections(self, credential_provider):
        mock_connection = Mock(spec=ConnectionInterface)
        mock_connection.retry = Retry(NoBackoff(), 0)
        mock_another_connection = Mock(spec=ConnectionInterface)
        mock_pool = Mock(spec=ConnectionPool)
        mock_pool.connection_kwargs = {
            "credential_provider": credential_provider,
        }
        mock_pool.get_connection.return_value = mock_connection
        mock_pool._available_connections = [mock_connection, mock_another_connection]
        mock_pool._lock = threading.RLock()
        auth_token = None

        def re_auth_callback(token):
            nonlocal auth_token
            auth_token = token
            with mock_pool._lock:
                for conn in mock_pool._available_connections:
                    conn.send_command("AUTH", token.try_get("oid"), token.get_value())
                    conn.read_response()

        mock_pool.re_auth_callback = re_auth_callback

        Redis(
            connection_pool=mock_pool,
            credential_provider=credential_provider,
        )

        credential_provider.get_credentials()
        sleep(0.5)

        mock_connection.send_command.assert_has_calls(
            [call("AUTH", auth_token.try_get("oid"), auth_token.get_value())]
        )
        mock_another_connection.send_command.assert_has_calls(
            [call("AUTH", auth_token.try_get("oid"), auth_token.get_value())]
        )

    @pytest.mark.parametrize(
        "credential_provider",
        [
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "cred_provider_kwargs": {"expiration_refresh_ratio": 0.00005},
                "mock_idp": True,
            }
        ],
        indirect=True,
    )
    def test_re_auth_partial_connections(self, credential_provider):
        mock_connection = Mock(spec=ConnectionInterface)
        mock_connection.retry = Retry(NoBackoff(), 3)
        mock_another_connection = Mock(spec=ConnectionInterface)
        mock_another_connection.retry = Retry(NoBackoff(), 3)
        mock_failed_connection = Mock(spec=ConnectionInterface)
        mock_failed_connection.read_response.side_effect = ConnectionError(
            "Failed auth"
        )
        mock_failed_connection.retry = Retry(NoBackoff(), 3)
        mock_pool = Mock(spec=ConnectionPool)
        mock_pool.connection_kwargs = {
            "credential_provider": credential_provider,
        }
        mock_pool.get_connection.return_value = mock_connection
        mock_pool._available_connections = [
            mock_connection,
            mock_another_connection,
            mock_failed_connection,
        ]
        mock_pool._lock = threading.RLock()

        def _raise(error: RedisError):
            pass

        def re_auth_callback(token):
            with mock_pool._lock:
                for conn in mock_pool._available_connections:
                    conn.retry.call_with_retry(
                        lambda: conn.send_command(
                            "AUTH", token.try_get("oid"), token.get_value()
                        ),
                        lambda error: _raise(error),
                    )
                    conn.retry.call_with_retry(
                        lambda: conn.read_response(), lambda error: _raise(error)
                    )

        mock_pool.re_auth_callback = re_auth_callback

        Redis(
            connection_pool=mock_pool,
            credential_provider=credential_provider,
        )

        credential_provider.get_credentials()
        sleep(0.5)

        mock_connection.read_response.assert_has_calls([call()])
        mock_another_connection.read_response.assert_has_calls([call()])
        mock_failed_connection.read_response.assert_has_calls([call(), call(), call()])

    @pytest.mark.parametrize(
        "credential_provider",
        [
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "cred_provider_kwargs": {"expiration_refresh_ratio": 0.00005},
                "mock_idp": True,
            }
        ],
        indirect=True,
    )
    def test_re_auth_pub_sub_in_resp3(self, credential_provider):
        mock_pubsub_connection = Mock(spec=ConnectionInterface)
        mock_pubsub_connection.get_protocol.return_value = 3
        mock_pubsub_connection.credential_provider = credential_provider
        mock_pubsub_connection.retry = Retry(NoBackoff(), 3)
        mock_another_connection = Mock(spec=ConnectionInterface)
        mock_another_connection.retry = Retry(NoBackoff(), 3)

        mock_pool = Mock(spec=ConnectionPool)
        mock_pool.connection_kwargs = {
            "credential_provider": credential_provider,
        }
        mock_pool.get_connection.side_effect = [
            mock_pubsub_connection,
            mock_another_connection,
        ]
        mock_pool._available_connections = [mock_another_connection]
        mock_pool._lock = threading.RLock()
        auth_token = None

        def re_auth_callback(token):
            nonlocal auth_token
            auth_token = token
            with mock_pool._lock:
                for conn in mock_pool._available_connections:
                    conn.send_command("AUTH", token.try_get("oid"), token.get_value())
                    conn.read_response()

        mock_pool.re_auth_callback = re_auth_callback

        r = Redis(
            connection_pool=mock_pool,
            credential_provider=credential_provider,
        )
        p = r.pubsub()
        p.subscribe("test")
        credential_provider.get_credentials()
        sleep(0.5)

        mock_pubsub_connection.send_command.assert_has_calls(
            [
                call("SUBSCRIBE", "test", check_health=True),
                call("AUTH", auth_token.try_get("oid"), auth_token.get_value()),
            ]
        )
        mock_another_connection.send_command.assert_has_calls(
            [call("AUTH", auth_token.try_get("oid"), auth_token.get_value())]
        )

    @pytest.mark.parametrize(
        "credential_provider",
        [
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "cred_provider_kwargs": {"expiration_refresh_ratio": 0.00005},
                "mock_idp": True,
            }
        ],
        indirect=True,
    )
    def test_do_not_re_auth_pub_sub_in_resp2(self, credential_provider):
        mock_pubsub_connection = Mock(spec=ConnectionInterface)
        mock_pubsub_connection.get_protocol.return_value = 2
        mock_pubsub_connection.credential_provider = credential_provider
        mock_pubsub_connection.retry = Retry(NoBackoff(), 3)
        mock_another_connection = Mock(spec=ConnectionInterface)
        mock_another_connection.retry = Retry(NoBackoff(), 3)

        mock_pool = Mock(spec=ConnectionPool)
        mock_pool.connection_kwargs = {
            "credential_provider": credential_provider,
        }
        mock_pool.get_connection.side_effect = [
            mock_pubsub_connection,
            mock_another_connection,
        ]
        mock_pool._available_connections = [mock_another_connection]
        mock_pool._lock = threading.RLock()
        auth_token = None

        def re_auth_callback(token):
            nonlocal auth_token
            auth_token = token
            with mock_pool._lock:
                for conn in mock_pool._available_connections:
                    conn.send_command("AUTH", token.try_get("oid"), token.get_value())
                    conn.read_response()

        mock_pool.re_auth_callback = re_auth_callback

        r = Redis(
            connection_pool=mock_pool,
            credential_provider=credential_provider,
        )
        p = r.pubsub()
        p.subscribe("test")
        credential_provider.get_credentials()
        sleep(0.5)

        mock_pubsub_connection.send_command.assert_has_calls(
            [
                call("SUBSCRIBE", "test", check_health=True),
            ]
        )
        mock_another_connection.send_command.assert_has_calls(
            [call("AUTH", auth_token.try_get("oid"), auth_token.get_value())]
        )

    @pytest.mark.parametrize(
        "credential_provider",
        [
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "cred_provider_kwargs": {"expiration_refresh_ratio": 0.00005},
                "mock_idp": True,
            }
        ],
        indirect=True,
    )
    def test_fails_on_token_renewal(self, credential_provider):
        credential_provider._token_mgr._idp.request_token.side_effect = [
            RequestTokenErr,
            RequestTokenErr,
            RequestTokenErr,
            RequestTokenErr,
        ]
        mock_connection = Mock(spec=ConnectionInterface)
        mock_connection.retry = Retry(NoBackoff(), 0)
        mock_another_connection = Mock(spec=ConnectionInterface)
        mock_pool = Mock(spec=ConnectionPool)
        mock_pool.connection_kwargs = {
            "credential_provider": credential_provider,
        }
        mock_pool.get_connection.return_value = mock_connection
        mock_pool._available_connections = [mock_connection, mock_another_connection]
        mock_pool._lock = threading.RLock()

        Redis(
            connection_pool=mock_pool,
            credential_provider=credential_provider,
        )

        with pytest.raises(RequestTokenErr):
            credential_provider.get_credentials()


@pytest.mark.onlynoncluster
@pytest.mark.cp_integration
@pytest.mark.skipif(not EntraIdCredentialsProvider, reason="requires redis-entraid")
class TestEntraIdCredentialsProvider:
    @pytest.mark.parametrize(
        "r_entra",
        [
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "single_connection_client": False,
            },
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "single_connection_client": True,
            },
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "idp_kwargs": {"auth_type": AuthType.DEFAULT_AZURE_CREDENTIAL},
            },
        ],
        ids=["pool", "single", "DefaultAzureCredential"],
        indirect=True,
    )
    @pytest.mark.onlynoncluster
    @pytest.mark.cp_integration
    def test_auth_pool_with_credential_provider(self, r_entra: redis.Redis):
        assert r_entra.ping() is True

    @pytest.mark.parametrize(
        "r_entra",
        [
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "single_connection_client": False,
            },
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "single_connection_client": True,
            },
        ],
        ids=["pool", "single"],
        indirect=True,
    )
    @pytest.mark.onlynoncluster
    @pytest.mark.cp_integration
    def test_auth_pipeline_with_credential_provider(self, r_entra: redis.Redis):
        pipe = r_entra.pipeline()

        pipe.set("key", "value")
        pipe.get("key")

        assert pipe.execute() == [True, b"value"]

    @pytest.mark.parametrize(
        "r_entra",
        [
            {
                "cred_provider_class": EntraIdCredentialsProvider,
            },
        ],
        indirect=True,
    )
    @pytest.mark.onlynoncluster
    @pytest.mark.cp_integration
    def test_auth_pubsub_with_credential_provider(self, r_entra: redis.Redis):
        p = r_entra.pubsub()
        p.subscribe("entraid")

        r_entra.publish("entraid", "test")
        r_entra.publish("entraid", "test")

        assert p.get_message()["type"] == "subscribe"
        assert p.get_message()["type"] == "message"


@pytest.mark.onlycluster
@pytest.mark.cp_integration
@pytest.mark.skipif(not EntraIdCredentialsProvider, reason="requires redis-entraid")
class TestClusterEntraIdCredentialsProvider:
    @pytest.mark.parametrize(
        "r_entra",
        [
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "single_connection_client": False,
            },
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "single_connection_client": True,
            },
            {
                "cred_provider_class": EntraIdCredentialsProvider,
                "idp_kwargs": {"auth_type": AuthType.DEFAULT_AZURE_CREDENTIAL},
            },
        ],
        ids=["pool", "single", "DefaultAzureCredential"],
        indirect=True,
    )
    @pytest.mark.onlycluster
    @pytest.mark.cp_integration
    def test_auth_pool_with_credential_provider(self, r_entra: redis.Redis):
        assert r_entra.ping() is True