Add native WireGuard DNS recovery and document verified activation

This commit is contained in:
Mikei386 committed 2026-10-28 08:35:34 +01:00
1 parent 3a0653224e
commit 745ee0700e
7 files changed
+446 -2

No files matched your search

+1
View File
@@ -23,6 +23,7 @@ FILES += sorted(str(p.relative_to(ROOT)) for folder in ('soulx-singer-web','soul
FILES += ['xvc.py','xvc_runtime.py','xvc_sources.json','xvc-ui.js','deploy/xvc-requirements.lock','deploy/prepare_xvc.py']
FILES += ['cuda_overlay.py','remix.py','remix_runtime.py','remix_worker.py','remix_sources.json','clearvoice_worker.py','deploy/ladypoly/patch_remix.py']
FILES += ['cpu_partition.py']
FILES += ['network/reconnect.py']
FILES += ['deploy/read_backup_snapshot.py','speech_text.py','tts_text_enhancer.py','strata_runtime.py','strata_worker.py','strata-ui.js','strata_sources.json','deploy/install_strata.py','deploy/strata_toolkit.py','deploy/strata-cuda13.lock.json','deploy/STRATA_NATIVE.md']
FILES += sorted(str(p.relative_to(ROOT)) for p in (ROOT/'deploy/xvc-web').rglob('*') if p.is_file() and not {'__pycache__','.pytest_cache'} & set(p.parts))
FILES += sorted(str(p.relative_to(ROOT)) for p in (ROOT/'deploy/applio-web').rglob('*') if p.is_file() and not {'__pycache__','.pytest_cache'} & set(p.parts))
+52 -2
View File
@@ -13,6 +13,55 @@ import time
import subprocess
MARKER='# Athena Deck native network service'
RECONNECT_MARKER='# Athena Deck native WireGuard endpoint refresh'
def install_reconnect_units():
"""Add a bounded DNS refresh timer without restarting the native gateway."""
service=Path('/etc/systemd/system/athena-deck-network-reconnect.service')
timer=Path('/etc/systemd/system/athena-deck-network-reconnect.timer')
for path in (service,timer):
if path.is_symlink() or path.exists() and not path.read_text().startswith(RECONNECT_MARKER):
raise SystemExit('Reconnect-Dienstname bereits anderweitig belegt.')
service.write_text(RECONNECT_MARKER+'''
[Unit]
Description=Athena Deck native WireGuard stale-endpoint DNS refresh
After=network-online.target athena-deck-network.service
Requisite=athena-deck-network.service
[Service]
Type=oneshot
WorkingDirectory=/opt/athena-deck-network
ExecStart=/usr/bin/python3 -m network.reconnect
Environment=PYTHONDONTWRITEBYTECODE=1
TimeoutStartSec=20
UMask=0077
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
CapabilityBoundingSet=CAP_NET_ADMIN
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK
ReadWritePaths=/run/athena-deck-network
''')
timer.write_text(RECONNECT_MARKER+'''
[Unit]
Description=Periodically refresh stale native Athena WireGuard endpoints
[Timer]
OnBootSec=30s
OnUnitActiveSec=60s
AccuracySec=5s
RandomizedDelaySec=5s
Unit=athena-deck-network-reconnect.service
[Install]
WantedBy=timers.target
''')
for path in (service,timer):path.chmod(0o644)
subprocess.run(['systemd-analyze','verify',str(service),str(timer)],check=True,capture_output=True)
subprocess.run(['systemctl','daemon-reload'],check=True)
subprocess.run(['systemctl','enable','--now',timer.name],check=True,capture_output=True)
def main():
p=argparse.ArgumentParser();p.add_argument('--client-uid',type=int,required=True);p.add_argument('--client-gid',type=int,required=True);p.add_argument('--lan-address',required=True);p.add_argument('--gui-port',type=int,default=8108);p.add_argument('--install-tools',action='store_true');p.add_argument('--ports',default='8108,8120,8121,8122,8123,8124');a=p.parse_args()
if os.geteuid()!=0 or not Path('/run/systemd/system').is_dir():raise SystemExit('Root auf Debian mit systemd erforderlich.')
@@ -31,7 +80,7 @@ def main():
if base.exists() and not (base/'managed-by-deck').exists():raise SystemExit('Installationsverzeichnis belegt.')
base.mkdir(mode=0o755,exist_ok=True);(base/'managed-by-deck').touch();(base/'network').mkdir(exist_ok=True)
source=Path(__file__).resolve().parent.parent/'network'
for name in ('__init__.py','native.py','config.py','policy.py','hosts.py'):shutil.copyfile(source/name,base/'network'/name)
for name in ('__init__.py','native.py','config.py','policy.py','hosts.py','reconnect.py'):shutil.copyfile(source/name,base/'network'/name)
state.mkdir(mode=0o700,exist_ok=True);state.chmod(0o700)
policy=state/'policy.json';interfaces=json.loads(subprocess.check_output(['ip','-j','address','show'],text=True))
interface=next((r['ifname'] for r in interfaces if any(v.get('local')==str(address) for v in r.get('addr_info',[]))),None)
@@ -82,5 +131,6 @@ WantedBy=multi-user.target
except (OSError,ValueError):pass
time.sleep(.2)
else:raise SystemExit('Nativer Dienst nicht bereit; systemctl status athena-deck-network.service prüfen.')
print('Nativer Netzwerkdienst installiert. Bestehender Gateway und dessen Konfiguration unverändert.')
install_reconnect_units()
print('Nativer Netzwerkdienst samt DNS-Wiederverbindung installiert. Bestehender Gateway und dessen Konfiguration unverändert.')
if __name__=='__main__':main()
+16
View File
@@ -58,3 +58,19 @@ LAN-Modussperre), Zustand nach Neuinitialisierung, alte Restore-Formate,
authentifizierte Parameterprüfung und verschlüsselten Backup-/Restore-Rundlauf
ohne WireGuard. Ein vollständiger Neuaufbau auf frischem Debian ist damit
nicht als geprüft ausgewiesen.
## Native Wiederverbindung nach DynDNS-/WAN-Wechsel
Der native Netzwerk-Installer richtet zusätzlich
`athena-deck-network-reconnect.timer` und die zugehörige kurze systemd-Aktion
aus `network/reconnect.py` ein. Der Timer prüft etwa minütlich und löst bei
einem veralteten Handshake den gespeicherten Peer-Hostnamen erneut auf.
Keepalive allein übernimmt diese erneute DNS-Auflösung nicht. Funktionierende
und bewusst deaktivierte Verbindungen bleiben unangetastet; es werden weder
Interfaces noch Anwendungsdienste neu gestartet.
Die Erweiterung benötigt keine Container und keine weiteren privaten Daten.
Bei einem bestehenden Gateway nur diese Erweiterung installieren, nicht den
gesamten Netzwerk-Installer erneut ausführen: dessen Hauptpfad startet den
Gateway-Dienst neu. Umfang, reale Abnahme, native Wiederherstellung und Rückfall:
[DNS-Wiederverbindung](maintenance/native-wireguard-reconnect-2026-10-28/README.md).
@@ -0,0 +1,109 @@
# Native WireGuard: DNS recovery installed · 28 October 2026
## Authorization and exclusions
Michael explicitly authorized native WireGuard diagnosis, reactivation and
persistent automatic recovery on Athena. This is a task-scoped exception, not
blanket permission for future VPN work. Files named `vpn.auth`, `/vpn`, the
excluded OpenVPN-KIT tree and every VPN container remain outside the scope.
No VPN container, other service's credentials or private VPN configuration
outside the native Deck network owner was accessed. No keys/configuration
contents are included in this document or Git.
## Root cause and one-time recovery
The native owner is `athena-deck-network.service`, not a wg-quick unit. Its
`wgdeck0` interface was UP but the handshake was more than three hours old.
The configured hostname resolved to a different address from the running peer
endpoint. Configured and runtime keepalive were already 25 seconds. The native
helper only resolves the endpoint during initial connection; `connect()` is a
no-op while enabled, so it did not refresh stale DNS after the WAN change.
A narrowly scoped `wg set ... peer ... endpoint <configured-hostname:port>`
resolved the name again without deleting the interface, changing routes/keys,
closing gateway listeners or restarting Strata. A new handshake and native
`connected` status were observed. Saved native configuration was unchanged.
NAS TCP checks then succeeded for `192.168.1.212` ports 22, 8108 and 8120.
## Installed unattended recovery
- Native module: `/opt/athena-deck-network/network/reconnect.py`.
- Unit: `athena-deck-network-reconnect.service`, a bounded root oneshot with
only CAP_NET_ADMIN and the required socket families; no container dependency.
- Timer: `athena-deck-network-reconnect.timer`, enabled at boot, first check
30 seconds after boot, then every 60 seconds with up to 5 seconds jitter.
- Persisted enabled intent, native backend/interface and the existing configured
peer are checked. A healthy handshake (at most 135 seconds old) is left alone.
A stale handshake causes resolution of the original configured hostname again.
- Enabled intent/configuration/peer are rechecked immediately before the narrow
update. No interface creation, key/route/listener change or restart fallback.
- Manually disabled tunnels and missing peers are skipped. DNS/helper failure
produces only a generic error and is retried on the next timer interval.
- Runtime-only, secret-free result:
`/run/athena-deck-network/reconnect-status.json` (0600).
- Private configuration remains solely with the existing native owner. No
plaintext configuration copy or new credential was created.
The installation command originally expired at the tool-approval gate without
running. Michael subsequently requested activation again and approved the
execution. Only then was the timer installed and enabled.
## Actual acceptance
- 21 local native-network/reconnect unit tests passed; `git diff --check` passed.
- Installed public module and installer recipe were read back and matched.
- `systemd-analyze verify` passed for both new units before enabling the timer.
- Timer read-back: loaded, **enabled**, **active/waiting**.
- A real timer trigger at **08:27:27 CET** completed the oneshot with
`Result=success`, `ExecMainStatus=0`.
- Recorded result: `connected`, handshake age 34 seconds,
`endpoint_refreshed=false`: the healthy connection was correctly left alone.
- Independent subsequent native status: connected, handshake age 71 seconds.
- Existing native network helper retained **MainPID 1061**, with no restart.
- Independent NAS TCP checks again succeeded on ports 22, 8108 and 8120.
- A later scheduled trigger at **08:31:48 CET** also returned success, with
handshake age 51 seconds and no unnecessary endpoint update.
Selected secret-free acceptance evidence: [activation.json](evidence/activation.json).
No Fritzbox WAN-address change, production outage or host reboot was forced to
validate the timer. Actual one-time stale-DNS recovery, real timer execution,
unit tests and boot enablement are verified separately; future WAN-change and
reboot acceptance have not been executed. No model inference test or Strata
replacement was performed as part of this networking task.
## Native installation, restore and maintenance
Sources: `network/reconnect.py`, `network/test_reconnect.py`,
`deploy/setup_network_helper.py`. The explicit deployment file allowlist also
contains `network/reconnect.py`. Dependencies are the existing native Python 3,
systemd (including systemd-analyze), wireguard-tools and iproute2. No Python
package, new credential, Docker daemon or VPN container is required.
On fresh native installation the network installer copies the module and
installs/verifies/enables both reconnect units after the owning native service
is ready. Restore retains the existing protected native network state and
its encrypted backup procedure; the timer does not introduce additional
private persistent state. Full fresh-Debian installation/restore remains
unqualified under `deploy/NATIVE_INSTALL_REQUIREMENTS.md`.
For an already running gateway, deploy only the public reconnect module and
invoke `install_reconnect_units()` from the reviewed recipe. **Do not invoke
its full `main()` just to add the timer:** that path also restarts the existing
native network gateway. Preserve the current owner's source, policy and state.
Before updating the automation, verify owned unit markers and the reviewed
module version; never overwrite an unrelated unit or symlink. Updating this
oneshot module does not require restarting Deck, Strata or the native gateway.
The public implementation, native recipes and this record are maintained
together in `michael/Athena-Deck`. Git publication does not establish a complete
restore test or authorize any additional production deployment.
## Rollback
Disable only `athena-deck-network-reconnect.timer` with its normal systemd
operation; if needed, stop only the associated reconnect oneshot. This removes
automatic endpoint refresh without resetting the currently recovered tunnel,
restarting its owner, or changing keys/routes/policy. Remove only these newly
owned units/module if permanent removal is explicitly requested, then reload
the systemd unit definitions. Never run broad VPN cleanup.
@@ -0,0 +1,34 @@
{
"scope": "User-approved native Athena WireGuard endpoint refresh; VPN containers and excluded files remain out of scope",
"installed": true,
"module_sha256": "fb442bc953f98bea60f173fa808dced44b7669b19c4e38b8cfdc61f1739e0456",
"native_helper_pid_unchanged_during_installation": true,
"native_helper_pid": 1061,
"timer": {
"name": "athena-deck-network-reconnect.timer",
"active_state": "active",
"sub_state": "waiting",
"unit_file_state": "enabled",
"on_boot_seconds": 30,
"on_unit_active_seconds": 60,
"randomized_delay_seconds": 5,
"first_verified_trigger": "2026-10-28T08:27:27+01:00",
"later_verified_trigger": "2026-10-28T08:31:48+01:00"
},
"oneshot_result": "success",
"oneshot_exit_status": 0,
"later_recorded_result": {
"state": "connected",
"handshake_age_seconds": 51,
"endpoint_refreshed": false,
"checked_at": 1793172708.9690228
},
"nas_tcp_checks": {"22": true, "8108": true, "8120": true},
"local_unit_tests_passed": 21,
"systemd_units_verified": true,
"forced_wan_change_test_performed": false,
"host_reboot_test_performed": false,
"strata_restarted_by_this_task": false,
"vpn_containers_accessed": false,
"credentials_included": false
}
+115
View File
@@ -0,0 +1,115 @@
"""Refresh only the native Deck peer endpoint after stale handshakes.
Never creates interfaces, changes routes/listeners, enables a disabled tunnel,
reads other VPN configurations, or prints credentials. Run by a systemd timer.
"""
import argparse
import json
import os
from pathlib import Path
import socket
import subprocess
import time
from network.config import parse_config
INTERFACE = 'wgdeck0'
STALE_SECONDS = 135
ENV = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LANG': 'C.UTF-8',
'WG_DNS_RESOLUTION_RETRIES': '0'}
def safe_path(path):
path = Path(path)
for value in (path, path.resolve()):
if 'vpn.auth' in value.parts or 'vpn' in value.parts or str(value).startswith('/mnt/nvme-storage/appdata/OpenVPN-KIT'):
raise ValueError('Excluded path')
return path
def command(args):
result = subprocess.run(args, capture_output=True, text=True, timeout=10, env=ENV)
if result.returncode:
raise ValueError('Native WireGuard action unavailable')
return result.stdout.strip()
def native_status(control):
with socket.socket(socket.AF_UNIX) as sock:
sock.settimeout(5)
sock.connect(str(control))
sock.sendall(b'{"action":"status"}\n')
with sock.makefile('rb') as stream:
data = json.loads(stream.readline(32769))
if data.get('error'):
raise ValueError('Native network helper unavailable')
return data
def enabled(root):
path = safe_path(root / 'enabled.json')
return path.is_file() and json.loads(path.read_text()) is True
def peer_handshake(peer):
for line in command(['wg', 'show', INTERFACE, 'latest-handshakes']).splitlines():
fields = line.split()
if len(fields) == 2 and fields[0] == peer:
return int(fields[1])
return None
def refresh(root=Path('/var/lib/athena-deck-network'),
control=Path('/run/athena-deck-network/control.sock'), now=None):
root = safe_path(root)
if not enabled(root):
return dict(state='disabled', endpoint_refreshed=False)
status = native_status(control)
if status.get('backend') != 'native-systemd' or status.get('interface') != INTERFACE:
raise ValueError('Unexpected native backend')
if status.get('enabled') is not True or status.get('configured') is not True:
return dict(state='disabled', endpoint_refreshed=False)
path = safe_path(root / 'config.json')
saved = path.read_bytes()
config = parse_config(json.loads(saved), native=True)
peer = config['peer']['PublicKey']
latest = peer_handshake(peer)
if latest is None:
return dict(state='peer_changed_or_missing', endpoint_refreshed=False)
age = (time.time() if now is None else now) - latest if latest else None
if age is not None and 0 <= age <= STALE_SECONDS:
return dict(state='connected', handshake_age_seconds=int(age), endpoint_refreshed=False)
# Recheck persisted intent and peer identity immediately before the narrow update.
# `wg set ... endpoint` cannot create an interface, alter keys/routes or reset it.
if not enabled(root) or path.read_bytes() != saved or peer_handshake(peer) is None:
return dict(state='configuration_changed', endpoint_refreshed=False)
command(['wg', 'set', INTERFACE, 'peer', peer, 'endpoint', config['peer']['Endpoint']])
return dict(state='endpoint_refreshed_waiting_for_handshake', endpoint_refreshed=True,
handshake_age_seconds=int(age) if age is not None else None)
def main(argv=None):
parser = argparse.ArgumentParser()
parser.add_argument('--state', type=Path, default=Path('/var/lib/athena-deck-network'))
parser.add_argument('--control', type=Path, default=Path('/run/athena-deck-network/control.sock'))
parser.add_argument('--status-file', type=Path, default=Path('/run/athena-deck-network/reconnect-status.json'))
options = parser.parse_args(argv)
code = 0
try:
value = refresh(options.state, options.control)
except Exception as error:
# Do not log exception strings, command arguments, peer identifiers or config values.
value = dict(state='retry_next_interval', endpoint_refreshed=False, error_type=type(error).__name__)
code = 1
value['checked_at'] = time.time()
target = safe_path(options.status_file)
temporary = target.with_suffix('.tmp')
fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, 'w') as stream:
json.dump(value, stream)
temporary.replace(target)
print(json.dumps(value))
return code
if __name__ == '__main__':
raise SystemExit(main())
+119
View File
@@ -0,0 +1,119 @@
"""Synthetic native reconnect regressions; no real tunnel, network or credentials."""
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
from network.reconnect import refresh
CONF = '''[Interface]
PrivateKey = AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=
Address = 192.0.2.10/32
[Peer]
PublicKey = AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI=
Endpoint = gateway.example.test:51820
AllowedIPs = 192.0.2.0/24
PersistentKeepalive = 25
'''
PEER = 'AgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgI='
STATUS = dict(backend='native-systemd', interface='wgdeck0', enabled=True, configured=True)
class ReconnectTests(unittest.TestCase):
def state(self, directory):
root = Path(directory)
(root / 'enabled.json').write_text('true')
(root / 'config.json').write_text(json.dumps(CONF))
return root
def test_disabled_does_not_read_config_or_call_helper(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
with patch('network.reconnect.native_status') as status, patch('network.reconnect.command') as command:
self.assertEqual(refresh(root)['state'], 'disabled')
status.assert_not_called()
command.assert_not_called()
def test_live_handshake_leaves_endpoint_untouched(self):
with tempfile.TemporaryDirectory() as directory:
root = self.state(directory)
with patch('network.reconnect.native_status', return_value=STATUS), \
patch('network.reconnect.command', return_value=PEER + '\t900') as command:
result = refresh(root, now=1000)
self.assertEqual(result['state'], 'connected')
self.assertFalse(result['endpoint_refreshed'])
self.assertEqual(command.call_count, 1)
def test_stale_handshake_refreshes_hostname_without_link_reset(self):
with tempfile.TemporaryDirectory() as directory:
root = self.state(directory)
before = (root / 'config.json').read_bytes()
calls = []
def command(args):
calls.append(args)
return PEER + '\t700' if args[1] == 'show' else ''
with patch('network.reconnect.native_status', return_value=STATUS), \
patch('network.reconnect.command', side_effect=command):
result = refresh(root, now=1000)
self.assertTrue(result['endpoint_refreshed'])
self.assertEqual(calls[-1], ['wg', 'set', 'wgdeck0', 'peer', PEER, 'endpoint', 'gateway.example.test:51820'])
self.assertTrue(all(call[0] == 'wg' for call in calls))
self.assertNotIn('PrivateKey', json.dumps(result))
self.assertEqual((root / 'config.json').read_bytes(), before)
def test_first_handshake_can_be_retried(self):
with tempfile.TemporaryDirectory() as directory:
root = self.state(directory)
with patch('network.reconnect.native_status', return_value=STATUS), \
patch('network.reconnect.command', side_effect=[PEER + '\t0', PEER + '\t0', '']):
self.assertTrue(refresh(root, now=1000)['endpoint_refreshed'])
def test_manual_disable_between_checks_prevents_update(self):
with tempfile.TemporaryDirectory() as directory:
root = self.state(directory)
with patch('network.reconnect.native_status', return_value=STATUS), \
patch('network.reconnect.enabled', side_effect=[True, False]), \
patch('network.reconnect.command', return_value=PEER + '\t700') as command:
result = refresh(root, now=1000)
self.assertEqual(result['state'], 'configuration_changed')
self.assertEqual(command.call_count, 1)
def test_missing_peer_is_never_added(self):
with tempfile.TemporaryDirectory() as directory:
root = self.state(directory)
with patch('network.reconnect.native_status', return_value=STATUS), \
patch('network.reconnect.command', return_value='') as command:
result = refresh(root, now=1000)
self.assertEqual(result['state'], 'peer_changed_or_missing')
self.assertEqual(command.call_count, 1)
def test_helper_disabled_is_respected(self):
with tempfile.TemporaryDirectory() as directory:
root = self.state(directory)
with patch('network.reconnect.native_status', return_value=dict(STATUS, enabled=False)), \
patch('network.reconnect.command') as command:
self.assertFalse(refresh(root)['endpoint_refreshed'])
command.assert_not_called()
def test_dns_failure_does_not_fall_back_to_restart(self):
with tempfile.TemporaryDirectory() as directory:
root = self.state(directory)
with patch('network.reconnect.native_status', return_value=STATUS), \
patch('network.reconnect.command', side_effect=[PEER + '\t700', PEER + '\t700', ValueError('DNS failure')]) as command:
with self.assertRaises(ValueError):
refresh(root, now=1000)
self.assertEqual(command.call_count, 3)
self.assertEqual(json.loads((root / 'enabled.json').read_text()), True)
def test_wrong_interface_is_refused(self):
with tempfile.TemporaryDirectory() as directory:
root = self.state(directory)
with patch('network.reconnect.native_status', return_value=dict(STATUS, interface='unrelated')), \
patch('network.reconnect.command') as command:
with self.assertRaises(ValueError):
refresh(root)
command.assert_not_called()
if __name__ == '__main__':
unittest.main()