| 393 | |
| 394 | |
| 395 | class GpgSigner: |
| 396 | def __init__(self, gpg_id: str, gpg_secret_key: str, gpg_passphrase: str): |
| 397 | self.gpg_id = gpg_id |
| 398 | self.gpg_secret_key = gpg_secret_key |
| 399 | self.gpg_passphrase = gpg_passphrase |
| 400 | |
| 401 | self.gpg_home = pathlib.Path.home() / ".gnupg-tmp" |
| 402 | self.gpg_home.mkdir(parents=True, exist_ok=True, mode=0o700) |
| 403 | |
| 404 | # write gpg secret key to file |
| 405 | self.gpg_secret_key_path = self.gpg_home / "gpg_secret" |
| 406 | self.gpg_secret_key_path.write_bytes(base64.b64decode(gpg_secret_key)) |
| 407 | |
| 408 | self.gpg_passphrase_path = self.gpg_home / "gpg_pass" |
| 409 | self.gpg_passphrase_path.write_text(gpg_passphrase) |
| 410 | |
| 411 | run_cmd(["gpg", "--version"]) |
| 412 | |
| 413 | info("Importing GPG key") |
| 414 | run_cmd(["gpg", "--list-keys"], env=self.gpg_env()) |
| 415 | run_cmd( |
| 416 | ["gpg", *self.sign_args(), "--allow-secret-key-import", "--import", self.gpg_secret_key_path], |
| 417 | env=self.gpg_env(), |
| 418 | ) |
| 419 | run_cmd(["gpg", "--list-keys"], env=self.gpg_env()) |
| 420 | |
| 421 | def gpg_env(self) -> Env: |
| 422 | return {**os.environ, "GNUPGHOME": self.gpg_home} |
| 423 | |
| 424 | def sign_args(self) -> Args: |
| 425 | return [ |
| 426 | "--batch", |
| 427 | "--pinentry-mode", |
| 428 | "loopback", |
| 429 | "--no-tty", |
| 430 | "--yes", |
| 431 | "--passphrase-file", |
| 432 | self.gpg_passphrase_path, |
| 433 | ] |
| 434 | |
| 435 | def sign_file(self, path: pathlib.Path) -> List[pathlib.Path]: |
| 436 | info(f"Signing {path.name}") |
| 437 | run_cmd( |
| 438 | ["gpg", "--detach-sign", *self.sign_args(), "--local-user", self.gpg_id, path], |
| 439 | env=self.gpg_env(), |
| 440 | ) |
| 441 | run_cmd( |
| 442 | ["gpg", "--detach-sign", *self.sign_args(), "--armor", "--local-user", self.gpg_id, path], |
| 443 | env=self.gpg_env(), |
| 444 | ) |
| 445 | return [path.with_suffix(f"{path.suffix}.asc"), path.with_suffix(f"{path.suffix}.sig")] |
| 446 | |
| 447 | def clean(self): |
| 448 | info("Cleaning gpg keys") |
| 449 | shutil.rmtree(self.gpg_home, ignore_errors=True) |
| 450 | |
| 451 | |
| 452 | def get_secretmanager_json(secret_id: str, secret_region: str): |