File: test_async_secret_refresh.py

package info (click to toggle)
python-azure 20251118%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 783,356 kB
  • sloc: python: 6,474,533; ansic: 804; javascript: 287; sh: 205; makefile: 198; xml: 109
file content (246 lines) | stat: -rw-r--r-- 10,283 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
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import time
import asyncio
import unittest
from unittest.mock import Mock, patch
from devtools_testutils.aio import recorded_by_proxy_async
from azure.appconfiguration import SecretReferenceConfigurationSetting
from azure.appconfiguration.provider import SettingSelector, WatchKey
from devtools_testutils import recorded_by_proxy
from async_preparers import app_config_aad_decorator_async
from asynctestcase import AppConfigTestCase


class TestAsyncSecretRefresh(AppConfigTestCase, unittest.TestCase):

    @app_config_aad_decorator_async
    @recorded_by_proxy_async
    async def testsecret_refresh_timer(
        self,
        appconfiguration_endpoint_string,
        appconfiguration_keyvault_secret_url,
        appconfiguration_keyvault_secret_url2,
    ):
        """Test that secrets are refreshed based on the secret_refresh_interval."""

        # Create an async mock callback
        async def async_callback():
            pass

        mock_callback = Mock(side_effect=async_callback)

        # Create client with key vault reference and secret refresh interval
        client = await self.create_client(
            endpoint=appconfiguration_endpoint_string,
            selects={SettingSelector(key_filter="*", label_filter="prod")},
            keyvault_secret_url=appconfiguration_keyvault_secret_url,
            keyvault_secret_url2=appconfiguration_keyvault_secret_url2,
            on_refresh_success=mock_callback,
            refresh_interval=999999,
            secret_refresh_interval=1,
        )

        # Verify initial state
        assert client["secret"] == "Very secret value"
        assert mock_callback.call_count == 0

        # Mock the refresh method to track calls
        with patch.object(client, "refresh") as mock_refresh:
            # Wait for the secret refresh interval to pass
            await asyncio.sleep(2)

            await client.refresh()

            # Verify refresh was called
            assert mock_refresh.call_count >= 1

            # Wait again to ensure multiple refreshes
            await asyncio.sleep(2)
            await client.refresh()

            # Should have been called at least twice now
            assert mock_refresh.call_count >= 2

    @app_config_aad_decorator_async
    @recorded_by_proxy_async
    async def test_secret_refresh_with_updated_values(
        self,
        appconfiguration_endpoint_string,
        appconfiguration_keyvault_secret_url,
        appconfiguration_keyvault_secret_url2,
    ):
        """Test that secrets are refreshed with updated values."""
        mock_callback = Mock()

        # Create client with the mock secret resolver
        client = await self.create_client(
            endpoint=appconfiguration_endpoint_string,
            selects={SettingSelector(key_filter="*", label_filter="prod")},
            keyvault_secret_url=appconfiguration_keyvault_secret_url,
            keyvault_secret_url2=appconfiguration_keyvault_secret_url2,
            on_refresh_success=mock_callback,
            refresh_on=[WatchKey("secret", "prod")],
            refresh_interval=1,
            secret_refresh_interval=1,  # Using a short interval for testing
        )

        # Add a key vault reference to the client (this will use mock resolver)
        appconfig_client = self.create_aad_sdk_client(appconfiguration_endpoint_string)

        # Get and modify a key vault reference setting
        kv_setting = await appconfig_client.get_configuration_setting(key="secret", label="prod")
        assert kv_setting is not None

        # Verify initial value from mock resolver
        assert client["secret"] == "Very secret value"
        assert kv_setting is not None
        assert isinstance(kv_setting, SecretReferenceConfigurationSetting)
        # Update the secret_id (which is the value for SecretReferenceConfigurationSetting)
        kv_setting.secret_id = appconfiguration_keyvault_secret_url2
        await appconfig_client.set_configuration_setting(kv_setting)

        # Wait for the secret refresh interval to pass
        await asyncio.sleep(2)

        # Access the value again to trigger refresh
        await client.refresh()

        # Verify the value was updated
        assert client["secret"] == "Very secret value 2"
        assert mock_callback.call_count >= 1

    @app_config_aad_decorator_async
    @recorded_by_proxy_async
    async def test_no_secret_refresh_without_timer(
        self,
        appconfiguration_endpoint_string,
        appconfiguration_keyvault_secret_url,
        appconfiguration_keyvault_secret_url2,
    ):
        """Test that secrets are not refreshed if secret_refresh_interval is not set."""

        # Create an async mock callback
        async def async_callback():
            pass

        mock_callback = Mock(side_effect=async_callback)

        # Create client without specifying secret_refresh_interval
        client = await self.create_client(
            endpoint=appconfiguration_endpoint_string,
            selects={SettingSelector(key_filter="*", label_filter="prod")},
            keyvault_secret_url=appconfiguration_keyvault_secret_url,
            keyvault_secret_url2=appconfiguration_keyvault_secret_url2,
            on_refresh_success=mock_callback,
            refresh_interval=999999,
        )

        # Verify initial state
        assert client["secret"] == "Very secret value"

        # Mock the refresh method to track calls
        with patch("time.time") as mock_time:
            # Make time.time() return increasing values to simulate passage of time
            mock_time.side_effect = [time.time(), time.time() + 100]

            # Access the key vault reference - this shouldn't trigger an auto-refresh since
            # we didn't set a secret_refresh_interval
            await client.refresh()

            # Access it again to verify no auto-refresh due to secrets timer
            await client.refresh()

            # The mock_time should have been called twice (for our side_effect setup)
            # but there should be no automatic refresh caused by the secret timer
            assert mock_time.call_count == 2

    @app_config_aad_decorator_async
    @recorded_by_proxy_async
    async def test_secret_refresh_timer_triggers_refresh(
        self,
        appconfiguration_endpoint_string,
        appconfiguration_keyvault_secret_url,
        appconfiguration_keyvault_secret_url2,
    ):
        """Test that the secret refresh timer triggers a refresh after the specified interval."""

        # Create an async mock callback
        async def async_callback():
            pass

        mock_callback = Mock(side_effect=async_callback)

        # Create client with key vault reference and separate refresh intervals
        client = await self.create_client(
            endpoint=appconfiguration_endpoint_string,
            selects={SettingSelector(key_filter="*", label_filter="prod")},
            keyvault_secret_url=appconfiguration_keyvault_secret_url,
            keyvault_secret_url2=appconfiguration_keyvault_secret_url2,
            on_refresh_success=mock_callback,
            refresh_interval=999999,
            secret_refresh_interval=5,  # Secret refresh interval is short
        )

        # Now patch the refresh method and secret_refresh_timer to control behavior
        with patch.object(client, "refresh") as mock_refresh:
            # Now patch the secret_refresh_timer to control its behavior
            with patch.object(client._secret_provider, "secret_refresh_timer") as mock_timer:
                # Make needs_refresh() return True to simulate timer expiration
                mock_timer.needs_refresh.return_value = True

                # Access a key vault reference which should trigger refresh due to timer
                await client.refresh()

                # Verify refresh was called
                assert mock_refresh.call_count > 0

    @app_config_aad_decorator_async
    @recorded_by_proxy_async
    async def test_secret_refresh_interval_parameter(
        self,
        appconfiguration_endpoint_string,
        appconfiguration_keyvault_secret_url,
        appconfiguration_keyvault_secret_url2,
    ):
        """Test that secret_refresh_interval parameter is correctly passed and used."""

        # Create an async mock callback
        async def async_callback():
            pass

        mock_callback = Mock(side_effect=async_callback)

        # Create client with specific secret_refresh_interval
        client = await self.create_client(
            endpoint=appconfiguration_endpoint_string,
            selects={SettingSelector(key_filter="*", label_filter="prod")},
            keyvault_secret_url=appconfiguration_keyvault_secret_url,
            keyvault_secret_url2=appconfiguration_keyvault_secret_url2,
            on_refresh_success=mock_callback,
            refresh_interval=999999,
            secret_refresh_interval=42,  # Use a specific value we can check for
        )

        # Verify the secret refresh timer exists
        assert client._secret_provider.secret_refresh_timer is not None

        # We can only verify that it exists, but can't directly access the internal refresh_interval
        # as it's a protected attribute

        # Check with no refresh interval to ensure it's properly handled
        client2 = await self.create_client(
            endpoint=appconfiguration_endpoint_string,
            selects={SettingSelector(key_filter="*", label_filter="prod")},
            keyvault_secret_url=appconfiguration_keyvault_secret_url,
            keyvault_secret_url2=appconfiguration_keyvault_secret_url2,
            on_refresh_success=mock_callback,
            # No secret_refresh_interval specified
        )

        # Verify timer is created only when secret_refresh_interval is provided
        assert client._secret_provider.secret_refresh_timer is not None
        assert client2._secret_provider.secret_refresh_timer is None