loft-cli 0.6.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. loft_cli/__init__.py +3 -0
  2. loft_cli/_builtins.py +269 -0
  3. loft_cli/addons/__init__.py +12 -0
  4. loft_cli/addons/goss/__init__.py +1 -0
  5. loft_cli/addons/goss/generator.py +202 -0
  6. loft_cli/addons/goss/renderer.py +207 -0
  7. loft_cli/addons/goss/shipper.py +174 -0
  8. loft_cli/agent_installer.py +65 -0
  9. loft_cli/checks/__init__.py +0 -0
  10. loft_cli/checks/compose.py +147 -0
  11. loft_cli/checks/container.py +24 -0
  12. loft_cli/checks/http.py +30 -0
  13. loft_cli/checks/nginx.py +21 -0
  14. loft_cli/checks/ports.py +24 -0
  15. loft_cli/checks/postgres.py +21 -0
  16. loft_cli/checks/ssh.py +66 -0
  17. loft_cli/checks/wireguard.py +21 -0
  18. loft_cli/cli.py +1161 -0
  19. loft_cli/compiler/__init__.py +0 -0
  20. loft_cli/compiler/normalizer.py +420 -0
  21. loft_cli/compiler/parser.py +42 -0
  22. loft_cli/compiler/planner.py +2543 -0
  23. loft_cli/local/__init__.py +0 -0
  24. loft_cli/local/ddl/__init__.py +0 -0
  25. loft_cli/local/ddl/bootstrap_tables.py +75 -0
  26. loft_cli/local/ddl/versionize_system.py +374 -0
  27. loft_cli/local/inventory.py +449 -0
  28. loft_cli/local/inventory_db.py +255 -0
  29. loft_cli/local/keys.py +45 -0
  30. loft_cli/local/remove.py +135 -0
  31. loft_cli/local/ssh_config.py +118 -0
  32. loft_cli/local/tunnel.py +228 -0
  33. loft_cli/local/wireguard_store.py +138 -0
  34. loft_cli/logs/__init__.py +0 -0
  35. loft_cli/logs/reader.py +55 -0
  36. loft_cli/logs/writer.py +58 -0
  37. loft_cli/runtime/__init__.py +0 -0
  38. loft_cli/runtime/agent_transport.py +115 -0
  39. loft_cli/runtime/executor.py +798 -0
  40. loft_cli/runtime/fabric_transport.py +68 -0
  41. loft_cli/runtime/secret_rotation.py +99 -0
  42. loft_cli/runtime/ssh.py +147 -0
  43. loft_cli/runtime/steps/__init__.py +0 -0
  44. loft_cli/runtime/steps/backup.py +72 -0
  45. loft_cli/runtime/steps/bootstrap.py +227 -0
  46. loft_cli/runtime/steps/compose.py +43 -0
  47. loft_cli/runtime/steps/container.py +40 -0
  48. loft_cli/runtime/steps/docker.py +15 -0
  49. loft_cli/runtime/steps/file_template.py +25 -0
  50. loft_cli/runtime/steps/nginx.py +126 -0
  51. loft_cli/runtime/steps/postgres.py +101 -0
  52. loft_cli/runtime/steps/postgres_ensure.py +141 -0
  53. loft_cli/runtime/steps/systemd.py +131 -0
  54. loft_cli/runtime/steps/wireguard.py +76 -0
  55. loft_cli/runtime/transport.py +43 -0
  56. loft_cli/updater.py +208 -0
  57. loft_cli-0.6.3.dist-info/METADATA +19 -0
  58. loft_cli-0.6.3.dist-info/RECORD +61 -0
  59. loft_cli-0.6.3.dist-info/WHEEL +5 -0
  60. loft_cli-0.6.3.dist-info/entry_points.txt +5 -0
  61. loft_cli-0.6.3.dist-info/top_level.txt +1 -0
