start.py 9.1 KB

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