feat(network): verify selected uplinks, roll back failures and manage NetBird policy

This commit is contained in:
DCCONSTRUCTIONS
2026-11-21 20:58:26 +03:00
parent a50d638ced
commit 43d4916331
63 changed files with 6743 additions and 12 deletions
@@ -257,6 +257,10 @@ func (p *Pairing) applyNetworkCommand(raw json.RawMessage) {
return
}
n := p.network
if (c.Action == "prepare" || c.Action == "apply") && p.uplink.pending() {
p.mu.Unlock()
return
}
if c.Action == "abort" && n.OperationID == c.ID {
p.mu.Unlock()
p.rollbackNetwork()
+1
View File
@@ -52,6 +52,7 @@ type Pairing struct {
DeviceEnrollment *DeviceEnrollment
networkCall func(string, string, map[string]any) (map[string]json.RawMessage, error)
network *NetworkProfile
uplink *uplinkController
mu sync.Mutex
path string
store *Store
@@ -152,6 +152,7 @@ func (p *Pairing) remoteHandler() http.Handler {
}
func (p *Pairing) Run(ctx context.Context) {
p.uplink = newUplink(ctx)
go monitorNetBird(ctx)
go p.networkWatch(ctx)
go p.channel(ctx)
@@ -355,6 +356,13 @@ func (p *Pairing) channel(ctx context.Context) {
payload["power"] = p.Power.Snapshot(ctx)
}
payload["network_profile"] = p.networkSnapshot()
payload["uplink"] = p.uplink.snapshot()
if p.uplink.pending() {
// A new TLS/TCP connection proves reachability after route selection.
for _, client := range p.clients {
client.CloseIdleConnections()
}
}
payload["core_endpoint"] = binding.Endpoint
payload["endpoint_revision"] = binding.EndpointRevision
if p.Sensors != nil {
@@ -377,9 +385,11 @@ func (p *Pairing) channel(ctx context.Context) {
payload["routers"] = p.Routers.Snapshot()
}
result, status, e := p.sendHeartbeat(ctx, *binding, payload)
received := time.Now()
var networkRequestResult json.RawMessage
var netbirdOffer json.RawMessage
var networkChange json.RawMessage
var uplinkChange, uplinkAck json.RawMessage
var configurationChange json.RawMessage
var routerCommands json.RawMessage
p.mu.Lock()
@@ -391,6 +401,7 @@ func (p *Pairing) channel(ctx context.Context) {
networkRequestResult = result["network_request_result"]
netbirdOffer = result["netbird_offer"]
networkChange = result["network_profile_change"]
uplinkChange, uplinkAck = result["uplink_change"], result["uplink_ack"]
routerCommands = result["router_commands"]
if p.RoverConfiguration != nil {
configurationChange = result["rover_configuration_change"]
@@ -451,6 +462,9 @@ func (p *Pairing) channel(ctx context.Context) {
p.acceptNetworkRequestResult(networkRequestResult)
p.acceptNetBirdOffer(netbirdOffer)
p.applyNetworkCommand(networkChange)
if e == nil && status == http.StatusOK {
p.acceptUplink(*binding, instance, uplinkChange, uplinkAck, received)
}
p.applyRouterCommands(routerCommands)
// Durable preference IO must not hold the pairing/control mutex.
if p.RoverConfiguration != nil {
+212
View File
@@ -0,0 +1,212 @@
package node
// Physical uplinks are independent of the private-network provider. The root
// adapter owns the timed rollback even if this process or Core disappears.
import (
"bufio"
"context"
"encoding/json"
"errors"
"net"
"net/url"
"sync"
"time"
)
type uplinkState map[string]any
type uplinkWork struct {
body map[string]any
id string
lease map[string]any
received time.Time
}
type uplinkController struct {
mu sync.Mutex
value uplinkState
observed time.Time
busy bool
receipt map[string]any
commands chan uplinkWork
call func(map[string]any) (uplinkState, error)
}
func uplinkHelper(body map[string]any) (uplinkState, error) {
c, err := net.DialTimeout("unix", "/run/mission-core-uplink/control.sock", time.Second)
if err != nil {
return nil, errors.New("Для выбора подключения обновите Node на борту.")
}
defer c.Close()
_ = c.SetDeadline(time.Now().Add(35 * time.Second))
if err = json.NewEncoder(c).Encode(body); err != nil {
return nil, err
}
raw, err := bufio.NewReaderSize(c, 32769).ReadSlice('\n')
var result struct {
OK bool `json:"ok"`
Result uplinkState `json:"result"`
Error string `json:"error"`
}
if err != nil || len(raw) > 32768 || json.Unmarshal(raw, &result) != nil {
return nil, errors.New("Нет подтверждения сетевой службы.")
}
if !result.OK {
return nil, errors.New(result.Error)
}
return result.Result, nil
}
func newUplink(ctx context.Context) *uplinkController {
u := &uplinkController{commands: make(chan uplinkWork, 1), call: uplinkHelper}
go u.run(ctx)
return u
}
func (u *uplinkController) run(ctx context.Context) {
timer := time.NewTicker(5 * time.Second)
defer timer.Stop()
work := uplinkWork{body: map[string]any{"action": "status"}}
for {
value, err := u.execute(work)
u.mu.Lock()
if err == nil {
u.value = value
u.observed = time.Now()
} else if work.id != "" {
u.receipt = map[string]any{"id": work.id, "phase": "failed", "message": err.Error()}
} else {
u.value = uplinkState{"supported": false, "reason": "Сетевая служба недоступна. Обновите Node или проверьте состояние борта.", "candidates": []any{}, "operation": u.value["operation"]}
u.observed = time.Now()
}
u.busy = false
u.mu.Unlock()
select {
case <-ctx.Done():
return
case work = <-u.commands:
u.mu.Lock()
u.busy = true
u.mu.Unlock()
case <-timer.C:
work = uplinkWork{body: map[string]any{"action": "status"}}
}
}
}
// The authenticated reply carrying a command is itself a Core lease. Renew it
// in the same serialized work item before staging; a command must not suppress
// the heartbeat whose freshness the helper requires. Never renew queued old data.
func (u *uplinkController) execute(work uplinkWork) (uplinkState, error) {
fresh := func() bool { return work.received.IsZero() || time.Since(work.received) <= 20*time.Second }
if !fresh() {
return nil, errors.New("Ответ Core устарел до выполнения команды. Повторите выбор подключения.")
}
if work.lease != nil {
if _, err := u.call(work.lease); err != nil {
return nil, err
}
if !fresh() {
return nil, errors.New("Подтверждение Core устарело. Подключение не изменено.")
}
}
return u.call(work.body)
}
func (u *uplinkController) snapshot() uplinkState {
if u == nil {
return uplinkState{"supported": false, "candidates": []any{}}
}
u.mu.Lock()
defer u.mu.Unlock()
result := uplinkState{}
for k, v := range u.value {
if k != "diagnostic" { // Local DEV evidence must not increase the heartbeat payload.
result[k] = v
}
}
if time.Since(u.observed) > 20*time.Second {
result["supported"] = false
result["reason"] = "Нет свежего подтверждения сетевой службы."
}
result["receipt"] = u.receipt
return result
}
func (u *uplinkController) pending() bool {
if u == nil {
return false
}
u.mu.Lock()
defer u.mu.Unlock()
op, _ := u.value["operation"].(map[string]any)
return u.busy || len(u.commands) > 0 || op["phase"] == "applying" || op["phase"] == "verifying" || op["phase"] == "rolling_back" || op["phase"] == "recovering"
}
func (u *uplinkController) submit(body map[string]any, id string) {
u.submitCore(body, id, nil, time.Time{})
}
func (u *uplinkController) submitCore(body map[string]any, id string, lease map[string]any, received time.Time) {
u.mu.Lock()
defer u.mu.Unlock()
if u.busy {
return
}
select {
case u.commands <- uplinkWork{body: body, id: id, lease: lease, received: received}:
u.busy = true
u.receipt = nil
default:
}
}
func (p *Pairing) acceptUplink(binding CoreBinding, instance string, raw, ack json.RawMessage, received time.Time) {
if p.uplink == nil {
return
}
p.mu.Lock()
valid := 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
_ = p.loadNetworkLocked()
overlayBusy := p.network != nil && p.network.Pending != nil
provider := ""
if p.network != nil {
provider = p.network.Provider
}
p.mu.Unlock()
if !valid {
return
}
scope := binding.BindingID + ":" + instance
endpoint, err := url.Parse(binding.Endpoint)
if err != nil || net.ParseIP(endpoint.Hostname()) == nil {
return
}
lease := map[string]any{"action": "heartbeat", "binding": scope, "provider": provider, "peer": endpoint.Hostname()}
var confirm struct {
ID string `json:"id"`
Nonce string `json:"nonce"`
}
if json.Unmarshal(ack, &confirm) == nil && networkOperationID.MatchString(confirm.ID) && networkOperationID.MatchString(confirm.Nonce) {
p.uplink.submitCore(map[string]any{"action": "confirm", "id": confirm.ID, "binding": scope, "nonce": confirm.Nonce}, confirm.ID, lease, received)
return
}
var command struct {
ID string `json:"id"`
Runtime string `json:"runtime"`
Target string `json:"target"`
Revision json.RawMessage `json:"revision"`
ExpiresAt int64 `json:"expires_at"`
Kind string `json:"kind"`
Enabled *bool `json:"enabled"`
}
if overlayBusy || json.Unmarshal(raw, &command) != nil || !networkOperationID.MatchString(command.ID) || command.Runtime != instance || command.ExpiresAt <= time.Now().Unix() || command.ExpiresAt > time.Now().Unix()+60 {
// Only this authenticated response path renews the onboard Core lease.
p.uplink.submitCore(lease, "", nil, received)
return
}
if command.Kind == "fallback" {
var revision int
if command.Enabled == nil || json.Unmarshal(command.Revision, &revision) != nil || revision < 0 {
return
}
p.uplink.submitCore(map[string]any{"action": "fallback", "id": command.ID, "binding": scope, "enabled": *command.Enabled, "revision": revision, "expires_at": command.ExpiresAt}, command.ID, lease, received)
return
}
var revision string
if command.Kind != "" || json.Unmarshal(command.Revision, &revision) != nil {
return
}
p.uplink.submitCore(map[string]any{"action": "stage", "id": command.ID, "binding": scope, "target": command.Target, "revision": revision, "expires_at": command.ExpiresAt}, command.ID, lease, received)
}
@@ -0,0 +1,94 @@
package node
import (
"encoding/json"
"errors"
"reflect"
"testing"
"time"
)
// Reproduce a command delivered after an interrupted heartbeat stream. The old
// worker sent stage alone, so the helper rejected a fresh command's stale lease.
func TestUplinkFreshReplyRenewsLeaseBeforeEveryCommand(t *testing.T) {
for _, kind := range []string{"stage", "fallback", "confirm"} {
t.Run(kind, func(t *testing.T) {
u := &uplinkController{commands: make(chan uplinkWork, 1)}
binding := CoreBinding{BindingID: "binding", Endpoint: "https://10.42.0.1:8782"}
p := &Pairing{uplink: u, network: &NetworkProfile{BindingID: "binding", Phase: "applied", Provider: "netbird"}, state: PairState{Phase: "paired", Binding: &binding}}
command := map[string]any{"id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "runtime": "runtime", "target": "target", "revision": "rev", "expires_at": time.Now().Unix() + 30}
var raw, ack json.RawMessage
switch kind {
case "fallback":
command["kind"] = "fallback"
command["revision"] = 2
command["enabled"] = false
case "confirm":
ack, _ = json.Marshal(map[string]any{"id": command["id"], "nonce": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"})
}
raw, _ = json.Marshal(command)
p.acceptUplink(binding, "runtime", raw, ack, time.Now())
work := <-u.commands
var actions []string
renewed := false
u.call = func(body map[string]any) (uplinkState, error) {
actions = append(actions, body["action"].(string))
if body["action"] == "heartbeat" {
if body["binding"] != "binding:runtime" || body["peer"] != "10.42.0.1" || body["provider"] != "netbird" {
t.Fatal(body)
}
renewed = true
} else if !renewed {
return nil, errors.New("stale helper lease")
}
return uplinkState{"supported": true}, nil
}
if _, err := u.execute(work); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(actions, []string{"heartbeat", kind}) {
t.Fatal(actions)
}
})
}
}
func TestUplinkOldQueuedReplyCannotRefreshLeaseOrSwitch(t *testing.T) {
for _, command := range []bool{false, true} {
called := false
u := &uplinkController{call: func(map[string]any) (uplinkState, error) { called = true; return nil, nil }}
work := uplinkWork{body: map[string]any{"action": "heartbeat"}, received: time.Now().Add(-21 * time.Second)}
if command {
work.id = "id"
work.lease = work.body
work.body = map[string]any{"action": "stage"}
}
if _, err := u.execute(work); err == nil || called {
t.Fatalf("stale reply had authority: %v %v", err, called)
}
}
}
func TestUplinkFailedLeaseRefreshCannotStage(t *testing.T) {
calls := 0
u := &uplinkController{call: func(body map[string]any) (uplinkState, error) { calls++; return nil, errors.New("helper unavailable") }}
_, err := u.execute(uplinkWork{body: map[string]any{"action": "stage"}, lease: map[string]any{"action": "heartbeat"}, received: time.Now()})
if err == nil || calls != 1 {
t.Fatalf("stage after failed refresh: %v %d", err, calls)
}
}
func TestUplinkPreviousEndpointReplyCannotRenewLease(t *testing.T) {
u := &uplinkController{commands: make(chan uplinkWork, 1)}
binding := CoreBinding{BindingID: "binding", Endpoint: "https://10.42.0.1:8782", EndpointRevision: 2}
p := &Pairing{uplink: u, state: PairState{Phase: "paired", Binding: &binding}}
previous := binding
previous.Endpoint = "https://10.42.0.2:8782"
p.acceptUplink(previous, "runtime", nil, nil, time.Now())
previous = binding
previous.EndpointRevision = 1
p.acceptUplink(previous, "runtime", nil, nil, time.Now())
if len(u.commands) != 0 {
t.Fatal("old endpoint response renewed the current lease")
}
}
@@ -0,0 +1,88 @@
package node
import (
"context"
"encoding/json"
"testing"
"time"
)
func TestUplinkUnavailableAndPendingAuthority(t *testing.T) {
var none *uplinkController
if none.pending() || none.snapshot()["supported"] != false {
t.Fatal("missing helper has authority")
}
u := &uplinkController{value: uplinkState{"supported": true, "operation": map[string]any{"phase": "verifying"}}, observed: time.Now().Add(-time.Minute)}
if u.snapshot()["supported"] != false || !u.pending() {
t.Fatal("stale snapshot or rollback guard lost")
}
}
func TestUplinkIPCWorkNeverBlocksHeartbeatAndKeepsReceipt(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
calls := make(chan map[string]any, 4)
u := &uplinkController{commands: make(chan uplinkWork, 1), call: func(body map[string]any) (uplinkState, error) {
calls <- body
return uplinkState{"supported": true}, nil
}}
go u.run(ctx)
<-calls
u.submit(map[string]any{"action": "stage"}, "id")
select {
case got := <-calls:
if got["action"] != "stage" {
t.Fatal(got)
}
case <-time.After(time.Second):
t.Fatal("no work")
}
}
func TestUplinkCommandRequiresBindingRuntimeAndFreshExpiry(t *testing.T) {
u := &uplinkController{commands: make(chan uplinkWork, 1)}
p := &Pairing{uplink: u, network: &NetworkProfile{BindingID: "binding", Phase: "applied", Provider: "netbird"}, state: PairState{Phase: "paired", Binding: &CoreBinding{BindingID: "binding", Endpoint: "https://10.42.0.1:8782"}}}
command := map[string]any{"id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "runtime": "wrong", "target": "target", "revision": "rev", "expires_at": time.Now().Unix() + 20}
send := func() {
raw, _ := json.Marshal(command)
p.acceptUplink(*p.state.Binding, "runtime", raw, nil, time.Now())
}
send()
if work := <-u.commands; work.body["action"] != "heartbeat" {
t.Fatal("accepted another runtime")
}
u.busy = false
command["runtime"] = "runtime"
command["expires_at"] = time.Now().Unix() - 1
send()
if work := <-u.commands; work.body["action"] != "heartbeat" {
t.Fatal("accepted expired command")
}
u.busy = false
command["expires_at"] = time.Now().Unix() + 20
p.network.Pending = &NetworkPending{}
send()
if work := <-u.commands; work.body["action"] != "heartbeat" {
t.Fatal("overlapped overlay migration")
}
u.busy = false
p.network.Pending = nil
send()
if len(u.commands) != 1 {
t.Fatal("valid command missing")
}
body := (<-u.commands).body
if body["binding"] != "binding:runtime" {
t.Fatal("scope not forwarded")
}
}
func TestFallbackFalseIsForwardedAsAnExplicitScopedCommand(t *testing.T) {
u := &uplinkController{commands: make(chan uplinkWork, 1)}
p := &Pairing{uplink: u, network: &NetworkProfile{BindingID: "binding", Phase: "applied", Provider: "netbird"}, state: PairState{Phase: "paired", Binding: &CoreBinding{BindingID: "binding", Endpoint: "https://10.42.0.1:8782"}}}
command := map[string]any{"id": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "runtime": "runtime", "kind": "fallback", "enabled": false, "revision": 2, "expires_at": time.Now().Unix() + 20}
raw, _ := json.Marshal(command)
p.acceptUplink(*p.state.Binding, "runtime", raw, nil, time.Now())
work := <-u.commands
if work.body["action"] != "fallback" || work.body["enabled"] != false || work.body["binding"] != "binding:runtime" || work.body["revision"] != 2 {
t.Fatal(work)
}
}