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

This commit is contained in:
DCCONSTRUCTIONS
2026-11-04 00:42:25 +03:00
parent 1e77b198cb
commit 2c0a10b687
47 changed files with 2721 additions and 82 deletions
+161
View File
@@ -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.
+1
View File
@@ -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)