forked from corpusops/bitwardentools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
3219 lines (2951 loc) · 109 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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""
API client Alike wrapper around @bitwarden/cli npm package bu also with local implementation
Tested with cli version 1.14.0
"""
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import enum
import itertools
import json
import os
import re
import secrets
import traceback
from base64 import b64decode, b64encode
from collections import OrderedDict
from copy import deepcopy
from subprocess import run
from time import time
import requests
from jwt import encode as jwt_encode
from packaging import version as _version
from bitwardentools import crypto as bwcrypto
from bitwardentools.common import L, caseinsentive_key_search
VAULTIER_FIELD_ID = "vaultiersecretid"
DEFAULT_CACHE = {"id": {}, "name": {}, "sync": False}
SYNC_ALL_ORGAS_ID = "__orga__all__ORGAS__"
SYNC_ORGA_ID = "__orga__{0}"
SECRET_CACHE = {"id": {}, "name": {}, "vaultiersecretid": {}, "sync": []}
DEFAULT_BITWARDEN_CACHE = {
"sync": {},
"templates": {},
"users": deepcopy(DEFAULT_CACHE),
"organizations": deepcopy(DEFAULT_CACHE),
"collections": {"sync": False, SYNC_ALL_ORGAS_ID: deepcopy(DEFAULT_CACHE)},
"ciphers": {
"sync": False,
"by_cipher": deepcopy(SECRET_CACHE),
"by_collection": {},
"by_organization": {},
},
}
CACHE = deepcopy(DEFAULT_BITWARDEN_CACHE)
FILTERED_ATTRS = re.compile("^_|^vaultier|^json$")
TYPES_MAPPING = {"org-collection": "orgcollection"}
REVERSE_TYPES_MAPPING = dict([(v, k) for k, v in TYPES_MAPPING.items()])
SERVER = os.environ.get("BITWARDEN_SERVER")
PRIVATE_KEY = os.environ.get("BITWARDEN_PRIVATE_KEY") or None
EMAIL = os.environ.get("BITWARDEN_EMAIL")
PASSWORD = os.environ.get("BITWARDEN_PW")
ADMIN_PASSWORD = os.environ.get("BITWARDEN_ADMIN_PASSWORD", "")
ADMIN_USER = os.environ.get("BITWARDEN_ADMIN_USER", "")
CUUID = os.environ.get("BITWARDEN_CLIENT_UUID", "42042042-0042-0042-0042-420004200042")
TYPMAPPER = {
"organization": "organization",
"collection": "collection",
"orgccollection": "collection",
"cipher": "cipher",
"cipherdetails": "cipher",
"item": "cipher",
"card": "cipher",
"note": "cipher",
"securenote": "cipher",
"identity": "cipher",
"login": "cipher",
"profile": "profile",
"user": "profile",
}
COLTYPMAPPER = {
"organization": "organizations",
"collection": "collections",
"orgcollection": "collections",
"user": "users",
"profiles": "users",
"profile": "users",
"cipher": "ciphers",
"cipherdetails": "ciphers",
"item": "ciphers",
"card": "ciphers",
"note": "ciphers",
"securenote": "ciphers",
"login": "ciphers",
}
ORGA_PERMISSIONS = {
"accessBusinessPortal": False,
"accessEventLogs": False,
"accessImportExport": False,
"accessReports": False,
"manageAllCollections": False,
"manageAssignedCollections": False,
"manageGroups": False,
"manageSso": False,
"managePolicies": False,
"manageUsers": False,
}
IS_BITWARDEN_RE = re.compile(
"[0-9][0-9][0-9][0-9][.][0-9][0-9]?[.][0-9][0-9]?", flags=re.I | re.U | re.M
)
API_CHANGES = {
"1.27.0": _version.parse("1.27.0"),
}
def uncapitzalize(s):
if not s or not isinstance(s, str):
return s
return s[0].lower() + s[1:]
def clibase64(item):
if not isinstance(item, str):
item = json.dumps(item)
enc = b64encode(item.encode()).replace(b"\n", b"")
return enc.decode()
def strip_dict_data(data, skip=None):
if skip and isinstance(skip, list):
skip = "|".join(skip)
if skip:
skip = re.compile(skip)
data = deepcopy(data)
if isinstance(data, dict):
for d in [a for a in data]:
if skip and skip.search(d):
data.pop(d, None)
continue
data[d] = strip_dict_data(data[d], skip=skip)
elif isinstance(data, (list, tuple, set)):
a = []
for i in data:
a.append(strip_dict_data(i, skip=skip))
data = type(data)(a)
return data
def rewrite_acls_collection(i, skip=None):
if skip and isinstance(skip, list):
skip = "|".join(skip)
if skip:
skip = re.compile(skip)
if isinstance(i, dict):
for v, k in {
"Data": "data",
"Id": "id",
"AccessAll": "accessAll",
"Email": "email",
"Name": "name",
"Status": "status",
"Collections": "collections",
"UserId": "userId",
"Type": "type",
"HidePasswords": "hidePasswords",
"ReadOnly": "readOnly",
}.items():
if skip and (skip.search(v) or skip.search(k)):
i.pop(v, None)
i.pop(k, None)
try:
i[k] = rewrite_acls_collection(i.pop(v), skip=skip)
except KeyError:
continue
return i
elif isinstance(i, list):
for idx in range(len(i)):
i[idx] = rewrite_acls_collection(i[idx], skip=skip)
return i
class BitwardenError(Exception):
"""."""
class ConfirmationAcceptError(BitwardenError):
"""."""
email = None
orga = None
class AlreadyConfirmedError(ConfirmationAcceptError):
"""."""
class PostConfirmedError(ConfirmationAcceptError):
"""."""
response = None
class InvitationAcceptError(BitwardenError):
"""."""
email = None
orga = None
class AlreadyInvitedError(InvitationAcceptError):
"""."""
class PostInvitedError(InvitationAcceptError):
"""."""
response = None
class BitwardenUncacheError(BitwardenError):
"""."""
class BitwardenInvalidInput(BitwardenError):
"""."""
inputs = None
class ResponseError(BitwardenError):
"""."""
response = None
class UnimplementedError(BitwardenError):
"""."""
class DecryptError(bwcrypto.DecryptError):
"""."""
class SearchError(BitwardenError):
"""."""
criteria = None
class OrganizationNotFound(SearchError):
"""."""
class CollectionNotFound(SearchError):
"""."""
class SecretNotFound(SearchError):
"""."""
class ColSecretsSearchError(SearchError):
"""."""
class SecretSearchError(SearchError):
"""."""
class UserNotFoundError(SearchError):
"""."""
class ColSearchError(SearchError):
"""."""
class RunError(BitwardenError):
"""."""
class NoOrganizationKeyError(BitwardenError):
"""."""
instance = None
class NoSingleItemForNameError(BitwardenError):
"""."""
instance = None
class NoSingleOrgaForNameError(NoSingleItemForNameError):
"""."""
class NoSingleCollectionForNameError(NoSingleItemForNameError):
"""."""
class NoAttachmentsError(BitwardenError):
"""."""
instance = None
class LoginError(ResponseError):
"""."""
class DeleteError(ResponseError):
"""."""
class CiphersError(ResponseError):
pass
class BitwardenValidateError(BitwardenError):
"""."""
email = None
class BitwardenPostValidateError(ResponseError, BitwardenValidateError):
"""."""
class CliRunError(BitwardenError):
"""."""
process = None
class CliLoginError(LoginError, CliRunError):
"""."""
process = None
class AlreadyExitingUserError(RunError):
"""."""
class NoAccessError(BitwardenError):
"""."""
objects = None
def _get_obj_type(t):
o = t.replace("-", "").lower().capitalize()
obj = globals()[o]
assert issubclass(obj, BWFactory)
return o, obj
def get_obj_type(t):
return _get_obj_type(t)[0]
def get_obj(t):
return _get_obj_type(t)[1]
def get_bw_type(t):
o = get_obj_type(t).lower()
return REVERSE_TYPES_MAPPING.get(o, o)
def get_types(t):
return {"obj": get_obj_type(t), "bw": get_bw_type(t)}
def get_type(obj, default=""):
if isinstance(obj, BWFactory):
objtyp = getattr(obj, "Object", getattr(obj, "object", ""))
elif isinstance(obj, dict):
objtyp = obj.get("Object", obj.get("object", ""))
else:
objtyp = default
return objtyp.lower()
def get_bw_cipher_type(obj):
if isinstance(obj, Item):
bwciphertyp = obj.__class__.__name__.lower()
else:
bwciphertyp = get_type(obj)
cipher_type = SECRETS_CLASSES_STR[bwciphertyp]
return cipher_type
def unmarshall_value(value, cycle=0):
if isinstance(value, (tuple, list)):
nvalue = type(value)([unmarshall_value(a, cycle + 1) for a in value])
elif isinstance(value, dict):
nvalue = type(value)()
for k, val in value.items():
nvalue[uncapitzalize(k)] = unmarshall_value(val, cycle + 1)
else:
nvalue = value
return nvalue
class BWFactory(object):
def __init__(
self,
jsond=None,
client=None,
vaultier=False,
vaultiersecretid=None,
unmarshall=False,
):
if unmarshall:
jsond = unmarshall_value(jsond)
self._client = client
self.json = jsond
if vaultiersecretid:
vaultier = True
for k in ["vaultier", "vaultiersecretid"]:
setattr(self, k, jsond.pop(k, locals()[k]))
self.broken_objs = OrderedDict()
def delete(self, client):
return client.delete(self)
def reflect(self):
for i, v in [
a for a in self.__dict__.items() if not FILTERED_ATTRS.match(a[0])
]:
self.json[i] = v
for i in [a for a in self.json if FILTERED_ATTRS.match(a)]:
self.json.pop(i)
return self
def load(self, jsond=None):
if jsond is None:
jsond = self.json
if jsond:
for i, val in jsond.items():
setattr(self, i, val)
if self.vaultiersecretid:
self.vaultier = True
fields = getattr(self, "fields", []) or []
for itm in fields:
for i in [a for a in itm]:
val = itm[i]
if hasattr(val, "decode"):
val = val.decode()
itm[i] = val
if self.vaultiersecretid or fields:
try:
item = None
for itm in fields:
if itm["name"] == VAULTIER_FIELD_ID:
item = itm
break
if item:
if self.vaultiersecretid:
item["value"] = f"{self.vaultiersecretid}"
self.vaultiersecretid = item["value"]
if self.vaultiersecretid:
if not item:
fields.append(
{
"value": f"{self.vaultiersecretid}",
"type": 0,
"name": VAULTIER_FIELD_ID,
}
)
self.vaultier = True
setattr(self, "fields", fields)
except AttributeError:
pass
return self
@classmethod
def construct(
kls,
jsond,
vaultier=None,
vaultiersecretid=None,
unmarshall=False,
object_class=None,
client=None,
*a,
**kw,
):
if object_class is None:
try:
object_class_name = jsond["object"]
except KeyError:
object_class_name = jsond["Object"]
if object_class_name.lower().startswith("cipher"):
try:
typ = jsond["Type"]
object_class = SECRETS_CLASSES[typ]
except KeyError:
L.error(f'Unkown cipher {jsond.get("Id", "")}')
else:
object_class = get_obj(object_class_name)
a = object_class(
jsond,
vaultier=vaultier,
vaultiersecretid=vaultiersecretid,
unmarshall=unmarshall,
client=client,
)
return a.load()
@classmethod
def patch(kls, action, client, bwtype=None, add_template=True, token=None, **jsond):
token = client.get_token(token=token)
if bwtype is None:
bwtype = get_bw_type(jsond["object"])
otype = get_obj_type(bwtype)
smethod = f"{action}_{otype.lower()}"
try:
api_method = getattr(client, smethod)
except AttributeError:
api_method = None
if api_method:
add_template = False
jsond["object"] = bwtype
if add_template:
jsond = client.get_template(**jsond)
obj = kls.construct(jsond).reflect()
log = f"{action.capitalize()}ed"
if not api_method:
tpl = {}
for k in [key for key in jsond]:
try:
tpl[k] = getattr(obj, k)
except AttributeError:
continue
enc = b64encode(json.dumps(tpl).encode())
denc = enc.decode()
cmd = f"{action} {bwtype}"
if action == "edit":
cmd += f' {tpl["id"]}'
orgaid = jsond.get("organizationId", "")
if orgaid:
orga = client.get_organization(orgaid, token=token)
organ = isinstance(orga, Organization) and orga.name or orga
cmd += f" --organizationid {client.item_or_id(orga)}"
log += f" in orga {organ}"
cmd += f" {denc}"
try:
ret = client.call(cmd, asjson=True, load=True)
except (CliRunError,):
trace = traceback.format_exc()
raise CliRunError(trace)
log += f": {otype}: {ret.name}/{ret.id}"
L.info(log)
else:
ret = api_method(**jsond)
return ret
@classmethod
def create(kls, client, *args, **kw):
return kls.patch("create", client, *args, **kw)
@classmethod
def edit(kls, client, *args, **kw):
return kls.patch("edit", client, *args, **kw)
class CipherType(enum.IntEnum):
Login = 1
Card = 3
Note = 2
Identity = 4
class CollectionAccess(enum.IntEnum):
owner = 0
admin = 1
manager = 3
user = 2
class Profile(BWFactory):
"""."""
class Organization(BWFactory):
"""."""
def __init__(self, *a, **kw):
ret = super(Organization, self).__init__(*a, **kw)
self._complete = False
return ret
class Cipher(BWFactory):
"""."""
class Cipherdetails(Cipher):
"""."""
class Item(Cipherdetails):
"""."""
def load(self, jsond=None):
super(Item, self).load(jsond)
if self.vaultier:
sid = [
a["value"]
for a in self.json.get("fields", [])
if a.get("name", "") == VAULTIER_FIELD_ID
]
if sid:
sid = sid[0]
else:
sid = None
self.vaultiersecretid = sid
return self
class Attachment(Item):
"""."""
class Login(Item):
"""."""
class Note(Item):
"""."""
SecureNote = Note
Securenote = Note
class Identity(Item):
"""."""
class Card(Item):
"""."""
class Folder(BWFactory):
"""."""
SECRETS_CLASSES = {
CipherType.Login: Login,
CipherType.Card: Card,
CipherType.Note: Note,
CipherType.Identity: Identity,
}
SECRETS_CLASSES_STR = {
"login": CipherType.Login,
"card": CipherType.Card,
"note": CipherType.Note,
"identity": CipherType.Identity,
}
class Collection(BWFactory):
"""."""
def __init__(self, *a, **kw):
BWFactory.__init__(self, *a, **kw)
self.externalId = getattr(self, "externalId", None)
self._orga = None
self.reflect()
def load(self, *a, **kw):
super(Collection, self).load(*a, **kw)
if self._client and getattr(self, "organizationId"):
try:
self._orga = self._client.get_organization(self.organizationId)
except OrganizationNotFound:
pass
return self
Orgcollection = Collection
class Client(object):
def __init__(
self,
server=SERVER,
email=EMAIL,
password=PASSWORD,
admin_user=ADMIN_USER,
admin_password=ADMIN_PASSWORD,
private_key=PRIVATE_KEY,
client_id="python",
client_uuid=CUUID,
login=True,
cache=None,
vaultier=False,
authentication_cb=None,
):
# goal is to allow shared cache amongst client instances
# but also if we want totally isolated caches
if cache is None:
cache = CACHE
if not email:
raise RunError("no email")
if not server:
raise RunError("no server")
if not password:
raise RunError("no password")
self.admin_user = admin_user
self.admin_password = admin_password
self._broken_ciphers = OrderedDict()
self.vaultier = vaultier
self.server = server
if not private_key:
private_key = None
self.private_key = private_key
if self.private_key:
if hasattr(self.private_key, "encode"):
self.private_key = b64decode(self.private_key)
self.password = password
self.email = email.lower()
self.sessions = OrderedDict()
self.client_id = client_id
self.client_uuid = client_uuid
self.templates = {}
self._cache = cache
self.tokens = {}
self.authentication_cb = authentication_cb
if login:
self.login()
self._is_vaultwarden = False
self._version = None
@property
def token(self):
return self.tokens.get(self.email, None)
@token.setter
def token_set(self, value):
self.tokens[self.email] = value
return self.tokens[self.email]
def adminr(
self,
uri,
method="post",
headers=None,
admin_user=None,
admin_password=None,
*a,
**kw,
):
admin_user = admin_user or self.admin_user
admin_password = admin_password or self.admin_password
if admin_user and admin_password:
kw["auth"] = (admin_user, admin_password)
url = uri
if not url.startswith("http"):
url = f"{self.server}/admin{uri}"
if headers is None:
headers = {}
return getattr(requests, method.lower())(url, headers=headers, *a, **kw)
def r(self, uri, method="post", headers=None, token=None, retry=True, *a, **kw):
url = uri
if not url.startswith("http"):
url = f"{self.server}{uri}"
if headers is None:
headers = {}
if token is not False:
token = self.get_token(token)
headers.update({"Authorization": f"Bearer {token['access_token']}"})
resp = getattr(requests, method.lower())(url, headers=headers, *a, **kw)
if resp.status_code in [401] and token is not False and retry:
L.debug(
f"Access denied, trying to retry after refreshing token for {token['email']}"
)
token = self.login(token["email"], token["password"])
headers.update({"Authorization": f"Bearer {token['access_token']}"})
resp = getattr(requests, method.lower())(url, headers=headers, *a, **kw)
return resp
def login(
self,
email=None,
password=None,
scope="api offline_access",
grant_type="password",
):
email = email or self.email
try:
token = self.tokens[email]
except KeyError:
pass
else:
# as token is already there, test if token is still usable
resp = self.r(
"/api/accounts/revision-date", token=token, retry=False, method="get"
)
try:
self.assert_bw_response(resp)
except ResponseError:
self.tokens.pop(email, None)
else:
token["_btw_login_count"] += 1
return token
password = password or self.password
data = self.r("/api/accounts/prelogin", json={"email": email}, token=False)
jdata = data.json()
iterations = caseinsentive_key_search(jdata, "kdfiterations")
hashed_password, master_key = bwcrypto.hash_password(
password, email, iterations=iterations
)
loginpayload = {
"scope": scope,
"client_id": self.client_id,
"grant_type": grant_type,
"username": email,
"password": hashed_password,
"deviceType": 9,
"deviceIdentifier": self.client_uuid,
"deviceName": "pyinviter",
}
if self.authentication_cb:
loginpayload = self.authentication_cb(loginpayload)
data = self.r("/identity/connect/token", token=False, data=loginpayload)
if not data.status_code == 200:
error_description = data.json().get("error_description", "unknown error")
exc = LoginError(f"Failed login for {email} ({error_description})")
exc.response = data
raise exc
token = data.json()
token["_btw_login_count"] = 1
token["iterations"] = iterations
token["password"] = password
token["hashed_password"] = hashed_password
token["master_key"] = master_key
token["email"] = email
for k, f in {"Key": "user_key", "PrivateKey": "orgs_key"}.items():
key = k != "PrivateKey" and master_key or token.get("user_key")
token[f] = bwcrypto.decrypt(token[k], key)
self.tokens[email] = token
return token
def item_or_id(self, item_or_id):
if isinstance(item_or_id, BWFactory):
item_or_id = item_or_id.id
return item_or_id
def raw_call(self, *args, **kw):
kw.setdefault("no_session", True)
kw.setdefault("asjson", False)
kw.setdefault("sync", False)
return self.call(*args, **kw)
def cli_login(self, email=None, password=None, force=False):
password, email = password or self.password, email or self.email
session = self.sessions.get(email, None)
if (session is None) or force:
ret = self.raw_call(f"config server {self.server}")
try:
ret = self.raw_call(f"login {email} {password}")
except CliRunError as exc:
sret = exc.args[0].decode()
if "already" in sret:
try:
ret = self.raw_call(f"unlock {password}")
except CliRunError as exc:
cexc = CliLoginError(exc.args[0])
cexc.process = ret
raise cexc
sret = ret.stdout.decode()
else:
raise LoginError("{email} cli login error")
sret = ret.stdout.decode()
s = (
[a for a in sret.splitlines() if "BW_SESSION=" in a][0]
.split()[-1]
.split('"')[1]
)
session = self.sessions[email] = s
return session
def call(
self,
cli,
input=None,
asjson=True,
capture_output=True,
load=False,
shell=True,
sync=False,
force_login=False,
no_session=False,
user=None,
email=None,
vaultier=None,
):
vaultier = self.get_vaultier(vaultier)
if force_login or not no_session:
os.environ["BW_SESSION"] = self.cli_login(user, email, force=force_login)
else:
sync = False
if sync or (cli and cli.startswith("sync")):
self.cli_sync()
if input is None:
input = f"{self.password}".encode()
env = os.environ.copy()
L.debug(f"Running bw {cli}")
ret = run(
f"bw {cli}",
input=input,
capture_output=capture_output,
env=env,
shell=shell,
)
if ret.returncode != 0:
exc = CliRunError(ret.stdout + ret.stderr)
exc.process = ret
raise exc
if asjson:
try:
ret = json.loads(ret.stdout)
except json.decoder.JSONDecodeError:
exc = CliRunError(
f"is not json\n"
f"{ret.stdout.decode()}\n"
f"{ret.stderr.decode()}\n"
)
exc.process = ret
raise exc
if load:
if isinstance(ret, (list, tuple)):
ret = type(ret)(
[
BWFactory.construct(r, client=self, vaultier=vaultier)
for r in ret
]
)
elif isinstance(ret, dict):
ret = BWFactory.construct(ret, client=self, vaultier=vaultier)
return ret
def get_template(self, otype=None, **kw):
if otype is None:
otype = kw["object"]
otype = get_obj_type(otype)
bwt = get_bw_type(otype)
try:
tpl = self._cache["templates"][otype]
except KeyError:
tpl = self._cache["templates"][otype] = self.call(f"get template {bwt}")
tpl = deepcopy(tpl)
tpl.update(kw)
return tpl
def api_sync(self, sync=None, cache=None, token=None):
_CACHE = self._cache["sync"]
k = "api_sync"
token = self.get_token(token)
if sync is None:
sync = False
if cache is None:
cache = True
if cache is False or sync:
_CACHE[k] = False
try:
assert _CACHE.get(k)
except AssertionError:
L.debug("api_sync")
resp = self.r(
"/api/sync",
json={"excludeDomains": True},
method="get",
token=token,
)
self.assert_bw_response(resp)
_CACHE.update(resp.json())
_CACHE[k] = True
return _CACHE
def cli_sync(self, sync=None):
return self.call("sync", asjson=False)
def sync(self, sync=None, token=None):
return self.api_sync(sync=sync, token=token)
def finish_orga(self, orga, cache=None, token=None, complete=None):
token = self.get_token(token)
if complete and not getattr("orga", "BillingEmail", "") and not orga._complete:
orga = BWFactory.construct(
self.r(f"/api/organizations/{orga.id}", method="get").json(),
client=self,
unmarshall=True,
)
orga._complete = True
self.cache(orga)
return orga
def get_organizations(self, sync=None, cache=None, token=None):
token = self.get_token(token)
_CACHE = self._cache["organizations"]