secret.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. case _:
  21. raise ValueError(f"Cannot read `{line}` as a secret spec")
  22. return sub_class.from_line(name, *args)
  23. @classmethod
  24. def read_sources(cls, file: Path) -> list["Secret"]:
  25. with open(file) as f:
  26. lines = f.readlines()
  27. return [cls.from_line(l.strip()) for l in lines]
  28. @dataclass
  29. class SecretKeepassAttachment(Secret):
  30. key: str
  31. attachment: str
  32. def create(self, keepass: KeePass):
  33. value = keepass.read_entry_attachment(self.key, self.attachment)
  34. args = ["podman", "secret", "create", "--replace", self.name, "-"]
  35. print(args)
  36. subprocess.run(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 = ["podman", "secret", "create", "--replace", self.name, "-"]
  47. print(args)
  48. subprocess.run(args, input=value.encode())
  49. @classmethod
  50. def from_line(cls, name: str, key: str, attribute: str):
  51. return cls(name=name, key=key, mode=0o0400, attribute=attribute)
  52. @dataclass
  53. class SecretFile(Secret):
  54. host_path: Path
  55. def create(self, keepass: KeePass):
  56. args = ["podman", "secret", "create", "--replace", self.name, self.host_path]
  57. print(args)
  58. subprocess.run(args)
  59. @classmethod
  60. def from_line(cls, name: str, path: str):
  61. path = Path(path).expanduser()
  62. return cls(host_path=path, name=name, mode=0o0400)