Debian Codegraph @

ansible_collections/amazon/aws/tests/unit/plugins/lookup/test_secretsmanager_secret.py

raw
1 #
2 # (c) 2024 Red Hat Inc.
3 #
4 # This file is part of Ansible
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 import random
8 from unittest.mock import ANY
9 from unittest.mock import MagicMock
10 from unittest.mock import call
11
12 import pytest
13 from botocore.exceptions import ClientError
14
15 from ansible.errors import AnsibleLookupError
16
17 # from ansible_collections.amazon.aws.plugins.lookup.secretsmanager_secret import AnsibleLookupError
18 from ansible_collections.amazon.aws.plugins.lookup.secretsmanager_secret import LookupModule
19
20
21 @pytest.fixture(name="lookup_plugin")
22 def fixture_lookup_plugin():
23 lookup = LookupModule()
24 lookup.params = {}
25
26 lookup.get_option = MagicMock()
27
28 def _get_option(x):
29 return lookup.params.get(x)
30
31 lookup.get_option.side_effect = _get_option
32 lookup.client = MagicMock()
33
34 return lookup
35
36
37 def pick_from_list(elements=None):
38 if elements is None:
39 elements = ["error", "warn", "skip"]
40 return random.choice(elements)
41
42
43 def _raise_boto_clienterror(code, msg):
44 params = {
45 "Error": {"Code": code, "Message": msg},
46 "ResponseMetadata": {"RequestId": "01234567-89ab-cdef-0123-456789abcdef"},
47 }
48 return ClientError(params, "get_secret_value")
49
50
51 class TestLookupModuleRun:
52 @pytest.mark.parametrize(
53 "params,err",
54 [
55 ({"on_missing": "test"}, '"on_missing" must be a string and one of "error", "warn" or "skip", not test'),
56 ({"on_denied": "return"}, '"on_denied" must be a string and one of "error", "warn" or "skip", not return'),
57 (
58 {"on_deleted": "delete"},
59 '"on_deleted" must be a string and one of "error", "warn" or "skip", not delete',
60 ),
61 (
62 {"on_missing": ["warn"]},
63 '"on_missing" must be a string and one of "error", "warn" or "skip", not [\'warn\']',
64 ),
65 ({"on_denied": True}, '"on_denied" must be a string and one of "error", "warn" or "skip", not True'),
66 (
67 {"on_deleted": {"error": True}},
68 '"on_deleted" must be a string and one of "error", "warn" or "skip", not {\'error\': True}',
69 ),
70 ],
71 )
72 def test_run_invalid_parameters(self, lookup_plugin, mocker, params, err):
73 aws_lookup_base_run = mocker.patch(
74 "ansible_collections.amazon.aws.plugins.lookup.secretsmanager_secret.AWSLookupBase.run"
75 )
76 aws_lookup_base_run.return_value = True
77 m_list_secrets = mocker.patch(
78 "ansible_collections.amazon.aws.plugins.lookup.secretsmanager_secret._list_secrets"
79 )
80 m_list_secrets.return_value = {"SecretList": []}
81
82 lookup_plugin.params = params
83 with pytest.raises(AnsibleLookupError) as exc_info:
84 lookup_plugin.run(terms=["testing_secret"], variables=[])
85 assert err == str(exc_info.value)
86
87 def test_run_by_path(self, lookup_plugin, mocker):
88 aws_lookup_base_run = mocker.patch(
89 "ansible_collections.amazon.aws.plugins.lookup.secretsmanager_secret.AWSLookupBase.run"
90 )
91 aws_lookup_base_run.return_value = True
92 m_list_secrets = mocker.patch(
93 "ansible_collections.amazon.aws.plugins.lookup.secretsmanager_secret._list_secrets"
94 )
95 secrets_lists = [{"Name": "secret-0"}, {"Name": "secret-1"}, {"Name": "secret-2"}]
96 m_list_secrets.return_value = [{"SecretList": secrets_lists}]
97
98 params = {
99 "on_missing": pick_from_list(),
100 "on_denied": pick_from_list(),
101 "on_deleted": pick_from_list(),
102 "bypath": True,
103 }
104 lookup_plugin.params = params
105
106 lookup_plugin.get_secret_value = MagicMock()
107 secrets_values = {
108 "secret-0": "value-0",
109 "secret-1": "value-1",
110 "secret-2": "value-2",
111 }
112 lookup_plugin.get_secret_value.side_effect = lambda x, client, **kwargs: secrets_values.get(x)
113
114 secretsmanager_client = MagicMock()
115 lookup_plugin.client.return_value = secretsmanager_client
116
117 term = "term0"
118 assert [secrets_values] == lookup_plugin.run(terms=[term], variables=[])
119
120 m_list_secrets.assert_called_once_with(secretsmanager_client, term)
121 lookup_plugin.client.assert_called_once_with("secretsmanager", ANY)
122 lookup_plugin.get_secret_value.assert_has_calls(
123 [
124 call(
125 "secret-0",
126 secretsmanager_client,
127 on_missing=params.get("on_missing"),
128 on_denied=params.get("on_denied"),
129 ),
130 call(
131 "secret-1",
132 secretsmanager_client,
133 on_missing=params.get("on_missing"),
134 on_denied=params.get("on_denied"),
135 ),
136 call(
137 "secret-2",
138 secretsmanager_client,
139 on_missing=params.get("on_missing"),
140 on_denied=params.get("on_denied"),
141 ),
142 ]
143 )
144
145 @pytest.mark.parametrize("join_secrets", [True, False])
146 @pytest.mark.parametrize(
147 "terms", [["secret-0"], ["secret-0", "secret-1"], ["secret-0", "secret-1", "secret-0", "secret-2"]]
148 )
149 def test_run(self, lookup_plugin, mocker, join_secrets, terms):
150 aws_lookup_base_run = mocker.patch(
151 "ansible_collections.amazon.aws.plugins.lookup.secretsmanager_secret.AWSLookupBase.run"
152 )
153 aws_lookup_base_run.return_value = True
154
155 params = {
156 "on_missing": pick_from_list(),
157 "on_denied": pick_from_list(),
158 "on_deleted": pick_from_list(),
159 "bypath": False,
160 "version_stage": MagicMock(),
161 "version_id": MagicMock(),
162 "nested": pick_from_list([True, False]),
163 "join": join_secrets,
164 }
165 lookup_plugin.params = params
166
167 lookup_plugin.get_secret_value = MagicMock()
168 secrets_values = {
169 "secret-0": "value-0",
170 "secret-1": "value-1",
171 }
172 lookup_plugin.get_secret_value.side_effect = lambda x, client, **kwargs: secrets_values.get(x)
173
174 secretsmanager_client = MagicMock()
175 lookup_plugin.client.return_value = secretsmanager_client
176
177 expected_secrets = [secrets_values.get(x) for x in terms if secrets_values.get(x) is not None]
178 if join_secrets:
179 expected_secrets = ["".join(expected_secrets)]
180
181 assert expected_secrets == lookup_plugin.run(terms=terms, variables=[])
182
183 lookup_plugin.client.assert_called_once_with("secretsmanager", ANY)
184 lookup_plugin.get_secret_value.assert_has_calls(
185 [
186 call(
187 x,
188 secretsmanager_client,
189 version_stage=params.get("version_stage"),
190 version_id=params.get("version_id"),
191 on_missing=params.get("on_missing"),
192 on_denied=params.get("on_denied"),
193 on_deleted=params.get("on_deleted"),
194 nested=params.get("nested"),
195 )
196 for x in terms
197 ]
198 )
199
200
201 class TestLookupModuleGetSecretValue:
202 def test_get_secret__invalid_nested_value(self, lookup_plugin):
203 params = {
204 "version_stage": MagicMock(),
205 "version_id": MagicMock(),
206 "on_missing": None,
207 "on_denied": None,
208 "on_deleted": None,
209 }
210 with pytest.raises(AnsibleLookupError) as exc_info:
211 client = MagicMock()
212 lookup_plugin.get_secret_value("aws_invalid_nested_secret", client, nested=True, **params)
213 assert "Nested query must use the following syntax: `aws_secret_name.<key_name>.<key_name>" == str(
214 exc_info.value
215 )
216
217 @pytest.mark.parametrize("versionId", [None, MagicMock()])
218 @pytest.mark.parametrize("versionStage", [None, MagicMock()])
219 @pytest.mark.parametrize(
220 "term,nested,secretId",
221 [
222 ("secret0", False, "secret0"),
223 ("secret0.child", False, "secret0.child"),
224 ("secret0.child", True, "secret0"),
225 ("secret0.root.child", False, "secret0.root.child"),
226 ("secret0.root.child", True, "secret0"),
227 ],
228 )
229 def test_get_secret__binary_secret(self, lookup_plugin, versionId, versionStage, term, nested, secretId):
230 params = {
231 "version_stage": versionStage,
232 "version_id": versionId,
233 "on_missing": None,
234 "on_denied": None,
235 "on_deleted": None,
236 }
237
238 client = MagicMock()
239 client.get_secret_value = MagicMock()
240 bin_secret_value = b"binary_value"
241 client.get_secret_value.return_value = {"SecretBinary": bin_secret_value}
242
243 assert bin_secret_value == lookup_plugin.get_secret_value(term, client, nested=nested, **params)
244 api_params = {"SecretId": secretId}
245 if versionId is not None:
246 api_params["VersionId"] = versionId
247 if versionStage:
248 api_params["VersionStage"] = versionStage
249 client.get_secret_value.assert_called_once_with(aws_retry=True, **api_params)
250
251 @pytest.mark.parametrize("on_missing", ["warn", "error"])
252 @pytest.mark.parametrize(
253 "term,missing_key",
254 [
255 ("secret_name.root.child1", "root.child1"),
256 ("secret_name.root.child1.nested", "root.child1"),
257 ("secret_name.root.child.nested1", "root.child.nested1"),
258 ("secret_name.root.child.nested.value", "root.child.nested.value"),
259 ],
260 )
261 def test_get_secret__missing_nested_secret(self, lookup_plugin, on_missing, term, missing_key):
262 client = MagicMock()
263 client.get_secret_value = MagicMock()
264 json_secret = '{"root": {"child": {"nested": "ansible-test-secret-0"}}}'
265 client.get_secret_value.return_value = {"SecretString": json_secret}
266
267 if on_missing == "error":
268 with pytest.raises(AnsibleLookupError) as exc_info:
269 lookup_plugin.get_secret_value(term, client, nested=True, on_missing=on_missing)
270 assert f"Successfully retrieved secret but there exists no key {missing_key} in the secret" == str(
271 exc_info.value
272 )
273 else:
274 lookup_plugin._display = MagicMock()
275 lookup_plugin._display.warning = MagicMock()
276 assert lookup_plugin.get_secret_value(term, client, nested=True, on_missing=on_missing) is None
277 lookup_plugin._display.warning.assert_called_once_with(
278 f"Skipping, Successfully retrieved secret but there exists no key {missing_key} in the secret"
279 )
280
281 def test_get_secret__missing_secret(self, lookup_plugin):
282 client = MagicMock()
283 client.get_secret_value = MagicMock()
284 client.get_secret_value.side_effect = _raise_boto_clienterror("UnexpecteError", "unable to retrieve Secret")
285
286 with pytest.raises(AnsibleLookupError) as exc_info:
287 lookup_plugin.get_secret_value(MagicMock(), client)
288 assert (
289 "Failed to retrieve secret: An error occurred (UnexpecteError) when calling the get_secret_value operation: unable to retrieve Secret"
290 == str(exc_info.value)
291 )
292
293 @pytest.mark.parametrize("on_denied", ["warn", "error"])
294 def test_get_secret__on_denied(self, lookup_plugin, on_denied):
295 client = MagicMock()
296 client.get_secret_value = MagicMock()
297 client.get_secret_value.side_effect = _raise_boto_clienterror(
298 "AccessDeniedException", "Access denied to Secret"
299 )
300 term = "ansible-test-secret-0123"
301
302 if on_denied == "error":
303 with pytest.raises(AnsibleLookupError) as exc_info:
304 lookup_plugin.get_secret_value(term, client, on_denied=on_denied)
305 assert f"Failed to access secret {term} (AccessDenied)" == str(exc_info.value)
306 else:
307 lookup_plugin._display = MagicMock()
308 lookup_plugin._display.warning = MagicMock()
309 assert lookup_plugin.get_secret_value(term, client, on_denied=on_denied) is None
310 lookup_plugin._display.warning.assert_called_once_with(f"Skipping, access denied for secret {term}")
311
312 @pytest.mark.parametrize("on_missing", ["warn", "error"])
313 def test_get_secret__on_missing(self, lookup_plugin, on_missing):
314 client = MagicMock()
315 client.get_secret_value = MagicMock()
316 client.get_secret_value.side_effect = _raise_boto_clienterror("ResourceNotFoundException", "secret not found")
317 term = "ansible-test-secret-4561"
318
319 if on_missing == "error":
320 with pytest.raises(AnsibleLookupError) as exc_info:
321 lookup_plugin.get_secret_value(term, client, on_missing=on_missing)
322 assert f"Failed to find secret {term} (ResourceNotFound)" == str(exc_info.value)
323 else:
324 lookup_plugin._display = MagicMock()
325 lookup_plugin._display.warning = MagicMock()
326 assert lookup_plugin.get_secret_value(term, client, on_missing=on_missing) is None
327 lookup_plugin._display.warning.assert_called_once_with(f"Skipping, did not find secret {term}")
328
329 @pytest.mark.parametrize("on_deleted", ["warn", "error"])
330 def test_get_secret__on_deleted(self, lookup_plugin, on_deleted):
331 client = MagicMock()
332 client.get_secret_value = MagicMock()
333 client.get_secret_value.side_effect = _raise_boto_clienterror(
334 "ResourceMarkedForDeletion", "marked for deletion"
335 )
336 term = "ansible-test-secret-8790"
337
338 if on_deleted == "error":
339 with pytest.raises(AnsibleLookupError) as exc_info:
340 lookup_plugin.get_secret_value(term, client, on_deleted=on_deleted)
341 assert f"Failed to find secret {term} (marked for deletion)" == str(exc_info.value)
342 else:
343 lookup_plugin._display = MagicMock()
344 lookup_plugin._display.warning = MagicMock()
345 assert lookup_plugin.get_secret_value(term, client, on_deleted=on_deleted) is None
346 lookup_plugin._display.warning.assert_called_once_with(
347 f"Skipping, did not find secret (marked for deletion) {term}"
348 )