vars: allow re-encrypting secrets when recipient keys were added.

When the users of a secret change, when for example a new admin user is added, an error will be thrown when generating vars, prompting the user to pass --fix to re-encrypt the secrets
This commit is contained in:
DavHau
2024-11-13 18:18:25 +07:00
parent 83b7c6d9a2
commit 54b8f5904e
9 changed files with 221 additions and 34 deletions

View File

@@ -103,7 +103,7 @@ def update_group_keys(flake_dir: Path, group: str) -> list[Path]:
if (secret / "groups" / group).is_symlink():
updated_paths += update_keys(
secret,
sorted(secrets.collect_keys_for_path(secret)),
secrets.collect_keys_for_path(secret),
)
return updated_paths

View File

@@ -1,7 +1,5 @@
import argparse
import functools
import getpass
import operator
import os
import shutil
import sys
@@ -45,7 +43,7 @@ def update_secrets(
changed_files.extend(
update_keys(
secret_path,
sorted_keys(collect_keys_for_path(secret_path)),
collect_keys_for_path(secret_path),
)
)
return changed_files
@@ -147,7 +145,7 @@ def encrypt_secret(
)
secret_path = secret_path / "secret"
encrypt_file(secret_path, value, sorted_keys(recipient_keys))
encrypt_file(secret_path, value, sorted(recipient_keys))
files_to_commit.append(secret_path)
if git_commit:
commit_files(
@@ -231,7 +229,7 @@ def allow_member(
changed.extend(
update_keys(
group_folder.parent,
sorted_keys(collect_keys_for_path(group_folder.parent)),
collect_keys_for_path(group_folder.parent),
)
)
return changed
@@ -257,12 +255,7 @@ def disallow_member(group_folder: Path, name: str) -> list[Path]:
if len(os.listdir(group_folder.parent)) == 0:
group_folder.parent.rmdir()
return update_keys(
target.parent.parent, sorted_keys(collect_keys_for_path(group_folder.parent))
)
sorted_keys = functools.partial(sorted, key=operator.itemgetter(0))
return update_keys(target.parent.parent, collect_keys_for_path(group_folder.parent))
def has_secret(secret_path: Path) -> bool:

View File

@@ -4,7 +4,7 @@ import json
import os
import shutil
import subprocess
from collections.abc import Iterator
from collections.abc import Iterable, Iterator
from contextlib import contextmanager, suppress
from dataclasses import dataclass
from pathlib import Path
@@ -182,8 +182,9 @@ def sops_manifest(keys: list[tuple[str, KeyType]]) -> Iterator[Path]:
yield Path(manifest.name)
def update_keys(secret_path: Path, keys: list[tuple[str, KeyType]]) -> list[Path]:
with sops_manifest(keys) as manifest:
def update_keys(secret_path: Path, keys: Iterable[tuple[str, KeyType]]) -> list[Path]:
keys_sorted = sorted(keys)
with sops_manifest(keys_sorted) as manifest:
secret_path = secret_path / "secret"
time_before = secret_path.stat().st_mtime
cmd = nix_shell(