start.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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. ssh_auth_sock: Path | None
  102. @classmethod
  103. def read(cls, hostname: str, login: str, config_dir: Path):
  104. secret_sources_file = config_dir / f"secret_sources_{hostname}_{login}"
  105. data_sources_file = config_dir / f"data_sources_{hostname}_{login}"
  106. ssh_auth_sock = os.getenv("SSH_AUTH_SOCK")
  107. return cls(
  108. secret_sources=Secret.read_sources(secret_sources_file),
  109. data_sources=read_data_sources(data_sources_file),
  110. borgmatic_d_path=config_dir / "borgmatic.d",
  111. borgmatic_path=config_dir / "borgmatic",
  112. history_file=config_dir / ".bash_history",
  113. ssh_auth_sock=Path(ssh_auth_sock) if ssh_auth_sock else None
  114. )
  115. @dataclass
  116. class BorgmaticContainer:
  117. hostname: str
  118. login: str
  119. name: str
  120. image: str = "ghcr.io/borgmatic-collective/borgmatic"
  121. def run(self, config: Configuration):
  122. container_name = f"borgmatic_{self.login}"
  123. config.history_file.touch()
  124. volumes = [
  125. f"{config.borgmatic_d_path}:/etc/borgmatic.d/",
  126. f"{config.borgmatic_path}:/etc/borgmatic/",
  127. f"{config.history_file}:/root/.bash_history",
  128. "borg_ssh_dir:/root/.ssh",
  129. "borg_config:/root/.config/borg",
  130. "borg_cache:/root/.cache/borg",
  131. "borgmatic_state:/root/.local/state/borgmatic",
  132. ]
  133. if config.ssh_auth_sock:
  134. volumes += [f"{config.ssh_auth_sock}:{config.ssh_auth_sock}:Z"]
  135. volumes += [
  136. f"{vol}:{self.to_source_path(vol)}:ro" for vol in config.data_sources
  137. ]
  138. volume_args = [a for vol in volumes for a in ["-v", vol]]
  139. secrets_args = [
  140. a
  141. for s in config.secret_sources
  142. for a in ["--secret", f"{s.name},mode=0{s.mode:o}"]
  143. ]
  144. args = (
  145. [
  146. "podman",
  147. "run",
  148. "-h",
  149. self.hostname,
  150. "--detach",
  151. "--name",
  152. container_name,
  153. "-e",
  154. "SSH_AUTH_SOCK",
  155. "-e",
  156. "TZ=Europe/Paris",
  157. "-e",
  158. "SSH_KEY_NAME",
  159. "-e",
  160. f"HOST_LOGIN={self.login}",
  161. "--security-opt=label=disable",
  162. ]
  163. + volume_args
  164. + secrets_args
  165. + [self.image]
  166. )
  167. print(args)
  168. subprocess.run(args)
  169. def rm(self):
  170. subprocess.run(["podman", "rm", "-f", self.name])
  171. def exec(self, cmd: list[str], env_vars: list[str] = []):
  172. args = ["podman", "exec", "-ti"]
  173. args += [a for var in env_vars for a in ["-e", var]]
  174. subprocess.run(args + [self.name] + cmd)
  175. @staticmethod
  176. def to_source_path(path: Path):
  177. mount_base = PurePosixPath("/mnt") / "source"
  178. inner_path = PurePosixPath(path)
  179. with_drive = PurePosixPath(inner_path.parts[0].replace(":", "")).joinpath(
  180. *inner_path.parts[1:]
  181. )
  182. return mount_base / with_drive.relative_to(with_drive.anchor)
  183. @classmethod
  184. def new(cls, hostname: str, login: str):
  185. return cls(hostname, login, f"borgmatic_{login}")
  186. class CliArguments:
  187. @staticmethod
  188. def read_command(parser):
  189. args = parser.parse_args()
  190. return args.command(args)
  191. @staticmethod
  192. def new() -> argparse.ArgumentParser:
  193. parser = argparse.ArgumentParser(prog=sys.argv[0])
  194. subparsers = parser.add_subparsers()
  195. for sub in [
  196. CommandStart,
  197. CommandRm,
  198. CommandBash,
  199. CommandCreateRepo,
  200. CommandExportKey,
  201. CommandCreateSecrets,
  202. ]:
  203. p = subparsers.add_parser(sub.command, help=sub.help)
  204. sub.init_subparser(p)
  205. p.set_defaults(command=sub)
  206. return parser
  207. class Command:
  208. def __init__(self, namespace) -> None:
  209. for k, v in vars(namespace).items():
  210. if k != "type_":
  211. setattr(self, k, v)
  212. @classmethod
  213. def init_subparser(cls, p): ...
  214. class CommandStart(Command):
  215. command = "start"
  216. help = "start container"
  217. def run(
  218. self,
  219. *,
  220. container: BorgmaticContainer,
  221. config: Configuration,
  222. **kwargs,
  223. ):
  224. container.run(config)
  225. class CommandRm(Command):
  226. command = "rm"
  227. help = "remove container"
  228. def run(self, *, container: BorgmaticContainer, **kwargs):
  229. container.rm()
  230. class CommandBash(Command):
  231. command = "bash"
  232. help = "run shell in container"
  233. def run(self, *, container: BorgmaticContainer, **kwargs):
  234. container.exec(["bash"])
  235. class CommandCreateRepo(Command):
  236. command = "create_repo"
  237. help = "create repository"
  238. env_vars = ["BORG_PASSPHRASE_NAME", "STORAGE_BOX_USER", "SSH_KEY_NAME"]
  239. def run(self, *, container: BorgmaticContainer, **kwargs):
  240. container.exec(
  241. ["borgmatic", "repo-create", "--encryption", "repokey"], self.env_vars
  242. )
  243. class CommandExportKey(Command):
  244. command = "export_key"
  245. help = "export the repository key"
  246. env_vars = ["BORG_PASSPHRASE_NAME", "STORAGE_BOX_USER", "SSH_KEY_NAME"]
  247. def run(self, *, container: BorgmaticContainer, **kwargs):
  248. container.exec(["borgmatic", "export", "key"], self.env_vars)
  249. class CommandCreateSecrets(Command):
  250. command = "create_secrets"
  251. help = "create podman secrets"
  252. def run(self, *, secret_sources: list[Secret], **kwargs):
  253. keepass = KeePass.new(self.keepass_path)
  254. for s in secret_sources:
  255. s.create(keepass)
  256. @classmethod
  257. def init_subparser(cls, p):
  258. p.add_argument("keepass_path", type=Path, help="Path to the keepass")
  259. def main():
  260. login = os.getlogin()
  261. hostname = socket.gethostname()
  262. config = Configuration.read(hostname, login, Path.cwd() / "pc_backup" / "config")
  263. if not config.secret_sources:
  264. print("no secret required ?")
  265. container = BorgmaticContainer.new(hostname, login)
  266. parser = CliArguments.new()
  267. command = CliArguments.read_command(parser)
  268. command.run(
  269. config=config,
  270. secret_sources=config.secret_sources,
  271. data_sources=config.data_sources,
  272. container=container,
  273. )
  274. if __name__ == "__main__":
  275. main()