bitwarden-crd-operator/src/utils/utils.py

83 lines
2.3 KiB
Python
Raw Normal View History

import os
2023-01-19 01:57:21 +00:00
import json
import subprocess
import distutils
bw_sync_interval = float(os.environ.get(
'BW_SYNC_INTERVAL', 900))
2023-04-21 12:39:06 +00:00
2022-11-26 20:33:31 +00:00
class BitwardenCommandException(Exception):
pass
2023-04-21 12:39:06 +00:00
def get_secret_from_bitwarden(logger, id, force_sync=False):
sync_bw(logger, force=force_sync)
return command_wrapper(logger, command=f"get item {id}")
2023-04-21 12:39:06 +00:00
def sync_bw(logger, force=False):
def _sync(logger):
status_output = command_wrapper(logger, command=f"sync")
logger.info(f"Sync successful {status_output}")
return
if force:
_sync(logger)
return
global_force_sync = bool(distutils.util.strtobool(
os.environ.get('BW_FORCE_SYNC', "false")))
2023-10-09 21:18:04 +00:00
if global_force_sync:
logger.debug("Running forced sync")
status_output = _sync(logger)
logger.info(f"Sync successful {status_output}")
else:
logger.debug("Running scheduled sync")
status_output = _sync(logger)
logger.info(f"Sync successful {status_output}")
def unlock_bw(logger):
status_output = command_wrapper(logger, "status", False)
status = status_output['data']['template']['status']
2023-01-19 01:57:21 +00:00
if status == 'unlocked':
logger.info("Already unlocked")
return
token_output = command_wrapper(logger, "unlock --passwordenv BW_PASSWORD")
os.environ["BW_SESSION"] = token_output["data"]["raw"]
logger.info("Signin successful. Session exported")
2023-04-21 12:39:06 +00:00
def command_wrapper(logger, command, use_success: bool = True):
system_env = dict(os.environ)
2023-04-21 12:39:06 +00:00
sp = subprocess.Popen(
[f"bw --response {command}"],
2023-04-21 12:39:06 +00:00
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True,
shell=True,
env=system_env)
out, err = sp.communicate()
2023-04-24 07:54:53 +00:00
if "DEBUG" in system_env:
2023-06-24 16:31:00 +00:00
logger.info(out.decode(encoding='UTF-8'))
resp = json.loads(out.decode(encoding='UTF-8'))
if resp["success"] != None and (not use_success or (use_success and resp["success"] == True)):
return resp
logger.warn(resp)
return None
2022-11-26 20:33:31 +00:00
2023-04-21 12:39:06 +00:00
2022-11-26 20:33:31 +00:00
def parse_login_scope(secret_json, key):
return secret_json["data"]["login"][key]
2022-11-26 20:33:31 +00:00
2023-04-21 12:39:06 +00:00
2022-11-26 20:33:31 +00:00
def parse_fields_scope(secret_json, key):
if "fields" not in secret_json["data"]:
return None
for entry in secret_json["data"]["fields"]:
2022-11-26 20:33:31 +00:00
if entry['name'] == key:
return entry['value']