Coverage for pass_import/managers/sphinx.py: 35%

46 statements  

« prev     ^ index     » next       coverage.py v7.4.3, created at 2024-02-26 12:11 +0000

1# -*- encoding: utf-8 -*- 

2# pass import - Passwords importer swiss army knife 

3# Copyright (C) 2022 Stefan Marsiske <sphinx@ctrlc.hu>. 

4# Copyright (C) 2022 Alexandre PUJOL <alexandre@pujol.io>. 

5# 

6 

7import urllib 

8 

9try: 

10 from pwdsphinx import sphinx 

11 PWDSPHINX = True 

12except ImportError: 

13 PWDSPHINX = False 

14 

15from pass_import.core import register_managers 

16from pass_import.errors import PMError 

17from pass_import.manager import PasswordExporter 

18from pass_import.tools import getpassword 

19 

20 

21class Sphinx(PasswordExporter): 

22 """Exporter for Sphinx.""" 

23 name = 'sphinx' 

24 default = True 

25 url = 'https://github.com/stef/pwdsphinx/' 

26 

27 # Export methods 

28 

29 def insert(self, entry): 

30 """Insert a password entry into Sphinx.""" 

31 if entry.pop('is_a_history_entry', False): 

32 raise PMError(f"Skipping historical '{entry['path']}'") 

33 pwd = entry.pop('password', '') 

34 if not pwd: 

35 raise PMError(f"Skipping empty password '{entry['path']}'") 

36 user = entry.pop('login', '') 

37 if not user: 

38 raise PMError(f"Skipping '{entry['path']}' has no user") 

39 url = entry.pop('url', None) 

40 if url: 

41 url = urllib.parse.urlparse(url) 

42 host = f"{url.hostname}" 

43 if url.port: 

44 host = f"{host}:{url.port}" 

45 else: 

46 host = entry.pop('path', '') 

47 # print("user", user, "host", host, "pwd", pwd) 

48 

49 try: 

50 sphinx.bin2pass.pass2bin(pwd, None) 

51 except OverflowError: 

52 raise PMError(f"Failed to import password for {user}@{host}" 

53 " to sphinx: password too long.") 

54 

55 s = sphinx.connect() 

56 try: 

57 sphinx.create(s, self.masterpassword, user, host, target=pwd) 

58 except Exception: 

59 raise PMError(f"Failed to export {user}@{host} to sphinx.") 

60 s.close() 

61 

62 # Context manager methods 

63 

64 def exist(self): 

65 """Nothing to do.""" 

66 return True 

67 

68 def open(self): 

69 """Get Sphinx master password.""" 

70 if not PWDSPHINX: 

71 raise ImportError(name='pwdsphinx') 

72 self.masterpassword = getpassword("sphinx").encode('utf8') 

73 

74 def close(self): 

75 """Forget Sphinx master password.""" 

76 self.masterpassword = None 

77 

78 

79register_managers(Sphinx)