Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_pritunl_api.py

raw
1 # Copyright (c) 2021, Florian Dambrine <[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 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 """
9 Pritunl API that offers CRUD operations on Pritunl Organizations and Users
10 """
11
12 from __future__ import annotations
13
14 import base64
15 import hashlib
16 import hmac
17 import json
18 import time
19 import typing as t
20 import uuid
21 from http import HTTPStatus
22
23 from ansible.module_utils.urls import open_url
24
25 if t.TYPE_CHECKING:
26 from ansible.module_utils.basic import AnsibleModule
27
28
29 class PritunlException(Exception):
30 pass
31
32
33 def pritunl_argument_spec() -> dict[str, t.Any]:
34 return dict(
35 pritunl_url=dict(required=True, type="str"),
36 pritunl_api_token=dict(required=True, type="str", no_log=False),
37 pritunl_api_secret=dict(required=True, type="str", no_log=True),
38 validate_certs=dict(required=False, type="bool", default=True),
39 )
40
41
42 def get_pritunl_settings(module: AnsibleModule) -> dict[str, t.Any]:
43 """
44 Helper function to set required Pritunl request params from module arguments.
45 """
46 return {
47 "api_token": module.params.get("pritunl_api_token"),
48 "api_secret": module.params.get("pritunl_api_secret"),
49 "base_url": module.params.get("pritunl_url"),
50 "validate_certs": module.params.get("validate_certs"),
51 }
52
53
54 def _get_pritunl_organizations(api_token, api_secret, base_url: str, validate_certs: bool = True):
55 return pritunl_auth_request(
56 base_url=base_url,
57 api_token=api_token,
58 api_secret=api_secret,
59 method="GET",
60 path="/organization",
61 validate_certs=validate_certs,
62 )
63
64
65 def _delete_pritunl_organization(
66 api_token, api_secret, base_url: str, organization_id: str, validate_certs: bool = True
67 ):
68 return pritunl_auth_request(
69 base_url=base_url,
70 api_token=api_token,
71 api_secret=api_secret,
72 method="DELETE",
73 path=f"/organization/{organization_id}",
74 validate_certs=validate_certs,
75 )
76
77
78 def _post_pritunl_organization(
79 api_token, api_secret, base_url: str, organization_data: object, validate_certs: bool = True
80 ):
81 return pritunl_auth_request(
82 api_token=api_token,
83 api_secret=api_secret,
84 base_url=base_url,
85 method="POST",
86 path="/organization",
87 headers={"Content-Type": "application/json"},
88 data=json.dumps(organization_data),
89 validate_certs=validate_certs,
90 )
91
92
93 def _get_pritunl_users(api_token, api_secret, base_url: str, organization_id: str, validate_certs: bool = True):
94 return pritunl_auth_request(
95 api_token=api_token,
96 api_secret=api_secret,
97 base_url=base_url,
98 method="GET",
99 path=f"/user/{organization_id}",
100 validate_certs=validate_certs,
101 )
102
103
104 def _delete_pritunl_user(
105 api_token, api_secret, base_url: str, organization_id: str, user_id: str, validate_certs: bool = True
106 ):
107 return pritunl_auth_request(
108 api_token=api_token,
109 api_secret=api_secret,
110 base_url=base_url,
111 method="DELETE",
112 path=f"/user/{organization_id}/{user_id}",
113 validate_certs=validate_certs,
114 )
115
116
117 def _post_pritunl_user(
118 api_token, api_secret, base_url: str, organization_id: str, user_data: object, validate_certs=True
119 ):
120 return pritunl_auth_request(
121 api_token=api_token,
122 api_secret=api_secret,
123 base_url=base_url,
124 method="POST",
125 path=f"/user/{organization_id}",
126 headers={"Content-Type": "application/json"},
127 data=json.dumps(user_data),
128 validate_certs=validate_certs,
129 )
130
131
132 def _put_pritunl_user(
133 api_token,
134 api_secret,
135 base_url: str,
136 organization_id: str,
137 user_id: str,
138 user_data: object,
139 validate_certs: bool = True,
140 ):
141 return pritunl_auth_request(
142 api_token=api_token,
143 api_secret=api_secret,
144 base_url=base_url,
145 method="PUT",
146 path=f"/user/{organization_id}/{user_id}",
147 headers={"Content-Type": "application/json"},
148 data=json.dumps(user_data),
149 validate_certs=validate_certs,
150 )
151
152
153 def list_pritunl_organizations(
154 api_token, api_secret, base_url: str, validate_certs: bool = True, filters: dict[str, t.Any] | None = None
155 ) -> list:
156 orgs = []
157
158 response = _get_pritunl_organizations(
159 api_token=api_token,
160 api_secret=api_secret,
161 base_url=base_url,
162 validate_certs=validate_certs,
163 )
164
165 if response.getcode() != HTTPStatus.OK:
166 raise PritunlException("Could not retrieve organizations from Pritunl")
167 else:
168 for org in json.loads(response.read()):
169 # No filtering
170 if filters is None:
171 orgs.append(org)
172 else:
173 if not any(filter_val != org[filter_key] for filter_key, filter_val in filters.items()):
174 orgs.append(org)
175
176 return orgs
177
178
179 def list_pritunl_users(
180 api_token,
181 api_secret,
182 base_url: str,
183 organization_id: str,
184 validate_certs: bool = True,
185 filters: dict[str, t.Any] | None = None,
186 ):
187 users = []
188
189 response = _get_pritunl_users(
190 api_token=api_token,
191 api_secret=api_secret,
192 base_url=base_url,
193 validate_certs=validate_certs,
194 organization_id=organization_id,
195 )
196
197 if response.getcode() != HTTPStatus.OK:
198 raise PritunlException("Could not retrieve users from Pritunl")
199 else:
200 for user in json.loads(response.read()):
201 # No filtering
202 if filters is None:
203 users.append(user)
204
205 else:
206 if not any(filter_val != user[filter_key] for filter_key, filter_val in filters.items()):
207 users.append(user)
208
209 return users
210
211
212 def post_pritunl_organization(
213 api_token,
214 api_secret,
215 base_url: str,
216 organization_name: str,
217 validate_certs: bool = True,
218 ):
219 response = _post_pritunl_organization(
220 api_token=api_token,
221 api_secret=api_secret,
222 base_url=base_url,
223 organization_data={"name": organization_name},
224 validate_certs=validate_certs,
225 )
226
227 if response.getcode() != HTTPStatus.OK:
228 raise PritunlException(f"Could not add organization {organization_name} to Pritunl")
229 # The user PUT request returns the updated user object
230 return json.loads(response.read())
231
232
233 def post_pritunl_user(
234 api_token,
235 api_secret,
236 base_url: str,
237 organization_id: str,
238 user_data: object,
239 user_id: str | None = None,
240 validate_certs: bool = True,
241 ):
242 # If user_id is provided will do PUT otherwise will do POST
243 if user_id is None:
244 response = _post_pritunl_user(
245 api_token=api_token,
246 api_secret=api_secret,
247 base_url=base_url,
248 organization_id=organization_id,
249 user_data=user_data,
250 validate_certs=validate_certs,
251 )
252
253 if response.getcode() != HTTPStatus.OK:
254 raise PritunlException(f"Could not remove user {user_id} from organization {organization_id} from Pritunl")
255 # user POST request returns an array of a single item,
256 # so return this item instead of the list
257 return json.loads(response.read())[0]
258 else:
259 response = _put_pritunl_user(
260 api_token=api_token,
261 api_secret=api_secret,
262 base_url=base_url,
263 organization_id=organization_id,
264 user_data=user_data,
265 user_id=user_id,
266 validate_certs=validate_certs,
267 )
268
269 if response.getcode() != HTTPStatus.OK:
270 raise PritunlException(f"Could not update user {user_id} from organization {organization_id} from Pritunl")
271 # The user PUT request returns the updated user object
272 return json.loads(response.read())
273
274
275 def delete_pritunl_organization(
276 api_token, api_secret, base_url: str, organization_id: str, validate_certs: bool = True
277 ):
278 response = _delete_pritunl_organization(
279 api_token=api_token,
280 api_secret=api_secret,
281 base_url=base_url,
282 organization_id=organization_id,
283 validate_certs=validate_certs,
284 )
285
286 if response.getcode() != HTTPStatus.OK:
287 raise PritunlException(f"Could not remove organization {organization_id} from Pritunl")
288
289 return json.loads(response.read())
290
291
292 def delete_pritunl_user(
293 api_token, api_secret, base_url: str, organization_id: str, user_id: str, validate_certs: bool = True
294 ):
295 response = _delete_pritunl_user(
296 api_token=api_token,
297 api_secret=api_secret,
298 base_url=base_url,
299 organization_id=organization_id,
300 user_id=user_id,
301 validate_certs=validate_certs,
302 )
303
304 if response.getcode() != HTTPStatus.OK:
305 raise PritunlException(f"Could not remove user {user_id} from organization {organization_id} from Pritunl")
306
307 return json.loads(response.read())
308
309
310 def pritunl_auth_request(
311 api_token,
312 api_secret,
313 base_url: str,
314 method: str,
315 path: str,
316 validate_certs: bool = True,
317 headers: dict[str, str] | None = None,
318 data: bytes | str | None = None,
319 ):
320 """
321 Send an API call to a Pritunl server.
322 Taken from https://pritunl.com/api and adapted to work with Ansible open_url
323 """
324 auth_timestamp = str(int(time.time()))
325 auth_nonce = uuid.uuid4().hex
326
327 auth_string = f"{api_token}&{auth_timestamp}&{auth_nonce}&{method.upper()}&{path}"
328
329 auth_signature = base64.b64encode(
330 hmac.new(api_secret.encode("utf-8"), auth_string.encode("utf-8"), hashlib.sha256).digest()
331 )
332
333 auth_headers = {
334 "Auth-Token": api_token,
335 "Auth-Timestamp": auth_timestamp,
336 "Auth-Nonce": auth_nonce,
337 "Auth-Signature": auth_signature,
338 }
339
340 if headers:
341 auth_headers.update(headers)
342
343 try:
344 uri = f"{base_url}{path}"
345
346 return open_url(
347 uri,
348 method=method.upper(),
349 headers=auth_headers,
350 data=data,
351 validate_certs=validate_certs,
352 )
353 except Exception as e:
354 raise PritunlException(e) from e