secret.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import subprocess
  2. from pathlib import Path
  3. from dataclasses import dataclass
  4. from pc_backup.keepass import KeePass
  5. @dataclass
  6. class Secret:
  7. name: str
  8. mode: int
  9. def create(self, keepass: KeePass): ...
  10. @classmethod
  11. def from_line(cls, line: str):
  12. name, type_, *args = line.split(",")
  13. match type_:
  14. case "file":
  15. sub_class = SecretFile
  16. case "keepass-attribute":
  17. sub_class = SecretKeepassAttribute
  18. case "keepass-attachment":
  19. sub_class = SecretKeepassAttachment
  20. return sub_class.from_line(name, *args)
  21. @classmethod
  22. def read_sources(cls, file: Path) -> list["Secret"]:
  23. with open(file) as f:
  24. lines = f.readlines()
  25. return [cls.from_line(l.strip()) for l in lines]
  26. @dataclass
  27. class SecretKeepassAttachment(Secret):
  28. key: str
  29. attachment: str
  30. def create(self, keepass: KeePass):
  31. value = keepass.read_entry_attachment(self.key, self.attachment)
  32. args = ["podman", "secret", "create", "--replace", self.name, "-"]
  33. print(args)
  34. subprocess.run(args, input=value.encode())
  35. @classmethod
  36. def from_line(cls, name: str, key: str, attachment: str):
  37. return cls(name=name, key=key, mode=0o0400, attachment=attachment)
  38. @dataclass
  39. class SecretKeepassAttribute(Secret):
  40. key: str
  41. attribute: str
  42. def create(self, keepass: KeePass):
  43. value = keepass.read_entry_attribute(self.key, self.attribute)
  44. args = ["podman", "secret", "create", "--replace", self.name, "-"]
  45. print(args)
  46. subprocess.run(args, input=value.encode())
  47. @classmethod
  48. def from_line(cls, name: str, key: str, attribute: str):
  49. return cls(name=name, key=key, mode=0o0400, attribute=attribute)
  50. @dataclass
  51. class SecretFile(Secret):
  52. host_path: Path
  53. def create(self, keepass: KeePass):
  54. args = ["podman", "secret", "create", "--replace", self.name, self.host_path]
  55. print(args)
  56. subprocess.run(args)
  57. @classmethod
  58. def from_line(cls, name: str, path: str):
  59. path = Path(path).expanduser()
  60. return cls(host_path=path, name=name, mode=0o0400)