loft_cli/local/keys.py ADDED
@@ -0,0 +1,45 @@
1
+ """Local SSH key management — ensure admin key pairs exist before applying."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import subprocess
6
+
7
+ from loft_cli_core.utils.files import expand_path
8
+
9
+
10
+ def ensure_admin_keys(spec, console=None) -> None:
11
+ """Generate SSH key pairs for any admin pubkeys whose private key is absent.
12
+
13
+ Only runs when the auth method is key-based (pubkeys list is non-empty).
14
+ Skips any pubkey path that doesn't follow the conventional '<name>.pub'
15
+ pattern, since we can't safely derive the private key path from it.
16
+
17
+ Root's login key is assumed to exist when private_key auth is used — we
18
+ never auto-generate it here.
19
+ """
20
+ for pubkey_path_str in spec.admin_user.pubkeys:
21
+ pub_path = expand_path(pubkey_path_str)
22
+
23
+ if pub_path.suffix != ".pub":
24
+ continue # can't derive private key path — skip
25
+
26
+ priv_path = pub_path.with_suffix("")
27
+
28
+ if priv_path.exists():
29
+ continue # key already exists — nothing to do
30
+
31
+ # Generate the key pair
32
+ pub_path.parent.mkdir(parents=True, exist_ok=True)
33
+ try:
34
+ subprocess.run(
35
+ ["ssh-keygen", "-t", "ed25519", "-f", str(priv_path), "-N", ""],
36
+ check=True,
37
+ capture_output=True,
38
+ )
39
+ except subprocess.CalledProcessError as e:
40
+ raise RuntimeError(
41
+ f"Failed to generate SSH key pair at {priv_path}: " f"{e.stderr.decode().strip()}"
42
+ ) from e
43
+
44
+ if console:
45
+ console.print(f"[green]✓ Generated SSH key pair:[/green] {priv_path}")
@@ -0,0 +1,135 @@
1
+ """Orchestrate removal of all local loft-cli state for a decommissioned host.
2
+
3
+ ``loft-cli remove <host>`` is the lifecycle endpoint: apply creates,
4
+ doctor monitors, remove cleans up. It tears down:
5
+
6
+ 1. Active WireGuard tunnel (if running)
7
+ 2. WireGuard local state (``~/.wg/loft-cli/{host}/``)
8
+ 3. SSH conf.d entry (``~/.ssh/conf.d/loft-cli/{host}.conf``)
9
+ 4. Inventory record (marked as decommissioned)
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import TYPE_CHECKING
15
+
16
+ if TYPE_CHECKING:
17
+ from rich.console import Console
18
+
19
+
20
+ def remove_host(host_name: str, *, console: Console | None = None) -> list[dict]:
21
+ """Remove all local state for a host.
22
+
23
+ Returns a list of result dicts: [{"action": ..., "status": ..., "detail": ...}].
24
+ """
25
+ results: list[dict] = []
26
+
27
+ if console is None:
28
+ from rich.console import Console
29
+
30
+ console = Console()
31
+
32
+ # 1. Tear down active WireGuard tunnel
33
+ try:
34
+ from loft_cli.local.tunnel import tunnel_down
35
+
36
+ ok, msg = tunnel_down(host_name)
37
+ results.append(
38
+ {"action": "tunnel_down", "status": "ok" if ok else "skipped", "detail": msg}
39
+ )
40
+ console.print(f" [{'green' if ok else 'dim'}]Tunnel: {msg}[/{'green' if ok else 'dim'}]")
41
+ except Exception as e:
42
+ results.append({"action": "tunnel_down", "status": "error", "detail": str(e)})
43
+ console.print(f" [yellow]Tunnel teardown: {e}[/yellow]")
44
+
45
+ # 2. Remove WireGuard local state
46
+ try:
47
+ from loft_cli.local.wireguard_store import _wg_host_dir
48
+
49
+ wg_dir = _wg_host_dir(host_name)
50
+ if wg_dir.exists():
51
+ import shutil
52
+
53
+ shutil.rmtree(wg_dir)
54
+ results.append(
55
+ {"action": "wireguard_state", "status": "ok", "detail": f"Removed {wg_dir}"}
56
+ )
57
+ console.print(f" [green]WireGuard state: removed {wg_dir}[/green]")
58
+ else:
59
+ results.append(
60
+ {"action": "wireguard_state", "status": "skipped", "detail": "No WG state found"}
61
+ )
62
+ console.print(" [dim]WireGuard state: none found[/dim]")
63
+ except Exception as e:
64
+ results.append({"action": "wireguard_state", "status": "error", "detail": str(e)})
65
+ console.print(f" [yellow]WireGuard state removal: {e}[/yellow]")
66
+
67
+ # 3. Remove SSH conf.d entry
68
+ try:
69
+ from loft_cli.local.ssh_config import remove_ssh_conf_d
70
+
71
+ remove_ssh_conf_d(host_name)
72
+ results.append(
73
+ {
74
+ "action": "ssh_config",
75
+ "status": "ok",
76
+ "detail": f"Removed SSH config for {host_name}",
77
+ }
78
+ )
79
+ console.print(f" [green]SSH config: removed conf.d entry for {host_name}[/green]")
80
+ except Exception as e:
81
+ results.append({"action": "ssh_config", "status": "error", "detail": str(e)})
82
+ console.print(f" [yellow]SSH config removal: {e}[/yellow]")
83
+
84
+ # 4. Mark inventory record as decommissioned
85
+ try:
86
+ import os
87
+
88
+ from loft_cli.local.inventory_db import InventoryDB
89
+ from loft_cli_core.registry.local_paths import get_local_paths
90
+
91
+ db_path = os.environ.get("LOFT_CLI_DB_PATH") or str(get_local_paths().inventory_db_path)
92
+ db = InventoryDB(db_path=db_path)
93
+ try:
94
+ db.open()
95
+ server = db.get_server(host_name)
96
+ if server:
97
+ db.upsert_server(
98
+ id=host_name,
99
+ name=server.get("name", host_name),
100
+ address=server.get("address", ""),
101
+ bootstrap_status="decommissioned",
102
+ os_family=server.get("os_family", ""),
103
+ ssh_alias=server.get("ssh_alias", ""),
104
+ ssh_host=server.get("ssh_host", ""),
105
+ ssh_user=server.get("ssh_user", ""),
106
+ ssh_port=server.get("ssh_port"),
107
+ ssh_identity_file=server.get("ssh_identity_file", ""),
108
+ wireguard_enabled=False,
109
+ wireguard_interface=server.get("wireguard_interface", ""),
110
+ wireguard_address=server.get("wireguard_address", ""),
111
+ )
112
+ results.append(
113
+ {
114
+ "action": "inventory",
115
+ "status": "ok",
116
+ "detail": f"Marked {host_name} as decommissioned",
117
+ }
118
+ )
119
+ console.print(f" [green]Inventory: marked {host_name} as decommissioned[/green]")
120
+ else:
121
+ results.append(
122
+ {
123
+ "action": "inventory",
124
+ "status": "skipped",
125
+ "detail": "No inventory record found",
126
+ }
127
+ )
128
+ console.print(" [dim]Inventory: no record found[/dim]")
129
+ finally:
130
+ db.close()
131
+ except Exception as e:
132
+ results.append({"action": "inventory", "status": "error", "detail": str(e)})
133
+ console.print(f" [yellow]Inventory update: {e}[/yellow]")
134
+
135
+ return results
@@ -0,0 +1,118 @@
1
+ """Local SSH conf.d management.
2
+
3
+ SSH config fragments are written to:
4
+
5
+ {ssh_conf_d_base}/{host_name}.conf
6
+
7
+ where ``ssh_conf_d_base`` defaults to ``~/.ssh/conf.d/loft-cli/`` but is
8
+ addon-overridable via ``register_local_paths()``. A single glob Include:
9
+
10
+ Include {ssh_conf_d_base}/*
11
+
12
+ is written once to ``~/.ssh/config`` and covers all fragments in the
13
+ directory — no per-file Include management needed.
14
+
15
+ Commercial clones that want a deeper folder structure (e.g.
16
+ ``~/.ssh/conf.d/mycompany/project1/env/``) only need to call
17
+ ``register_local_paths()`` in their addon's ``register()`` function; this
18
+ module never needs to be modified.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import shutil
24
+ from datetime import UTC, datetime
25
+ from pathlib import Path
26
+
27
+
28
+ def _conf_d_base() -> Path:
29
+ """Return the active SSH conf.d base directory (addon-overridable)."""
30
+ from loft_cli_core.registry.local_paths import get_local_paths
31
+
32
+ return get_local_paths().ssh_conf_d_base
33
+
34
+
35
+ def write_ssh_conf_d(
36
+ host_name: str,
37
+ address: str,
38
+ user: str,
39
+ port: int,
40
+ identity_file: str | None = None,
41
+ tunnel_comment: str | None = None,
42
+ ) -> Path:
43
+ """Write {ssh_conf_d_base}/{host_name}.conf and return the path.
44
+
45
+ Idempotent: overwrites own file on re-run.
46
+
47
+ Parameters
48
+ ----------
49
+ tunnel_comment:
50
+ Optional comment noting a WireGuard tunnel dependency, e.g.
51
+ ``# Requires: loft-cli tunnel up {host}``. Inserted as the
52
+ second line of the generated config.
53
+ """
54
+ base = _conf_d_base()
55
+ base.mkdir(parents=True, exist_ok=True)
56
+ base.chmod(0o700)
57
+
58
+ conf_file = base / f"{host_name}.conf"
59
+
60
+ lines = [
61
+ f"# loft-cli managed: {host_name}",
62
+ ]
63
+ if tunnel_comment:
64
+ lines.append(tunnel_comment)
65
+ lines.extend(
66
+ [
67
+ f"Host {host_name}",
68
+ f" HostName {address}",
69
+ f" User {user}",
70
+ f" Port {port}",
71
+ ]
72
+ )
73
+ if identity_file:
74
+ expanded = str(Path(identity_file).expanduser())
75
+ lines.append(f" IdentityFile {expanded}")
76
+ lines.append(" IdentitiesOnly yes")
77
+
78
+ content = "\n".join(lines) + "\n"
79
+ conf_file.write_text(content, encoding="utf-8")
80
+ conf_file.chmod(0o600)
81
+ return conf_file
82
+
83
+
84
+ def remove_ssh_conf_d(host_name: str) -> None:
85
+ """Remove the conf.d file for a host."""
86
+ conf_file = _conf_d_base() / f"{host_name}.conf"
87
+ if conf_file.exists():
88
+ conf_file.unlink()
89
+
90
+
91
+ def ensure_include(config_path: Path) -> None:
92
+ """Ensure 'Include {ssh_conf_d_base}/*' exists in ~/.ssh/config.
93
+
94
+ Writes a single glob Include that covers all fragments in the loft-cli
95
+ conf.d directory. Written once, never removed — safe to call repeatedly.
96
+ """
97
+ config = config_path.expanduser()
98
+ config.parent.mkdir(parents=True, exist_ok=True)
99
+ config.touch()
100
+ config.chmod(0o600)
101
+
102
+ include_line = f"Include {_conf_d_base()}/*"
103
+ existing_lines = config.read_text(encoding="utf-8").splitlines()
104
+ if include_line not in existing_lines:
105
+ with open(config, "a", encoding="utf-8") as f:
106
+ f.write(f"{include_line}\n")
107
+
108
+
109
+ def backup_ssh_config(config_path: Path) -> Path | None:
110
+ """Create a timestamped backup of ~/.ssh/config if it exists."""
111
+ config = config_path.expanduser()
112
+ if not config.exists():
113
+ return None
114
+ ts = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ")
115
+ backup = config.parent / f"config.{ts}.bak"
116
+ shutil.copy2(config, backup)
117
+ backup.chmod(0o600)
118
+ return backup
@@ -0,0 +1,228 @@
1
+ """WireGuard tunnel management — up, down, status.
2
+
3
+ Manages client-side WireGuard tunnels using ``wg-quick``. Each host gets a
4
+ uniquely-named interface (``wg-{host}``) so multiple tunnels can coexist
5
+ (e.g. Vagrant + Hetzner + production simultaneously).
6
+
7
+ State discovery uses ``~/.wg/loft-cli/{host}/`` directories created by
8
+ ``wireguard_store.save_wireguard_state()``.
9
+
10
+ Requires ``wg-quick`` (part of ``wireguard-tools``) and ``sudo`` access.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import subprocess
17
+ from pathlib import Path
18
+
19
+
20
+ def _wg_state_base() -> Path:
21
+ """Return the WireGuard state base directory."""
22
+ from loft_cli_core.registry.local_paths import get_local_paths
23
+
24
+ return get_local_paths().wg_state_base
25
+
26
+
27
+ def _interface_name(host_name: str) -> str:
28
+ """Derive the client-side WireGuard interface name from the host name.
29
+
30
+ Uses ``wg-{host}`` (truncated to 15 chars — Linux interface name limit).
31
+ Server side always keeps ``wg0`` (it only has one tunnel).
32
+ """
33
+ raw = f"wg-{host_name}"
34
+ return raw[:15]
35
+
36
+
37
+ def _host_dir(host_name: str) -> Path:
38
+ """Return the per-host WireGuard state directory."""
39
+ return _wg_state_base() / host_name
40
+
41
+
42
+ def _client_conf_path(host_name: str) -> Path:
43
+ """Return the path to the client wg-quick config file."""
44
+ return _host_dir(host_name) / "client.conf"
45
+
46
+
47
+ def tunnel_up(host_name: str) -> tuple[bool, str]:
48
+ """Bring up the WireGuard tunnel for a host.
49
+
50
+ Creates a temporary config file named after the interface so
51
+ ``wg-quick`` creates the correctly-named interface.
52
+
53
+ Returns (success: bool, message: str).
54
+ """
55
+ conf_path = _client_conf_path(host_name)
56
+ if not conf_path.exists():
57
+ return False, f"No client.conf found at {conf_path} — run loft-cli apply first"
58
+
59
+ iface = _interface_name(host_name)
60
+
61
+ # Check if the interface is already active
62
+ if _is_interface_active(iface):
63
+ return True, f"Tunnel {iface} is already active"
64
+
65
+ # Create a temporary config named after the interface so wg-quick
66
+ # creates the right interface name. wg-quick derives the interface
67
+ # name from the config file stem.
68
+ iface_conf = conf_path.parent / f"{iface}.conf"
69
+ try:
70
+ # Copy client.conf content to {iface}.conf
71
+ iface_conf.write_text(conf_path.read_text(encoding="utf-8"), encoding="utf-8")
72
+ iface_conf.chmod(0o600)
73
+
74
+ result = subprocess.run(
75
+ ["sudo", "wg-quick", "up", str(iface_conf)],
76
+ capture_output=True,
77
+ text=True,
78
+ timeout=30,
79
+ )
80
+ if result.returncode == 0:
81
+ return True, f"Tunnel {iface} is up"
82
+ else:
83
+ stderr = result.stderr.strip()
84
+ return False, f"wg-quick up failed (exit {result.returncode}): {stderr}"
85
+ except FileNotFoundError:
86
+ return False, "wg-quick not found — install wireguard-tools"
87
+ except subprocess.TimeoutExpired:
88
+ return False, "wg-quick up timed out (30s)"
89
+ except PermissionError:
90
+ return False, "sudo access required for wg-quick"
91
+ finally:
92
+ # Clean up the temporary interface config
93
+ if iface_conf.exists() and iface_conf != conf_path:
94
+ iface_conf.unlink(missing_ok=True)
95
+
96
+
97
+ def tunnel_down(host_name: str) -> tuple[bool, str]:
98
+ """Tear down the WireGuard tunnel for a host.
99
+
100
+ Creates a temporary config file (mirroring ``tunnel_up``) so
101
+ ``wg-quick down`` can find the interface configuration. If
102
+ ``client.conf`` is missing (e.g. host already removed), falls back
103
+ to ``ip link del`` as a last resort.
104
+
105
+ Returns (success: bool, message: str).
106
+ """
107
+ iface = _interface_name(host_name)
108
+
109
+ if not _is_interface_active(iface):
110
+ return True, f"Tunnel {iface} is not active"
111
+
112
+ conf_path = _client_conf_path(host_name)
113
+ iface_conf = conf_path.parent / f"{iface}.conf" if conf_path.exists() else None
114
+
115
+ try:
116
+ # Primary path: use wg-quick down with a temp config file
117
+ if iface_conf is not None:
118
+ iface_conf.write_text(conf_path.read_text(encoding="utf-8"), encoding="utf-8")
119
+ iface_conf.chmod(0o600)
120
+ result = subprocess.run(
121
+ ["sudo", "wg-quick", "down", str(iface_conf)],
122
+ capture_output=True,
123
+ text=True,
124
+ timeout=30,
125
+ )
126
+ if result.returncode == 0:
127
+ return True, f"Tunnel {iface} is down"
128
+ # wg-quick failed — fall through to ip link del
129
+
130
+ # Fallback: delete the interface directly
131
+ result = subprocess.run(
132
+ ["sudo", "ip", "link", "del", iface],
133
+ capture_output=True,
134
+ text=True,
135
+ timeout=10,
136
+ )
137
+ if result.returncode == 0:
138
+ return True, f"Tunnel {iface} torn down (ip link del fallback)"
139
+ stderr = result.stderr.strip()
140
+ return False, f"Failed to tear down {iface}: {stderr}"
141
+ except FileNotFoundError:
142
+ return False, "wg-quick not found — install wireguard-tools"
143
+ except subprocess.TimeoutExpired:
144
+ return False, "wg-quick down timed out (30s)"
145
+ except PermissionError:
146
+ return False, "sudo access required for wg-quick"
147
+ finally:
148
+ if iface_conf is not None and iface_conf.exists() and iface_conf != conf_path:
149
+ iface_conf.unlink(missing_ok=True)
150
+
151
+
152
+ def tunnel_status() -> list[dict]:
153
+ """List all known hosts with their WireGuard tunnel status.
154
+
155
+ Scans ``{wg_state_base}/*/metadata.json`` for host info and
156
+ cross-references with active interfaces via ``wg show``.
157
+
158
+ Returns a list of dicts with keys:
159
+ host_name, interface, endpoint, vpn_ip, peer_address, active, deployed_at
160
+ """
161
+ base = _wg_state_base()
162
+ if not base.exists():
163
+ return []
164
+
165
+ # Get list of active WireGuard interfaces
166
+ active_interfaces = _get_active_interfaces()
167
+
168
+ hosts = []
169
+ for host_dir in sorted(base.iterdir()):
170
+ if not host_dir.is_dir():
171
+ continue
172
+
173
+ metadata_path = host_dir / "metadata.json"
174
+ if not metadata_path.exists():
175
+ continue
176
+
177
+ try:
178
+ metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
179
+ except (json.JSONDecodeError, OSError):
180
+ continue
181
+
182
+ host_name = host_dir.name
183
+ iface = _interface_name(host_name)
184
+ vpn_ip = metadata.get("address", "").split("/")[0]
185
+
186
+ hosts.append(
187
+ {
188
+ "host_name": host_name,
189
+ "interface": iface,
190
+ "endpoint": metadata.get("endpoint", ""),
191
+ "vpn_ip": vpn_ip,
192
+ "peer_address": metadata.get("peer_address", ""),
193
+ "active": iface in active_interfaces,
194
+ "deployed_at": metadata.get("deployed_at", ""),
195
+ }
196
+ )
197
+
198
+ return hosts
199
+
200
+
201
+ def _is_interface_active(iface: str) -> bool:
202
+ """Check if a WireGuard interface is currently active."""
203
+ try:
204
+ result = subprocess.run(
205
+ ["sudo", "wg", "show", iface],
206
+ capture_output=True,
207
+ text=True,
208
+ timeout=5,
209
+ )
210
+ return result.returncode == 0
211
+ except (FileNotFoundError, subprocess.TimeoutExpired, PermissionError):
212
+ return False
213
+
214
+
215
+ def _get_active_interfaces() -> set[str]:
216
+ """Return the set of active WireGuard interface names."""
217
+ try:
218
+ result = subprocess.run(
219
+ ["sudo", "wg", "show", "interfaces"],
220
+ capture_output=True,
221
+ text=True,
222
+ timeout=5,
223
+ )
224
+ if result.returncode == 0:
225
+ return set(result.stdout.strip().split())
226
+ except (FileNotFoundError, subprocess.TimeoutExpired, PermissionError):
227
+ pass
228
+ return set()
@@ -0,0 +1,138 @@
1
+ """Local WireGuard state storage.
2
+
3
+ After a successful WireGuard bootstrap, loft-cli persists a local copy of
4
+ all key material and configuration under:
5
+
6
+ {wg_state_base}/{host_name}/
7
+ private.key — server Curve25519 private key (mode 0600)
8
+ public.key — server public key derived via PyNaCl (mode 0644)
9
+ wg0.conf — server wg-quick config deployed to remote (mode 0600)
10
+ client.key — auto-generated client private key (mode 0600)
11
+ client.conf — client wg-quick config for local use (mode 0600)
12
+ metadata.json — interface details, peer config, deployment provenance
13
+
14
+ The base directory is addon-overridable via ``register_local_paths()``, so
15
+ commercial clones can use a deeper nested structure without touching this file:
16
+
17
+ register_local_paths(LocalPathsConfig(
18
+ wg_state_base=Path("~/.wg/mycompany/project1/").expanduser(),
19
+ ))
20
+ # → ~/.wg/mycompany/project1/{host_name}/private.key etc.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import json
26
+ from datetime import UTC, datetime
27
+ from pathlib import Path
28
+
29
+ from loft_cli_core.utils.files import ensure_dir
30
+
31
+
32
+ def _wg_host_dir(host_name: str) -> Path:
33
+ """Return the per-host WireGuard state directory (not yet created)."""
34
+ from loft_cli_core.registry.local_paths import get_local_paths
35
+
36
+ return get_local_paths().wg_state_base / host_name
37
+
38
+
39
+ def save_wireguard_state(
40
+ *,
41
+ host_name: str,
42
+ spec_name: str,
43
+ private_key: str,
44
+ public_key: str,
45
+ wg_conf_content: str,
46
+ client_private_key: str,
47
+ client_public_key: str,
48
+ client_conf_content: str,
49
+ interface: str,
50
+ address: str,
51
+ endpoint: str,
52
+ peer_address: str,
53
+ persistent_keepalive: int,
54
+ ) -> Path:
55
+ """Persist WireGuard key material and config for one host.
56
+
57
+ Parameters
58
+ ----------
59
+ host_name:
60
+ Value of ``spec.host.name`` — used as the directory name.
61
+ spec_name:
62
+ Value of ``spec.meta.name`` — recorded in metadata for provenance.
63
+ private_key:
64
+ Base64-encoded Curve25519 server private key (contents of private_key_file).
65
+ public_key:
66
+ Derived server public key (populated by the normalizer via PyNaCl).
67
+ wg_conf_content:
68
+ Exact string uploaded to ``/etc/wireguard/{interface}.conf`` on the remote.
69
+ client_private_key:
70
+ Auto-generated client Curve25519 private key (base64).
71
+ client_public_key:
72
+ Derived client public key.
73
+ client_conf_content:
74
+ Client wg-quick config for local use (``wg-quick up client.conf``).
75
+ interface:
76
+ WireGuard interface name (e.g. ``wg0``).
77
+ address:
78
+ Server interface CIDR address (e.g. ``10.10.0.1/24``).
79
+ endpoint:
80
+ Server public endpoint (e.g. ``192.168.56.10:51820``).
81
+ peer_address:
82
+ Client/peer VPN IP CIDR (e.g. ``10.10.0.2/32``).
83
+ persistent_keepalive:
84
+ Keepalive interval in seconds.
85
+
86
+ Returns
87
+ -------
88
+ Path
89
+ The per-host directory that was created/updated.
90
+ """
91
+ host_dir = _wg_host_dir(host_name)
92
+ ensure_dir(host_dir, mode=0o700)
93
+
94
+ # Server private key — write-once (stable server identity across re-runs)
95
+ server_key_path = host_dir / "private.key"
96
+ if not server_key_path.exists():
97
+ _write(server_key_path, private_key + "\n", mode=0o600)
98
+
99
+ # Server public key — not secret
100
+ _write(host_dir / "public.key", public_key + "\n", mode=0o644)
101
+
102
+ # Server wg-quick config deployed to remote — contains private key
103
+ _write(host_dir / f"{interface}.conf", wg_conf_content, mode=0o600)
104
+
105
+ # Client private key — only write if not already present (stable peer identity)
106
+ client_key_path = host_dir / "client.key"
107
+ if not client_key_path.exists():
108
+ _write(client_key_path, client_private_key + "\n", mode=0o600)
109
+
110
+ # Client wg-quick config for local use — always refresh (server config may change)
111
+ _write(host_dir / "client.conf", client_conf_content, mode=0o600)
112
+
113
+ # metadata — provenance + interface/peer summary
114
+ metadata = {
115
+ "host_name": host_name,
116
+ "spec_name": spec_name,
117
+ "deployed_at": datetime.now(UTC).isoformat(),
118
+ "interface": interface,
119
+ "client_interface": f"wg-{host_name}"[:15],
120
+ "address": address,
121
+ "endpoint": endpoint,
122
+ "peer_address": peer_address,
123
+ "persistent_keepalive": persistent_keepalive,
124
+ "server_public_key": public_key,
125
+ "client_public_key": client_public_key,
126
+ }
127
+ _write(
128
+ host_dir / "metadata.json",
129
+ json.dumps(metadata, indent=2) + "\n",
130
+ mode=0o644,
131
+ )
132
+
133
+ return host_dir
134
+
135
+
136
+ def _write(path: Path, content: str, mode: int) -> None:
137
+ path.write_text(content, encoding="utf-8")
138
+ path.chmod(mode)
File without changes