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. from pc_backup.podman import Podman
  6. @dataclass
  7. class Secret:
  8. name: str
  9. mode: int
  10. def create(self, keepass: KeePass): ...
  11. @classmethod
  12. def from_line(cls, line: str):
  13. name, type_, *args = line.split(",")
  14. match type_:
  15. case "file":
  16. sub_class = SecretFile
  17. case "keepass-attribute":
  18. sub_class = SecretKeepassAttribute
  19. case "keepass-attachment":
  20. sub_class = SecretKeepassAttachment
  21. case _:
  22. raise ValueError(f"Cannot read `{line}` as a secret spec")
  23. return sub_class.from_line(name, *args)
  24. @classmethod
  25. def read_sources(cls, file: Path) -> list["Secret"]:
  26. with open(file) as f:
  27. lines = f.readlines()
  28. return [cls.from_line(l.strip()) for l in lines]
  29. @dataclass
  30. class SecretKeepassAttachment(Secret):
  31. key: str
  32. attachment: str
  33. def create(self, keepass: KeePass):
  34. value = keepass.read_entry_attachment(self.key, self.attachment)
  35. args = ["--replace", self.name, "-"]
  36. Podman.secret_create(args, input=value.encode())
  37. @classmethod
  38. def from_line(cls, name: str, key: str, attachment: str):
  39. return cls(name=name, key=key, mode=0o0400, attachment=attachment)
  40. @dataclass
  41. class SecretKeepassAttribute(Secret):
  42. key: str
  43. attribute: str
  44. def create(self, keepass: KeePass):
  45. value = keepass.read_entry_attribute(self.key, self.attribute)
  46. args = ["--replace", self.name, "-"]
  47. Podman.secret_create(args, input=value.encode())
  48. @classmethod
  49. def from_line(cls, name: str, key: str, attribute: str):
  50. return cls(name=name, key=key, mode=0o0400, attribute=attribute)
  51. @dataclass
  52. class SecretFile(Secret):
  53. host_path: Path
  54. def create(self, keepass: KeePass):
  55. args = ["--replace", self.name, self.host_path]
  56. Podman.secret_create(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)