feat(network): integrate NetBird clients, profiles and private backups
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
import {Fragment,useEffect,useState} from 'react';
|
||||
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
|
||||
|
||||
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
|
||||
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'|'vps-wireguard'|'vps-netbird'}){
|
||||
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
|
||||
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
|
||||
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import {useRef} from 'react';
|
||||
import {Button,Description,Icon,SettingsCard,StatusBadge} from '@nodedc/ui-react';
|
||||
import {useNetBirdBackups} from '../../core/fleet/useNetBirdBackups';
|
||||
export function NetBirdBackups(){
|
||||
const {items,loading,busy,error,upload}=useNetBirdBackups();const input=useRef<HTMLInputElement>(null);
|
||||
return <SettingsCard title="Резервные копии сети" description="Полная копия базы NetBird, ключей и зарегистрированных устройств хранится в этом Mission Core отдельно от VPS. Она содержит секреты сети." actions={<StatusBadge tone={items.length?'success':'warning'}>{loading?'Проверяем хранилище':items.length?`Сохранено: ${items.length}`:'Копий пока нет'}</StatusBadge>}>
|
||||
<Description>После изменения устройств или настроек сети сохраните свежую копию. Автоматическое получение копий пока не настроено.</Description>
|
||||
<input ref={input} type="file" accept=".zip,application/zip" hidden aria-label="Полная резервная копия NetBird" disabled={busy} onChange={event=>{const file=event.target.files?.[0];event.target.value='';if(file)void upload(file);}}/>
|
||||
<Button icon={<Icon name="upload"/>} loading={busy} disabled={busy||loading} onClick={()=>input.current?.click()}>Сохранить копию в Mission Core</Button>
|
||||
{error&&<StatusBadge tone="danger">{error}</StatusBadge>}
|
||||
{items.map(item=><SettingsCard key={item.id} title={item.domain} description={`Сохранена ${new Date(item.stored_at).toLocaleString('ru-RU')} · ${(item.bytes/1024/1024).toFixed(1)} МиБ · Контрольные суммы проверены`}>
|
||||
<Button icon={<Icon name="download"/>} onClick={()=>{const link=document.createElement('a');link.href=`/api/v1/fleet/netbird/backups/${item.id}/download`;link.download='mission-core-netbird-backup.zip';link.click();}}>Скачать для восстановления</Button>
|
||||
</SettingsCard>)}
|
||||
</SettingsCard>;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import {useEffect,useState} from 'react';
|
||||
import {Button,Description,Icon,Select,SettingsCard,StatusBadge,TextField} from '@nodedc/ui-react';
|
||||
import {InstallerCard} from './InstallerCard';
|
||||
import {NetBirdBackups} from './NetBirdBackups';
|
||||
import {useNetBird,type NetBirdState} from '../../core/fleet/useNetBird';
|
||||
|
||||
const labels:Record<NetBirdState,string>={missing_client:'Клиент не установлен',unsupported_client:'Требуется другая версия клиента',unavailable:'Клиент недоступен',disconnected:'Не подключён',connecting:'Подключение',connected:'Подключён',other_network:'Клиент подключён к другой сети',address_conflict:'Проверьте адресацию сервера'};
|
||||
export function NetBirdConnection(){
|
||||
const network=useNetBird();const {status,clients,error,busy,clientError}=network;
|
||||
const [server,setServer]=useState(''),[edited,setEdited]=useState(false),[installer,setInstaller]=useState('macos');
|
||||
useEffect(()=>{if(!edited&&status?.server_url)setServer(status.server_url);},[status?.server_url,edited]);
|
||||
const selected=clients.find(item=>item.id===installer);
|
||||
const state=status?.pending==='installing'?'Устанавливаем клиент':status?.pending==='cancelling'?'Отменяем подключение':status?.pending==='authentication'?'Требуется вход':status?.pending==='verifying'?'Проверяем соединение':status?.pending?'Подключаемся':status?labels[status.state]:'Получаем состояние';
|
||||
return <>
|
||||
<InstallerCard kind="vps-netbird"/>
|
||||
<NetBirdBackups/>
|
||||
<SettingsCard title="Этот компьютер" description="NetBird соединяет компьютеры через ваш сервер. Вход выполняется в браузере; подключение поддерживает системный клиент." actions={<StatusBadge tone={busy?'warning':status?.state==='connected'?'success':'neutral'}>{state}</StatusBadge>}>
|
||||
<TextField label="Адрес сервера NetBird" placeholder="https://netbird.example.com" value={server} maxLength={300} disabled={busy} onChange={event=>{setEdited(true);setServer(event.target.value);}} hint="Адрес выдаёт установщик VPS или администратор вашей сети."/>
|
||||
{status?.state==='connected'&&<Description>Адрес этого компьютера: {status.address}</Description>}
|
||||
{status?.can_install&&['missing_client','unsupported_client'].includes(status.state)&&<Button disabled={busy||!clients.find(item=>item.id==='macos')?.available} onClick={()=>void network.action('install')}>Установить клиент на этот Mac</Button>}
|
||||
<Button variant="primary" disabled={busy||!server.trim()||!status||['missing_client','unsupported_client','unavailable','other_network'].includes(status.state)} onClick={()=>void network.action('connect',server)}>{status?.state==='connected'?'Проверить подключение':'Подключить этот компьютер'}</Button>
|
||||
{status?.pending&&status.pending!=='installing'&&<Button disabled={network.requestBusy||status.pending==='cancelling'} onClick={()=>void network.action('cancel')}>Прекратить ожидание</Button>}
|
||||
{status?.auth_url&&<Button onClick={()=>window.open(status.auth_url,'_blank','noopener,noreferrer')}>Войти на сервере</Button>}
|
||||
{status?.pending==='installing'&&<Description>Подтвердите системный запрос macOS. Пароль администратора вводится только в системном окне.</Description>}
|
||||
{(error||status?.error)&&<StatusBadge tone="danger">{error||status?.error}</StatusBadge>}
|
||||
</SettingsCard>
|
||||
<SettingsCard title="Клиенты для других компьютеров" description={`Официальные установщики NetBird${status?.client_version?' '+status.client_version:''}. Файлы хранятся в этом Mission Core и проверяются перед скачиванием.`}>
|
||||
{clientError&&<StatusBadge tone="danger">{clientError}</StatusBadge>}
|
||||
<Select label="Операционная система" value={installer} options={clients.map(item=>({value:item.id,label:item.label}))} onChange={setInstaller}/>
|
||||
<Button icon={<Icon name="download"/>} disabled={!selected?.available} onClick={()=>{if(selected){const link=document.createElement('a');link.href=selected.download_url;link.download=selected.filename;link.click();}}}>Скачать клиент</Button>
|
||||
<Description>Установите клиент, укажите этот же адрес сервера в его настройках и выполните вход. Mission Core на другом компьютере для подключения к сети не требуется.</Description>
|
||||
{installer.startsWith('linux')&&<Description>Пакет «интерфейс» устанавливается вместе с основным клиентом той же версии. Для устройства без экрана используйте ключ подключения из панели NetBird.</Description>}
|
||||
{selected&&!selected.available&&<Description>Этот установщик пока отсутствует в локальном каталоге.</Description>}
|
||||
</SettingsCard>
|
||||
</>;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import {Button,Window,WindowFooterActions} from '@nodedc/ui-react';
|
||||
import {NetBirdConnection} from './NetBirdConnection';
|
||||
|
||||
export function OperatorNetworkWindow({onClose}:{onClose:()=>void}){
|
||||
return <Window open title="Сеть операторского компьютера" subtitle="NetBird · WireGuard" size="lg" onClose={onClose}
|
||||
footer={<WindowFooterActions><Button variant="secondary" onClick={onClose}>Закрыть</Button></WindowFooterActions>}>
|
||||
<NetBirdConnection/>
|
||||
</Window>;
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {fleetRequest} from './useFleet';
|
||||
export type NetworkProvider='tailscale'|'wireguard';
|
||||
export type NetworkProvider='tailscale'|'wireguard'|'netbird';
|
||||
export interface SharedNetworkProfile {id:string;name:string;endpoint:string;state:string;boards:number}
|
||||
export interface BoardNetworkView {
|
||||
profiles:SharedNetworkProfile[];available:boolean;
|
||||
node:{provider:NetworkProvider;server_id?:string;revision:number;phase:string;error?:string;tailscale_endpoint?:string}|null;
|
||||
node:{provider:NetworkProvider;server_id?:string;revision:number;phase:string;error?:string;tailscale_endpoint?:string;netbird_endpoint?:string;netbird?:{state:string;address:string;server_url:string}}|null;
|
||||
operation:{id:string;state:string;error?:string}|null;
|
||||
}
|
||||
export function useBoardNetwork(vehicleId:string){
|
||||
@@ -31,5 +31,5 @@ export function useBoardNetwork(vehicleId:string){
|
||||
await fleetRequest(`/${encodeURIComponent(vehicleId)}/network-profile`,'PUT',{provider,profile_id:provider==='wireguard'?profileId:null,expected_revision:value.node.revision});await refresh();
|
||||
}catch(e){setError(e instanceof Error?e.message:'Подключение не применено.');}finally{setBusy(false);}};
|
||||
return {value,provider,setProvider,profileId,setProfileId,error,busy,applying,dirty,importing,save,
|
||||
canSave:Boolean(value?.available&&dirty&&!busy&&!applying&&(provider==='tailscale'?value.node?.tailscale_endpoint:profileId))};
|
||||
canSave:Boolean(value?.available&&dirty&&!busy&&!applying&&(provider==='tailscale'?value.node?.tailscale_endpoint:provider==='netbird'?value.node?.netbird_endpoint:profileId))};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {fleetRequest} from './useFleet';
|
||||
|
||||
export type NetBirdState='missing_client'|'unsupported_client'|'unavailable'|'disconnected'|'connecting'|'connected'|'other_network'|'address_conflict';
|
||||
export interface NetBirdStatus {state:NetBirdState;server_url:string;address:string;client_version:string;pending:string;auth_url:string;error:string;can_install:boolean}
|
||||
export interface NetBirdInstaller {id:string;label:string;filename:string;available:boolean;download_url:string;bytes:number}
|
||||
export function useNetBird(){
|
||||
const [status,setStatus]=useState<NetBirdStatus|null>(null),[clients,setClients]=useState<NetBirdInstaller[]>([]);
|
||||
const [statusError,setStatusError]=useState(''),[actionError,setActionError]=useState(''),[clientError,setClientError]=useState('');
|
||||
const [requestBusy,setRequestBusy]=useState(false);
|
||||
const operation=useRef(false),generation=useRef(0),mounted=useRef(false);
|
||||
useEffect(()=>{
|
||||
mounted.current=true;let active=true;let timer:ReturnType<typeof setTimeout>;const controller=new AbortController();
|
||||
const poll=async()=>{
|
||||
const epoch=generation.current;
|
||||
try{
|
||||
const value=await fleetRequest<NetBirdStatus>('/netbird','GET',undefined,20000,controller.signal);
|
||||
if(active&&epoch===generation.current&&!operation.current){setStatus(value);setStatusError('');}
|
||||
}catch{
|
||||
if(active&&epoch===generation.current&&!operation.current){setStatusError('Состояние клиента недоступно.');setStatus(null);}
|
||||
}finally{if(active)timer=setTimeout(poll,3000);}
|
||||
};
|
||||
void poll();
|
||||
void fleetRequest<{items:NetBirdInstaller[]}>('/netbird/clients','GET',undefined,30000,controller.signal)
|
||||
.then(value=>{if(active){setClients(value.items);setClientError('');}})
|
||||
.catch(()=>{if(active)setClientError('Установщики недоступны. Повторите открытие настроек.');});
|
||||
return()=>{active=false;mounted.current=false;controller.abort();clearTimeout(timer);};
|
||||
},[]);
|
||||
const action=useCallback(async(kind:'connect'|'install'|'cancel',server_url?:string)=>{
|
||||
if(operation.current)return;
|
||||
operation.current=true;generation.current+=1;setRequestBusy(true);setActionError('');
|
||||
try{
|
||||
const next=await fleetRequest<NetBirdStatus>(`/netbird/${kind}`,'POST',kind==='connect'?{server_url}:undefined,30000);
|
||||
if(mounted.current){setStatus(next);setStatusError('');}
|
||||
}catch(e){if(mounted.current)setActionError(e instanceof Error?e.message:'Операция не завершена.');}
|
||||
finally{operation.current=false;generation.current+=1;if(mounted.current)setRequestBusy(false);}
|
||||
},[]);
|
||||
return {status,clients,clientError,error:actionError||statusError,
|
||||
requestBusy,busy:requestBusy||Boolean(status?.pending),action};
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import {useCallback,useEffect,useRef,useState} from 'react';
|
||||
import {fleetRequest} from './useFleet';
|
||||
export interface NetworkBackup {id:string;domain:string;server_url:string;bytes:number;stored_at:string;verification:'checksums_verified'}
|
||||
export function useNetBirdBackups(){
|
||||
const [items,setItems]=useState<NetworkBackup[]>([]),[loading,setLoading]=useState(true),[busy,setBusy]=useState(false),[error,setError]=useState('');
|
||||
const mounted=useRef(false),operation=useRef(false);
|
||||
const refresh=useCallback(async()=>{const result=await fleetRequest<{items:NetworkBackup[]}>('/netbird/backups');if(mounted.current)setItems(result.items);},[]);
|
||||
useEffect(()=>{mounted.current=true;void refresh().catch(()=>{if(mounted.current)setError('Не удалось прочитать резервные копии.');}).finally(()=>{if(mounted.current)setLoading(false);});return()=>{mounted.current=false;};},[refresh]);
|
||||
const upload=useCallback(async(file:File)=>{
|
||||
if(operation.current)return;
|
||||
operation.current=true;setBusy(true);setError('');
|
||||
try{
|
||||
if(file.size>256*1024*1024)throw Error('Резервная копия превышает 256 МиБ.');
|
||||
const response=await fetch('/api/v1/fleet/netbird/backups',{method:'POST',body:file,headers:{'Content-Type':'application/zip'},signal:AbortSignal.timeout(120000)});
|
||||
if(!response.ok){let detail='Не удалось сохранить копию.';try{const data=await response.json() as {detail?:string};detail=data.detail||detail;}catch{/* retain public error */}throw Error(detail);}
|
||||
await refresh();
|
||||
}catch(e){if(mounted.current)setError(e instanceof Error?e.message:'Не удалось сохранить копию.');}
|
||||
finally{operation.current=false;if(mounted.current)setBusy(false);}
|
||||
},[refresh]);
|
||||
return {items,loading,busy,error,upload};
|
||||
}
|
||||
@@ -8,11 +8,11 @@ export function BoardNetworkSettings({network}:{network:ReturnType<typeof useBoa
|
||||
const current=value?.node;
|
||||
const selected=value?.profiles.find(p=>p.id===profileId);
|
||||
const progress=value?.operation?.state;
|
||||
const label=progress==='rolling_back'?'Восстанавливаем прежнее подключение':progress==='applying'?'Проверяем связь с бортом':!value?.available?'Нет свежего подтверждения борта':current?.provider==='wireguard'?'WireGuard подключён':'Tailscale подключён';
|
||||
const label=progress==='rolling_back'?'Восстанавливаем прежнее подключение':progress==='applying'?'Проверяем связь с бортом':!value?.available?'Нет свежего подтверждения борта':current?.provider==='netbird'?'NetBird подключён':current?.provider==='wireguard'?'WireGuard подключён':'Tailscale подключён';
|
||||
return <div className="fleet-form">
|
||||
<SettingsCard title="Связь с Core" description="Профиль связи этого бортового компьютера с Mission Core. Вычислительный Worker сохраняет своё подключение." actions={<StatusBadge tone={applying?'warning':value?.available?'success':'neutral'}>{label}</StatusBadge>}>
|
||||
<Select label="Способ подключения" value={provider} options={[{value:'tailscale',label:'Tailscale'},{value:'wireguard',label:'WireGuard · VPS'}]} onChange={v=>network.setProvider(v as NetworkProvider)} disabled={busy||applying}/>
|
||||
{provider==='tailscale'?<p>{current?.tailscale_endpoint?`Сохранённое подключение: ${current.tailscale_endpoint}`:current?'Подключите Tailscale в приложении Node.':'Параметры появятся после получения настроек БК.'}</p>:<>
|
||||
<Select label="Способ подключения" value={provider} options={[{value:'tailscale',label:'Tailscale'},{value:'netbird',label:'NetBird · WireGuard'},{value:'wireguard',label:'WireGuard · VPS'}]} onChange={v=>network.setProvider(v as NetworkProvider)} disabled={busy||applying}/>
|
||||
{provider==='tailscale'?<p>{current?.tailscale_endpoint?`Сохранённое подключение: ${current.tailscale_endpoint}`:current?'Подключите Tailscale в приложении Node.':'Параметры появятся после получения настроек БК.'}</p>:provider==='netbird'?<p>{current?.netbird_endpoint?`Борт подключён к ${current.netbird?.server_url}. Новый канал будет проверен перед сохранением.`:'Подключите Core и борт к одному серверу NetBird. На борту: Система → Частная сеть.'}</p>:<>
|
||||
<Select label="Общий профиль VPS" value={profileId} options={[{value:'',label:'Выберите профиль'},...(value?.profiles??[]).filter(p=>p.state==='ready').map(p=>({value:p.id,label:p.name,description:`Подключено бортов: ${p.boards} · ${p.endpoint}`}))]} onChange={network.setProfileId} disabled={busy||applying}/>
|
||||
{selected&&<StatusBadge tone={selected.state==='ready'?'success':'warning'}>{selected.state==='ready'?`VPS подключён · Подключено бортов: ${selected.boards}`:'Подключение VPS не завершено'}</StatusBadge>}
|
||||
<p>Один профиль используется всем парком. У каждого борта будет отдельное защищённое подключение.</p>
|
||||
|
||||
@@ -7,6 +7,7 @@ import {BoardMonitorView} from './BoardMonitorView';
|
||||
import {BoardComputerSettings} from './BoardComputer';
|
||||
import {NodeInvitationForm,platformLabel} from './NodeInvitationForm';
|
||||
import {VehicleFleetRow} from './VehicleFleetRow';
|
||||
import {OperatorNetworkWindow} from '../../components/network/OperatorNetworkWindow';
|
||||
import './fleet.css';
|
||||
|
||||
export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerToolsHost?:HTMLElement|null;headerTitleHost?:HTMLElement|null}){
|
||||
@@ -15,6 +16,7 @@ export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerTools
|
||||
const [expanded,setExpanded]=useState<string[]>([]);
|
||||
const [adding,setAdding]=useState<Vehicle|null|undefined>();
|
||||
const [boardSettings,setBoardSettings]=useState<string|null>(null);
|
||||
const [operatorNetwork,setOperatorNetwork]=useState(false);
|
||||
const [revoking,setRevoking]=useState<Vehicle|null>(null),[error,setError]=useState('');
|
||||
const detail=fleet.items?.find(item=>item.id===view?.vehicleID);
|
||||
const settingsVehicle=fleet.items?.find(item=>item.id===boardSettings);
|
||||
@@ -22,7 +24,7 @@ export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerTools
|
||||
const refresh=()=>{void fleet.refresh().catch(()=>setError('Не удалось обновить аппарат. Повторите получение сведений.'));};
|
||||
const showEquipment=(id:string)=>{setExpanded(current=>current.includes(id)?current:[...current,id]);setView(null);};
|
||||
const complete=(item:Vehicle)=>{setAdding(undefined);showEquipment(item.id);refresh();};
|
||||
const addButton=<IconButton label="Добавить аппарат" onClick={()=>setAdding(null)}><Icon name="plus"/></IconButton>;
|
||||
const addButton=<><IconButton label="Сеть операторского компьютера" onClick={()=>setOperatorNetwork(true)}><Icon name="network"/></IconButton><IconButton label="Добавить аппарат" onClick={()=>setAdding(null)}><Icon name="plus"/></IconButton></>;
|
||||
const headerAdd=!detail&&(headerToolsHost?createPortal(addButton,headerToolsHost):addButton);
|
||||
const titleSuffix=detail?` — ${detail.name} / ${platformLabel(detail.platform)}`:'';
|
||||
const content=detail&&view?.mode==='observation'?<BoardObservationCenter key={detail.id} vehicleID={detail.id} name={detail.name} enabled={enabled(detail)} paired={detail.enrollment==='paired'} back={()=>setView(null)} configure={()=>showEquipment(detail.id)} headerToolsHost={headerToolsHost}/>
|
||||
@@ -31,6 +33,7 @@ export function VehiclesWorkspace({headerToolsHost,headerTitleHost}:{headerTools
|
||||
{!fleet.items?<LoadingRegion loading={!fleet.error} label="Получение аппаратов"/>:fleet.items.length===0?<SettingsCard title="Аппаратов пока нет" description="Создайте аппарат и подключите его бортовой компьютер по приглашению Mission Core Node."/>:<ResourceList aria-label="Аппараты">{fleet.items.map(item=><VehicleFleetRow key={item.id} vehicle={item} available={!fleet.error} expanded={expanded.includes(item.id)} onToggle={()=>setExpanded(current=>current.includes(item.id)?current.filter(id=>id!==item.id):[...current,item.id])} onObserve={()=>setView({vehicleID:item.id,mode:'observation'})} onAddComputer={()=>setAdding(item)} onBoardSettings={()=>setBoardSettings(item.id)} onMonitor={()=>setView({vehicleID:item.id,mode:'monitor'})} onUpdated={fleet.acceptVehicle}/>)}</ResourceList>}
|
||||
</div>;
|
||||
return <>{headerTitleHost&&createPortal(titleSuffix,headerTitleHost)}{headerAdd}{content}
|
||||
{operatorNetwork&&<OperatorNetworkWindow onClose={()=>setOperatorNetwork(false)}/>}
|
||||
{adding!==undefined&&<NodeInvitationForm key={adding?.id??'new'} vehicle={adding??undefined} onClose={()=>setAdding(undefined)} onComplete={complete} renderWindow={({content,actions,busy})=><Window open title={adding?'Подключить бортовой компьютер':'Добавить аппарат'} subtitle={adding?adding.name:'Создать аппарат и подключить БК по приглашению Node'} size="md" closeOnBackdrop={false} closeOnEscape={!busy} onClose={()=>{if(!busy)setAdding(undefined);}} footer={<WindowFooterActions>{actions}</WindowFooterActions>}>{content}</Window>}/>}
|
||||
{settingsVehicle&&<BoardComputerSettings vehicle={settingsVehicle} enabled={enabled(settingsVehicle)} onClose={()=>setBoardSettings(null)} onRevoke={()=>{setBoardSettings(null);setRevoking(settingsVehicle);}}/>}
|
||||
<ConfirmationModal open={revoking!==null} title="Отозвать привязку БК?" description={`Аппарат «${revoking?.name??''}» останется в реестре. БК потеряет доступ к Core и получит отзыв при следующем соединении.`} confirmLabel="Отозвать" cancelLabel="Отмена" danger onClose={()=>setRevoking(null)} onConfirm={async()=>{if(!revoking)return;try{await fleetRequest(`/${encodeURIComponent(revoking.id)}`,'DELETE');await fleet.refresh();setRevoking(null);}catch(e){setError(e instanceof Error?e.message:'Не удалось отозвать привязку.');throw e;}}}/>
|
||||
|
||||
@@ -1,11 +1 @@
|
||||
import {Fragment,useEffect,useState} from 'react';
|
||||
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
|
||||
|
||||
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
|
||||
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'|'vps-wireguard'}){
|
||||
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
|
||||
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
|
||||
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
|
||||
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
|
||||
</SettingsCard>;
|
||||
}
|
||||
export {InstallerCard} from '../../../components/network/InstallerCard';
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {build} from 'esbuild';
|
||||
const bundle=await build({entryPoints:[new URL('../src/core/fleet/useNetBird.ts',import.meta.url).pathname],bundle:true,write:false,platform:'node',format:'esm',plugins:[{name:'fixture',setup(b){
|
||||
b.onResolve({filter:/^(react|\.\/useFleet)$/},a=>({path:a.path,namespace:'fixture'}));
|
||||
b.onLoad({filter:/.*/,namespace:'fixture'},a=>({contents:a.path==='react'?
|
||||
'export const useState=v=>globalThis.netBirdUI.state(v),useRef=v=>globalThis.netBirdUI.ref(v),useEffect=(f,d)=>globalThis.netBirdUI.effect(f,d),useCallback=f=>f;':
|
||||
'export const fleetRequest=(...args)=>globalThis.netBirdUI.request(...args);'}));
|
||||
}}]});
|
||||
const {useNetBird}=await import('data:text/javascript;base64,'+Buffer.from(bundle.outputFiles[0].contents).toString('base64'));
|
||||
const status=(pending='',state='disconnected')=>({pending,state,server_url:'https://network.example',error:'',auth_url:'',client_version:'0.82.0'});
|
||||
function deferred(){let resolve,reject;const promise=new Promise((a,b)=>{resolve=a;reject=b;});return{promise,resolve,reject};}
|
||||
async function fixture(run){
|
||||
const old={setTimeout:globalThis.setTimeout,clearTimeout:globalThis.clearTimeout,netBirdUI:globalThis.netBirdUI};
|
||||
const values=[],effects=[],tasks=[],timers=new Map(),requests=[];let cursor=0,dirty=true,id=0,closed=false;
|
||||
const h={requests,timers,view:null,
|
||||
state(v){const i=cursor++;if(!(i in values))values[i]=v;return[values[i],next=>{values[i]=typeof next==='function'?next(values[i]):next;dirty=true;}];},
|
||||
ref(v){return values[cursor++]??={current:v};},
|
||||
effect(f,d){const i=cursor++;if(!effects[i]){effects[i]={};tasks.push(()=>{effects[i].cleanup=f();});}},
|
||||
request(...args){const response=deferred();requests.push({args,...response});return response.promise;},
|
||||
async settle(){for(let n=0;n<20;n++){await Promise.resolve();if(dirty&&!closed){dirty=false;cursor=0;h.view=useNetBird();tasks.splice(0).forEach(f=>f());}}},
|
||||
async tick(){for(const [id,fn] of [...timers]){timers.delete(id);fn();}await h.settle();},
|
||||
close(){closed=true;effects.forEach(e=>e?.cleanup?.());},
|
||||
};
|
||||
globalThis.netBirdUI=h;globalThis.setTimeout=f=>{timers.set(++id,f);return id;};globalThis.clearTimeout=id=>timers.delete(id);
|
||||
try{await h.settle();await run(h);}finally{h.close();Object.assign(globalThis,old);}
|
||||
}
|
||||
|
||||
test('a late poll cannot overwrite accepted connection and double click submits once',()=>fixture(async h=>{
|
||||
const poll=h.requests[0];h.requests[1].resolve({items:[]});
|
||||
const first=h.view.action('connect','https://network.example');
|
||||
const second=h.view.action('connect','https://network.example');
|
||||
assert.equal(h.requests.filter(x=>x.args[1]==='POST').length,1);
|
||||
h.requests[2].resolve(status('authentication'));await first;await second;
|
||||
poll.resolve(status());await h.settle();
|
||||
assert.equal(h.view.status.pending,'authentication');assert.equal(h.view.busy,true);
|
||||
}));
|
||||
|
||||
test('successful status polling does not erase action or installer failures',()=>fixture(async h=>{
|
||||
h.requests[0].resolve(status());h.requests[1].reject(Error('download unavailable'));await h.settle();
|
||||
const action=h.view.action('connect','https://network.example');
|
||||
h.requests[2].reject(Error('Server unavailable'));await action;await h.settle();
|
||||
await h.tick();h.requests[3].resolve(status());await h.settle();
|
||||
assert.equal(h.view.error,'Server unavailable');assert.match(h.view.clientError,/Установщики недоступны/);
|
||||
}));
|
||||
|
||||
test('cancel stays available while waiting for browser authentication',()=>fixture(async h=>{
|
||||
h.requests[0].resolve(status('authentication'));h.requests[1].resolve({items:[]});await h.settle();
|
||||
assert.equal(h.view.busy,true);assert.equal(h.view.requestBusy,false);
|
||||
const cancel=h.view.action('cancel');assert.equal(h.requests[2].args[0],'/netbird/cancel');
|
||||
h.requests[2].resolve(status());await cancel;await h.settle();assert.equal(h.view.busy,false);
|
||||
}));
|
||||
|
||||
test('closing the window cancels polling without cancelling the system connection',()=>fixture(async h=>{
|
||||
h.close();h.requests[0].resolve(status('connecting'));h.requests[1].resolve({items:[]});await h.settle();
|
||||
assert.equal(h.timers.size,0);assert.equal(h.requests.length,2);
|
||||
assert.equal(h.requests[0].args[4].aborted,true);
|
||||
}));
|
||||
@@ -0,0 +1,161 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type NetBirdStatus struct {
|
||||
State string `json:"state"`
|
||||
Address string `json:"address"`
|
||||
ServerURL string `json:"server_url"`
|
||||
Network string `json:"network"`
|
||||
}
|
||||
|
||||
var netbirdObservation struct {
|
||||
sync.RWMutex
|
||||
value NetBirdStatus
|
||||
at time.Time
|
||||
}
|
||||
|
||||
func netbirdSnapshot() NetBirdStatus {
|
||||
netbirdObservation.RLock()
|
||||
defer netbirdObservation.RUnlock()
|
||||
if time.Since(netbirdObservation.at) > 20*time.Second {
|
||||
return NetBirdStatus{State: "unavailable"}
|
||||
}
|
||||
return netbirdObservation.value
|
||||
}
|
||||
func netbirdCall(action string, fields map[string]string) (json.RawMessage, error) {
|
||||
connection, err := net.DialTimeout("unix", "/run/mission-core-netbird/control.sock", time.Second)
|
||||
if err != nil {
|
||||
return nil, errors.New("Служба NetBird недоступна. Обновите и подготовьте окружение БК.")
|
||||
}
|
||||
defer connection.Close()
|
||||
_ = connection.SetDeadline(time.Now().Add(10 * time.Second))
|
||||
body := map[string]string{"action": action}
|
||||
for k, v := range fields {
|
||||
body[k] = v
|
||||
}
|
||||
if err = json.NewEncoder(connection).Encode(body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw, err := bufio.NewReaderSize(connection, 16385).ReadSlice('\n')
|
||||
var result struct {
|
||||
OK bool `json:"ok"`
|
||||
Result json.RawMessage `json:"result"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if err != nil || len(raw) > 16384 || json.Unmarshal(raw, &result) != nil {
|
||||
return nil, errors.New("Нет подтверждения NetBird.")
|
||||
}
|
||||
if !result.OK {
|
||||
return nil, errors.New(result.Error)
|
||||
}
|
||||
if action == "status" {
|
||||
var status NetBirdStatus
|
||||
if json.Unmarshal(result.Result, &status) == nil {
|
||||
netbirdObservation.Lock()
|
||||
netbirdObservation.value = status
|
||||
netbirdObservation.at = time.Now()
|
||||
netbirdObservation.Unlock()
|
||||
}
|
||||
}
|
||||
return result.Result, nil
|
||||
}
|
||||
func monitorNetBird(ctx context.Context) {
|
||||
timer := time.NewTicker(5 * time.Second)
|
||||
defer timer.Stop()
|
||||
for {
|
||||
_, _ = netbirdCall("status", nil)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
func (s *Server) netbirdRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("GET /api/network/netbird", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
out, err := netbirdCall("status", nil)
|
||||
if err != nil {
|
||||
reply(w, 200, map[string]string{"state": "unavailable", "error": err.Error()})
|
||||
return
|
||||
}
|
||||
reply(w, 200, out)
|
||||
})
|
||||
for _, action := range []string{"connect", "cancel"} {
|
||||
mux.HandleFunc("POST /api/network/netbird/"+action, func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
ServerURL string `json:"server_url"`
|
||||
SetupKey string `json:"setup_key"`
|
||||
}
|
||||
if !decode(w, r, &body) {
|
||||
return
|
||||
}
|
||||
fields := map[string]string{}
|
||||
if action == "connect" {
|
||||
fields["server_url"] = body.ServerURL
|
||||
fields["setup_key"] = body.SetupKey
|
||||
}
|
||||
out, err := netbirdCall(action, fields)
|
||||
if err != nil {
|
||||
reply(w, 409, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
reply(w, 200, out)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Offers arrive only in an authenticated response from this board's bound Core.
|
||||
func (p *Pairing) acceptNetBirdOffer(raw json.RawMessage) {
|
||||
var offer struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
Config json.RawMessage `json:"config"`
|
||||
}
|
||||
if len(raw) > 4096 || json.Unmarshal(raw, &offer) != nil || !privateEndpoint(offer.Endpoint, CorePort) {
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.loadNetworkLocked() != nil || p.state.Binding == nil {
|
||||
return
|
||||
}
|
||||
if p.network.NetBirdEndpoint == offer.Endpoint && string(p.network.NetBirdConfig) == string(offer.Config) {
|
||||
return
|
||||
}
|
||||
p.network.NetBirdEndpoint = offer.Endpoint
|
||||
p.network.NetBirdConfig = offer.Config
|
||||
_ = p.saveNetworkLocked()
|
||||
}
|
||||
|
||||
func (p *Pairing) acceptNetworkRequestResult(raw json.RawMessage) {
|
||||
var result struct {
|
||||
ID string `json:"id"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if len(raw) > 4096 || json.Unmarshal(raw, &result) != nil {
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if p.network == nil || p.network.LocalRequest == nil || p.network.LocalRequest.ID != result.ID {
|
||||
return
|
||||
}
|
||||
p.network.LocalRequest = nil
|
||||
p.network.LocalError = result.Error
|
||||
_ = p.saveNetworkLocked()
|
||||
}
|
||||
@@ -23,18 +23,28 @@ type NetworkPending struct {
|
||||
Config json.RawMessage `json:"config,omitempty"`
|
||||
Local bool `json:"local,omitempty"`
|
||||
}
|
||||
type LocalNetworkRequest struct {
|
||||
ID string `json:"id"`
|
||||
Provider string `json:"provider"`
|
||||
Revision int64 `json:"revision"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
}
|
||||
type NetworkProfile struct {
|
||||
BindingID string `json:"binding_id"`
|
||||
Revision int64 `json:"revision"`
|
||||
Provider string `json:"provider"`
|
||||
ServerID string `json:"server_id,omitempty"`
|
||||
Config json.RawMessage `json:"config,omitempty"`
|
||||
TailscaleEndpoint string `json:"tailscale_endpoint,omitempty"`
|
||||
OperationID string `json:"operation_id,omitempty"`
|
||||
Phase string `json:"phase"`
|
||||
PublicKey string `json:"public_key,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Pending *NetworkPending `json:"pending,omitempty"`
|
||||
LocalRequest *LocalNetworkRequest `json:"local_request,omitempty"`
|
||||
LocalError string `json:"local_error,omitempty"`
|
||||
NetBirdEndpoint string `json:"netbird_endpoint,omitempty"`
|
||||
NetBirdConfig json.RawMessage `json:"netbird_config,omitempty"`
|
||||
BindingID string `json:"binding_id"`
|
||||
Revision int64 `json:"revision"`
|
||||
Provider string `json:"provider"`
|
||||
ServerID string `json:"server_id,omitempty"`
|
||||
Config json.RawMessage `json:"config,omitempty"`
|
||||
TailscaleEndpoint string `json:"tailscale_endpoint,omitempty"`
|
||||
OperationID string `json:"operation_id,omitempty"`
|
||||
Phase string `json:"phase"`
|
||||
PublicKey string `json:"public_key,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Pending *NetworkPending `json:"pending,omitempty"`
|
||||
}
|
||||
type NetworkCommand struct {
|
||||
ID string `json:"id"`
|
||||
@@ -133,12 +143,18 @@ func (p *Pairing) networkViewLocked() map[string]any {
|
||||
result["pending_provider"] = n.Pending.Provider
|
||||
result["rollback_at"] = n.Pending.Deadline
|
||||
}
|
||||
result["local_request"] = n.LocalRequest
|
||||
result["local_error"] = n.LocalError
|
||||
result["netbird_endpoint"] = n.NetBirdEndpoint
|
||||
result["netbird"] = netbirdSnapshot()
|
||||
return result
|
||||
}
|
||||
func (p *Pairing) networkSnapshot() map[string]any {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
return p.networkViewLocked()
|
||||
result := p.networkViewLocked()
|
||||
result["netbird"] = netbirdSnapshot()
|
||||
return result
|
||||
}
|
||||
func (p *Pairing) networkEndpointLocked(endpoint string) error {
|
||||
b := p.state.Binding
|
||||
@@ -250,7 +266,7 @@ func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if c.ExpectedRevision != n.Revision || (c.Provider != "tailscale" && c.Provider != "wireguard") || (c.Provider == "wireguard" && !networkID.MatchString(c.ServerID)) {
|
||||
if c.ExpectedRevision != n.Revision || (c.Provider != "tailscale" && c.Provider != "wireguard" && c.Provider != "netbird") || (c.Provider == "wireguard" && !networkID.MatchString(c.ServerID)) {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
@@ -258,7 +274,7 @@ func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if c.Action == "prepare" {
|
||||
if c.Action == "prepare" && c.Provider == "wireguard" {
|
||||
if n.OperationID == c.ID && n.Phase == "prepared" {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
@@ -297,16 +313,24 @@ func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
|
||||
}
|
||||
} else {
|
||||
var config struct {
|
||||
ServerID string `json:"server_id"`
|
||||
Address string `json:"address"`
|
||||
Subnet string `json:"subnet"`
|
||||
Role string `json:"role"`
|
||||
Allowed []string `json:"allowed_ips"`
|
||||
ServerURL string `json:"server_url"`
|
||||
ServerID string `json:"server_id"`
|
||||
Address string `json:"address"`
|
||||
Subnet string `json:"subnet"`
|
||||
Role string `json:"role"`
|
||||
Allowed []string `json:"allowed_ips"`
|
||||
}
|
||||
if json.Unmarshal(c.Config, &config) != nil || config.ServerID != c.ServerID || config.Role != "node" {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
if c.Provider == "netbird" {
|
||||
status := netbirdSnapshot()
|
||||
if status.State != "connected" || status.ServerURL != config.ServerURL || status.Address != config.Address || status.Network != config.Subnet || c.ServerID != "netbird" {
|
||||
p.mu.Unlock()
|
||||
return
|
||||
}
|
||||
}
|
||||
_, network, err := net.ParseCIDR(config.Subnet)
|
||||
u, e := url.Parse(c.CoreEndpoint)
|
||||
if err != nil || e != nil || !privateEndpoint(c.CoreEndpoint, CorePort) || !network.Contains(net.ParseIP(u.Hostname())) {
|
||||
@@ -384,7 +408,7 @@ func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
|
||||
*n = previous
|
||||
return
|
||||
}
|
||||
if oldServer != "" && oldServer != pending.ServerID {
|
||||
if networkID.MatchString(oldServer) && oldServer != pending.ServerID {
|
||||
// The confirmed endpoint is durable before retiring the previous tunnel.
|
||||
_, _ = p.callNetwork("disable", oldServer, nil)
|
||||
}
|
||||
@@ -393,7 +417,7 @@ func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
|
||||
p.mu.Unlock()
|
||||
}
|
||||
func (p *Pairing) networkAddressLocked(address string) bool {
|
||||
if p.network == nil || p.network.Provider != "wireguard" {
|
||||
if p.network == nil || (p.network.Provider != "wireguard" && p.network.Provider != "netbird") {
|
||||
return tailnetAddress(address)
|
||||
}
|
||||
var config struct {
|
||||
@@ -436,15 +460,37 @@ func (p *Pairing) networkLocalRoutes(mux *http.ServeMux, s *Server) {
|
||||
}
|
||||
reply(w, 200, p.networkSnapshot())
|
||||
})
|
||||
mux.HandleFunc("POST /api/network/profile/tailscale", func(w http.ResponseWriter, r *http.Request) {
|
||||
mux.HandleFunc("POST /api/network/profile/{provider}", func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
return
|
||||
}
|
||||
provider := r.PathValue("provider")
|
||||
if provider != "tailscale" && provider != "netbird" {
|
||||
reply(w, 400, map[string]string{"error": "Неизвестная сеть."})
|
||||
return
|
||||
}
|
||||
p.mu.Lock()
|
||||
_ = p.loadNetworkLocked()
|
||||
if p.network == nil || p.network.TailscaleEndpoint == "" {
|
||||
if p.network == nil || (provider == "tailscale" && p.network.TailscaleEndpoint == "") || (provider == "netbird" && p.network.NetBirdEndpoint == "") {
|
||||
p.mu.Unlock()
|
||||
reply(w, 409, map[string]string{"error": "Нет сохранённого подключения Tailscale."})
|
||||
reply(w, 409, map[string]string{"error": "Core ещё не подтвердил доступность выбранной сети."})
|
||||
return
|
||||
}
|
||||
if provider == "netbird" {
|
||||
if p.network.Pending != nil || (p.network.LocalRequest != nil && p.network.LocalRequest.ExpiresAt > time.Now().Unix()) {
|
||||
p.mu.Unlock()
|
||||
reply(w, 409, map[string]string{"error": "Дождитесь завершения переключения."})
|
||||
return
|
||||
}
|
||||
p.network.LocalRequest = &LocalNetworkRequest{ID: digest(token())[:32], Provider: provider, Revision: p.network.Revision, ExpiresAt: time.Now().Unix() + 110}
|
||||
p.network.LocalError = ""
|
||||
err := p.saveNetworkLocked()
|
||||
p.mu.Unlock()
|
||||
if err != nil {
|
||||
reply(w, 500, map[string]string{"error": "Не удалось сохранить запрос."})
|
||||
return
|
||||
}
|
||||
reply(w, 200, p.networkSnapshot())
|
||||
return
|
||||
}
|
||||
op := digest(token())[:32]
|
||||
|
||||
@@ -103,3 +103,82 @@ func TestNetworkCommitStorageFailureKeepsRollbackState(t *testing.T) {
|
||||
t.Fatal("rollback after storage failure failed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNetBirdSwitchRequiresFreshMatchingDaemonAndCommitsWithoutWGHelper(t *testing.T) {
|
||||
p, c, actions := networkFixture(t)
|
||||
c.Provider = "netbird"
|
||||
c.ServerID = "netbird"
|
||||
c.CoreEndpoint = "https://10.204.1.2:8782"
|
||||
c.Config = json.RawMessage(`{"server_id":"netbird","server_url":"https://network.example.org","address":"10.204.1.3","subnet":"10.204.0.0/16","role":"node","allowed_ips":["10.204.1.2/32"]}`)
|
||||
netbirdObservation.Lock()
|
||||
netbirdObservation.at = time.Time{}
|
||||
netbirdObservation.Unlock()
|
||||
networkSend(p, c)
|
||||
if p.network.Pending != nil {
|
||||
t.Fatal("stale status authorized transition")
|
||||
}
|
||||
netbirdObservation.Lock()
|
||||
netbirdObservation.value = NetBirdStatus{State: "connected", Address: "10.204.1.3", ServerURL: "https://other.example.org", Network: "10.204.0.0/16"}
|
||||
netbirdObservation.at = time.Now()
|
||||
netbirdObservation.Unlock()
|
||||
networkSend(p, c)
|
||||
if p.network.Pending != nil {
|
||||
t.Fatal("other server authorized transition")
|
||||
}
|
||||
netbirdObservation.Lock()
|
||||
netbirdObservation.value.ServerURL = "https://network.example.org"
|
||||
netbirdObservation.Unlock()
|
||||
defer func() { netbirdObservation.Lock(); netbirdObservation.at = time.Time{}; netbirdObservation.Unlock() }()
|
||||
networkSend(p, c)
|
||||
if p.network.Phase != "verifying" || p.network.Provider != "tailscale" {
|
||||
t.Fatal("unverified switch")
|
||||
}
|
||||
c.Action = "commit"
|
||||
networkSend(p, c)
|
||||
if p.network.Provider != "netbird" || p.network.Revision != 1 || len(*actions) != 0 {
|
||||
t.Fatal("NetBird owns unexpected WG changes")
|
||||
}
|
||||
if !p.networkAddressLocked("10.204.1.3") || p.networkAddressLocked("10.204.1.4") || !p.networkPeerLocked("10.204.1.2") || p.networkPeerLocked("192.168.1.1") {
|
||||
t.Fatal("peer boundary widened")
|
||||
}
|
||||
}
|
||||
func TestNetBirdAPIRequiresAuthorizedSession(t *testing.T) {
|
||||
s := newTestServer(t)
|
||||
for _, method := range []string{"GET", "POST"} {
|
||||
path := "/api/network/netbird"
|
||||
if method == "POST" {
|
||||
path += "/connect"
|
||||
}
|
||||
if got := call(s, method, path, "{}", nil); got.Code != 401 {
|
||||
t.Fatal(got.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalNetBirdSelectionQueuesCoreAdmissionWithoutMovingEndpoint(t *testing.T) {
|
||||
p, _, actions := networkFixture(t)
|
||||
p.mu.Lock()
|
||||
_ = p.loadNetworkLocked()
|
||||
p.network.NetBirdEndpoint = "https://10.204.1.2:8782"
|
||||
p.mu.Unlock()
|
||||
s := newTestServer(t)
|
||||
s.Pairing = p
|
||||
cookie := login(t, s)
|
||||
result := call(s, "POST", "/api/network/profile/netbird", "{}", cookie)
|
||||
if result.Code != 200 || p.network.LocalRequest == nil {
|
||||
t.Fatal(result.Code, result.Body.String())
|
||||
}
|
||||
if p.state.Binding.Endpoint != "https://100.64.1.2:8782" || p.network.Pending != nil || len(*actions) != 0 {
|
||||
t.Fatal("local UI bypassed Core admission")
|
||||
}
|
||||
id := p.network.LocalRequest.ID
|
||||
p.acceptNetworkRequestResult(json.RawMessage(`{"id":"foreign","error":"bad"}`))
|
||||
if p.network.LocalRequest == nil {
|
||||
t.Fatal("foreign receipt consumed request")
|
||||
}
|
||||
raw, _ := json.Marshal(map[string]string{"id": id, "error": "Отключите управление"})
|
||||
p.acceptNetworkRequestResult(raw)
|
||||
if p.network.LocalRequest != nil || p.network.LocalError == "" {
|
||||
t.Fatal("admission failure lost")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -152,6 +152,7 @@ func (p *Pairing) remoteHandler() http.Handler {
|
||||
}
|
||||
|
||||
func (p *Pairing) Run(ctx context.Context) {
|
||||
go monitorNetBird(ctx)
|
||||
go p.networkWatch(ctx)
|
||||
go p.channel(ctx)
|
||||
go p.roverChannel(ctx)
|
||||
@@ -369,12 +370,16 @@ func (p *Pairing) channel(ctx context.Context) {
|
||||
payload["routers"] = p.Routers.Snapshot()
|
||||
}
|
||||
result, status, e := p.sendHeartbeat(ctx, *binding, payload)
|
||||
var networkRequestResult json.RawMessage
|
||||
var netbirdOffer json.RawMessage
|
||||
var networkChange json.RawMessage
|
||||
var configurationChange json.RawMessage
|
||||
var routerCommands json.RawMessage
|
||||
p.mu.Lock()
|
||||
if p.state.Phase == "paired" && p.state.Binding != nil && p.state.Binding.BindingID == binding.BindingID && p.state.Binding.Endpoint == binding.Endpoint && p.state.Binding.EndpointRevision == binding.EndpointRevision {
|
||||
if e == nil && status == 200 {
|
||||
networkRequestResult = result["network_request_result"]
|
||||
netbirdOffer = result["netbird_offer"]
|
||||
networkChange = result["network_profile_change"]
|
||||
routerCommands = result["router_commands"]
|
||||
if p.RoverConfiguration != nil {
|
||||
@@ -433,6 +438,8 @@ func (p *Pairing) channel(ctx context.Context) {
|
||||
if e == nil && status == http.StatusOK {
|
||||
p.networkLocalAcknowledged(*binding)
|
||||
}
|
||||
p.acceptNetworkRequestResult(networkRequestResult)
|
||||
p.acceptNetBirdOffer(netbirdOffer)
|
||||
p.applyNetworkCommand(networkChange)
|
||||
p.applyRouterCommands(routerCommands)
|
||||
// Durable preference IO must not hold the pairing/control mutex.
|
||||
|
||||
@@ -84,6 +84,7 @@ func reply(w http.ResponseWriter, status int, v any) {
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
s.routerRoutes(mux)
|
||||
s.netbirdRoutes(mux)
|
||||
s.linkBudgetRoutes(mux)
|
||||
s.localPreviewRoutes(mux)
|
||||
s.monitorRoutes(mux)
|
||||
|
||||
@@ -3,7 +3,7 @@ import { ActivityIndicator, Button, ConfirmationModal, Select, SettingsCard, Sta
|
||||
import { request } from "./api";
|
||||
|
||||
interface CoreState {
|
||||
network_profile?: {provider:string;phase:string;error?:string;tailscale_endpoint?:string};
|
||||
network_profile?: {provider:string;phase:string;error?:string;tailscale_endpoint?:string;netbird_endpoint?:string;local_request?:{expires_at:number}|null;local_error?:string};
|
||||
phase: "unpaired" | "inviting" | "pending" | "paired" | "revoked";
|
||||
connection: string; node_id: string; last_seen: number; notice: string; addresses: string[];
|
||||
invitation?: { id: string; endpoint: string; expires_at: number };
|
||||
@@ -54,7 +54,7 @@ export function CoreConnectionView({ failure }: { failure: (error: unknown) => v
|
||||
</dl>
|
||||
{value.notice && <p className="node-note" role="status">{value.notice}</p>}
|
||||
{paired ? <p className="node-note">БК сохраняет привязку при перезапуске и восстанавливает соединение автоматически. Для подключения к другому Core сначала отзовите текущую привязку.</p> : value.phase === "pending" ? <ActivityIndicator label="Core принимает приглашение. Дождитесь подтверждения связи." /> : <div className="node-form">
|
||||
<p className="node-note">Выберите адрес, доступный компьютеру с Mission Core: в общей локальной сети или Tailscale. Создайте приглашение и вставьте его в Core: «Парк → Аппараты → Добавить аппарат».</p>
|
||||
<p className="node-note">Выберите адрес, доступный компьютеру с Mission Core: в общей локальной сети, Tailscale или NetBird. Создайте приглашение и вставьте его в Core: «Парк → Аппараты → Добавить аппарат».</p>
|
||||
<Select label="Адрес БК для подключения" value={address} options={value.addresses.map(item => ({ value: item, label: item }))} onChange={setAddress} disabled={pending || !available} />
|
||||
{value.addresses.length === 0 && <p className="node-note">Подключите БК к частной сети. Доступные адреса появятся автоматически.</p>}
|
||||
<Button disabled={pending || !available || !address} onClick={() => void create()}>{pending ? "Создаём…" : value.phase === "inviting" ? "Создать новое приглашение" : "Создать приглашение"}</Button>
|
||||
@@ -66,11 +66,14 @@ export function CoreConnectionView({ failure }: { failure: (error: unknown) => v
|
||||
{notice && <p role="status" className="node-note">{notice}</p>}
|
||||
</>}
|
||||
</SettingsCard>
|
||||
{paired&&value?.network_profile&&<SettingsCard title="Связь с Core" description="Настройки применяются к этому БК из Mission Core: Парк → Бортовой компьютер → Связь с Core.">
|
||||
<StatusBadge tone={value.connection==='online'?'success':'neutral'}>{value.network_profile.provider==='wireguard'?'WireGuard · VPS':'Tailscale'}</StatusBadge>
|
||||
{paired&&value?.network_profile&&<SettingsCard title="Связь с Core" description="Выберите проверенную частную сеть для этого БК. Настройки также доступны в Mission Core: Парк → Бортовой компьютер → Связь с Core.">
|
||||
<StatusBadge tone={value.connection==='online'?'success':'neutral'}>{value.network_profile.provider==='netbird'?'NetBird':value.network_profile.provider==='wireguard'?'WireGuard · VPS':'Tailscale'}</StatusBadge>
|
||||
{['preparing','verifying'].includes(value.network_profile.phase)&&<p className="node-note">Проверяем новое подключение. При отсутствии подтверждения вернётся прежний профиль.</p>}
|
||||
{value.network_profile.error&&<p role="status" className="node-note">{value.network_profile.error}</p>}
|
||||
{value.network_profile.provider==='wireguard'&&<Button disabled={pending||!value.network_profile.tailscale_endpoint||['preparing','verifying'].includes(value.network_profile.phase)} onClick={async()=>{setPending(true);try{await request('/api/network/profile/tailscale','POST',{});await refresh();}catch(e){failure(e);}finally{setPending(false);}}}>Восстановить Tailscale</Button>}
|
||||
{value.network_profile.local_error&&<StatusBadge tone="danger">{value.network_profile.local_error}</StatusBadge>}
|
||||
{value.network_profile.local_request&&value.network_profile.local_request.expires_at>Date.now()/1000&&<p className="node-note">Ожидаем разрешение переключения от Core. Активное управление должно быть отключено.</p>}
|
||||
{value.network_profile.provider!=='netbird' &&<Button disabled={pending||Boolean(value.network_profile.local_request&&value.network_profile.local_request.expires_at>Date.now()/1000)||!value.network_profile.netbird_endpoint||['preparing','verifying'].includes(value.network_profile.phase)} onClick={async()=>{setPending(true);try{await request('/api/network/profile/netbird','POST',{});await refresh();}catch(e){failure(e);}finally{setPending(false);}}}>Использовать NetBird</Button>}
|
||||
{value.network_profile.provider!=='tailscale'&&<Button disabled={pending||!value.network_profile.tailscale_endpoint||['preparing','verifying'].includes(value.network_profile.phase)} onClick={async()=>{setPending(true);try{await request('/api/network/profile/tailscale','POST',{});await refresh();}catch(e){failure(e);}finally{setPending(false);}}}>Восстановить Tailscale</Button>}
|
||||
</SettingsCard>}
|
||||
<ConfirmationModal open={remove} title={value?.binding ? "Отозвать привязку к Core?" : "Отменить приглашение?"} description={value?.binding ? "Этот БК прекратит соединение с Core. Аппарат останется в его реестре; отзыв будет доставлен при доступности сети." : "Этот код больше нельзя будет использовать. Вы сможете создать новый."} confirmLabel="Отозвать" cancelLabel="Отмена" danger onClose={() => setRemove(false)} onConfirm={async () => { try { await request("/api/core", "DELETE"); setCode(""); setNotice(""); await refresh(); setRemove(false); } catch (error) { failure(error); throw error; } }} />
|
||||
</div>;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useState } from "react";
|
||||
import { ActivityIndicator, Button, Icon, ResourceList, ResourceRow, SettingsCard, StatusBadge } from "@nodedc/ui-react";
|
||||
import { environmentSetupAvailable } from "./api";
|
||||
import type { useEnvironment } from "./useEnvironment";
|
||||
import { TailnetAccess } from "./TailnetAccess";
|
||||
import { PrivateNetwork } from "./PrivateNetwork";
|
||||
import { SystemAccess } from "./SystemAccess";
|
||||
|
||||
const labels:Record<string,string>={pending:"Ожидает",running:"Выполняется",error:"Ошибка",blocked:"Не выполнено"};
|
||||
@@ -25,14 +25,14 @@ export function EnvironmentView({environment,failure,success}: {environment:Retu
|
||||
return <li key={specification.id}><ResourceRow icon={state==="running"?<ActivityIndicator size="compact" />:<Icon name={state==="error"?"alert":"circle"} />} title={specification.label} description={specification.description} metadata={step?.detail} status={state==="complete"?<Icon name="check" label="Этап завершён" />:<StatusBadge tone={state==="error"?"warning":"neutral"}>{labels[state]??"Неизвестно"}</StatusBadge>} /></li>;
|
||||
})}</ResourceList>
|
||||
{value.run&&!running&&value.run.updated_at>0&&<p className="node-note">Результат проверки от {new Date(value.run.updated_at*1000).toLocaleString("ru-RU")}.</p>}
|
||||
{complete&&!running&&<p className="node-note">Системные этапы завершены. Ниже проверьте вход в Tailscale и доверенный ключ для SSH.</p>}
|
||||
{complete&&!running&&<p className="node-note">Системные этапы завершены. Ниже выберите частную сеть и проверьте доверенный ключ для SSH.</p>}
|
||||
{value.run?.state==="error"&&!running&&<p className="node-note">Часть этапов не завершена. Исправьте указанные причины и повторите настройку.</p>}
|
||||
{value.run?.state==="interrupted"&&<p className="node-note">Предыдущая настройка прервана. Повторный запуск проверит уже выполненные этапы.</p>}
|
||||
</>}
|
||||
</SettingsCard>
|
||||
{!running&&<>
|
||||
<SettingsCard title="Доверенное устройство для SSH"><SystemAccess revision={revision} failure={failure} success={success} adding={adding} closeAdd={()=>setAdding(false)} startAdd={()=>setAdding(true)} /></SettingsCard>
|
||||
<TailnetAccess failure={failure} revision={revision} />
|
||||
<PrivateNetwork failure={failure} revision={revision} />
|
||||
</>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import {useEffect,useState} from "react";
|
||||
import {ActivityIndicator,Button,Select,SettingsCard,StatusBadge,TextField} from "@nodedc/ui-react";
|
||||
import {desktopAction,networkSetupAvailable,openNetworkLogin,request} from "./api";
|
||||
import {TailnetAccess} from "./TailnetAccess";
|
||||
interface NetBird {state:string;address?:string;server_url?:string;pending?:string;auth_url?:string;error?:string}
|
||||
export function PrivateNetwork({failure,revision}:{failure:(error:unknown)=>void;revision:string}) {
|
||||
const [provider,setProvider]=useState("tailscale"),[value,setValue]=useState<NetBird|null>(null);
|
||||
const [server,setServer]=useState(""),[method,setMethod]=useState("browser"),[key,setKey]=useState("");
|
||||
const [busy,setBusy]=useState(false),[error,setError]=useState("");
|
||||
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>;const controller=new AbortController();
|
||||
const poll=async()=>{try{const next=await request<NetBird>("/api/network/netbird","GET",undefined,controller.signal);if(active){setValue(next);setServer(old=>old||next.server_url||"");}}catch{if(active)setValue({state:"unavailable"});}finally{if(active)timer=setTimeout(poll,2500);}};
|
||||
void poll();return()=>{active=false;controller.abort();clearTimeout(timer);};
|
||||
},[revision]);
|
||||
async function connect(){setBusy(true);setError("");const secret=key;setKey("");try{setValue(await request<NetBird>("/api/network/netbird/connect","POST",{server_url:server,setup_key:method==="key"?secret:""}));}catch(e){setError(e instanceof Error?e.message:"Не удалось подключиться.");}finally{setBusy(false);}}
|
||||
const pending=busy||Boolean(value?.pending);
|
||||
return <div className="node-content">
|
||||
<SettingsCard title="Частная сеть" description="Подключение бортового компьютера к сети оператора">
|
||||
<Select label="Сеть" value={provider} onChange={setProvider} options={[{value:"tailscale",label:"Tailscale"},{value:"netbird",label:"NetBird · WireGuard"}]} disabled={pending}/>
|
||||
<p className="node-note">После входа выберите канал в «Mission Core → Связь с Core». Текущий канал сохраняется до проверки нового.</p>
|
||||
</SettingsCard>
|
||||
{provider==="tailscale"?<TailnetAccess failure={failure} revision={revision}/>:<SettingsCard title="NetBird" description="Укажите сервер вашей сети или запросите его адрес у администратора." actions={<StatusBadge tone={value?.state==="connected"?"success":"neutral"}>{value?.state==="connected"?"Подключено":pending?"Подключение…":"Не подключено"}</StatusBadge>}>
|
||||
{!value?<ActivityIndicator label="Проверяем NetBird"/>:<>
|
||||
{value.state==="missing_client"&&<><p className="node-note">Завершите подготовку окружения: приложение установит проверенный клиент. После этого здесь можно будет выбрать сервер и войти.</p><Button disabled={!networkSetupAvailable()} onClick={()=>desktopAction("configure-system")}>Подготовить окружение</Button></>}
|
||||
<TextField label="Адрес сервера" placeholder="https://netbird.example.org" value={server} onChange={e=>setServer(e.target.value)} disabled={pending}/>
|
||||
{value.state!=="connected"&&<><Select label="Способ входа" value={method} onChange={setMethod} options={[{value:"browser",label:"Войти в браузере"},{value:"key",label:"Ключ подключения"}]} disabled={pending}/>
|
||||
{method==="key"&&<><TextField label="Ключ подключения борта" type="password" autoComplete="off" value={key} onChange={e=>setKey(e.target.value)} disabled={pending}/><p className="node-note">Получите ключ для группы бортов у администратора сети. Ключ нужен только при первом подключении.</p></>}</>}
|
||||
<Button disabled={pending||!server||value.state==="missing_client"||(method==="key"&&value.state!=="connected"&&!key)} onClick={()=>void connect()}>{value.state==="connected"?"Проверить подключение":"Подключить"}</Button>
|
||||
{value.auth_url&&<Button onClick={()=>openNetworkLogin(value.auth_url!)}>Продолжить вход в браузере</Button>}
|
||||
{value.pending&&<><ActivityIndicator label={value.auth_url?"Завершите вход в браузере. Состояние обновится автоматически.":"Проверяем подключение к серверу…"}/><Button disabled={busy} onClick={async()=>{try{setValue(await request<NetBird>("/api/network/netbird/cancel","POST",{}));}catch(e){failure(e);}}}>Отменить ожидание</Button></>}
|
||||
{value.state==="connected"&&<p className="node-note">Адрес борта: {value.address}. Подключение восстанавливается автоматически после запуска системы.</p>}
|
||||
{value.state==="other_network"&&<p className="node-note">NetBird подключён к другой сети. Отключите её в официальном клиенте перед сменой сервера.</p>}
|
||||
{value.state==="unsupported_client"&&<p className="node-note">Версия клиента не соответствует установщику. Обновите окружение БК.</p>}
|
||||
{(error||value.error)&&<StatusBadge tone="danger">{error||value.error}</StatusBadge>}
|
||||
</>}
|
||||
</SettingsCard>}
|
||||
</div>;
|
||||
}
|
||||
@@ -43,3 +43,10 @@ export async function loginFromLaunch(): Promise<void> {
|
||||
if (location.hash) history.replaceState(null, "", location.pathname);
|
||||
if (token) await request("/api/session", "POST", { token });
|
||||
}
|
||||
|
||||
export function openNetworkLogin(url:string):void {
|
||||
const parsed=new URL(url);if(parsed.protocol!=="https:"||!parsed.pathname.startsWith("/oauth2/")||parsed.username||parsed.password)return;
|
||||
const host=window as Window & {webkit?:{messageHandlers?:{node?:{postMessage:(message:string)=>void}}}};
|
||||
if(host.webkit?.messageHandlers?.node)host.webkit.messageHandlers.node.postMessage(JSON.stringify({action:"netbird-login",url}));
|
||||
else window.open(url,"_blank","noopener,noreferrer");
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import { roots, views, type RootId, type ViewId } from "./nodeModel";
|
||||
import { NodeOverview } from "./NodeOverview";
|
||||
import { USBView, DiagnosticsView, NetworkView } from "./InventoryViews";
|
||||
import { SystemAccess } from "./SystemAccess";
|
||||
import { TailnetAccess } from "./TailnetAccess";
|
||||
import { PrivateNetwork } from "./PrivateNetwork";
|
||||
import { useEnvironment } from "./useEnvironment";
|
||||
import { EnvironmentView } from "./EnvironmentView";
|
||||
import { CoreConnectionView } from "./CoreConnectionView";
|
||||
@@ -43,7 +43,7 @@ function App() {
|
||||
: workspace.activeView === "usb" ? <USBView value={value} />
|
||||
: workspace.activeView === "core" ? <CoreConnectionView failure={failure} />
|
||||
: workspace.activeView === "diagnostics" ? <DiagnosticsView value={value} />
|
||||
: workspace.activeView === "tailscale" ? <TailnetAccess failure={failure} revision={value.host.collected_at} />
|
||||
: workspace.activeView === "tailscale" ? <PrivateNetwork failure={failure} revision={value.host.collected_at} />
|
||||
: workspace.activeView === "ssh" ? <SystemAccess revision={value.host.collected_at} failure={failure} success={node.success} adding={adding} closeAdd={() => setAdding(false)} /> : null;
|
||||
return <>
|
||||
<ApplicationShell data-nodedc-ui className="node-app" header={<AppHeader brandMonochrome brandHref="/" brand={<img src="/nodedc-logo.svg" alt="NODE.DC" />} brandLabel={presentation.settings.pages.home.headerLabel}
|
||||
|
||||
@@ -12,7 +12,7 @@ export const views: { id: ViewId; root: RootId; label: string; icon: IconName }[
|
||||
{ id: "network", root: "system", label: "Сеть", icon: "network" },
|
||||
{ id: "usb", root: "system", label: "USB-устройства", icon: "camera" },
|
||||
{ id: "core", root: "system", label: "Mission Core", icon: "network" },
|
||||
{ id: "tailscale", root: "system", label: "Tailscale", icon: "globe" },
|
||||
{ id: "tailscale", root: "system", label: "Частная сеть", icon: "globe" },
|
||||
{ id: "ssh", root: "system", label: "SSH · доверенные устройства", icon: "key" },
|
||||
{ id: "diagnostics", root: "system", label: "Диагностика", icon: "clipboard" },
|
||||
];
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# NetBird on the onboard computer
|
||||
|
||||
Surface brief: the owner requests network selection in onboard settings after automatic Ubuntu preparation. Extend the existing System private-network page (formerly Tailscale) and the same section following environment preparation. This keeps one lifecycle and existing SettingsCard, Select, TextField, Button, ActivityIndicator and StatusBadge. The presentation-only global settings window is unsuitable for operating-system configuration. No new product root or shared visual primitive is introduced.
|
||||
|
||||
The versioned Ubuntu 24.04 amd64 installer carries the pinned official client. Environment preparation installs it idempotently, preserves foreign versions/configuration, and enables automatic service startup. It does not enroll a machine or guess a server. The user supplies an HTTPS server URL, then browser authentication or a setup key issued for the boards group. The key is passed in an environment variable to the CLI, never saved by Node, exposed in argv or returned in status. Browser authentication requires the administrator to place the peer in the boards group; operator and board permissions remain separate.
|
||||
|
||||
The unprivileged Node API is protected by the existing OS-authorized session, same-origin checks and a fixed root-owned Unix adapter restricted by peer UID. Core and Node ship the same client implementation, pin, server receipt validation, bounded connection operation and cancellation rules. DNS, subnet routes, exit routes, remote SSH/jobs and IPv6 stay disabled in the owned NetBird profile. Worker settings and Synology routes are not modified.
|
||||
|
||||
A joined network is separate from the active Core channel. Authenticated heartbeats compare server URL and subnet, prepare only the exact Core/board addresses, and advertise a verified alternative to the board UI. A local NetBird selection is first sent to Core over the existing authenticated channel; the same control-session interlock as remote settings rejects it while vehicle control is active. An accepted request stages the endpoint, requires an authenticated response over it and commits only after confirmation. The existing timeout restores the previous endpoint. Keys and board identity survive service restart; a stale status cannot authorize a new endpoint.
|
||||
|
||||
## Operator path
|
||||
|
||||
1. Download the Node installer from Mission Core and run its installation window
|
||||
on Ubuntu 24.04 amd64: `python3 mission-core-node-install.pyz --launch`.
|
||||
2. Open Node's system preparation and confirm the OS administrator prompt. The
|
||||
shipped environment profile installs Tailscale and the pinned NetBird client,
|
||||
enables their services and reports each preparation step.
|
||||
3. In **System → Private network**, choose **NetBird**, enter the server URL
|
||||
(this deployment: `https://netbird.nodedc.ru:8443`) and authenticate in the
|
||||
browser or enter a setup key whose automatic group is Mission Core boards.
|
||||
The server address is operator input, not an installer default.
|
||||
4. Pair Node with Core separately if it is a new board. Once both peers are
|
||||
connected to the same server, choose NetBird in Node's **Mission Core** page
|
||||
or Core's **Onboard computer → Connection to Core**, then save. Wait for the
|
||||
verified channel to be applied. Network enrollment alone does not select
|
||||
the application channel or grant motor control.
|
||||
|
||||
The client keeps its own peer identity and reconnects automatically; a setup key
|
||||
is only enrollment material. The server receipt must confirm both peer login
|
||||
and inactivity expiration are disabled. This removes scheduled reauthentication,
|
||||
not failures caused by Internet loss or a stopped VPS. The active profile must
|
||||
not be copied with private keys to another computer.
|
||||
|
||||
## Accepted scope, 2026-10-31
|
||||
|
||||
Node `0.8.51-96` was built through the bounded Linux source artifact and installed
|
||||
on N006 with the versioned owner installer. X4 stayed at `0.1.3-30`. All 24 Linux
|
||||
qualification steps passed, including Go/race checks, Node UI/environment checks
|
||||
and systemd validation. The final focused Core/NetBird/network-profile suite had
|
||||
54 passing tests; Ruff passed. The Linux helper's private XDG configuration
|
||||
directory allows the official CLI to mirror its profile without weakening
|
||||
`ProtectHome`; Core's selection API now admits the NetBird provider explicitly.
|
||||
|
||||
Live UI acceptance covered Node enrollment, selecting NetBird locally, selecting
|
||||
Tailscale in Core and selecting NetBird again in Core. Final state was
|
||||
`provider=netbird`, `phase=applied`, revision 6, fresh telemetry, no active vehicle
|
||||
control. The peer connection used the deployment's VPS relay. A bounded WebRTC
|
||||
preview decoded 1280×640 frames with advancing playback time; it was stopped
|
||||
afterward, with camera recording off. This is not a long-duration media or
|
||||
latency qualification, and no motor commands were sent.
|
||||
|
||||
Environment preparation completed at revision `ubuntu-24.04-amd64/4`; Node,
|
||||
NetBird and its restricted adapter were enabled and active without restarts.
|
||||
VPS account expiry flags remained false, with four role policies and no networks
|
||||
or routes. Policy semantics were unchanged; the boards group's peer count grew
|
||||
from zero to one. Worker and Synology configuration were not changed.
|
||||
|
||||
Published owner release: `eb6559831c2e2a79517848fe`.
|
||||
Installer SHA-256:
|
||||
`62f7b6682c72ff821e5a6e94b38972849503dbe37ae9e3f3dcecb3ece0d6f9a3`.
|
||||
Node DEB SHA-256:
|
||||
`1584b6d83f3063427c1c4e4aa910e73cfc4deb6023870146547c348b039ca77b`.
|
||||
Private evidence is retained under `.runtime/netbird-node95`; qualified build
|
||||
outputs are under `apps/node-agent/build/qualified-0.8.51-96`. Node94 remains a
|
||||
rollback release. No secrets or raw telemetry belong in this document.
|
||||
|
||||
A prepared N006 and an empty-dpkg-status dependency simulation are not evidence
|
||||
of installing on a clean OS image. Clean Ubuntu execution, reboot, Wi-Fi handover,
|
||||
new standalone clients and fleet load still require separate qualification.
|
||||
@@ -16,7 +16,7 @@ def main():
|
||||
parser.add_argument("--file", type=Path, required=True)
|
||||
parser.add_argument("--sha256", required=True)
|
||||
parser.add_argument("--version", required=True)
|
||||
parser.add_argument("--kind", choices=("node", "vps-arnavi", "vps-wireguard"), required=True)
|
||||
parser.add_argument("--kind", choices=("node", "vps-arnavi", "vps-wireguard", "vps-netbird"), required=True)
|
||||
args = parser.parse_args()
|
||||
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9]+)?", args.version):
|
||||
raise ValueError("Invalid release version")
|
||||
@@ -59,6 +59,12 @@ def main():
|
||||
"Скопируйте пакет на VPS. Запустите: sudo python3 mission-core-wireguard-vps.pyz",
|
||||
"Дождитесь завершения установки. Файл подключения: /var/lib/ndc-wireguard-vps/mission-core-wireguard.json.",
|
||||
"Перенесите файл подключения на этот компьютер и загрузите его в настройках связи БК."])
|
||||
if args.kind == "vps-netbird":
|
||||
value.update(label="Сервер NetBird", os="Ubuntu Server 24.04 LTS · x86-64", instructions=[
|
||||
"Направьте домен сети на адрес VPS. Перенесите установщик на сервер.",
|
||||
"Проверьте план: sudo python3 mission-core-netbird-vps.pyz plan --domain ДОМЕН",
|
||||
"Примените план: sudo python3 mission-core-netbird-vps.pyz apply --domain ДОМЕН --plan-sha256 ХЕШ_ПЛАНА",
|
||||
"Адрес сети и файл доступа администратора появятся после установки."])
|
||||
temporary = root / (args.kind + ".json.new")
|
||||
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
|
||||
temporary.chmod(0o600)
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fetch exactly the reviewed vendor release into a portable local catalog."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from k1link.fleet.netbird.assets import LOCK, directory, verify
|
||||
|
||||
|
||||
def publish(root: Path, identifiers: list[str]) -> None:
|
||||
folder = directory(root)
|
||||
folder.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
for row in LOCK["items"]:
|
||||
if identifiers and row["id"] not in identifiers:
|
||||
continue
|
||||
try:
|
||||
verify(root, row["id"])
|
||||
print(row["id"], "already verified", flush=True)
|
||||
continue
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
fd, temporary = tempfile.mkstemp(prefix=".download-", dir=folder)
|
||||
try:
|
||||
digest, count, deadline = hashlib.sha256(), 0, time.monotonic() + 600
|
||||
with (
|
||||
os.fdopen(fd, "wb") as output,
|
||||
urllib.request.urlopen(
|
||||
urllib.request.Request(
|
||||
row["source_url"], headers={"User-Agent": "MissionCoreRelease"}
|
||||
),
|
||||
timeout=30,
|
||||
) as source,
|
||||
):
|
||||
while chunk := source.read(256 * 1024):
|
||||
count += len(chunk)
|
||||
if count > row["bytes"] or time.monotonic() > deadline:
|
||||
raise ValueError("Download size/time limit")
|
||||
digest.update(chunk)
|
||||
output.write(chunk)
|
||||
output.flush()
|
||||
os.fsync(output.fileno())
|
||||
if count != row["bytes"] or digest.hexdigest() != row["sha256"]:
|
||||
raise ValueError("Vendor checksum mismatch")
|
||||
os.replace(temporary, folder / row["filename"])
|
||||
verify(root, row["id"])
|
||||
print(row["id"], count, "verified", flush=True)
|
||||
finally:
|
||||
Path(temporary).unlink(missing_ok=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--fleet-root", required=True, type=Path)
|
||||
parser.add_argument(
|
||||
"--client", action="append", choices=[r["id"] for r in LOCK["items"]], default=[]
|
||||
)
|
||||
arguments = parser.parse_args()
|
||||
publish(arguments.fleet_root, arguments.client)
|
||||
@@ -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.
|
||||
@@ -0,0 +1 @@
|
||||
"""Official NetBird integration; independent from vehicle and Worker authority."""
|
||||
@@ -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}
|
||||
@@ -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
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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"},
|
||||
)
|
||||
@@ -0,0 +1,438 @@
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import APIRouter, FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from k1link.fleet.netbird import assets, client
|
||||
from k1link.web.fleet_api import local_operator
|
||||
from k1link.web.netbird_api import register
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url",
|
||||
[
|
||||
"http://example.com",
|
||||
"https://admin:password@example.com",
|
||||
"https://example.com/api",
|
||||
"https://example.com?key=secret",
|
||||
"https://localhost",
|
||||
"https://127.0.0.1",
|
||||
"https://169.254.169.254",
|
||||
"https://example.com:99999",
|
||||
"--help",
|
||||
],
|
||||
)
|
||||
def test_server_url_rejects_unsafe_or_ambiguous_target(url):
|
||||
with pytest.raises(ValueError):
|
||||
client.server_url(url)
|
||||
|
||||
|
||||
def test_connected_means_selected_daemon_profile_and_private_overlay():
|
||||
status = {
|
||||
"management": {"url": "https://network.example:8443", "connected": True},
|
||||
"signal": {"connected": True},
|
||||
"profileName": "mission-core",
|
||||
"netbirdIp": "10.204.5.7/16",
|
||||
}
|
||||
assert client.project_status(status, "https://network.example:8443")["state"] == "connected"
|
||||
assert client.project_status(status, "https://other.example")["state"] == "other_network"
|
||||
assert (
|
||||
client.project_status(status | {"profileName": "personal"}, "https://network.example:8443")[
|
||||
"state"
|
||||
]
|
||||
== "other_network"
|
||||
)
|
||||
assert (
|
||||
client.project_status(
|
||||
status | {"netbirdIp": "100.80.6.113/16"}, "https://network.example:8443"
|
||||
)["state"]
|
||||
== "address_conflict"
|
||||
)
|
||||
assert (
|
||||
client.project_status(
|
||||
status | {"signal": {"connected": False}}, "https://network.example:8443"
|
||||
)["state"]
|
||||
== "disconnected"
|
||||
)
|
||||
|
||||
|
||||
def test_damaged_local_profile_does_not_stop_mission_core(tmp_path):
|
||||
path = tmp_path / "networks/netbird.json"
|
||||
path.parent.mkdir()
|
||||
path.write_text("damaged")
|
||||
value = client.Client(tmp_path)
|
||||
assert value.server == ""
|
||||
assert value.error
|
||||
|
||||
|
||||
def test_foreign_connected_client_is_never_reconfigured(tmp_path, monkeypatch):
|
||||
value = client.Client(tmp_path)
|
||||
monkeypatch.setattr(client, "executable", lambda: Path("/synthetic/netbird"))
|
||||
monkeypatch.setattr(value, "status", lambda **kw: {"state": "other_network"})
|
||||
monkeypatch.setattr(client.subprocess, "Popen", lambda *a, **kw: pytest.fail("must not spawn"))
|
||||
value.connect("https://our.example")
|
||||
value.worker.join(timeout=2)
|
||||
assert "другую сеть" in value.error
|
||||
assert not value.path.exists()
|
||||
|
||||
|
||||
def test_failed_server_preflight_never_runs_client_or_saves_target(tmp_path, monkeypatch):
|
||||
value = client.Client(tmp_path)
|
||||
monkeypatch.setattr(value, "status", lambda **kw: {"state": "disconnected"})
|
||||
monkeypatch.setattr(client, "preflight", lambda url: (_ for _ in ()).throw(ValueError()))
|
||||
monkeypatch.setattr(client.subprocess, "Popen", lambda *a, **kw: pytest.fail("must not spawn"))
|
||||
value._connect(Path("/synthetic/netbird"), "https://our.example")
|
||||
assert value.error and not value.pending
|
||||
assert not value.path.exists()
|
||||
|
||||
|
||||
def test_local_catalog_rejects_modified_payload_and_symlink(tmp_path, monkeypatch):
|
||||
payload = b"synthetic vendor package"
|
||||
row = dict(
|
||||
id="test",
|
||||
label="Test",
|
||||
filename="test.pkg",
|
||||
bytes=len(payload),
|
||||
sha256=hashlib.sha256(payload).hexdigest(),
|
||||
)
|
||||
monkeypatch.setattr(assets, "LOCK", {"items": [row]})
|
||||
directory = assets.directory(tmp_path)
|
||||
directory.mkdir(parents=True)
|
||||
file = directory / "test.pkg"
|
||||
file.write_bytes(payload)
|
||||
assert assets.verify(tmp_path, "test") == file
|
||||
file.write_bytes(b"X" * len(payload))
|
||||
assert not assets.catalog(tmp_path)["items"][0]["available"]
|
||||
file.unlink()
|
||||
other = tmp_path / "other.pkg"
|
||||
other.write_bytes(payload)
|
||||
file.symlink_to(other)
|
||||
with pytest.raises(ValueError):
|
||||
assets.verify(tmp_path, "test")
|
||||
with pytest.raises(ValueError):
|
||||
assets.verify(tmp_path, "../other.pkg")
|
||||
|
||||
|
||||
def test_network_controls_have_same_local_operator_boundary(tmp_path):
|
||||
app = FastAPI()
|
||||
router = APIRouter(prefix="/api/v1/fleet")
|
||||
register(router, local_operator)
|
||||
app.include_router(router)
|
||||
app.state.fleet = SimpleNamespace(
|
||||
netbird=SimpleNamespace(status=lambda: {"state": "missing_client"}), root=tmp_path
|
||||
)
|
||||
with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 32123)) as web:
|
||||
assert web.get("/api/v1/fleet/netbird").status_code == 200
|
||||
assert (
|
||||
web.post(
|
||||
"/api/v1/fleet/netbird/install", headers={"Origin": "https://unrelated.example"}
|
||||
).status_code
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
web.get("/api/v1/fleet/netbird", headers={"Host": "unrelated.example"}).status_code
|
||||
== 403
|
||||
)
|
||||
assert web.get("/api/v1/fleet/netbird/clients/unknown").status_code == 404
|
||||
|
||||
|
||||
def test_client_does_not_request_dns_routes_remote_shell_or_motion():
|
||||
assert "--disable-dns" in client.SAFE_FLAGS
|
||||
assert "--disable-client-routes" in client.SAFE_FLAGS
|
||||
assert "--disable-server-routes" in client.SAFE_FLAGS
|
||||
assert "--allow-server-ssh=false" in client.SAFE_FLAGS
|
||||
assert "--network-monitor=true" in client.SAFE_FLAGS
|
||||
|
||||
|
||||
def test_preflight_refuses_redirect_before_contacting_destination():
|
||||
handler = client._NoRedirect()
|
||||
request = client.urllib.request.Request(
|
||||
"https://network.example/.well-known/missioncore-network.json"
|
||||
)
|
||||
with pytest.raises(ValueError, match="перенаправляет"):
|
||||
handler.redirect_request(request, None, 302, "Found", {}, "http://127.0.0.1:8000")
|
||||
|
||||
|
||||
@pytest.mark.skipif(client.platform.system() != "Darwin", reason="macOS installer staging")
|
||||
def test_macos_install_stages_verified_package_outside_protected_folder(tmp_path, monkeypatch):
|
||||
payload = b"synthetic signed installer"
|
||||
package = tmp_path / "Downloads" / "NetBird.pkg"
|
||||
package.parent.mkdir()
|
||||
package.write_bytes(payload)
|
||||
monkeypatch.setattr(client, "item", lambda _: {"sha256": hashlib.sha256(payload).hexdigest()})
|
||||
observed = []
|
||||
|
||||
def install(arguments, **kwargs):
|
||||
import re
|
||||
|
||||
assert arguments[:2] == ["/usr/bin/osascript", "-e"]
|
||||
match = re.search(r"(/private/tmp/ndc-netbird-install-[^ /]+/NetBird.pkg)", arguments[2])
|
||||
staged = Path(match[1])
|
||||
assert staged.read_bytes() == payload
|
||||
assert staged.stat().st_mode & 0o077 == 0
|
||||
assert "with administrator privileges" in arguments[2]
|
||||
observed.append(staged)
|
||||
return SimpleNamespace(returncode=0)
|
||||
|
||||
monkeypatch.setattr(client.subprocess, "run", install)
|
||||
value = client.Client(tmp_path)
|
||||
value._install(package)
|
||||
assert not value.error
|
||||
assert len(observed) == 1 and not observed[0].exists()
|
||||
assert package.read_bytes() == payload
|
||||
|
||||
|
||||
def connected_raw():
|
||||
return {
|
||||
"management": {"url": "https://network.example:8443", "connected": True},
|
||||
"signal": {"connected": True},
|
||||
"profileName": client.PROFILE,
|
||||
"daemonVersion": client.VERSION,
|
||||
"netbirdIp": "10.204.5.7/16",
|
||||
}
|
||||
|
||||
|
||||
def test_selected_network_and_daemon_version_are_required():
|
||||
raw = connected_raw()
|
||||
assert (
|
||||
client.project_status(raw, "https://network.example:8443", "10.205.0.0/16")["state"]
|
||||
== "address_conflict"
|
||||
)
|
||||
assert (
|
||||
client.project_status(
|
||||
raw | {"netbirdIp": "10.203.172.2/24"}, "https://network.example:8443"
|
||||
)["state"]
|
||||
== "address_conflict"
|
||||
)
|
||||
assert (
|
||||
client.project_status(raw | {"daemonVersion": "0.81.0"}, "https://network.example:8443")[
|
||||
"state"
|
||||
]
|
||||
== "unsupported_client"
|
||||
)
|
||||
|
||||
|
||||
def test_slow_probe_does_not_block_cancel_and_other_polls(tmp_path, monkeypatch):
|
||||
import threading
|
||||
import time
|
||||
|
||||
value = client.Client(tmp_path)
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
monkeypatch.setattr(client, "executable", lambda: Path("/synthetic/netbird"))
|
||||
|
||||
def invoke(*args):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return SimpleNamespace(returncode=1, stdout="")
|
||||
|
||||
monkeypatch.setattr(client, "invoke", invoke)
|
||||
thread = threading.Thread(target=value.status)
|
||||
thread.start()
|
||||
try:
|
||||
assert entered.wait(1)
|
||||
start = time.monotonic()
|
||||
assert value.status()["state"] == "unavailable"
|
||||
value.cancel()
|
||||
assert time.monotonic() - start < 0.5
|
||||
finally:
|
||||
release.set()
|
||||
thread.join(3)
|
||||
|
||||
|
||||
def test_failed_cli_status_cannot_be_connected(tmp_path, monkeypatch):
|
||||
import json
|
||||
|
||||
value = client.Client(tmp_path)
|
||||
value.server = "https://network.example:8443"
|
||||
monkeypatch.setattr(client, "executable", lambda: Path("/synthetic/netbird"))
|
||||
monkeypatch.setattr(
|
||||
client,
|
||||
"invoke",
|
||||
lambda _, cmd, *args: SimpleNamespace(
|
||||
returncode=0 if cmd == "version" else 1,
|
||||
stdout=client.VERSION if cmd == "version" else json.dumps(connected_raw()),
|
||||
),
|
||||
)
|
||||
assert value.status()["state"] == "unavailable"
|
||||
|
||||
|
||||
def test_cancelled_preflight_cannot_launch_connection(tmp_path, monkeypatch):
|
||||
import threading
|
||||
|
||||
value = client.Client(tmp_path)
|
||||
entered, release = threading.Event(), threading.Event()
|
||||
monkeypatch.setattr(client, "executable", lambda: Path("/synthetic/netbird"))
|
||||
monkeypatch.setattr(value, "status", lambda **kw: {"state": "disconnected"})
|
||||
|
||||
def preflight(url):
|
||||
entered.set()
|
||||
assert release.wait(3)
|
||||
return {"network": "10.204.0.0/16"}
|
||||
|
||||
monkeypatch.setattr(client, "preflight", preflight)
|
||||
monkeypatch.setattr(client.subprocess, "Popen", lambda *a, **kw: pytest.fail("cancelled"))
|
||||
value.connect("https://network.example:8443")
|
||||
assert entered.wait(1)
|
||||
with pytest.raises(ValueError, match="текущей операции"):
|
||||
value.connect("https://network.example:8443")
|
||||
value.cancel()
|
||||
release.set()
|
||||
value.worker.join(3)
|
||||
assert not value.path.exists() and not value.pending
|
||||
assert "отменено" in value.error
|
||||
|
||||
|
||||
def test_repeated_connect_verifies_server_without_restart(tmp_path, monkeypatch):
|
||||
import json
|
||||
|
||||
value = client.Client(tmp_path)
|
||||
value.server = "https://network.example:8443"
|
||||
monkeypatch.setattr(client, "executable", lambda: Path("/synthetic/netbird"))
|
||||
monkeypatch.setattr(value, "status", lambda **kw: {"state": "connected"})
|
||||
monkeypatch.setattr(client, "preflight", lambda url: {"network": "10.204.0.0/16"})
|
||||
monkeypatch.setattr(
|
||||
client.subprocess, "Popen", lambda *a, **kw: pytest.fail("already connected")
|
||||
)
|
||||
value.connect(value.server)
|
||||
value.worker.join(3)
|
||||
assert not value.error and not value.pending
|
||||
assert json.loads(value.path.read_text())["network"] == "10.204.0.0/16"
|
||||
assert "token" not in value.path.read_text()
|
||||
|
||||
|
||||
def test_preflight_requires_verified_access_policy(tmp_path, monkeypatch):
|
||||
import io
|
||||
import json
|
||||
|
||||
url = "https://network.example:8443"
|
||||
receipt = {
|
||||
"schema": "missioncore.netbird-server/v1",
|
||||
"ready": True,
|
||||
"management_url": url,
|
||||
"network": "10.204.0.0/16",
|
||||
"client_version": client.VERSION,
|
||||
}
|
||||
|
||||
def opener(*args):
|
||||
def open_response(*args, **kwargs):
|
||||
stream = io.BytesIO(json.dumps(receipt).encode())
|
||||
stream.url = url + "/.well-known/missioncore-network.json"
|
||||
return stream
|
||||
|
||||
return SimpleNamespace(open=open_response)
|
||||
|
||||
monkeypatch.setattr(client.urllib.request, "build_opener", opener)
|
||||
with pytest.raises(ValueError, match="правила доступа"):
|
||||
client.preflight(url)
|
||||
receipt["access_policy_revision"] = 1
|
||||
with pytest.raises(ValueError, match="без срока действия"):
|
||||
client.preflight(url)
|
||||
receipt.update(
|
||||
session_policy_revision=1,
|
||||
peer_login_expiration_enabled=False,
|
||||
peer_inactivity_expiration_enabled=False,
|
||||
)
|
||||
assert client.preflight(url)["ready"]
|
||||
for key in ("peer_login_expiration_enabled", "peer_inactivity_expiration_enabled"):
|
||||
receipt[key] = True
|
||||
with pytest.raises(ValueError, match="без срока действия"):
|
||||
client.preflight(url)
|
||||
receipt[key] = False
|
||||
|
||||
|
||||
def test_verified_download_keeps_the_checked_descriptor(tmp_path, monkeypatch):
|
||||
payload = b"verified bytes"
|
||||
row = dict(
|
||||
id="test",
|
||||
label="Test",
|
||||
filename="test.pkg",
|
||||
bytes=len(payload),
|
||||
sha256=hashlib.sha256(payload).hexdigest(),
|
||||
)
|
||||
monkeypatch.setattr(assets, "LOCK", {"items": [row]})
|
||||
folder = assets.directory(tmp_path)
|
||||
folder.mkdir(parents=True)
|
||||
file = folder / row["filename"]
|
||||
file.write_bytes(payload)
|
||||
with assets.open_verified(tmp_path, "test") as (stream, _):
|
||||
replacement = folder / "replacement"
|
||||
replacement.write_bytes(b"unchecked bytes")
|
||||
replacement.replace(file)
|
||||
assert stream.read() == payload
|
||||
|
||||
|
||||
@pytest.mark.parametrize("confirmed", [True, False])
|
||||
def test_cli_exit_requires_daemon_confirmation_and_uses_scoped_flags(
|
||||
tmp_path, monkeypatch, confirmed
|
||||
):
|
||||
import io
|
||||
|
||||
value = client.Client(tmp_path)
|
||||
calls = []
|
||||
states = iter(
|
||||
[{"state": "disconnected"}, {"state": "connected" if confirmed else "disconnected"}]
|
||||
)
|
||||
monkeypatch.setattr(value, "status", lambda **kw: next(states, {"state": "disconnected"}))
|
||||
monkeypatch.setattr(client, "preflight", lambda url: {"network": "10.204.0.0/16"})
|
||||
monkeypatch.setattr(client, "VERIFY_SECONDS", 0.01)
|
||||
|
||||
def spawn(args, **kwargs):
|
||||
calls.append(args)
|
||||
return SimpleNamespace(
|
||||
stdout=io.BytesIO(b"Connected\n"), poll=lambda: 0, wait=lambda **kw: 0
|
||||
)
|
||||
|
||||
monkeypatch.setattr(client.subprocess, "Popen", spawn)
|
||||
value._connect(Path("/synthetic/netbird"), "https://network.example:8443")
|
||||
assert len(calls) == 1 and calls[0][:4] == [
|
||||
"/synthetic/netbird",
|
||||
"up",
|
||||
"--profile",
|
||||
client.PROFILE,
|
||||
]
|
||||
assert set(client.SAFE_FLAGS) <= set(calls[0])
|
||||
assert "--no-browser" in calls[0]
|
||||
assert not value.pending and not value.auth_url
|
||||
if confirmed:
|
||||
assert not value.error
|
||||
else:
|
||||
assert "соединение не подтверждено" in value.error
|
||||
|
||||
|
||||
def test_cancel_wins_over_preflight_timeout(tmp_path, monkeypatch):
|
||||
value = client.Client(tmp_path)
|
||||
monkeypatch.setattr(value, "status", lambda **kw: {"state": "disconnected"})
|
||||
|
||||
def preflight(url):
|
||||
value.pending = "connecting"
|
||||
assert value.cancel()["pending"] == "cancelling"
|
||||
raise TimeoutError("connection deadline")
|
||||
|
||||
monkeypatch.setattr(client, "preflight", preflight)
|
||||
value._connect(Path("/synthetic/netbird"), "https://network.example:8443")
|
||||
assert "отменено" in value.error
|
||||
assert not value.path.exists() and not value.pending
|
||||
|
||||
|
||||
def test_onboard_setup_key_stays_out_of_argv_and_persistent_profile(tmp_path, monkeypatch):
|
||||
import io
|
||||
value = client.Client(tmp_path)
|
||||
secret = '00000000-1111-2222-3333-444444444444'
|
||||
observed = []
|
||||
states = iter([{'state': 'disconnected'}, {'state': 'connected'}])
|
||||
monkeypatch.setattr(value, 'status', lambda **kw: next(states))
|
||||
monkeypatch.setattr(client, 'preflight', lambda url: {'network': '10.204.0.0/16'})
|
||||
monkeypatch.setenv('NB_MANAGEMENT_URL', 'https://foreign.example.org')
|
||||
def spawn(argv, **kw):
|
||||
observed.append((argv, kw['env']))
|
||||
return SimpleNamespace(stdout=io.BytesIO(b'Connected\n'), poll=lambda: 0, wait=lambda **kw: 0)
|
||||
monkeypatch.setattr(client.subprocess, 'Popen', spawn)
|
||||
value._connect(Path('/synthetic/netbird'), 'https://network.example.org', secret)
|
||||
assert observed[0][1]['NB_SETUP_KEY'] == secret
|
||||
assert 'NB_MANAGEMENT_URL' not in observed[0][1]
|
||||
assert secret not in ' '.join(observed[0][0])
|
||||
assert secret not in value.path.read_text()
|
||||
assert secret not in str(value._snapshot())
|
||||
@@ -0,0 +1,80 @@
|
||||
import hashlib
|
||||
import json
|
||||
import zipfile
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import APIRouter, FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from k1link.fleet.netbird import backups
|
||||
from k1link.web.netbird_backup_api import register
|
||||
|
||||
|
||||
def archive(path, *, extra=None):
|
||||
files = {name: b"synthetic-private-state" for name in backups.REQUIRED}
|
||||
if extra:
|
||||
files.update(extra)
|
||||
manifest = {
|
||||
"schema": "missioncore.netbird-transfer/v1",
|
||||
"domain": "network.example",
|
||||
"management_url": "https://network.example:8443",
|
||||
"identity_sha256": "a" * 64,
|
||||
"files": {
|
||||
name: {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
|
||||
for name, data in files.items()
|
||||
},
|
||||
}
|
||||
with zipfile.ZipFile(path, "w") as output:
|
||||
output.writestr("manifest.json", json.dumps(manifest))
|
||||
for name, data in files.items():
|
||||
output.writestr(name, data)
|
||||
path.chmod(0o600)
|
||||
return path
|
||||
|
||||
|
||||
def test_private_backup_import_deduplicates_and_export_checks_integrity(tmp_path):
|
||||
root = tmp_path / "fleet"
|
||||
source = archive(tmp_path / "input.zip")
|
||||
original = source.read_bytes()
|
||||
row = backups.admit(root, source)
|
||||
assert not source.exists()
|
||||
assert "synthetic-private-state" not in json.dumps(row)
|
||||
saved = backups.download(root, row["id"])
|
||||
assert saved.read_bytes() == original
|
||||
assert saved.stat().st_mode & 0o077 == 0
|
||||
source.write_bytes(original)
|
||||
assert backups.admit(root, source) == row
|
||||
assert len(backups.catalog(root)["items"]) == 1
|
||||
saved.write_bytes(b"x" * len(original))
|
||||
with pytest.raises(zipfile.BadZipFile):
|
||||
backups.download(root, row["id"])
|
||||
|
||||
|
||||
def test_invalid_archive_cannot_write_paths_or_replace_previous_backup(tmp_path):
|
||||
root = tmp_path / "fleet"
|
||||
safe = backups.admit(root, archive(tmp_path / "safe.zip"))
|
||||
unsafe = archive(tmp_path / "unsafe.zip", extra={"../../outside": b"no"})
|
||||
with pytest.raises(ValueError):
|
||||
backups.admit(root, unsafe)
|
||||
assert not (tmp_path / "outside").exists()
|
||||
assert backups.catalog(root)["items"] == [safe]
|
||||
|
||||
|
||||
def test_api_import_export_is_binary_and_does_not_return_secrets(tmp_path):
|
||||
app = FastAPI()
|
||||
router = APIRouter()
|
||||
register(router, lambda: SimpleNamespace(root=tmp_path / "fleet"))
|
||||
app.include_router(router)
|
||||
raw = archive(tmp_path / "source.zip").read_bytes()
|
||||
with TestClient(app) as client:
|
||||
response = client.post("/netbird/backups", content=raw)
|
||||
assert response.status_code == 200
|
||||
row = response.json()
|
||||
assert "synthetic-private-state" not in response.text
|
||||
assert client.get("/netbird/backups").json()["items"] == [row]
|
||||
downloaded = client.get(f"/netbird/backups/{row['id']}/download")
|
||||
assert downloaded.content == raw
|
||||
assert downloaded.headers["cache-control"] == "no-store"
|
||||
assert client.post("/netbird/backups", content=b"not an archive").status_code == 409
|
||||
assert not list((tmp_path / "fleet/networks/netbird-backups").glob(".upload-*"))
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Package preparation admission uses synthetic OS/dpkg state; no host mutation."""
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def installer(tmp_path, monkeypatch):
|
||||
source = Path(__file__).parents[2] / 'apps/node-agent/packaging/netbird_install.py'
|
||||
spec = importlib.util.spec_from_file_location('node_netbird_install', source)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
system = tmp_path / 'os-release'
|
||||
system.write_text('ID=ubuntu\nVERSION_ID="24.04"\n')
|
||||
monkeypatch.setattr(module, 'Path', lambda name: system if name == '/etc/os-release' else Path(name))
|
||||
monkeypatch.setattr(module.os, 'uname', lambda: SimpleNamespace(machine='x86_64'))
|
||||
module.ROOT = tmp_path
|
||||
payload = b'synthetic pinned Debian payload'
|
||||
(tmp_path / 'netbird.deb').write_bytes(payload)
|
||||
lock = {'version': '0.82.0', 'items': [{'id': 'linux-amd64', 'filename': 'netbird.deb', 'bytes': len(payload), 'sha256': hashlib.sha256(payload).hexdigest()}]}
|
||||
(tmp_path / 'clients.lock.json').write_text(json.dumps(lock))
|
||||
return module
|
||||
|
||||
|
||||
def test_existing_other_version_is_preserved(installer, monkeypatch):
|
||||
calls = []
|
||||
def run(argv, **kwargs):
|
||||
calls.append(argv)
|
||||
return SimpleNamespace(returncode=0, stdout='0.99.0')
|
||||
monkeypatch.setattr(installer.subprocess, 'run', run)
|
||||
with pytest.raises(ValueError, match='другая версия'):
|
||||
installer.install()
|
||||
assert len(calls) == 1 and calls[0][0] == '/usr/bin/dpkg-query'
|
||||
|
||||
|
||||
def test_corrupted_payload_never_reaches_package_manager(installer, monkeypatch):
|
||||
(installer.ROOT / 'netbird.deb').write_bytes(b'corrupt')
|
||||
monkeypatch.setattr(installer.subprocess, 'run', lambda *a, **kw: pytest.fail('OS mutation'))
|
||||
with pytest.raises(ValueError, match='повреждён'):
|
||||
installer.install()
|
||||
|
||||
|
||||
def test_first_install_and_repeat_preserve_credentials(installer, monkeypatch):
|
||||
calls = []
|
||||
installed = False
|
||||
def run(argv, **kwargs):
|
||||
nonlocal installed
|
||||
calls.append(argv)
|
||||
if argv[0] == '/usr/bin/dpkg-query':
|
||||
return SimpleNamespace(returncode=0 if installed else 1, stdout='0.82.0\tinstalled' if installed else '')
|
||||
if argv[0] == '/usr/bin/apt-get':
|
||||
installed = True
|
||||
return SimpleNamespace(returncode=0, stdout='')
|
||||
monkeypatch.setattr(installer.subprocess, 'run', run)
|
||||
installer.install()
|
||||
installer.install()
|
||||
assert sum(c[0] == '/usr/bin/apt-get' for c in calls) == 1
|
||||
assert all('up' not in c and 'down' not in c and 'login' not in c for c in calls)
|
||||
assert any('--no-remove' in c for c in calls)
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Exercise the operator HTTP contract, including the third network provider."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from fastapi import APIRouter, FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from k1link.web.fleet_api import local_operator
|
||||
from k1link.web.fleet_network_api import register
|
||||
|
||||
|
||||
def test_netbird_selection_reaches_admission_without_weakening_http_boundary():
|
||||
calls = []
|
||||
|
||||
def start(*args):
|
||||
calls.append(args)
|
||||
raise ValueError("Отключите управление перед изменением сети борта.")
|
||||
|
||||
app = FastAPI()
|
||||
router = APIRouter(prefix="/api/v1/fleet")
|
||||
register(router, local_operator)
|
||||
app.include_router(router)
|
||||
app.state.fleet = SimpleNamespace(network_profiles=SimpleNamespace(start=start))
|
||||
body = {"provider": "netbird", "profile_id": None, "expected_revision": 5}
|
||||
with TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 32123)) as web:
|
||||
path = "/api/v1/fleet/board/network-profile"
|
||||
denied = web.put(path, json=body, headers={"Origin": "https://unrelated.example"})
|
||||
assert denied.status_code == 403 and not calls
|
||||
response = web.put(path, json=body)
|
||||
assert response.status_code == 409
|
||||
assert "Отключите управление" in response.json()["detail"]
|
||||
assert calls == [("board", "netbird", None, 5)]
|
||||
assert web.put(path, json=body | {"provider": "unknown"}).status_code == 422
|
||||
assert web.put(path, json=body | {"expected_revision": "5"}).status_code == 422
|
||||
assert len(calls) == 1
|
||||
@@ -0,0 +1,43 @@
|
||||
"""A phase reported over the previous route cannot confirm the candidate route."""
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.fleet.network_profiles import NetworkProfiles
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phase", ["verifying", "applied"])
|
||||
def test_wait_requires_phase_and_candidate_endpoint(tmp_path, monkeypatch, phase):
|
||||
fleet = SimpleNamespace(root=tmp_path, trust=SimpleNamespace(core_id="core_test"),
|
||||
stop=threading.Event())
|
||||
profiles = NetworkProfiles(fleet)
|
||||
target = "https://10.203.45.2:8782"
|
||||
profiles.latest["node"] = {"endpoint": "https://100.64.2.3:8782",
|
||||
"value": {"operation_id": "op", "phase": phase}}
|
||||
waits = []
|
||||
|
||||
def receive_candidate(*, timeout):
|
||||
waits.append(timeout)
|
||||
profiles.latest["node"] = {"endpoint": target,
|
||||
"value": {"operation_id": "op", "phase": phase}}
|
||||
|
||||
monkeypatch.setattr(profiles.changed, "wait", receive_candidate)
|
||||
accepted = profiles.wait("node", "op", phase, endpoint=target)
|
||||
assert len(waits) == 1
|
||||
assert accepted["endpoint"] == target
|
||||
|
||||
|
||||
def test_wrong_route_never_confirms_and_rollback_remains_terminal(tmp_path, monkeypatch):
|
||||
fleet = SimpleNamespace(root=tmp_path, trust=SimpleNamespace(core_id="core_test"),
|
||||
stop=threading.Event())
|
||||
profiles = NetworkProfiles(fleet)
|
||||
profiles.latest["node"] = {"endpoint": "https://100.64.2.3:8782",
|
||||
"value": {"operation_id": "op", "phase": "verifying"}}
|
||||
|
||||
def receive_rollback(*, timeout):
|
||||
profiles.latest["node"]["value"].update(phase="rolled_back", error="rolled back")
|
||||
|
||||
monkeypatch.setattr(profiles.changed, "wait", receive_rollback)
|
||||
with pytest.raises(ValueError, match="rolled back"):
|
||||
profiles.wait("node", "op", "verifying", endpoint="https://10.203.45.2:8782")
|
||||
@@ -146,3 +146,66 @@ def test_core_accepts_more_than_fifty_routes(monkeypatch):
|
||||
config['role']='node';config['address']='10.203.45.83'
|
||||
with pytest.raises(ValueError, match='only its Core'):
|
||||
module.validate(config)
|
||||
|
||||
|
||||
def test_failed_reimport_preserves_new_revocation_and_other_profile_changes(tmp_path, monkeypatch):
|
||||
import copy
|
||||
fleet = SimpleNamespace(root=tmp_path, trust=SimpleNamespace(core_id='core_test'))
|
||||
profiles = NetworkProfiles(fleet)
|
||||
row = {**document(), 'name': 'Fleet', 'state': 'ready',
|
||||
'status': {'peers': [{'id': 'node_1', 'kind': 'node'}]}}
|
||||
identity = row['server_id']
|
||||
other = 'wg_' + '2' * 32
|
||||
profiles.profiles[identity] = copy.deepcopy(row)
|
||||
profiles.profiles[other] = {**row, 'server_id': other, 'name': 'Before'}
|
||||
def fail(*args):
|
||||
profiles.profiles[other]['name'] = 'Concurrent change'
|
||||
profiles.revoke_node('node_1')
|
||||
profiles.profiles[identity]['endpoint'] = 'https://failed.example:19444'
|
||||
raise ValueError('retry')
|
||||
monkeypatch.setattr(profiles, '_import_file', fail)
|
||||
with pytest.raises(ValueError, match='retry'):
|
||||
profiles.import_file(json.dumps(document()))
|
||||
assert profiles.profiles[identity]['endpoint'] == row['endpoint']
|
||||
assert profiles.profiles[identity]['revocations'] == ['node_1']
|
||||
assert profiles.profiles[other]['name'] == 'Concurrent change'
|
||||
|
||||
|
||||
def test_netbird_offer_requires_same_server_and_narrow_exact_peers(tmp_path):
|
||||
operator = dict(state='connected', server_url='https://network.example.org', network='10.204.0.0/16', address='10.204.1.2')
|
||||
listened, saved = [], []
|
||||
fleet = SimpleNamespace(root=tmp_path, trust=SimpleNamespace(core_id='core_test'),
|
||||
netbird=SimpleNamespace(observation=lambda: operator.copy()),
|
||||
listen=listened.append, save=lambda row: saved.append(row.copy()))
|
||||
manager = NetworkProfiles(fleet)
|
||||
row = {'node_id': 'board'}
|
||||
board = {**operator, 'address': '10.204.1.3'}
|
||||
assert manager.netbird_offer(row, {'netbird': {**board, 'server_url': 'https://other.example.org'}}) is None
|
||||
assert manager.netbird_offer(row, {'netbird': {**board, 'state': 'unavailable'}}) is None
|
||||
assert not listened and not saved
|
||||
offer = manager.netbird_offer(row, {'netbird': board})
|
||||
assert offer['config']['allowed_ips'] == ['10.204.1.2/32']
|
||||
assert row['network_paths'] == {'netbird': {'core': '10.204.1.2', 'node': '10.204.1.3'}}
|
||||
manager.netbird_offer(row, {'netbird': board})
|
||||
assert len(saved) == 1
|
||||
|
||||
|
||||
def test_local_netbird_request_uses_control_guard_and_is_not_replayed(tmp_path, monkeypatch):
|
||||
fleet = SimpleNamespace(root=tmp_path, trust=SimpleNamespace(core_id='core_test'))
|
||||
manager = NetworkProfiles(fleet)
|
||||
row = {'id': 'vehicle', 'node_id': 'board'}
|
||||
calls = []
|
||||
def start(*args):
|
||||
calls.append(args)
|
||||
raise ValueError('Отключите управление перед изменением сети борта.')
|
||||
monkeypatch.setattr(manager, 'start', start)
|
||||
request = {'id': '1'*32, 'provider': 'netbird', 'revision': 3, 'expires_at': int(time.time()) + 100}
|
||||
heartbeat = {'network_profile': {'provider': 'tailscale', 'phase': 'applied', 'revision': 3, 'local_request': request}}
|
||||
first = manager.heartbeat(row, heartbeat)
|
||||
second = manager.heartbeat(row, heartbeat)
|
||||
assert first == second and 'Отключите управление' in first['network_request_result']['error']
|
||||
assert calls == [('vehicle', 'netbird', 'netbird', 3)]
|
||||
request['id'] = '2'*32
|
||||
request['expires_at'] = int(time.time()) - 1
|
||||
assert not manager.heartbeat(row, heartbeat)
|
||||
assert len(calls) == 1
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Recovery of local listeners must not choose a different board provider."""
|
||||
import copy
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from k1link.fleet import recovery
|
||||
from k1link.fleet.registry import FleetRegistry
|
||||
|
||||
|
||||
def saved_board():
|
||||
return {
|
||||
"id": "vehicle", "enrollment": "paired", "core_address": "10.204.1.2",
|
||||
"network_active": "netbird",
|
||||
"network_paths": {
|
||||
"netbird": {"core": "10.204.1.2", "node": "10.204.1.3"},
|
||||
"wg_previous": {"core": "10.203.7.2", "node": "10.203.7.3"},
|
||||
},
|
||||
"binding": {"binding_id": "unchanged", "endpoint": "https://10.204.1.2:8782"},
|
||||
"inventory": {"networks": [
|
||||
{"up": True, "addresses": ["192.168.3.4/24", "100.64.20.4/32"]},
|
||||
{"up": False, "addresses": ["100.64.21.4/32"]},
|
||||
]},
|
||||
}
|
||||
|
||||
|
||||
def routing(monkeypatch, source):
|
||||
calls = []
|
||||
|
||||
class Route:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
pass
|
||||
|
||||
def connect(self, destination):
|
||||
calls.append(destination)
|
||||
if isinstance(source, Exception):
|
||||
raise source
|
||||
|
||||
def getsockname(self):
|
||||
return source, 30000
|
||||
|
||||
def send(self, *args):
|
||||
pytest.fail("Listener recovery must not send packets")
|
||||
|
||||
def socket(family, kind):
|
||||
assert family == recovery.socket.AF_INET
|
||||
assert kind == recovery.socket.SOCK_DGRAM
|
||||
return Route()
|
||||
|
||||
monkeypatch.setattr(recovery.socket, "socket", socket)
|
||||
return calls
|
||||
|
||||
|
||||
def test_restart_restores_return_listener_without_selecting_tailscale(monkeypatch):
|
||||
calls = routing(monkeypatch, "100.64.20.5")
|
||||
row = saved_board()
|
||||
before = copy.deepcopy(row)
|
||||
assert recovery.listener_addresses(row) == ["10.203.7.2", "10.204.1.2", "100.64.20.5"]
|
||||
assert calls == [("100.64.20.4", 8781)]
|
||||
assert recovery.node_addresses(row) == ["10.204.1.3"]
|
||||
assert row == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize("source", ["192.168.3.5", "10.204.1.2", OSError("No route")])
|
||||
def test_missing_tailnet_does_not_open_underlay_or_other_vpn_listener(monkeypatch, source):
|
||||
routing(monkeypatch, source)
|
||||
assert recovery.listener_addresses(saved_board()) == ["10.203.7.2", "10.204.1.2"]
|
||||
|
||||
|
||||
def test_listener_uses_current_route_instead_of_a_cached_host_address(monkeypatch):
|
||||
routing(monkeypatch, "100.64.20.9")
|
||||
assert "100.64.20.9" in recovery.listener_addresses(saved_board())
|
||||
row = saved_board()
|
||||
row["inventory"] = {}
|
||||
assert recovery.listener_addresses(row) == ["10.203.7.2", "10.204.1.2"]
|
||||
|
||||
|
||||
def test_reconcile_retries_alternative_listener_after_address_returns(monkeypatch):
|
||||
routing(monkeypatch, "100.64.20.5")
|
||||
stop = threading.Event()
|
||||
row = saved_board()
|
||||
revoked = {**saved_board(), "id": "revoked", "enrollment": "revoked",
|
||||
"core_address": "10.203.8.2"}
|
||||
fleet = SimpleNamespace(
|
||||
stop=stop, lock=threading.RLock(), routers=SimpleNamespace(prune=lambda: None),
|
||||
network_profiles=SimpleNamespace(reconcile=lambda: None),
|
||||
rows=lambda: [row, revoked], listeners={}, previews={},
|
||||
)
|
||||
attempts = []
|
||||
|
||||
def listen(address):
|
||||
attempts.append(address)
|
||||
if address == "100.64.20.5" and attempts.count(address) == 1:
|
||||
raise OSError("Interface not ready")
|
||||
fleet.listeners[address] = SimpleNamespace(refresh_at=float("inf"))
|
||||
|
||||
fleet.listen = listen
|
||||
ticks = []
|
||||
|
||||
def wait(_):
|
||||
ticks.append(1)
|
||||
if len(ticks) == 2:
|
||||
stop.set()
|
||||
|
||||
monkeypatch.setattr(stop, "wait", wait)
|
||||
FleetRegistry.reconcile(fleet)
|
||||
assert attempts.count("100.64.20.5") == 2
|
||||
assert "100.64.20.5" in fleet.listeners
|
||||
assert "10.203.7.2" in fleet.listeners
|
||||
assert "10.203.8.2" not in fleet.listeners
|
||||
assert row["network_active"] == "netbird"
|
||||
|
||||
|
||||
def test_start_keeps_fallback_listener_when_primary_vps_is_absent(monkeypatch):
|
||||
routing(monkeypatch, "100.64.20.5")
|
||||
monkeypatch.setattr(threading, "Thread", lambda **kw: SimpleNamespace(start=lambda: None))
|
||||
attempts = []
|
||||
|
||||
def listen(address):
|
||||
attempts.append(address)
|
||||
if address == "10.204.1.2":
|
||||
raise OSError("Primary address absent")
|
||||
|
||||
fleet = SimpleNamespace(lock=threading.RLock(), rows=lambda: [saved_board()],
|
||||
network_profiles=SimpleNamespace(profiles={}), listen=listen,
|
||||
reconcile=lambda: None)
|
||||
FleetRegistry.start(fleet)
|
||||
assert set(attempts) == {"10.204.1.2", "10.203.7.2", "100.64.20.5"}
|
||||
Reference in New Issue
Block a user