| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081 |
- import subprocess
- from pathlib import Path
- from dataclasses import dataclass
- from pc_backup.keepass import KeePass
- @dataclass
- class Secret:
- name: str
- mode: int
- def create(self, keepass: KeePass): ...
- @classmethod
- def from_line(cls, line: str):
- name, type_, *args = line.split(",")
- match type_:
- case "file":
- sub_class = SecretFile
- case "keepass-attribute":
- sub_class = SecretKeepassAttribute
- case "keepass-attachment":
- sub_class = SecretKeepassAttachment
- case _:
- raise ValueError(f"Cannot read `{line}` as a secret spec")
- return sub_class.from_line(name, *args)
- @classmethod
- def read_sources(cls, file: Path) -> list["Secret"]:
- with open(file) as f:
- lines = f.readlines()
- return [cls.from_line(l.strip()) for l in lines]
- @dataclass
- class SecretKeepassAttachment(Secret):
- key: str
- attachment: str
- def create(self, keepass: KeePass):
- value = keepass.read_entry_attachment(self.key, self.attachment)
- args = ["podman", "secret", "create", "--replace", self.name, "-"]
- print(args)
- subprocess.run(args, input=value.encode())
- @classmethod
- def from_line(cls, name: str, key: str, attachment: str):
- return cls(name=name, key=key, mode=0o0400, attachment=attachment)
- @dataclass
- class SecretKeepassAttribute(Secret):
- key: str
- attribute: str
- def create(self, keepass: KeePass):
- value = keepass.read_entry_attribute(self.key, self.attribute)
- args = ["podman", "secret", "create", "--replace", self.name, "-"]
- print(args)
- subprocess.run(args, input=value.encode())
- @classmethod
- def from_line(cls, name: str, key: str, attribute: str):
- return cls(name=name, key=key, mode=0o0400, attribute=attribute)
- @dataclass
- class SecretFile(Secret):
- host_path: Path
- def create(self, keepass: KeePass):
- args = ["podman", "secret", "create", "--replace", self.name, self.host_path]
- print(args)
- subprocess.run(args)
- @classmethod
- def from_line(cls, name: str, path: str):
- path = Path(path).expanduser()
- return cls(host_path=path, name=name, mode=0o0400)
|