keepassxc.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import logging
  2. import os
  3. import shlex
  4. import borgmatic.execute
  5. logger = logging.getLogger(__name__)
  6. def load_credential(hook_config, config, credential_parameters):
  7. '''
  8. Given the hook configuration dict, the configuration dict, and a credential parameters tuple
  9. containing a KeePassXC database path and an attribute name to load, run keepassxc-cli to fetch
  10. the corresponding KeePassXC credential and return it.
  11. Raise ValueError if keepassxc-cli can't retrieve the credential.
  12. '''
  13. try:
  14. database_path, attribute_name = credential_parameters[:2]
  15. except ValueError:
  16. raise ValueError( f'Invalid KeePassXC credential parameters: {credential_parameters}')
  17. expanded_database_path = os.path.expanduser(database_path)
  18. if not os.path.exists(expanded_database_path):
  19. raise ValueError( f'KeePassXC database path does not exist: {database_path}')
  20. # Retrieve key file and Yubikey options from config
  21. key_file = hook_config.get('key_file')
  22. yubikey = hook_config.get('yubikey')
  23. # Build the keepassxc-cli command
  24. command = (
  25. tuple(shlex.split((hook_config or {}).get('keepassxc_cli_command', 'keepassxc-cli')))
  26. + (
  27. 'show',
  28. '--show-protected',
  29. '--attributes',
  30. 'Password',
  31. expanded_database_path,
  32. attribute_name,
  33. )
  34. )
  35. if key_file:
  36. command += ('--key-file', key_file)
  37. if yubikey:
  38. command += ('--yubikey', yubikey)
  39. try:
  40. return borgmatic.execute.execute_command_and_capture_output(command).rstrip(os.linesep)
  41. except Exception as e:
  42. raise ValueError(f'Failed to retrieve credential: {e}')