start.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. import argparse
  2. import os
  3. import sys
  4. import subprocess
  5. import socket
  6. from pathlib import Path, PurePosixPath
  7. from dataclasses import dataclass
  8. from typing import Any
  9. is_windows = os.name == "nt"
  10. def read_data_sources(file: Path) -> list[Path]:
  11. with open(file) as f:
  12. paths = f.readlines()
  13. return [Path(p_str.strip()).expanduser() for p_str in paths]
  14. @dataclass
  15. class KeePass:
  16. path: Path
  17. bin: str | Path
  18. def read_entry_attribute(self, key, attribute):
  19. return self._exec(["show", "-a", attribute, self.path, key]).strip()
  20. def read_entry_attachment(self, key, attachment):
  21. return self._exec(
  22. ["attachment-export", "--stdout", self.path, key, attachment, "/dev/null"]
  23. )
  24. def _exec(self, args: list[Any]):
  25. try:
  26. return subprocess.check_output([self.bin] + args, text=True)
  27. except subprocess.CalledProcessError as e:
  28. print("\nThere was an error on call to keepass, please check the outout")
  29. exit(1)
  30. @classmethod
  31. def new(cls, path: Path):
  32. binary = (
  33. Path("C:\\") / "Program Files" / "KeePassXC" / "keepassxc-cli.exe"
  34. if is_windows
  35. else "keepassxc-cli"
  36. )
  37. return cls(path=path, bin=binary)
  38. @dataclass
  39. class Secret:
  40. name: str
  41. mode: int
  42. def create(self, keepass: KeePass): ...
  43. @classmethod
  44. def from_line(cls, line: str):
  45. name, type_, *args = line.split(",")
  46. match type_:
  47. case "file":
  48. sub_class = SecretFile
  49. case "keepass-attribute":
  50. sub_class = SecretKeepassAttribute
  51. case "keepass-attachment":
  52. sub_class = SecretKeepassAttachment
  53. return sub_class.from_line(name, *args)
  54. @classmethod
  55. def read_sources(cls, file: Path) -> list["Secret"]:
  56. with open(file) as f:
  57. lines = f.readlines()
  58. return [cls.from_line(l.strip()) for l in lines]
  59. @dataclass
  60. class SecretKeepassAttachment(Secret):
  61. key: str
  62. attachment: str
  63. def create(self, keepass: KeePass):
  64. value = keepass.read_entry_attachment(self.key, self.attachment)
  65. args = ["podman", "secret", "create", "--replace", self.name, "-"]
  66. print(args)
  67. subprocess.run(args, input=value.encode())
  68. @classmethod
  69. def from_line(cls, name: str, key: str, attachment: str):
  70. return cls(name=name, key=key, mode=0o0400, attachment=attachment)
  71. @dataclass
  72. class SecretKeepassAttribute(Secret):
  73. key: str
  74. attribute: str
  75. def create(self, keepass: KeePass):
  76. value = keepass.read_entry_attribute(self.key, self.attribute)
  77. args = ["podman", "secret", "create", "--replace", self.name, "-"]
  78. print(args)
  79. subprocess.run(args, input=value.encode())
  80. @classmethod
  81. def from_line(cls, name: str, key: str, attribute: str):
  82. return cls(name=name, key=key, mode=0o0400, attribute=attribute)
  83. @dataclass
  84. class SecretFile(Secret):
  85. host_path: Path
  86. def create(self, keepass: KeePass):
  87. args = ["podman", "secret", "create", "--replace", self.name, self.host_path]
  88. print(args)
  89. subprocess.run(args)
  90. @classmethod
  91. def from_line(cls, name: str, path: str):
  92. path = Path(path).expanduser()
  93. return cls(host_path=path, name=name, mode=0o0400)
  94. @dataclass
  95. class Configuration:
  96. secret_sources: list[Secret]
  97. data_sources: list[Path]
  98. borgmatic_d_path: Path
  99. borgmatic_path: Path
  100. history_file: Path
  101. @classmethod
  102. def read(cls, hostname: str, login: str, config_dir: Path):
  103. secret_sources_file = config_dir / f"secret_sources_{hostname}_{login}"
  104. data_sources_file = config_dir / f"data_sources_{hostname}_{login}"
  105. return cls(
  106. secret_sources=Secret.read_sources(secret_sources_file),
  107. data_sources=read_data_sources(data_sources_file),
  108. borgmatic_d_path=config_dir / "borgmatic.d",
  109. borgmatic_path=config_dir / "borgmatic",
  110. history_file=config_dir / ".bash_history",
  111. )
  112. @dataclass
  113. class BorgmaticContainer:
  114. hostname: str
  115. login: str
  116. name: str
  117. image: str = "ghcr.io/borgmatic-collective/borgmatic"
  118. def run(self, config: Configuration):
  119. container_name = f"borgmatic_{self.login}"
  120. ssh_auth_sock = os.getenv("SSH_AUTH_SOCK")
  121. config.history_file.touch()
  122. volumes = [
  123. f"{config.borgmatic_d_path}:/etc/borgmatic.d/",
  124. f"{config.borgmatic_path}:/etc/borgmatic/",
  125. f"{config.history_file}:/root/.bash_history",
  126. "borg_ssh_dir:/root/.ssh",
  127. "borg_config:/root/.config/borg",
  128. "borg_cache:/root/.cache/borg",
  129. "borgmatic_state:/root/.local/state/borgmatic",
  130. ]
  131. if ssh_auth_sock:
  132. volumes += [f"{ssh_auth_sock}:{ssh_auth_sock}:Z"]
  133. volumes += [
  134. f"{vol}:{self.to_source_path(vol)}:ro" for vol in config.data_sources
  135. ]
  136. volume_args = [a for vol in volumes for a in ["-v", vol]]
  137. secrets_args = [
  138. a
  139. for s in config.secret_sources
  140. for a in ["--secret", f"{s.name},mode=0{s.mode:o}"]
  141. ]
  142. args = (
  143. [
  144. "podman",
  145. "run",
  146. "-h",
  147. self.hostname,
  148. "--detach",
  149. "--name",
  150. container_name,
  151. "-e",
  152. "SSH_AUTH_SOCK",
  153. "-e",
  154. "TZ=Europe/Paris",
  155. "-e",
  156. "SSH_KEY_NAME",
  157. "-e",
  158. f"HOST_LOGIN={self.login}",
  159. "--security-opt=label=disable",
  160. ]
  161. + volume_args
  162. + secrets_args
  163. + [self.image]
  164. )
  165. print(args)
  166. subprocess.run(args)
  167. def rm(self):
  168. subprocess.run(["podman", "rm", "-f", self.name])
  169. def exec(self, cmd: list[str], env_vars: list[str] = []):
  170. args = ["podman", "exec", "-ti"]
  171. args += [a for var in env_vars for a in ["-e", var]]
  172. subprocess.run(args + [self.name] + cmd)
  173. @staticmethod
  174. def to_source_path(path: Path):
  175. mount_base = PurePosixPath("/mnt") / "source"
  176. inner_path = PurePosixPath(path)
  177. with_drive = PurePosixPath(inner_path.parts[0].replace(":", "")).joinpath(
  178. *inner_path.parts[1:]
  179. )
  180. return mount_base / with_drive.relative_to(with_drive.anchor)
  181. @classmethod
  182. def new(cls, hostname: str, login: str):
  183. return cls(hostname, login, f"borgmatic_{login}")
  184. class CliArguments:
  185. @staticmethod
  186. def read_command(parser):
  187. args = parser.parse_args()
  188. return args.command(args)
  189. @staticmethod
  190. def new() -> argparse.ArgumentParser:
  191. parser = argparse.ArgumentParser(prog=sys.argv[0])
  192. subparsers = parser.add_subparsers()
  193. for sub in [
  194. CommandStart,
  195. CommandRm,
  196. CommandBash,
  197. CommandCreateRepo,
  198. CommandExportKey,
  199. CommandCreateSecrets,
  200. ]:
  201. p = subparsers.add_parser(sub.command, help=sub.help)
  202. sub.init_subparser(p)
  203. p.set_defaults(command=sub)
  204. return parser
  205. class Command:
  206. def __init__(self, namespace) -> None:
  207. for k, v in vars(namespace).items():
  208. if k != "type_":
  209. setattr(self, k, v)
  210. @classmethod
  211. def init_subparser(cls, p): ...
  212. class CommandStart(Command):
  213. command = "start"
  214. help = "start container"
  215. def run(
  216. self,
  217. *,
  218. container: BorgmaticContainer,
  219. config: Configuration,
  220. **kwargs,
  221. ):
  222. container.run(config)
  223. class CommandRm(Command):
  224. command = "rm"
  225. help = "remove container"
  226. def run(self, *, container: BorgmaticContainer, **kwargs):
  227. container.rm()
  228. class CommandBash(Command):
  229. command = "bash"
  230. help = "run shell in container"
  231. def run(self, *, container: BorgmaticContainer, **kwargs):
  232. container.exec(["bash"])
  233. class CommandCreateRepo(Command):
  234. command = "create_repo"
  235. help = "create repository"
  236. env_vars = ["BORG_PASSPHRASE_NAME", "STORAGE_BOX_USER", "SSH_KEY_NAME"]
  237. def run(self, *, container: BorgmaticContainer, **kwargs):
  238. container.exec(
  239. ["borgmatic", "repo-create", "--encryption", "repokey"], self.env_vars
  240. )
  241. class CommandExportKey(Command):
  242. command = "export_key"
  243. help = "export the repository key"
  244. env_vars = ["BORG_PASSPHRASE_NAME", "STORAGE_BOX_USER", "SSH_KEY_NAME"]
  245. def run(self, *, container: BorgmaticContainer, **kwargs):
  246. container.exec(["borgmatic", "export", "key"], self.env_vars)
  247. class CommandCreateSecrets(Command):
  248. command = "create_secrets"
  249. help = "create podman secrets"
  250. def run(self, *, secret_sources: list[Secret], **kwargs):
  251. keepass = KeePass.new(self.keepass_path)
  252. for s in secret_sources:
  253. s.create(keepass)
  254. @classmethod
  255. def init_subparser(cls, p):
  256. p.add_argument("keepass_path", type=Path, help="Path to the keepass")
  257. def main():
  258. login = os.getlogin()
  259. hostname = socket.gethostname()
  260. config = Configuration.read(hostname, login, Path.cwd() / "pc_backup" / "config")
  261. if not config.secret_sources:
  262. print("no secret required ?")
  263. container = BorgmaticContainer.new(hostname, login)
  264. parser = CliArguments.new()
  265. command = CliArguments.read_command(parser)
  266. command.run(
  267. config=config,
  268. secret_sources=config.secret_sources,
  269. data_sources=config.data_sources,
  270. container=container,
  271. )
  272. if __name__ == "__main__":
  273. main()