feat(network): integrate NetBird clients, profiles and private backups

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:25 +03:00
parent 1e77b198cb
commit 2c0a10b687
47 changed files with 2721 additions and 82 deletions
@@ -0,0 +1,16 @@
This BSD-3-Clause license applies to all parts of the repository except for the directories management/, signal/, relay/ and combined/.
Those directories are licensed under the GNU Affero General Public License version 3.0 (AGPLv3). See the respective LICENSE files inside each directory.
BSD 3-Clause License
Copyright (c) 2022-2026 NetBird GmbH & AUTHORS
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+1
View File
@@ -0,0 +1 @@
"""Official NetBird integration; independent from vehicle and Worker authority."""
+63
View File
@@ -0,0 +1,63 @@
"""Pinned vendor packages served locally; no runtime redirects to latest downloads."""
import hashlib
import json
import os
import stat
from contextlib import contextmanager
from pathlib import Path
LOCK = json.loads(Path(__file__).with_name("clients.lock.json").read_text())
VERSION = LOCK["version"]
def item(identifier: str) -> dict:
for row in LOCK["items"]:
if row["id"] == identifier:
return row
raise ValueError("Неизвестный установщик NetBird.")
def directory(root: Path) -> Path:
return root / "installers" / "netbird" / VERSION
@contextmanager
def open_verified(root: Path, identifier: str):
row = item(identifier)
folder = directory(root)
path = folder / row["filename"]
if any(p.is_symlink() for p in (folder, folder.parent, path)):
raise ValueError("Установщик NetBird изменён.")
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
with os.fdopen(fd, "rb") as stream:
info = os.fstat(stream.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_size != row["bytes"]:
raise ValueError("Установщик NetBird изменён.")
if hashlib.file_digest(stream, "sha256").hexdigest() != row["sha256"]:
raise ValueError("Установщик NetBird изменён.")
stream.seek(0)
yield stream, path
def verify(root: Path, identifier: str) -> Path:
with open_verified(root, identifier) as (_, path):
return path
def catalog(root: Path) -> dict:
entries = []
for row in LOCK["items"]:
try:
verify(root, row["id"])
available = True
except (OSError, ValueError):
available = False
entries.append(
{k: row[k] for k in ("id", "label", "filename", "bytes", "sha256")}
| {
"available": available,
"download_url": f"/api/v1/fleet/netbird/clients/{row['id']}",
}
)
return {"version": VERSION, "items": entries}
+157
View File
@@ -0,0 +1,157 @@
"""Private full-network backups owned by Mission Core, outside the source checkout."""
import hashlib
import json
import os
import re
import tempfile
import threading
import zipfile
from datetime import UTC, datetime
from pathlib import Path, PurePosixPath
MAX_BYTES = 256 * 1024 * 1024
MAX_STORED_BYTES = 1024 * 1024 * 1024
MAX_BACKUPS = 20
LOCK = threading.Lock()
REQUIRED = {"config/config.json", "control/installed.json", "state/store.db", "state/idp.db"}
def directory(root):
path = Path(root) / "networks" / "netbird-backups"
if path.is_symlink():
raise ValueError("Хранилище резервных копий недоступно.")
path.mkdir(parents=True, exist_ok=True, mode=0o700)
path.chmod(0o700)
return path
def inspect(path):
with zipfile.ZipFile(path) as archive:
entries = archive.infolist()
names = [entry.filename for entry in entries]
if len(entries) > 4097 or len(names) != len(set(names)) or "manifest.json" not in names:
raise ValueError("Некорректный состав резервной копии.")
if (
archive.getinfo("manifest.json").file_size > 2 * 1024**2
or sum(x.file_size for x in entries) > MAX_BYTES
):
raise ValueError("Резервная копия превышает допустимый размер.")
manifest = json.loads(archive.read("manifest.json"))
files = manifest.get("files", {})
if (
manifest.get("schema") != "missioncore.netbird-transfer/v1"
or not isinstance(files, dict)
or set(names) != set(files) | {"manifest.json"}
or not files.keys() >= REQUIRED
):
raise ValueError("Нет полной резервной копии NetBird.")
for entry in entries:
if entry.filename == "manifest.json":
continue
relative = PurePosixPath(entry.filename)
if (
str(relative) != entry.filename
or relative.is_absolute()
or ".." in relative.parts
or "\\" in entry.filename
or len(relative.parts) < 2
or relative.parts[0] not in {"config", "control", "state", "tls"}
or (entry.external_attr >> 16) & 0o170000 not in (0, 0o100000)
):
raise ValueError("Недопустимый путь в резервной копии.")
checksum = hashlib.sha256()
with archive.open(entry) as stream:
while chunk := stream.read(262144):
checksum.update(chunk)
expected = files[entry.filename]
if (
expected.get("bytes") != entry.file_size
or expected.get("sha256") != checksum.hexdigest()
):
raise ValueError("Резервная копия повреждена: контрольные суммы не совпадают.")
domain = manifest.get("domain", "")
identity = manifest.get("identity_sha256", "")
if not re.fullmatch(
r"[a-z0-9](?:[a-z0-9.-]{0,250})\.[a-z]{2,63}", domain
) or not re.fullmatch(r"[a-f0-9]{64}", identity):
raise ValueError("Идентичность сети не подтверждена.")
if manifest.get("management_url") != f"https://{domain}:8443":
raise ValueError("Адрес сети в резервной копии не совпадает.")
with Path(path).open("rb") as stream:
checksum = hashlib.file_digest(stream, "sha256").hexdigest()
return {
"id": checksum,
"domain": domain,
"server_url": manifest["management_url"],
"identity_sha256": identity,
"bytes": Path(path).stat().st_size,
"verification": "checksums_verified",
}
def catalog(root):
result = []
for path in directory(root).glob("*.json"):
if not re.fullmatch(r"[a-f0-9]{64}\.json", path.name) or path.is_symlink():
continue
try:
row = json.loads(path.read_text())
blob = path.with_suffix(".zip")
if (
row.get("id") == path.stem
and blob.is_file()
and not blob.is_symlink()
and blob.stat().st_size == row["bytes"]
):
result.append(row)
except (OSError, ValueError, KeyError, TypeError):
continue
return {"items": sorted(result, key=lambda row: row["stored_at"], reverse=True)}
def admit(root, incoming):
if Path(incoming).stat().st_size > MAX_BYTES:
raise ValueError("Резервная копия превышает 256 МиБ.")
row = inspect(incoming)
path = directory(root)
with LOCK:
saved = catalog(root)["items"]
existing = next((item for item in saved if item["id"] == row["id"]), None)
if existing:
return existing
# Preserve recovery history instead of silently deleting older identities.
if (
len(saved) >= MAX_BACKUPS
or sum(item["bytes"] for item in saved) + row["bytes"] > MAX_STORED_BYTES
):
raise ValueError("Хранилище резервных копий заполнено. Существующие копии сохранены.")
row["stored_at"] = datetime.now(UTC).isoformat()
target = path / (row["id"] + ".zip")
os.chmod(incoming, 0o600)
os.replace(incoming, target)
fd, name = tempfile.mkstemp(prefix=".receipt-", dir=path)
temporary = Path(name)
try:
with os.fdopen(fd, "w") as output:
json.dump(row, output, ensure_ascii=False)
output.flush()
os.fsync(output.fileno())
os.replace(temporary, target.with_suffix(".json"))
descriptor = os.open(path, os.O_RDONLY)
try:
os.fsync(descriptor)
finally:
os.close(descriptor)
finally:
temporary.unlink(missing_ok=True)
return row
def download(root, identifier):
if not re.fullmatch(r"[a-f0-9]{64}", identifier):
raise ValueError("Резервная копия не найдена.")
path = directory(root) / (identifier + ".zip")
if path.is_symlink() or inspect(path)["id"] != identifier:
raise ValueError("Резервная копия повреждена.")
return path
+499
View File
@@ -0,0 +1,499 @@
"""Bounded adapter to the official daemon. No route, DNS or WireGuard key ownership."""
import hashlib
import ipaddress
import json
import os
import platform
import re
import shlex
import shutil
import subprocess
import tempfile
import threading
import time
import urllib.request
from pathlib import Path
from urllib.parse import urlsplit
from .assets import VERSION, item, verify
from .persistence import atomic_private
PROFILE = "mission-core"
VERIFY_SECONDS = 20
SAFE_FLAGS = [
"--disable-dns",
"--disable-client-routes",
"--disable-server-routes",
"--disable-ipv6",
"--allow-server-ssh=false",
"--allow-remote-jobs=false",
"--network-monitor=true",
"--disable-auto-connect=false",
]
def server_url(value: str) -> str:
try:
parsed = urlsplit(value.strip())
if (
parsed.scheme != "https"
or not parsed.hostname
or parsed.username is not None
or parsed.password is not None
or parsed.path not in ("", "/")
or parsed.query
or parsed.fragment
or any(c.isspace() for c in value)
or not re.fullmatch(r"[a-zA-Z0-9.-]+", parsed.hostname)
or parsed.hostname in ("localhost", "localhost.localdomain")
or (parsed.port is not None and not 1 <= parsed.port <= 65535)
):
raise ValueError
try:
ip = ipaddress.ip_address(parsed.hostname)
except ValueError:
ip = None
if ip and (ip.is_loopback or ip.is_link_local or ip.is_unspecified or ip.is_multicast):
raise ValueError
host = parsed.hostname.lower()
return "https://" + host + (f":{parsed.port}" if parsed.port not in (None, 443) else "")
except (ValueError, TypeError, AttributeError):
raise ValueError("Укажите HTTPS-адрес сервера без пути, логина и пароля.") from None
def executable() -> Path | None:
candidates = {
"Darwin": [
"/Applications/NetBird.app/Contents/MacOS/netbird",
"/usr/local/bin/netbird",
"/opt/homebrew/bin/netbird",
],
"Linux": ["/usr/bin/netbird", "/usr/local/bin/netbird"],
"Windows": [
str(Path(os.environ.get("PROGRAMFILES", "C:/Program Files")) / "NetBird/netbird.exe")
],
}.get(platform.system(), [])
return next((Path(p) for p in candidates if Path(p).is_file()), None)
def invoke(binary: Path, *arguments: str) -> subprocess.CompletedProcess:
return subprocess.run(
[str(binary), *arguments, "--log-file", "console"],
capture_output=True,
text=True,
timeout=8,
check=False,
)
def project_status(raw: dict, server: str, network: str = "") -> dict:
management, signal = raw.get("management", {}), raw.get("signal", {})
try:
actual = server_url(management.get("url", ""))
except ValueError:
actual = ""
connected = bool(management.get("connected") and signal.get("connected"))
address = str(raw.get("netbirdIp", "")).split("/")[0]
try:
ip = ipaddress.IPv4Address(address)
address_ok = any(
ip in ipaddress.ip_network(c) for c in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")
)
except ValueError:
address_ok = False
if address_ok:
address_ok = ip not in ipaddress.ip_network("10.203.0.0/16")
if network:
address_ok = address_ok and ip in ipaddress.IPv4Network(network)
owned = bool(server and actual == server and raw.get("profileName") == PROFILE)
state = "connected" if connected and owned and address_ok else "disconnected"
if connected and not owned:
state = "other_network"
elif connected and not address_ok:
state = "address_conflict"
if raw.get("daemonVersion") not in (None, "", VERSION):
state = "unsupported_client"
return {
"state": state,
"address": address if state == "connected" else "",
"owned": owned,
"daemon_version": raw.get("daemonVersion", ""),
"peers_connected": raw.get("peers", {}).get("connected", 0),
}
class _NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise ValueError("Сервер перенаправляет проверку на другой адрес.")
def preflight(url: str) -> dict:
# Only our qualified VPS package exposes this receipt after account/ACL bootstrap.
# Default CGNAT allocation can overlap Tailscale; do not discover this after joining.
request = urllib.request.Request(url + "/.well-known/missioncore-network.json")
# Reject before following Location, including a redirect to a local service.
opener = urllib.request.build_opener(_NoRedirect())
with opener.open(request, timeout=8) as response:
if server_url(response.url.split("/.well-known/")[0]) != url:
raise ValueError("Адрес сервера изменился при проверке.")
raw = response.read(8193)
if len(raw) > 8192:
raise ValueError("Ответ сервера слишком большой.")
data = json.loads(raw)
if data.get("schema") != "missioncore.netbird-server/v1" or data.get("ready") is not True:
raise ValueError("Подготовка сервера NetBird ещё не завершена.")
subnet = ipaddress.IPv4Network(data["network"])
private = any(
subnet.subnet_of(ipaddress.ip_network(cidr))
for cidr in ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")
)
if not private or subnet.overlaps(ipaddress.ip_network("10.203.0.0/16")):
raise ValueError("Адресация сервера не прошла проверку совместимости.")
if data.get("access_policy_revision") != 1:
raise ValueError("Обновите правила доступа установщиком VPS перед подключением.")
if data.get("session_policy_revision") != 1 or any(
data.get(key) is not False
for key in ("peer_login_expiration_enabled", "peer_inactivity_expiration_enabled")
):
raise ValueError(
"Сервер не подтверждает подключение без срока действия. "
"Обновите настройки авторизации установщиком VPS."
)
if data.get("management_url") != url or data.get("client_version") != VERSION:
raise ValueError("Версия сервера и клиента не согласованы.")
return data
class Client:
def __init__(self, root: Path):
self.root = root
self.path = root / "networks" / "netbird.json"
self.lock = threading.RLock()
self.worker: threading.Thread | None = None
self.process: subprocess.Popen | None = None
self.pending = ""
self.auth_url = ""
self.error = ""
self.cached: dict = {}
self.checked = 0.0
self.server = ""
self.network = ""
self.probe_lock = threading.Lock()
self.cancelled = threading.Event()
self.closed = False
self.observer: threading.Thread | None = None
if self.path.exists():
try:
saved = json.loads(self.path.read_text())
self.server = server_url(saved["server_url"])
if saved.get("network"):
self.network = str(ipaddress.IPv4Network(saved["network"]))
except (OSError, ValueError, KeyError, TypeError):
self.error = "Сохранённый адрес сервера повреждён. Укажите его заново."
def _snapshot(self) -> dict:
result = dict(self.cached or {"state": "unavailable", "address": "", "owned": False})
if self.checked and time.monotonic() - self.checked > 20:
result.update(state="unavailable", address="")
result.update(
server_url=self.server,
network=self.network,
client_version=VERSION,
error=self.error,
pending=self.pending,
auth_url=self.auth_url,
can_install=platform.system() == "Darwin",
)
return result
def observation(self) -> dict:
"""Heartbeat paths never wait for the external CLI or daemon."""
with self.lock:
if (
not self.closed
and (not self.observer or not self.observer.is_alive())
and time.monotonic() - self.checked > 5
):
self.observer = threading.Thread(target=self.status, daemon=True)
self.observer.start()
return self._snapshot()
def status(self, *, force: bool = False) -> dict:
with self.lock:
if not force and self.cached and time.monotonic() - self.checked < 2:
return self._snapshot()
server, network = self.server, self.network
# A slow daemon must not block cancellation, operation registration or
# every polling HTTP request behind the same global lock.
if not (
self.probe_lock.acquire(timeout=18)
if force
else self.probe_lock.acquire(blocking=False)
):
with self.lock:
return self._snapshot()
try:
binary = executable()
result = {"state": "missing_client", "address": "", "owned": False}
if binary:
try:
version = invoke(binary, "version")
if version.returncode or version.stdout.strip() != VERSION:
result["state"] = "unsupported_client"
else:
response = invoke(binary, "status", "--json")
if response.returncode:
raise ValueError("Daemon status failed")
result = project_status(json.loads(response.stdout), server, network)
except (OSError, subprocess.SubprocessError, ValueError, AttributeError, TypeError):
result["state"] = "unavailable"
with self.lock:
# A probe begun before selecting a new server cannot publish its
# result as evidence for the new selection.
if (server, network) == (self.server, self.network):
self.cached, self.checked = result, time.monotonic()
return self._snapshot()
finally:
self.probe_lock.release()
def _start(self, pending: str, target, *args) -> dict:
with self.lock:
if self.closed:
raise ValueError("Mission Core завершает работу.")
if self.worker and self.worker.is_alive():
raise ValueError("Дождитесь завершения текущей операции.")
self.cancelled.clear()
self.pending, self.error, self.auth_url = pending, "", ""
self.worker = threading.Thread(target=target, args=args, daemon=True)
self.worker.start()
return self._snapshot()
def connect(self, value: str, setup_key: str = "") -> dict:
target = server_url(value)
if setup_key and not re.fullmatch(r"[A-Za-z0-9-]{20,128}", setup_key):
raise ValueError("Некорректный ключ подключения.")
binary = executable()
if not binary:
raise ValueError("Клиент NetBird не найден.")
return self._start("connecting", self._connect, binary, target, setup_key)
def _check_cancelled(self):
if self.cancelled.is_set():
raise InterruptedError("Connection wait cancelled")
@staticmethod
def _stop_process(process):
if process and process.poll() is None:
try:
process.terminate()
process.wait(timeout=3)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=3)
except ProcessLookupError:
pass
def cancel(self) -> dict:
with self.lock:
if self.pending == "installing":
raise ValueError("Отмените установку в системном окне macOS.")
self.cancelled.set()
if self.pending:
self.pending = "cancelling"
self.auth_url = ""
process = self.process
# Stop only the CLI operation owned by Core. Never stop a foreign daemon
# or tear down an established connection from a cancellation click.
self._stop_process(process)
with self.lock:
return self._snapshot()
def _connect(self, binary: Path, target: str, setup_key: str = "") -> None:
process = None
timer = None
try:
current = self.status(force=True)
if current["state"] in ("missing_client", "unsupported_client", "unavailable"):
raise ValueError("Установите и запустите предложенную версию клиента NetBird.")
if current["state"] == "other_network" or (
current["state"] == "connected" and target != self.server
):
raise ValueError("Сначала отключите другую сеть в официальном клиенте NetBird.")
self._check_cancelled()
receipt = preflight(target)
self._check_cancelled()
atomic_private(
self.path,
json.dumps({"server_url": target, "network": receipt["network"]}).encode(),
)
with self.lock:
self.server, self.network = target, receipt["network"]
self.cached, self.checked = {}, 0
if current["state"] == "connected":
if self.status(force=True)["state"] != "connected":
raise ValueError("Адресация клиента не соответствует выбранному серверу.")
return
environment = {k: v for k, v in os.environ.items() if not k.startswith("NB_")}
if setup_key:
environment["NB_SETUP_KEY"] = setup_key
process = subprocess.Popen(
[
str(binary),
"up",
"--profile",
PROFILE,
"--management-url",
target,
"--no-browser",
"--log-file",
"console",
*SAFE_FLAGS,
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=environment,
)
with self.lock:
self.process = process
self._check_cancelled()
timer = threading.Timer(180, self._stop_process, args=(process,))
timer.daemon = True
timer.start()
observed = bytearray()
assert process.stdout is not None
while chunk := process.stdout.read1(2048):
self._check_cancelled()
observed.extend(chunk)
if len(observed) > 65536:
raise ValueError("Подключение не завершено. Проверьте клиент NetBird.")
# Authentication links remain in RAM, never in logs or persisted profiles.
for match in re.findall(
r'https://[^\s<>"\x1b]+', observed.decode(errors="replace").rsplit("\n", 1)[0]
):
parsed = urlsplit(match)
try:
same_server = server_url(f"{parsed.scheme}://{parsed.netloc}") == target
except ValueError:
same_server = False
if same_server and parsed.path.startswith("/oauth2/"):
with self.lock:
self.auth_url, self.pending = match, "authentication"
self.checked = 0
self._check_cancelled()
if process.wait(timeout=3) != 0:
raise ValueError("Вход не завершён. Повторите подключение к серверу.")
with self.lock:
self.auth_url, self.pending = "", "verifying"
# CLI exit is not connection evidence: wait for this exact daemon
# profile, both control-plane connections and its assigned address.
deadline = time.monotonic() + VERIFY_SECONDS
while time.monotonic() < deadline:
self._check_cancelled()
if self.status(force=True)["state"] == "connected":
break
self.cancelled.wait(0.5)
else:
raise ValueError(
"Вход выполнен, но соединение не подтверждено. "
"Проверьте клиент и повторите подключение."
)
except InterruptedError:
with self.lock:
self.error = "Ожидание входа отменено. Подключение можно повторить."
except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError) as error:
with self.lock:
self.error = (
str(error)
if isinstance(error, ValueError)
and str(error).startswith(
(
"Установите",
"Сначала",
"Вход",
"Обновите",
"Подготовка",
"Адресация",
"Версия",
)
)
else "Не удалось подключиться. Проверьте адрес и подготовку VPS, "
"затем повторите вход."
)
if self.cancelled.is_set():
self.error = "Ожидание входа отменено. Подключение можно повторить."
finally:
if timer:
timer.cancel()
self._stop_process(process)
if process and process.stdout:
process.stdout.close()
with self.lock:
self.process, self.pending, self.auth_url, self.checked = None, "", "", 0
def install(self) -> dict:
if platform.system() != "Darwin":
raise ValueError("Скачайте официальный установщик для своей системы.")
# Validation runs inside the registered operation, not under the state lock.
return self._start("installing", self._install_verified)
def _install_verified(self):
try:
package = verify(self.root, "macos")
except (OSError, ValueError):
with self.lock:
self.error, self.pending = (
"Проверенный установщик недоступен. Обновите каталог пакетов.",
"",
)
return
if not self.closed:
self._install(package)
def _install(self, package: Path) -> None:
try:
# Root's installer does not inherit Core's access to protected folders.
with tempfile.TemporaryDirectory(
prefix="ndc-netbird-install-", dir="/private/tmp"
) as temporary:
staged = Path(temporary) / "NetBird.pkg"
shutil.copyfile(package, staged)
staged.chmod(0o600)
with staged.open("rb") as stream:
if hashlib.file_digest(stream, "sha256").hexdigest() != item("macos")["sha256"]:
raise ValueError("Staged package checksum mismatch")
command = "/usr/sbin/installer -pkg " + shlex.quote(str(staged)) + " -target /"
script = "do shell script " + json.dumps(command) + " with administrator privileges"
subprocess.run(
["/usr/bin/osascript", "-e", script],
capture_output=True,
timeout=600,
check=True,
)
except (OSError, ValueError, subprocess.SubprocessError) as error:
diagnostic = {
"operation": "install",
"type": type(error).__name__,
"returncode": getattr(error, "returncode", None),
"stderr": (getattr(error, "stderr", b"") or b"")[:2048].decode(errors="replace"),
}
atomic_private(
self.path.with_name("netbird-install-diagnostic.json"),
json.dumps(diagnostic).encode(),
)
with self.lock:
self.error = (
"Установка не завершена. Подтвердите системный запрос macOS или скачайте пакет."
)
finally:
with self.lock:
self.pending, self.checked = "", 0
def close(self) -> None:
with self.lock:
self.closed = True
self.cancelled.set()
process, worker = self.process, self.worker
self._stop_process(process)
if worker:
worker.join(timeout=10)
@@ -0,0 +1,70 @@
{
"version": "0.82.0",
"release_url": "https://github.com/netbirdio/netbird/releases/tag/v0.82.0",
"items": [
{
"id": "macos",
"label": "macOS · Apple Silicon и Intel",
"filename": "netbird_0.82.0_darwin.pkg",
"bytes": 48381929,
"sha256": "b550f0c22b2e0b33483027bb9654caeb5b90e9e57af347fc4b4126e11cb1bc8d",
"source_url": "https://github.com/netbirdio/netbird/releases/download/v0.82.0/netbird_0.82.0_darwin.pkg"
},
{
"id": "windows-amd64",
"label": "Windows · x64",
"filename": "netbird_installer_0.82.0_windows_amd64.exe",
"bytes": 21015160,
"sha256": "4936b5f037b00747b2e50d880a6b8bb77847ce9697b74e36def1f565408ec7d8",
"source_url": "https://github.com/netbirdio/netbird/releases/download/v0.82.0/netbird_installer_0.82.0_windows_amd64.exe"
},
{
"id": "windows-arm64",
"label": "Windows · ARM64",
"filename": "netbird_installer_0.82.0_windows_arm64.exe",
"bytes": 18302072,
"sha256": "de4662a74be46102a3ce910e1c1bc55400e215ac6db11f6b35aab8e30feb3ff7",
"source_url": "https://github.com/netbirdio/netbird/releases/download/v0.82.0/netbird_installer_0.82.0_windows_arm64.exe"
},
{
"id": "linux-amd64",
"label": "Linux · Debian / Ubuntu · x64",
"filename": "netbird_0.82.0_linux_amd64.deb",
"bytes": 15857818,
"sha256": "8facd1bb67661c5598699404590b77025e35eae2b11d85c1c26b0347efe703ec",
"source_url": "https://github.com/netbirdio/netbird/releases/download/v0.82.0/netbird_0.82.0_linux_amd64.deb"
},
{
"id": "linux-arm64",
"label": "Linux · Debian / Ubuntu · ARM64",
"filename": "netbird_0.82.0_linux_arm64.deb",
"bytes": 14505598,
"sha256": "aeec646d685443b6ca918d31a42953b20d79286761ed45106099b40d8ef08164",
"source_url": "https://github.com/netbirdio/netbird/releases/download/v0.82.0/netbird_0.82.0_linux_arm64.deb"
},
{
"id": "linux-ui-amd64",
"label": "Linux · интерфейс · Debian / Ubuntu · x64",
"filename": "netbird-ui_0.82.0_linux_amd64.deb",
"bytes": 12083196,
"sha256": "89d69e46bcc8e782d079687b30bc4e010c1d075b864d0eac219562dc693b9385",
"source_url": "https://github.com/netbirdio/netbird/releases/download/v0.82.0/netbird-ui_0.82.0_linux_amd64.deb"
},
{
"id": "linux-rpm-amd64",
"label": "Linux · RPM · x64",
"filename": "netbird_0.82.0_linux_amd64.rpm",
"bytes": 16031397,
"sha256": "c231c26f2feb6902be444630ac2e1bbcdd74d361408d136dcc81957c0feedcc8",
"source_url": "https://github.com/netbirdio/netbird/releases/download/v0.82.0/netbird_0.82.0_linux_amd64.rpm"
},
{
"id": "linux-rpm-arm64",
"label": "Linux · RPM · ARM64",
"filename": "netbird_0.82.0_linux_arm64.rpm",
"bytes": 14650074,
"sha256": "0892b0f5a9c09b4f0f0e10aeefbc46a83d6b7f1b98bced31265823680880b4f6",
"source_url": "https://github.com/netbirdio/netbird/releases/download/v0.82.0/netbird_0.82.0_linux_arm64.rpm"
}
]
}
+25
View File
@@ -0,0 +1,25 @@
"""Private atomic state, shared with the standalone onboard adapter."""
import os
import tempfile
from pathlib import Path
def atomic_private(path: Path, data: bytes) -> None:
path.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
if path.is_symlink():
raise ValueError("Обнаружен конфликт файла доверия.")
fd, name = tempfile.mkstemp(prefix=".fleet-", dir=path.parent)
try:
with os.fdopen(fd, "wb") as f:
f.write(data)
f.flush()
os.fsync(f.fileno())
os.replace(name, path)
directory = os.open(path.parent, os.O_RDONLY)
try:
os.fsync(directory)
finally:
os.close(directory)
finally:
Path(name).unlink(missing_ok=True)
+88 -15
View File
@@ -59,6 +59,7 @@ class NetworkProfiles:
self.commands = {}
self.operations = {}
self.workers = {}
self.local_requests = {}
self.import_lock = threading.Lock()
self.sync_lock = threading.RLock()
self.revoke_retry = {}
@@ -79,6 +80,15 @@ class NetworkProfiles:
self.save()
def reconcile(self):
client = getattr(self.fleet, "netbird", None)
if client is not None:
observed = client.observation()
if observed.get("state") == "connected":
with self.fleet.lock:
try:
self.fleet.listen(observed["address"])
except OSError:
pass
# Durable revocation retries run outside registry/control locks.
now = time.monotonic()
with self.lock:
@@ -174,18 +184,24 @@ class NetworkProfiles:
return config
def import_file(self, raw, name="", interface=None):
identity = parse_file(raw)["server_id"]
if not self.import_lock.acquire(blocking=False):
raise ValueError("Дождитесь завершения импорта профиля.")
previous = copy.deepcopy(self.profiles)
with self.lock:
previous = copy.deepcopy(self.profiles.get(identity))
try:
return self._import_file(raw, name, interface)
except Exception:
# A failed new claim keeps its retry token; an existing active profile
# retains its last verified endpoint and peer set.
with self.lock:
for identity, row in previous.items():
if row.get("state") == "ready":
self.profiles[identity] = row
if previous and previous.get("state") == "ready":
# Revocations can arrive while the administrator is confirming
# installation. Never undo them or other profiles on failure.
current = self.profiles.get(identity, {})
previous["revocations"] = sorted(set(previous.get("revocations", [])) |
set(current.get("revocations", [])))
self.profiles[identity] = previous
self.save()
raise
finally:
@@ -201,7 +217,7 @@ class NetworkProfiles:
raise ValueError("Файл подключения просрочен. Получите новый файл на VPS.")
if any(p["server_id"] != value["server_id"] and p["subnet"] == value["subnet"] for p in self.profiles.values()):
raise ValueError("Адресация совпадает с другим подключённым VPS.")
row = {**value, "name": name.strip()[:80] or (old or {}).get("name") or "WireGuard · " + urlsplit(value["endpoint"]).hostname,
row = {**copy.deepcopy(old or {}), **value, "name": name.strip()[:80] or (old or {}).get("name") or "WireGuard · " + urlsplit(value["endpoint"]).hostname,
"token": (old or {}).get("token") or secrets.token_urlsafe(32),
"state": (old or {}).get("state", "pending"), "network_interface": interface or (old or {}).get("network_interface")}
# Persist the retry credential before either administrator interaction or claim.
@@ -233,17 +249,59 @@ class NetworkProfiles:
def heartbeat(self, row, value):
snapshot = value.get("network_profile")
if isinstance(snapshot, dict) and snapshot.get("phase") in ("applied", "rolled_back"):
selected = snapshot.get("server_id") if snapshot.get("provider") == "wireguard" else "tailscale"
selected = snapshot.get("server_id") if snapshot.get("provider") in ("wireguard", "netbird") else "tailscale"
if selected == "tailscale" or selected in row.get("network_paths", {}):
row["network_active"] = selected
offer = self.netbird_offer(row, snapshot) if isinstance(snapshot, dict) else None
response = {"netbird_offer": offer} if offer else {}
with self.changed:
if isinstance(snapshot, dict) and len(json.dumps(snapshot)) < 16384:
self.latest[row["node_id"]] = {"value": copy.deepcopy(snapshot), "received": time.monotonic(), "endpoint": value.get("core_endpoint")}
self.changed.notify_all()
local = snapshot.get("local_request") if isinstance(snapshot, dict) else None
if isinstance(local, dict) and local.get("provider") == "netbird":
identity = local.get("id", "")
expires = local.get("expires_at")
if isinstance(identity, str) and re.fullmatch(r"[a-f0-9]{32}", identity) and type(expires) is int and time.time() < expires <= time.time() + 180:
previous = self.local_requests.get(row["node_id"])
if previous is None or previous["id"] != identity:
previous = {"id": identity, "error": ""}
try:
self.start(row["id"], "netbird", "netbird", local.get("revision"))
except ValueError as error:
previous["error"] = str(error)
self.local_requests[row["node_id"]] = previous
response["network_request_result"] = previous.copy()
command = self.commands.get(row["node_id"])
if command and command["expires_at"] > time.time():
return {"network_profile_change": copy.deepcopy(command)}
return {}
return {**response, "network_profile_change": copy.deepcopy(command)}
return response
def netbird_offer(self, row, snapshot):
client = getattr(self.fleet, "netbird", None)
if client is None:
return None
operator = client.observation()
board = snapshot.get("netbird", {})
if not isinstance(board, dict) or operator.get("state") != "connected" or board.get("state") != "connected":
return None
if not operator.get("server_url") or board.get("server_url") != operator["server_url"] or board.get("network") != operator.get("network"):
return None
try:
subnet = ipaddress.IPv4Network(operator["network"])
core_ip, node_ip = ipaddress.IPv4Address(operator["address"]), ipaddress.IPv4Address(board["address"])
if core_ip not in subnet or node_ip not in subnet or core_ip == node_ip:
return None
self.fleet.listen(str(core_ip))
except (ValueError, KeyError, OSError):
return None
path = {"core": str(core_ip), "node": str(node_ip)}
if row.setdefault("network_paths", {}).get("netbird") != path:
row["network_paths"]["netbird"] = path
self.fleet.save(row)
return {"endpoint": "https://" + str(core_ip) + ":8782", "config": {
"server_id": "netbird", "server_url": operator["server_url"], "address": str(node_ip),
"subnet": str(subnet), "allowed_ips": [str(core_ip) + "/32"], "role": "node"}}
def view(self, node_id):
with self.lock:
@@ -252,7 +310,7 @@ class NetworkProfiles:
"node": copy.deepcopy(latest["value"]) if latest else None,
"operation": copy.deepcopy(self.operations.get(node_id))}
def wait(self, node_id, operation, phase, timeout=45):
def wait(self, node_id, operation, phase, timeout=45, *, endpoint=None):
end = time.monotonic() + timeout
with self.changed:
while time.monotonic() < end and not self.fleet.stop.is_set():
@@ -261,7 +319,10 @@ class NetworkProfiles:
if value.get("operation_id") == operation:
if value.get("phase") in ("failed", "rolled_back"):
raise ValueError(value.get("error") or "Борт вернул прежнее подключение.")
if value.get("phase") == phase:
# An in-flight inventory may contain the new phase while its
# authenticated transport still uses the previous endpoint.
if (value.get("phase") == phase
and (endpoint is None or latest["endpoint"] == endpoint)):
return copy.deepcopy(latest)
self.changed.wait(timeout=min(2, max(0, end - time.monotonic())))
raise ValueError("Борт не подтвердил применение подключения.")
@@ -271,13 +332,15 @@ class NetworkProfiles:
self.commands[node_id] = {**value, "expires_at": int(time.time()) + 110}
def start(self, vehicle_id, provider, profile_id, expected_revision):
if provider not in ("tailscale", "wireguard"):
if provider not in ("tailscale", "wireguard", "netbird"):
raise ValueError("Неизвестный способ подключения.")
with self.fleet.lock:
vehicle = copy.deepcopy(self.fleet.find(vehicle_id))
if vehicle["enrollment"] != "paired":
raise ValueError("Сначала привяжите бортовой компьютер.")
node_id = vehicle["node_id"]
if provider == "netbird":
profile_id = "netbird"
with self.lock:
if self.workers.get(node_id) and self.workers[node_id].is_alive():
raise ValueError("Дождитесь завершения текущего переключения.")
@@ -323,6 +386,18 @@ class NetworkProfiles:
paths[profile_id] = {"core": operator["address"], "node": peer["address"]}
self.fleet.save(latest)
self.command(node_id, {**command, "action": "apply", "config": config, "core_endpoint": endpoint})
elif provider == "netbird":
with self.lock:
snapshot = copy.deepcopy(self.latest[node_id]["value"])
with self.fleet.lock:
current = self.fleet.find(vehicle["id"])
if current["enrollment"] != "paired" or current["binding"]["binding_id"] != vehicle["binding"]["binding_id"]:
raise ValueError("Привязка БК изменилась.")
offer = self.netbird_offer(current, snapshot)
if offer is None:
raise ValueError("Подключите Core и борт к одному серверу NetBird в настройках частной сети.")
endpoint = offer["endpoint"]
self.command(node_id, {**command, "action": "apply", "config": offer["config"], "core_endpoint": endpoint})
else:
with self.lock:
snapshot = copy.deepcopy(self.latest[node_id]["value"])
@@ -333,11 +408,9 @@ class NetworkProfiles:
with self.fleet.lock:
self.fleet.listen(urlsplit(endpoint).hostname)
self.command(node_id, {**command, "action": "apply", "core_endpoint": endpoint})
applied = self.wait(node_id, op, "verifying", timeout=55)
if applied["endpoint"] != endpoint:
raise ValueError("Борт ответил через другое подключение.")
self.wait(node_id, op, "verifying", timeout=55, endpoint=endpoint)
self.command(node_id, {**command, "action": "commit"})
self.wait(node_id, op, "applied", timeout=30)
self.wait(node_id, op, "applied", timeout=30, endpoint=endpoint)
with self.lock:
self.operations[node_id]["state"] = "applied"
except Exception as error:
+32 -1
View File
@@ -9,6 +9,7 @@ from __future__ import annotations
import http.client
import ipaddress
import json
import socket
import ssl
import time
@@ -33,6 +34,11 @@ def node_addresses(row):
if selected and selected != "tailscale":
path = row.get("network_paths", {}).get(selected)
return [path["node"]] if path else []
return reported_tailnet_addresses(row)
def reported_tailnet_addresses(row):
"""Bounded tailnet addresses from this already authenticated Node inventory."""
addresses = set()
for network in (row.get("inventory") or {}).get("networks", [])[:64]:
if not isinstance(network, dict) or not network.get("up"):
@@ -43,6 +49,28 @@ def node_addresses(row):
return sorted(addresses)[:2]
def listener_addresses(row):
"""Keep saved channels available without selecting or migrating a provider.
UDP connect only asks the local routing table for its source address; no
datagram is sent. This restores the Tailscale return listener even when an
older saved record predates network_paths and currently selects another VPS.
The existing mTLS heartbeat still has to authenticate and confirm a switch.
"""
addresses = {row["core_address"]}
addresses.update(path["core"] for path in row.get("network_paths", {}).values())
for peer in reported_tailnet_addresses(row):
try:
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as route:
route.connect((peer, 8781))
local = route.getsockname()[0]
if tailnet_address(local):
addresses.add(local)
except OSError:
continue
return sorted(addresses)
def client_context(trust):
# Keep the pinned Core key, but distinguish the leaf from its issuer.
# Go rejects same-subject/same-SPKI certificates without SAN as a chain loop.
@@ -94,7 +122,10 @@ def recover(registry, row, address, context):
connection.connect()
verify_node_certificate(connection.sock.getpeercert(binary_form=True), row["node_id"])
local = connection.sock.getsockname()[0]
if not (tailnet_address(local) or any(path.get("core") == local and path.get("node") == address for path in row.get("network_paths", {}).values())):
if not (tailnet_address(local) or any(
path.get("core") == local and path.get("node") == address
for path in row.get("network_paths", {}).values()
)):
raise PairingError("Обратный адрес Core не относится к частному каналу.")
body = {"schema": SCHEMA, "binding_id": row["binding"]["binding_id"]}
value = request(connection, "/v1/channel/inspect", body)
+9 -4
View File
@@ -21,6 +21,7 @@ from missioncore_plugin_sdk.v0alpha2.identity import ExecutionBinding
from . import sensors
from .channel_binding import authenticate, endpoint_error
from .recovery import listener_addresses
from .sensor_transient import cache as sensor_transient
from .trust import SCHEMA, CoreTrust, PairingError, node_request, parse_invitation, pem, public_id
@@ -57,6 +58,8 @@ class FleetRegistry:
self.trust = CoreTrust(root)
from .network_profiles import NetworkProfiles
self.network_profiles = NetworkProfiles(self)
from .netbird.client import Client as NetBirdClient
self.netbird = NetBirdClient(root)
path = root / "fleet.sqlite3"
if path.is_symlink():
raise PairingError("Конфликт файла реестра.")
@@ -123,9 +126,10 @@ class FleetRegistry:
with self.lock:
for row in self.rows():
if row["enrollment"] in ("pending", "paired"):
# Address absent: keep the binding and show offline.
with suppress(OSError):
self.listen(row["core_address"])
# Address absent: preserve trust and retry saved listeners.
for address in listener_addresses(row):
with suppress(OSError):
self.listen(address)
for profile in self.network_profiles.profiles.values():
if profile.get("state") == "ready":
import ipaddress
@@ -147,6 +151,7 @@ class FleetRegistry:
def close(self):
self.stop.set()
self.netbird.close()
if self.vps_hosts is not None:
self.vps_hosts.close()
if self.worker:
@@ -423,7 +428,7 @@ class FleetRegistry:
with self.lock:
self.routers.prune()
active = [row for row in self.rows() if row["enrollment"] in ("pending", "paired")]
for address in {row["core_address"] for row in active}:
for address in {address for row in active for address in listener_addresses(row)}:
try:
self.listen(address)
server = self.listeners[address]
+2
View File
@@ -66,6 +66,8 @@ from .fleet_router_api import register as register_router_equipment
register_router_equipment(router, local_operator)
from .fleet_network_api import register as register_network_profiles
register_network_profiles(router, local_operator)
from .netbird_api import register as register_netbird
register_netbird(router, local_operator)
class BoardLayoutChange(BaseModel):
+31 -7
View File
@@ -1,18 +1,23 @@
"""Operator-only network profile actions, separate from compute contours."""
from typing import Annotated, Literal
from fastapi import Depends, HTTPException, Response
from pydantic import BaseModel, ConfigDict, Field
from k1link.fleet.registry import FleetRegistry
class ImportProfile(BaseModel):
model_config = ConfigDict(extra="forbid")
document: str = Field(min_length=1, max_length=16384)
name: str = Field(default="", max_length=80)
network_interface: str | None = Field(default=None, max_length=20)
class SelectProfile(BaseModel):
model_config = ConfigDict(extra="forbid")
provider: Literal["tailscale", "wireguard"]
provider: Literal["tailscale", "wireguard", "netbird"]
profile_id: str | None = Field(default=None, max_length=80)
expected_revision: int = Field(ge=0, lt=2**53, strict=True)
@@ -23,14 +28,27 @@ def register(router, local_operator):
return {"items": fleet.network_profiles.listing()}
@router.post("/network-profiles/import")
def import_profile(body: ImportProfile, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
def import_profile(
body: ImportProfile, fleet: Annotated[FleetRegistry, Depends(local_operator)]
):
try:
return fleet.network_profiles.import_file(body.document, body.name, body.network_interface)
return fleet.network_profiles.import_file(
body.document, body.name, body.network_interface
)
except (ValueError, OSError) as error:
raise HTTPException(409, str(error) if isinstance(error, ValueError) else "Не удалось подготовить подключение.") from None
raise HTTPException(
409,
str(error)
if isinstance(error, ValueError)
else "Не удалось подготовить подключение.",
) from None
@router.get("/{vehicle_id}/network-profile")
def view(vehicle_id: str, response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
def view(
vehicle_id: str,
response: Response,
fleet: Annotated[FleetRegistry, Depends(local_operator)],
):
response.headers["Cache-Control"] = "no-store"
with fleet.lock:
try:
@@ -40,8 +58,14 @@ def register(router, local_operator):
return fleet.network_profiles.view(node_id)
@router.put("/{vehicle_id}/network-profile")
def apply(vehicle_id: str, body: SelectProfile, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
def apply(
vehicle_id: str,
body: SelectProfile,
fleet: Annotated[FleetRegistry, Depends(local_operator)],
):
try:
return fleet.network_profiles.start(vehicle_id, body.provider, body.profile_id, body.expected_revision)
return fleet.network_profiles.start(
vehicle_id, body.provider, body.profile_id, body.expected_revision
)
except ValueError as error:
raise HTTPException(409, str(error)) from None
+2 -1
View File
@@ -14,11 +14,12 @@ from k1link.web.fleet_api import local_operator
router = APIRouter(prefix="/api/v1/fleet/installers", tags=["installers"])
Fleet = Annotated[FleetRegistry, Depends(local_operator)]
KINDS = {"node", "vps-arnavi", "vps-wireguard"}
KINDS = {"node", "vps-arnavi", "vps-wireguard", "vps-netbird"}
DOWNLOAD_NAMES = {
"node": "mission-core-node-install.pyz",
"vps-arnavi": "mission-core-vps-install.pyz",
"vps-wireguard": "mission-core-wireguard-vps.pyz",
"vps-netbird": "mission-core-netbird-vps.pyz",
}
+92
View File
@@ -0,0 +1,92 @@
"""Local operator admission to the official NetBird client and pinned downloads."""
from typing import Annotated
from fastapi import Depends, HTTPException, Response
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, ConfigDict, Field
from starlette.background import BackgroundTask
from k1link.fleet.netbird import assets
from k1link.fleet.registry import FleetRegistry
class Connect(BaseModel):
model_config = ConfigDict(extra="forbid")
server_url: str = Field(min_length=8, max_length=300)
def register(router, local_operator):
from .netbird_backup_api import register as register_backups
register_backups(router, local_operator)
@router.get("/netbird")
def status(response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
response.headers["Cache-Control"] = "no-store"
return fleet.netbird.status()
@router.get("/netbird/clients")
def clients(response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
response.headers["Cache-Control"] = "no-store"
return assets.catalog(fleet.root)
@router.get("/netbird/clients/{identifier}")
def download(identifier: str, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
try:
source = assets.open_verified(fleet.root, identifier)
stream, path = source.__enter__()
except (OSError, ValueError):
raise HTTPException(404, "Проверенный установщик недоступен.") from None
def chunks():
try:
while chunk := stream.read(262144):
yield chunk
finally:
source.__exit__(None, None, None)
return StreamingResponse(
chunks(),
media_type="application/octet-stream",
headers={
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
"Content-Length": str(assets.item(identifier)["bytes"]),
"Content-Disposition": f'attachment; filename="{path.name}"',
},
background=BackgroundTask(source.__exit__, None, None, None),
)
@router.post("/netbird/connect")
def connect(
body: Connect, response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)]
):
response.headers["Cache-Control"] = "no-store"
try:
return fleet.netbird.connect(body.server_url)
except (OSError, ValueError) as error:
raise HTTPException(
409, str(error) if isinstance(error, ValueError) else "Клиент NetBird недоступен."
) from None
@router.post("/netbird/install")
def install(response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
response.headers["Cache-Control"] = "no-store"
try:
return fleet.netbird.install()
except (OSError, ValueError) as error:
raise HTTPException(
409,
str(error)
if isinstance(error, ValueError)
else "Проверенный установщик недоступен.",
) from None
@router.post("/netbird/cancel")
def cancel(response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
response.headers["Cache-Control"] = "no-store"
try:
return fleet.netbird.cancel()
except ValueError as error:
raise HTTPException(409, str(error)) from None
+64
View File
@@ -0,0 +1,64 @@
"""Local-operator-only backup import/export; never return archive credentials as JSON."""
import asyncio
import os
import tempfile
import zipfile
from pathlib import Path
from typing import Annotated
from fastapi import Depends, HTTPException, Request, Response
from fastapi.responses import FileResponse
from k1link.fleet.netbird import backups
from k1link.fleet.registry import FleetRegistry
def register(router, local_operator):
@router.get("/netbird/backups")
def catalog(response: Response, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
response.headers["Cache-Control"] = "no-store"
return backups.catalog(fleet.root)
@router.post("/netbird/backups")
async def upload(
request: Request,
response: Response,
fleet: Annotated[FleetRegistry, Depends(local_operator)],
):
response.headers["Cache-Control"] = "no-store"
fd, name = tempfile.mkstemp(prefix=".upload-", dir=backups.directory(fleet.root))
path = Path(name)
try:
size = 0
with os.fdopen(fd, "wb") as output:
async for chunk in request.stream():
size += len(chunk)
if size > backups.MAX_BYTES:
raise HTTPException(413, "Резервная копия превышает 256 МиБ.")
output.write(chunk)
output.flush()
os.fsync(output.fileno())
try:
return await asyncio.to_thread(backups.admit, fleet.root, path)
except (OSError, ValueError, KeyError, TypeError, zipfile.BadZipFile):
raise HTTPException(
409,
"Не удалось проверить и сохранить полную копию NetBird. "
"Исходный файл и прежние копии сохранены.",
) from None
finally:
path.unlink(missing_ok=True)
@router.get("/netbird/backups/{identifier}/download")
def download(identifier: str, fleet: Annotated[FleetRegistry, Depends(local_operator)]):
try:
path = backups.download(fleet.root, identifier)
except (OSError, ValueError, KeyError, TypeError, zipfile.BadZipFile):
raise HTTPException(404, "Проверенная резервная копия недоступна.") from None
return FileResponse(
path,
filename="mission-core-netbird-backup.zip",
media_type="application/zip",
headers={"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"},
)