Debian Codegraph @

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

raw
1 # Copyright (c) 2022, Jonathan Lung <[email protected]>
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 re
8 import unittest
9 from unittest.mock import patch
10
11 from ansible.errors import AnsibleError
12 from ansible.parsing.ajson import AnsibleJSONEncoder
13 from ansible.plugins.loader import lookup_loader
14
15 from ansible_collections.community.general.plugins.lookup.bitwarden import Bitwarden, BitwardenException
16
17 MOCK_COLLECTION_ID = "3b12a9da-7c49-40b8-ad33-aede017a7ead"
18 MOCK_ORGANIZATION_ID = "292ba0c6-f289-11ee-9301-ef7b639ccd2a"
19
20 MOCK_RECORDS = [
21 {
22 "collectionIds": [MOCK_COLLECTION_ID],
23 "deletedDate": None,
24 "favorite": False,
25 "fields": [
26 {"linkedId": None, "name": "a_new_secret", "type": 1, "value": "this is a new secret"},
27 {"linkedId": None, "name": "not so secret", "type": 0, "value": "not secret"},
28 ],
29 "folderId": "3b12a9da-7c49-40b8-ad33-aede017a7ead",
30 "id": "90992f63-ddb6-4e76-8bfc-aede016ca5eb",
31 "login": {
32 "password": "passwordA3",
33 "passwordRevisionDate": "2022-07-26T23:03:23.399Z",
34 "totp": None,
35 "username": "userA",
36 },
37 "name": "a_test",
38 "notes": None,
39 "object": "item",
40 "organizationId": MOCK_ORGANIZATION_ID,
41 "passwordHistory": [
42 {"lastUsedDate": "2022-07-26T23:03:23.405Z", "password": "a_new_secret: this is secret"},
43 {"lastUsedDate": "2022-07-26T23:03:23.399Z", "password": "passwordA2"},
44 {"lastUsedDate": "2022-07-26T22:59:52.885Z", "password": "passwordA"},
45 ],
46 "reprompt": 0,
47 "revisionDate": "2022-07-26T23:03:23.743Z",
48 "type": 1,
49 },
50 {
51 "collectionIds": [],
52 "deletedDate": None,
53 "favorite": False,
54 "folderId": None,
55 "id": "5ebd4d31-104c-49fc-a09c-aedf003d28ad",
56 "login": {"password": "b", "passwordRevisionDate": None, "totp": None, "username": "a"},
57 "name": "dupe_name",
58 "notes": None,
59 "object": "item",
60 "organizationId": None,
61 "reprompt": 0,
62 "revisionDate": "2022-07-27T03:42:40.353Z",
63 "type": 1,
64 },
65 {
66 "collectionIds": [MOCK_COLLECTION_ID],
67 "deletedDate": None,
68 "favorite": False,
69 "folderId": None,
70 "id": "90657653-6695-496d-9431-aedf003d3015",
71 "login": {"password": "d", "passwordRevisionDate": None, "totp": None, "username": "c"},
72 "name": "dupe_name",
73 "notes": None,
74 "object": "item",
75 "organizationId": MOCK_ORGANIZATION_ID,
76 "reprompt": 0,
77 "revisionDate": "2022-07-27T03:42:46.673Z",
78 "type": 1,
79 },
80 {
81 "collectionIds": [],
82 "deletedDate": None,
83 "favorite": False,
84 "folderId": None,
85 "id": "2bf517be-fb13-11ee-be89-a345aa369a94",
86 "login": {"password": "e", "passwordRevisionDate": None, "totp": None, "username": "f"},
87 "name": "non_collection_org_record",
88 "notes": None,
89 "object": "item",
90 "organizationId": MOCK_ORGANIZATION_ID,
91 "reprompt": 0,
92 "revisionDate": "2024-14-15T11:30:00.000Z",
93 "type": 1,
94 },
95 {
96 "object": "collection",
97 "id": MOCK_COLLECTION_ID,
98 "organizationId": MOCK_ORGANIZATION_ID,
99 "name": "MOCK_COLLECTION",
100 "externalId": None,
101 },
102 {
103 "object": "collection",
104 "id": "3b12a9da-7c49-40b8-ad33-aede017a8ead",
105 "organizationId": "3b12a9da-7c49-40b8-ad33-aede017a9ead",
106 "name": "some/other/collection",
107 "externalId": None,
108 },
109 ]
110
111
112 class MockBitwarden(Bitwarden):
113 unlocked = True
114
115 def _run(self, args, stdin=None, expected_rc=0):
116 if args[0] == "get":
117 if args[1] == "item":
118 for item in MOCK_RECORDS:
119 if item.get("id") == args[2]:
120 return AnsibleJSONEncoder().encode(item), ""
121 if args[0] == "list":
122 if args[1] == "items":
123 try:
124 search_value = args[args.index("--search") + 1]
125 except ValueError:
126 search_value = None
127
128 try:
129 collection_to_filter = args[args.index("--collectionid") + 1]
130 except ValueError:
131 collection_to_filter = None
132
133 try:
134 organization_to_filter = args[args.index("--organizationid") + 1]
135 except ValueError:
136 organization_to_filter = None
137
138 items = []
139 for item in MOCK_RECORDS:
140 if item.get("object") != "item":
141 continue
142
143 if search_value and not re.search(search_value, item.get("name")):
144 continue
145 if collection_to_filter and collection_to_filter not in item.get("collectionIds", []):
146 continue
147 if organization_to_filter and item.get("organizationId") != organization_to_filter:
148 continue
149 items.append(item)
150 return AnsibleJSONEncoder().encode(items), ""
151 elif args[1] == "collections":
152 try:
153 search_value = args[args.index("--search") + 1]
154 except ValueError:
155 search_value = None
156
157 try:
158 collection_to_filter = args[args.index("--collectionid") + 1]
159 except ValueError:
160 collection_to_filter = None
161
162 try:
163 organization_to_filter = args[args.index("--organizationid") + 1]
164 except ValueError:
165 organization_to_filter = None
166
167 collections = []
168 for item in MOCK_RECORDS:
169 if item.get("object") != "collection":
170 continue
171
172 if search_value and not re.search(search_value, item.get("name")):
173 continue
174 if collection_to_filter and collection_to_filter not in item.get("collectionIds", []):
175 continue
176 if organization_to_filter and item.get("organizationId") != organization_to_filter:
177 continue
178 collections.append(item)
179 return AnsibleJSONEncoder().encode(collections), ""
180
181 return "[]", ""
182
183
184 class LoggedOutMockBitwarden(MockBitwarden):
185 unlocked = False
186
187
188 class TestLookupModule(unittest.TestCase):
189 def setUp(self):
190 self.lookup = lookup_loader.get("community.general.bitwarden")
191
192 @patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
193 def test_bitwarden_plugin_no_match(self):
194 # Entry 0, "a_test" of the test input should have no duplicates.
195 self.assertEqual([], self.lookup.run(["not_here"], field="password")[0])
196
197 @patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
198 def test_bitwarden_plugin_fields(self):
199 # Entry 0, "a_test" of the test input should have no duplicates.
200 record = MOCK_RECORDS[0]
201 record_name = record["name"]
202 for k, v in record["login"].items():
203 self.assertEqual([v], self.lookup.run([record_name], field=k)[0])
204
205 @patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
206 def test_bitwarden_plugin_duplicates(self):
207 # There are two records with name dupe_name; we need to be order-insensitive with
208 # checking what was retrieved.
209 self.assertEqual({"b", "d"}, set(self.lookup.run(["dupe_name"], field="password")[0]))
210
211 @patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
212 def test_bitwarden_plugin_full_item(self):
213 # Try to retrieve the full record of the first entry where the name is "a_name".
214 self.assertEqual([MOCK_RECORDS[0]], self.lookup.run(["a_test"])[0])
215
216 @patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", LoggedOutMockBitwarden())
217 def test_bitwarden_plugin_unlocked(self):
218 record = MOCK_RECORDS[0]
219 record_name = record["name"]
220 with self.assertRaises(AnsibleError) as raised_error:
221 self.lookup.run([record_name], field="password")
222
223 self.assertEqual("Bitwarden Vault locked. Run 'bw unlock'.", str(raised_error.exception))
224
225 def test_bitwarden_plugin_without_session_option(self):
226 mock_bitwarden = MockBitwarden()
227 with patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", mock_bitwarden):
228 record = MOCK_RECORDS[0]
229 record_name = record["name"]
230
231 self.lookup.run([record_name], field=None)
232 self.assertIsNone(mock_bitwarden.session)
233
234 def test_bitwarden_plugin_session_option(self):
235 mock_bitwarden = MockBitwarden()
236 with patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", mock_bitwarden):
237 record = MOCK_RECORDS[0]
238 record_name = record["name"]
239 session = "session"
240
241 self.lookup.run([record_name], field=None, bw_session=session)
242 self.assertEqual(mock_bitwarden.session, session)
243
244 @patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
245 def test_bitwarden_plugin_full_collection(self):
246 # Try to retrieve the full records of the given collection.
247 self.assertEqual([MOCK_RECORDS[0], MOCK_RECORDS[2]], self.lookup.run(None, collection_id=MOCK_COLLECTION_ID)[0])
248
249 @patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
250 def test_bitwarden_plugin_full_organization(self):
251 self.assertEqual(
252 [MOCK_RECORDS[0], MOCK_RECORDS[2], MOCK_RECORDS[3]],
253 self.lookup.run(None, organization_id=MOCK_ORGANIZATION_ID)[0],
254 )
255
256 @patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
257 def test_bitwarden_plugin_filter_organization(self):
258 self.assertEqual([MOCK_RECORDS[2]], self.lookup.run(["dupe_name"], organization_id=MOCK_ORGANIZATION_ID)[0])
259
260 @patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
261 def test_bitwarden_plugin_full_collection_organization(self):
262 self.assertEqual(
263 [MOCK_RECORDS[0], MOCK_RECORDS[2]],
264 self.lookup.run(None, collection_id=MOCK_COLLECTION_ID, organization_id=MOCK_ORGANIZATION_ID)[0],
265 )
266
267 @patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
268 def test_bitwarden_plugin_collection_name_filter(self):
269 # all passwords from MOCK_COLLECTION
270 self.assertEqual(
271 [MOCK_RECORDS[0], MOCK_RECORDS[2]], self.lookup.run(None, collection_name="MOCK_COLLECTION")[0]
272 )
273 # Existing collection, no results
274 self.assertEqual([], self.lookup.run(None, collection_name="some/other/collection")[0])
275
276 # Non-Existent collection
277 with self.assertRaises(BitwardenException):
278 self.lookup.run(None, collection_name="nonexistent")
279
280 @patch("ansible_collections.community.general.plugins.lookup.bitwarden._bitwarden", new=MockBitwarden())
281 def test_bitwarden_plugin_result_count_check(self):
282 self.lookup.run(None, collection_id=MOCK_COLLECTION_ID, organization_id=MOCK_ORGANIZATION_ID, result_count=2)
283 with self.assertRaises(BitwardenException):
284 self.lookup.run(
285 None, collection_id=MOCK_COLLECTION_ID, organization_id=MOCK_ORGANIZATION_ID, result_count=1
286 )
287
288 self.lookup.run(None, organization_id=MOCK_ORGANIZATION_ID, result_count=3)
289 with self.assertRaises(BitwardenException):
290 self.lookup.run(None, organization_id=MOCK_ORGANIZATION_ID, result_count=0)