Debian Codegraph @

ansible_collections/community/general/plugins/lookup/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 from __future__ import annotations
5
6 DOCUMENTATION = r"""
7 name: bitwarden
8 author:
9 - Jonathan Lung (@lungj) <[email protected]>
10 requirements:
11 - bw (command line utility)
12 - be logged into bitwarden
13 - bitwarden vault unlocked
14 - E(BW_SESSION) environment variable set
15 short_description: Retrieve secrets from Bitwarden
16 version_added: 5.4.0
17 description:
18 - Retrieve secrets from Bitwarden.
19 options:
20 _terms:
21 description: Key(s) to fetch values for from login info.
22 required: true
23 type: list
24 elements: str
25 search:
26 description:
27 - Field to retrieve, for example V(name) or V(id).
28 - If set to V(id), only zero or one element can be returned. Use the Jinja C(first) filter to get the only list element.
29 - If set to V(None) or V(''), or if O(_terms) is empty, records are not filtered by fields.
30 type: str
31 default: name
32 version_added: 5.7.0
33 field:
34 description: Field to fetch. Leave unset to fetch whole response.
35 type: str
36 collection_id:
37 description:
38 - Collection ID to filter results by collection. Leave unset to skip filtering.
39 - O(collection_id) and O(collection_name) are mutually exclusive.
40 type: str
41 version_added: 6.3.0
42 collection_name:
43 description:
44 - Collection name to filter results by collection. Leave unset to skip filtering.
45 - O(collection_id) and O(collection_name) are mutually exclusive.
46 type: str
47 version_added: 10.4.0
48 organization_id:
49 description: Organization ID to filter results by organization. Leave unset to skip filtering.
50 type: str
51 version_added: 8.5.0
52 bw_session:
53 description: Pass session key instead of reading from env.
54 type: str
55 version_added: 8.4.0
56 result_count:
57 description:
58 - Number of results expected for the lookup query. Task fails if O(result_count) is set but does not match the number
59 of query results. Leave empty to skip this check.
60 type: int
61 version_added: 10.4.0
62 """
63
64 EXAMPLES = r"""
65 - name: "Get 'password' from all Bitwarden records named 'a_test'"
66 ansible.builtin.debug:
67 msg: >-
68 {{ lookup('community.general.bitwarden', 'a_test', field='password') }}
69
70 - name: "Get 'password' from Bitwarden record with ID 'bafba515-af11-47e6-abe3-af1200cd18b2'"
71 ansible.builtin.debug:
72 msg: >-
73 {{ lookup('community.general.bitwarden', 'bafba515-af11-47e6-abe3-af1200cd18b2', search='id', field='password') | first }}
74
75 - name: "Get 'password' from all Bitwarden records named 'a_test' from collection"
76 ansible.builtin.debug:
77 msg: >-
78 {{ lookup('community.general.bitwarden', 'a_test', field='password', collection_id='bafba515-af11-47e6-abe3-af1200cd18b2') }}
79
80 - name: "Get list of all full Bitwarden records named 'a_test'"
81 ansible.builtin.debug:
82 msg: >-
83 {{ lookup('community.general.bitwarden', 'a_test') }}
84
85 - name: "Get custom field 'api_key' from all Bitwarden records named 'a_test'"
86 ansible.builtin.debug:
87 msg: >-
88 {{ lookup('community.general.bitwarden', 'a_test', field='api_key') }}
89
90 - name: "Get 'password' from all Bitwarden records named 'a_test', using given session key"
91 ansible.builtin.debug:
92 msg: >-
93 {{ lookup('community.general.bitwarden', 'a_test', field='password', bw_session='bXZ9B5TXi6...') }}
94
95 - name: "Get all Bitwarden records from collection"
96 ansible.builtin.debug:
97 msg: >-
98 {{ lookup('community.general.bitwarden', None, collection_id='bafba515-af11-47e6-abe3-af1200cd18b2') }}
99
100 - name: "Get all Bitwarden records from collection"
101 ansible.builtin.debug:
102 msg: >-
103 {{ lookup('community.general.bitwarden', None, collection_name='my_collections/test_collection') }}
104
105 - name: "Get Bitwarden record named 'a_test', ensure there is exactly one match"
106 ansible.builtin.debug:
107 msg: >-
108 {{ lookup('community.general.bitwarden', 'a_test', result_count=1) }}
109 """
110
111 RETURN = r"""
112 _raw:
113 description:
114 - A one-element list that contains a list of requested fields or JSON objects of matches.
115 - If you use C(query), you get a list of lists. If you use C(lookup) without C(wantlist=true), this always gets reduced
116 to a list of field values or JSON objects.
117 type: list
118 elements: list
119 """
120
121 from subprocess import PIPE, Popen
122
123 from ansible.errors import AnsibleError, AnsibleOptionsError
124 from ansible.module_utils.common.text.converters import to_bytes, to_text
125 from ansible.parsing.ajson import AnsibleJSONDecoder
126 from ansible.plugins.lookup import LookupBase
127
128 from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_wrong_terms
129
130
131 class BitwardenException(AnsibleError):
132 pass
133
134
135 class Bitwarden:
136 def __init__(self, path="bw"):
137 self._cli_path = path
138 self._session = None
139
140 @property
141 def cli_path(self):
142 return self._cli_path
143
144 @property
145 def session(self):
146 return self._session
147
148 @session.setter
149 def session(self, value):
150 self._session = value
151
152 @property
153 def unlocked(self):
154 out, err = self._run(["status"], stdin="")
155 decoded = AnsibleJSONDecoder().raw_decode(out)[0]
156 return decoded["status"] == "unlocked"
157
158 def _run(self, args, stdin=None, expected_rc=0):
159 if self.session:
160 args += ["--session", self.session]
161
162 p = Popen([self.cli_path] + args, stdout=PIPE, stderr=PIPE, stdin=PIPE)
163 out, err = p.communicate(to_bytes(stdin))
164 rc = p.wait()
165 if rc != expected_rc:
166 if len(args) > 2 and args[0] == "get" and args[1] == "item" and b"Not found." in err:
167 return "null", ""
168 raise BitwardenException(err)
169 return to_text(out, errors="surrogate_or_strict"), to_text(err, errors="surrogate_or_strict")
170
171 def _get_matches(self, search_value, search_field, collection_id=None, organization_id=None):
172 """Return matching records whose search_field is equal to key."""
173
174 # Prepare set of params for Bitwarden CLI
175 if search_field == "id":
176 params = ["get", "item", search_value]
177 else:
178 params = ["list", "items"]
179 if search_value:
180 params.extend(["--search", search_value])
181
182 if collection_id:
183 params.extend(["--collectionid", collection_id])
184 if organization_id:
185 params.extend(["--organizationid", organization_id])
186
187 out, err = self._run(params)
188
189 # This includes things that matched in different fields.
190 initial_matches = AnsibleJSONDecoder().raw_decode(out)[0]
191
192 if search_field == "id":
193 if initial_matches is None:
194 initial_matches = []
195 else:
196 initial_matches = [initial_matches]
197
198 # Filter to only include results from the right field, if a search is requested by value or field
199 return [
200 item
201 for item in initial_matches
202 if not search_value or not search_field or item.get(search_field) == search_value
203 ]
204
205 def get_field(self, field, search_value, search_field="name", collection_id=None, organization_id=None):
206 """Return a list of the specified field for records whose search_field match search_value
207 and filtered by collection if collection has been provided.
208
209 If field is None, return the whole record for each match.
210 """
211 matches = self._get_matches(search_value, search_field, collection_id, organization_id)
212 if not field:
213 return matches
214 field_matches = []
215 for match in matches:
216 # if there are no custom fields, then `match` has no key 'fields'
217 if "fields" in match:
218 custom_field_found = False
219 for custom_field in match["fields"]:
220 if field == custom_field["name"]:
221 field_matches.append(custom_field["value"])
222 custom_field_found = True
223 break
224 if custom_field_found:
225 continue
226 if "login" in match and field in match["login"]:
227 field_matches.append(match["login"][field])
228 continue
229 if field in match:
230 field_matches.append(match[field])
231 continue
232
233 if matches and not field_matches:
234 raise AnsibleError(f"field {field} does not exist in {search_value}")
235
236 return field_matches
237
238 def get_collection_ids(self, collection_name: str, organization_id=None) -> list[str]:
239 """Return matching IDs of collections whose name is equal to collection_name."""
240
241 # Prepare set of params for Bitwarden CLI
242 params = ["list", "collections", "--search", collection_name]
243
244 if organization_id:
245 params.extend(["--organizationid", organization_id])
246
247 out, err = self._run(params)
248
249 # This includes things that matched in different fields.
250 initial_matches = AnsibleJSONDecoder().raw_decode(out)[0] # type: ignore[operator]
251
252 # Filter to only return the ID of a collections with exactly matching name
253 return [item["id"] for item in initial_matches if str(item.get("name")).lower() == collection_name.lower()]
254
255
256 class LookupModule(LookupBase):
257 def run(self, terms=None, variables=None, **kwargs):
258 self.set_options(var_options=variables, direct=kwargs)
259 check_for_wrong_terms(self, direct=kwargs)
260 field = self.get_option("field")
261 search_field = self.get_option("search")
262 collection_id = self.get_option("collection_id")
263 collection_name = self.get_option("collection_name")
264 organization_id = self.get_option("organization_id")
265 result_count = self.get_option("result_count")
266 _bitwarden.session = self.get_option("bw_session")
267
268 if not _bitwarden.unlocked:
269 raise AnsibleError("Bitwarden Vault locked. Run 'bw unlock'.")
270
271 if not terms:
272 terms = [None]
273
274 if collection_name and collection_id:
275 raise AnsibleOptionsError("'collection_name' and 'collection_id' are mutually exclusive!")
276 elif collection_name:
277 collection_ids = _bitwarden.get_collection_ids(collection_name, organization_id)
278 if not collection_ids:
279 raise BitwardenException("No matching collections found!")
280 else:
281 collection_ids = [collection_id]
282
283 results = [
284 _bitwarden.get_field(field, term, search_field, collection_id, organization_id)
285 for collection_id in collection_ids
286 for term in terms
287 ]
288
289 for result in results:
290 if result_count is not None and len(result) != result_count:
291 raise BitwardenException(
292 f"Number of results doesn't match result_count! ({len(result)} != {result_count})"
293 )
294
295 return results
296
297
298 _bitwarden = Bitwarden()