Debian Codegraph @

ansible_collections/community/general/tests/unit/plugins/lookup/test_onepassword.py

raw
1 # Copyright (c) 2022 Ansible Project
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 from __future__ import annotations
6
7 import itertools
8 import json
9 import operator
10
11 import pytest
12 from ansible.errors import AnsibleLookupError, AnsibleOptionsError
13 from ansible.plugins.loader import lookup_loader
14
15 from ansible_collections.community.general.plugins.lookup.onepassword import (
16 OnePassCLIv2,
17 )
18
19 from .onepassword_common import MOCK_ENTRIES
20
21 OP_VERSION_FIXTURES = ["opv2"]
22
23
24 @pytest.mark.parametrize(
25 ("args", "out", "expected_call_args", "expected_call_kwargs", "expected"),
26 (
27 (
28 [],
29 "list of accounts",
30 ["account", "get"],
31 {"ignore_errors": True},
32 True,
33 ),
34 (
35 ["acme"],
36 "list of accounts",
37 ["account", "get", "--account", "acme.1password.com"],
38 {"ignore_errors": True},
39 True,
40 ),
41 (
42 [],
43 "",
44 ["account", "list"],
45 {},
46 False,
47 ),
48 ),
49 )
50 def test_assert_logged_in_v2(mocker, args, out, expected_call_args, expected_call_kwargs, expected):
51 mocker.patch.object(OnePassCLIv2, "_run", return_value=[0, out, ""])
52 op_cli = OnePassCLIv2(*args)
53 result = op_cli.assert_logged_in()
54
55 op_cli._run.assert_called_with(expected_call_args, **expected_call_kwargs)
56 assert result == expected
57
58
59 def test_assert_logged_in_v2_connect():
60 op_cli = OnePassCLIv2(connect_host="http://localhost:8080", connect_token="foobar")
61 result = op_cli.assert_logged_in()
62 assert result
63
64
65 def test_full_signin_v2(mocker):
66 mocker.patch.object(OnePassCLIv2, "_run", return_value=[0, "", ""])
67
68 op_cli = OnePassCLIv2(
69 subdomain="acme",
70 username="[email protected]",
71 secret_key="SECRET",
72 master_password="ONEKEYTORULETHEMALL",
73 )
74 result = op_cli.full_signin()
75
76 op_cli._run.assert_called_with(
77 [
78 "account",
79 "add",
80 "--raw",
81 "--address",
82 "acme.1password.com",
83 "--email",
84 b"[email protected]",
85 "--signin",
86 ],
87 command_input=b"ONEKEYTORULETHEMALL",
88 environment_update={"OP_SECRET_KEY": "SECRET"},
89 )
90 assert result == [0, "", ""]
91
92
93 @pytest.mark.parametrize(
94 ("version", "version_class"),
95 (("2.27.4", OnePassCLIv2),),
96 )
97 def test_op_correct_cli_class(fake_op, version, version_class):
98 op = fake_op(version)
99 assert op._cli.version == version
100 assert isinstance(op._cli, version_class)
101
102
103 def test_op_unsupported_cli_version(fake_op):
104 with pytest.raises(AnsibleLookupError, match="is unsupported"):
105 fake_op("1.17.2")
106 with pytest.raises(AnsibleLookupError, match="is unsupported"):
107 fake_op("99.77.77")
108
109
110 @pytest.mark.parametrize("op_fixture", OP_VERSION_FIXTURES)
111 def test_op_set_token_with_config(op_fixture, mocker, request):
112 op = request.getfixturevalue(op_fixture)
113 token = "F5417F77529B41B595D7F9D6F76EC057"
114 mocker.patch("os.path.isfile", return_value=True)
115 mocker.patch.object(op._cli, "signin", return_value=(0, f"{token}\n", ""))
116
117 op.set_token()
118
119 assert op.token == token
120
121
122 @pytest.mark.parametrize(
123 ("op_fixture", "message"),
124 [
125 (op, value)
126 for op in OP_VERSION_FIXTURES
127 for value in (
128 "Missing required parameters",
129 "The operation is unauthorized",
130 )
131 ],
132 )
133 def test_op_set_token_with_config_missing_args(op_fixture, message, request, mocker):
134 op = request.getfixturevalue(op_fixture)
135 mocker.patch("os.path.isfile", return_value=True)
136 mocker.patch.object(op._cli, "signin", return_value=(99, "", ""), side_effect=AnsibleLookupError(message))
137 mocker.patch.object(op._cli, "full_signin", return_value=(0, "", ""))
138
139 with pytest.raises(AnsibleLookupError, match=message):
140 op.set_token()
141
142 op._cli.full_signin.assert_not_called()
143
144
145 @pytest.mark.parametrize("op_fixture", OP_VERSION_FIXTURES)
146 def test_op_set_token_with_config_full_signin(op_fixture, request, mocker):
147 op = request.getfixturevalue(op_fixture)
148 mocker.patch("os.path.isfile", return_value=True)
149 mocker.patch.object(
150 op._cli, "signin", return_value=(99, "", ""), side_effect=AnsibleLookupError("Raised intentionally")
151 )
152 mocker.patch.object(op._cli, "full_signin", return_value=(0, "", ""))
153
154 op.set_token()
155
156 op._cli.full_signin.assert_called()
157
158
159 @pytest.mark.parametrize("op_fixture", OP_VERSION_FIXTURES)
160 def test_op_set_token_without_config(op_fixture, request, mocker):
161 op = request.getfixturevalue(op_fixture)
162 token = "B988E8A2680A4A348962751A96861FA1"
163 mocker.patch("os.path.isfile", return_value=False)
164 mocker.patch.object(op._cli, "signin", return_value=(99, "", ""))
165 mocker.patch.object(op._cli, "full_signin", return_value=(0, f"{token}\n", ""))
166
167 op.set_token()
168
169 op._cli.signin.assert_not_called()
170 assert op.token == token
171
172
173 @pytest.mark.parametrize(
174 ("op_fixture", "login_status"), [(op, value) for op in OP_VERSION_FIXTURES for value in [False, True]]
175 )
176 def test_op_assert_logged_in(mocker, login_status, op_fixture, request):
177 op = request.getfixturevalue(op_fixture)
178 mocker.patch.object(op._cli, "assert_logged_in", return_value=login_status)
179 mocker.patch.object(op, "set_token")
180
181 op.assert_logged_in()
182
183 op._cli.assert_logged_in.assert_called_once()
184 assert op.logged_in == login_status
185
186 if not login_status:
187 op.set_token.assert_called_once()
188
189
190 @pytest.mark.parametrize(
191 ("op_fixture", "output", "expected"),
192 (
193 list(itertools.chain([op], d))
194 for op in OP_VERSION_FIXTURES
195 for d in [
196 ("RAW OUTPUT", "RAW OUTPUT"),
197 (None, ""),
198 ("", ""),
199 ]
200 ),
201 )
202 def test_op_get_field(mocker, op_fixture, output, expected, request):
203 op = request.getfixturevalue(op_fixture)
204 mocker.patch.object(op, "get_raw", return_value=output)
205 mocker.patch.object(op._cli, "_parse_field", return_value=output)
206
207 result = op.get_field("some item", "some field")
208
209 assert result == expected
210
211
212 # This test sometimes fails on older Python versions because the gathered tests mismatch.
213 # Sort the fixture data to make this reliable
214 # https://github.com/pytest-dev/pytest-xdist/issues/432
215 @pytest.mark.parametrize(
216 ("cli_class", "vault", "queries", "kwargs", "output", "expected"),
217 (
218 (_cli_class, item["vault_name"], item["queries"], item.get("kwargs", {}), item["output"], item["expected"])
219 for _cli_class in sorted(MOCK_ENTRIES, key=operator.attrgetter("__name__"))
220 for item in MOCK_ENTRIES[_cli_class]
221 ),
222 )
223 def test_op_lookup(mocker, cli_class, vault, queries, kwargs, output, expected):
224 mocker.patch("ansible_collections.community.general.plugins.lookup.onepassword.OnePass._get_cli_class", cli_class)
225 mocker.patch(
226 "ansible_collections.community.general.plugins.lookup.onepassword.OnePass.assert_logged_in", return_value=True
227 )
228 mocker.patch(
229 "ansible_collections.community.general.plugins.lookup.onepassword.OnePassCLIBase._run",
230 return_value=(0, json.dumps(output), ""),
231 )
232
233 op_lookup = lookup_loader.get("community.general.onepassword")
234 result = op_lookup.run(queries, vault=vault, **kwargs)
235
236 assert result == expected
237
238
239 @pytest.mark.parametrize("op_fixture", OP_VERSION_FIXTURES)
240 def test_signin(op_fixture, request):
241 op = request.getfixturevalue(op_fixture)
242 op._cli.master_password = "master_pass"
243 op._cli.signin()
244 op._cli._run.assert_called_once_with(["signin", "--raw"], command_input=b"master_pass")
245
246
247 def test_op_doc(mocker):
248 document_contents = "Document Contents\n"
249
250 mocker.patch(
251 "ansible_collections.community.general.plugins.lookup.onepassword.OnePass.assert_logged_in", return_value=True
252 )
253 mocker.patch(
254 "ansible_collections.community.general.plugins.lookup.onepassword.OnePassCLIBase._run",
255 return_value=(0, document_contents, ""),
256 )
257
258 op_lookup = lookup_loader.get("community.general.onepassword_doc")
259 result = op_lookup.run(["Private key doc"])
260
261 assert result == [document_contents]
262
263
264 @pytest.mark.parametrize(
265 ("plugin", "connect_host", "connect_token"),
266 [
267 (plugin, connect_host, connect_token)
268 for plugin in ("community.general.onepassword", "community.general.onepassword_raw")
269 for (connect_host, connect_token) in (
270 ("http://localhost", None),
271 (None, "foobar"),
272 )
273 ],
274 )
275 def test_op_connect_partial_args(plugin, connect_host, connect_token, mocker):
276 op_lookup = lookup_loader.get(plugin)
277
278 mocker.patch(
279 "ansible_collections.community.general.plugins.lookup.onepassword.OnePass._get_cli_class", OnePassCLIv2
280 )
281
282 with pytest.raises(AnsibleOptionsError):
283 op_lookup.run("login", vault_name="test vault", connect_host=connect_host, connect_token=connect_token)