-
Notifications
You must be signed in to change notification settings - Fork 31
/
client.py
425 lines (347 loc) · 15.2 KB
/
client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
"""Python Client for connecting to 1Password Connect"""
import httpx
from httpx import HTTPError
import json
import os
from onepasswordconnectsdk.async_client import AsyncClient
from onepasswordconnectsdk.serializer import Serializer
from onepasswordconnectsdk.utils import build_headers, is_valid_uuid, PathBuilder
from onepasswordconnectsdk.errors import (
FailedToRetrieveItemException,
FailedToRetrieveVaultException,
EnvironmentHostNotSetException,
EnvironmentTokenNotSetException,
)
from onepasswordconnectsdk.models import Item, ItemVault
from onepasswordconnectsdk.models.constants import CONNECT_HOST_ENV_VARIABLE
ENV_SERVICE_ACCOUNT_JWT_VARIABLE = "OP_CONNECT_TOKEN"
ENV_IS_ASYNC_CLIENT = "OP_CONNECT_CLIENT_ASYNC"
class Client:
"""Python Client Class"""
def __init__(self, url: str, token: str):
"""Initialize client"""
self.url = url
self.token = token
self.session = self.create_session(url, token)
self.serializer = Serializer()
def create_session(self, url: str, token: str):
return httpx.Client(base_url=url, headers=self.build_headers(token))
def build_headers(self, token: str):
return build_headers(token)
def __del__(self):
self.session.close()
def get_file(self, file_id: str, item_id: str, vault_id: str):
url = PathBuilder().vaults(vault_id).items(item_id).files(file_id).build()
response = self.build_request("GET", url)
try:
response.raise_for_status()
except HTTPError:
raise FailedToRetrieveItemException(
f"Unable to retrieve item. Received {response.status_code}\
for {url} with message: {response.json().get('message')}"
)
return self.serializer.deserialize(response.content, "File")
def get_files(self, item_id: str, vault_id: str):
url = PathBuilder().vaults(vault_id).items(item_id).files().build()
response = self.build_request("GET", url)
try:
response.raise_for_status()
except HTTPError:
raise FailedToRetrieveItemException(
f"Unable to retrieve item. Received {response.status_code}\
for {url} with message: {response.json().get('message')}"
)
return self.serializer.deserialize(response.content, "list[File]")
def get_file_content(self, file_id: str, item_id: str, vault_id: str, content_path: str = None):
url = content_path
if content_path is None:
url = PathBuilder().vaults(vault_id).items(item_id).files(file_id).content().build()
response = self.build_request("GET", url)
try:
response.raise_for_status()
except HTTPError:
raise FailedToRetrieveItemException(
f"Unable to retrieve items. Received {response.status_code} \
for {url} with message: {response.json().get('message')}"
)
return response.content
def download_file(self, file_id: str, item_id: str, vault_id: str, path: str):
file_object = self.get_file(file_id, item_id, vault_id)
filename = file_object.name or "1password_item_file.txt"
content = self.get_file_content(file_id, item_id, vault_id, file_object.content_path)
global_path = os.path.join(path, filename)
file = open(global_path, "wb")
file.write(content)
file.close()
def get_item(self, item: str, vault: str):
"""Get a specific item
Args:
item (str): the id or title of the item to be fetched
vault (str): the id or name of the vault in which to get the item from
Raises:
FailedToRetrieveItemException: Thrown when a HTTP error is returned
from the 1Password Connect API
Returns:
Item object: The found item
"""
vault_id = vault
if not is_valid_uuid(vault):
vault_id = self.get_vault_by_title(vault).id
if is_valid_uuid(item):
return self.get_item_by_id(item, vault_id)
else:
return self.get_item_by_title(item, vault_id)
def get_item_by_id(self, item_id: str, vault_id: str):
"""Get a specific item by uuid
Args:
item_id (str): The id of the item to be fetched
vault_id (str): The id of the vault in which to get the item from
Raises:
FailedToRetrieveItemException: Thrown when a HTTP error is returned
from the 1Password Connect API
Returns:
Item object: The found item
"""
url = PathBuilder().vaults(vault_id).items(item_id).build()
response = self.build_request("GET", url)
try:
response.raise_for_status()
except HTTPError:
raise FailedToRetrieveItemException(
f"Unable to retrieve item. Received {response.status_code}\
for {url} with message: {response.json().get('message')}"
)
return self.serializer.deserialize(response.content, "Item")
def get_item_by_title(self, title: str, vault_id: str):
"""Get a specific item by title
Args:
title (str): The title of the item to be fetched
vault_id (str): The id of the vault in which to get the item from
Raises:
FailedToRetrieveItemException: Thrown when a HTTP error is returned
from the 1Password Connect API
Returns:
Item object: The found item
"""
filter_query = f'title eq "{title}"'
url = PathBuilder().vaults(vault_id).items().query("filter", filter_query).build()
response = self.build_request("GET", url)
try:
response.raise_for_status()
except HTTPError:
raise FailedToRetrieveItemException(
f"Unable to retrieve items. Received {response.status_code} \
for {url} with message: {response.json().get('message')}"
)
if len(response.json()) != 1:
raise FailedToRetrieveItemException(
f"Found {len(response.json())} items in vault {vault_id} with \
title {title}"
)
item_summary = self.serializer.deserialize(response.content, "list[SummaryItem]")[0]
return self.get_item_by_id(item_summary.id, vault_id)
def get_items(self, vault_id: str, filter_query: str = None):
"""Returns a list of item summaries for the specified vault
Args:
vault_id (str): The id of the vault in which to get the items from
filter_query (str): A optional query statement. `title eq "Example Item"`
Raises:
FailedToRetrieveItemException: Thrown when a HTTP error is returned
from the 1Password Connect API
Returns:
List[SummaryItem]: A list of summarized items
"""
if filter_query is None:
url = PathBuilder().vaults(vault_id).items().build()
else:
url = PathBuilder().vaults(vault_id).items().query("filter", filter_query).build()
response = self.build_request("GET", url)
try:
response.raise_for_status()
except HTTPError:
raise FailedToRetrieveItemException(
f"Unable to retrieve items. Received {response.status_code} \
for {url} with message: {response.json().get('message')}"
)
return self.serializer.deserialize(response.content, "list[SummaryItem]")
def delete_item(self, item_id: str, vault_id: str):
"""Deletes a specified item from a specified vault
Args:
item_id (str): The id of the item in which to delete the item from
vault_id (str): The id of the vault in which to delete the item
Raises:
FailedToRetrieveItemException: Thrown when a HTTP error is returned
from the 1Password Connect API
"""
url = PathBuilder().vaults(vault_id).items(item_id).build()
response = self.build_request("DELETE", url)
try:
response.raise_for_status()
except HTTPError:
raise FailedToRetrieveItemException(
f"Unable to delete item. Received {response.status_code}\
for {url} with message: {response.json().get('message')}"
)
def create_item(self, vault_id: str, item: Item):
"""Creates an item at the specified vault
Args:
vault_id (str): The id of the vault in which add the item to
item (Item): The item to create
Raises:
FailedToRetrieveItemException: Thrown when a HTTP error is returned
from the 1Password Connect API
Returns:
Item: The created item
"""
url = PathBuilder().vaults(vault_id).items().build()
response = self.build_request("POST", url, item)
try:
response.raise_for_status()
except HTTPError:
raise FailedToRetrieveItemException(
f"Unable to post item. Received {response.status_code}\
for {url} with message: {response.json().get('message')}"
)
return self.serializer.deserialize(response.content, "Item")
def update_item(self, item_uuid: str, vault_id: str, item: Item):
"""Update the specified item at the specified vault.
Args:
item_uuid (str): The id of the item in which to update
vault_id (str): The id of the vault in which to update the item
item (Item): The updated item
Raises:
FailedToRetrieveItemException: Thrown when a HTTP error is returned
from the 1Password Connect API
Returns:
Item: The updated item
"""
url = PathBuilder().vaults(vault_id).items(item_uuid).build()
item.id = item_uuid
item.vault = ItemVault(id=vault_id)
response = self.build_request("PUT", url, item)
try:
response.raise_for_status()
except HTTPError:
raise FailedToRetrieveItemException(
f"Unable to post item. Received {response.status_code}\
for {url} with message: {response.json().get('message')}"
)
return self.serializer.deserialize(response.content, "Item")
def get_vault(self, vault_id: str):
"""Returns the vault with the given vault_id
Args:
vault_id (str): The id of the vault in which to fetch
Raises:
FailedToRetrieveVaultException: Thrown when a HTTP error is
returned from the 1Password Connect API
Returns:
Vault: The specified vault
"""
url = PathBuilder().vaults(vault_id).build()
response = self.build_request("GET", url)
try:
response.raise_for_status()
except HTTPError:
raise FailedToRetrieveVaultException(
f"Unable to retrieve vault. Received {response.status_code} \
for {url} with message {response.json().get('message')}"
)
return self.serializer.deserialize(response.content, "Vault")
def get_vault_by_title(self, name: str):
"""Returns the vault with the given name
Args:
name (str): The name of the vault in which to fetch
Raises:
FailedToRetrieveVaultException: Thrown when a HTTP error is
returned from the 1Password Connect API
Returns:
Vault: The specified vault
"""
filter_query = f'name eq "{name}"'
url = PathBuilder().vaults().query("filter", filter_query).build()
response = self.build_request("GET", url)
try:
response.raise_for_status()
except HTTPError:
raise FailedToRetrieveVaultException(
f"Unable to retrieve vaults. Received {response.status_code} \
for {url} with message {response.json().get('message')}"
)
if len(response.json()) != 1:
raise FailedToRetrieveItemException(
f"Found {len(response.json())} vaults with \
name {name}"
)
return self.serializer.deserialize(response.content, "list[Vault]")[0]
def get_vaults(self):
"""Returns all vaults for service account set in client
Raises:
FailedToRetrieveVaultException: Thrown when a HTTP error is
returned from the 1Password Connect API
Returns:
List[Vault]: All vaults for the service account in use
"""
url = PathBuilder().vaults().build()
response = self.build_request("GET", url)
try:
response.raise_for_status()
except HTTPError:
raise FailedToRetrieveVaultException(
f"Unable to retrieve vaults. Received {response.status_code} \
for {url} with message {response.json().get('message')}"
)
return self.serializer.deserialize(response.content, "list[Vault]")
def build_request(self, method: str, path: str, body=None):
"""Builds a http request
Parameters:
method (str): The rest method to be used
path (str): The request path
body (str): The request body
Returns:
Response object: The request response
"""
if body:
serialized_body = json.dumps(self.serializer.sanitize_for_serialization(body))
response = self.session.request(method, path, data=serialized_body)
else:
response = self.session.request(method, path)
return response
def deserialize(self, response, response_type):
return self.serializer.deserialize(response, response_type)
def sanitize_for_serialization(self, obj):
return self.serializer.sanitize_for_serialization(obj)
def new_client(url: str, token: str, is_async: bool = False):
"""Builds a new client for interacting with 1Password Connect
Parameters:
url: The url of the 1Password Connect API
token: The 1Password Service Account token
is_async: Initialize async or sync client
Returns:
Client: The 1Password Connect client
"""
if is_async:
return AsyncClient(url, token)
return Client(url, token)
def new_client_from_environment(url: str = None):
"""Builds a new client for interacting with 1Password Connect
using the OP_TOKEN environment variable
Parameters:
url: The url of the 1Password Connect API
token: The 1Password Service Account token
Returns:
Client: The 1Password Connect client
"""
token = os.environ.get(ENV_SERVICE_ACCOUNT_JWT_VARIABLE)
is_async = os.environ.get(ENV_IS_ASYNC_CLIENT) == "True"
if url is None:
url = os.environ.get(CONNECT_HOST_ENV_VARIABLE)
if url is None:
raise EnvironmentHostNotSetException(
f"{CONNECT_HOST_ENV_VARIABLE} environment variable is not set"
)
if token is None:
raise EnvironmentTokenNotSetException(
"There is no token available in the "
f"{ENV_SERVICE_ACCOUNT_JWT_VARIABLE} variable"
)
return new_client(url, token, is_async)