clan-cli: Add validity check for age key generation #1642

Merged
clan-bot merged 1 commits from Qubasa/clan-core:Qubasa-main into main 2024-06-21 13:18:34 +00:00
3 changed files with 25 additions and 2 deletions

View File

@ -75,12 +75,12 @@ def get_user_name(flake_dir: Path, user: str) -> str:
def ensure_user_or_machine(flake_dir: Path, pub_key: str) -> SopsKey:
key = SopsKey(pub_key, username="")
folders = [sops_users_folder(flake_dir), sops_machines_folder(flake_dir)]
for folder in folders:
if folder.exists():
for user in folder.iterdir():
if not (user / "key.json").exists():
continue
if read_key(user) == pub_key:
key.username = user.name
return key

View File

@ -1,3 +1,5 @@
import subprocess
import pytest
@ -7,6 +9,18 @@ class KeyPair:
self.privkey = privkey
def is_valid_age_key(secret_key: str) -> bool:
# Run the age-keygen command with the -y flag to check the key format
result = subprocess.run(
["age-keygen", "-y"], input=secret_key, capture_output=True, text=True
)
if result.returncode == 0:
return True
else:
raise ValueError(f"Invalid age key: {secret_key}")
KEYS = [
KeyPair(
"age1dhwqzkah943xzc34tc3dlmfayyevcmdmxzjezdgdy33euxwf59vsp3vk3c",

View File

@ -2,12 +2,13 @@ import ipaddress
from typing import TYPE_CHECKING
import pytest
from age_keys import is_valid_age_key
from cli import Cli
from fixtures_flakes import FlakeForTest
from clan_cli.machines.facts import machine_get_fact
from clan_cli.secrets.folders import sops_secrets_folder
from clan_cli.secrets.secrets import has_secret
from clan_cli.secrets.secrets import decrypt_secret, has_secret
if TYPE_CHECKING:
from age_keys import KeyPair
@ -59,6 +60,10 @@ def test_generate_secret(
age_key_mtime = age_key.lstat().st_mtime_ns
secret1_mtime = identity_secret.lstat().st_mtime_ns
# Assert that the age key is valid
age_secert = decrypt_secret(test_flake_with_core.path, "vm1-age.key")
assert is_valid_age_key(age_secert)
# test idempotency for vm1 and also generate for vm2
cli.run(["facts", "generate", "--flake", str(test_flake_with_core.path)])
assert age_key.lstat().st_mtime_ns == age_key_mtime
@ -72,3 +77,7 @@ def test_generate_secret(
assert has_secret(test_flake_with_core.path, "vm2-zerotier-identity-secret")
ip = machine_get_fact(test_flake_with_core.path, "vm1", "zerotier-ip")
assert ipaddress.IPv6Address(ip).is_private
# Assert that the age key is valid
age_secert = decrypt_secret(test_flake_with_core.path, "vm2-age.key")
assert is_valid_age_key(age_secert)