feat(network): verify selected uplinks, roll back failures and manage NetBird policy
This commit is contained in:
@@ -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()
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BINARY_VERSION = "0.8.53"
|
||||
VERSION = "0.8.53-124"
|
||||
VERSION = "0.8.53-128"
|
||||
sys.path.insert(0, str(ROOT.parents[1] / "scripts/packaging"))
|
||||
from debian import package
|
||||
|
||||
@@ -44,7 +44,7 @@ Architecture: amd64
|
||||
Maintainer: NODE.DC local build <noreply@example.invalid>
|
||||
Section: admin
|
||||
Priority: optional
|
||||
Depends: adduser, systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), python3-gi, python3-dbus, bluez (>= 5.72), gir1.2-gtk-3.0, gir1.2-webkit2-4.1, pkexec, polkitd, ca-certificates, hicolor-icon-theme, network-manager, iproute2, wireguard-tools, python3-psycopg2, postgresql-16 (>= 16.15), timescaledb-2-oss-postgresql-16 (= 2.29.2~ubuntu24.04-1615), udev, usbutils, libc6 (>= 2.39), libstdc++6 (>= 12), libgcc-s1, zlib1g
|
||||
Depends: adduser, systemd (>= 255), python3 (>= 3.12), python3 (<< 3.13), python3-gi, python3-dbus, bluez (>= 5.72), gir1.2-gtk-3.0, gir1.2-webkit2-4.1, pkexec, polkitd, ca-certificates, hicolor-icon-theme, network-manager (>= 1.46), iproute2, wireguard-tools, python3-psycopg2, postgresql-16 (>= 16.15), timescaledb-2-oss-postgresql-16 (= 2.29.2~ubuntu24.04-1615), udev, usbutils, libc6 (>= 2.39), libstdc++6 (>= 12), libgcc-s1, zlib1g
|
||||
Description: Mission Core onboard computer configuration
|
||||
Local graphical setup, host inventory, SSH access and persistent node identity.
|
||||
""".encode()
|
||||
@@ -53,6 +53,11 @@ Description: Mission Core onboard computer configuration
|
||||
files = [("usr/lib/mission-core-node/node-agent", payload, 0o755)]
|
||||
files.append(("usr/lib/mission-core-node/wireguard_helper.py", (ROOT.parent / "wireguard-client/helper.py").read_bytes(), 0o644))
|
||||
files.append(("usr/lib/systemd/system/mission-core-node-wireguard.service", (p / "mission-core-node-wireguard.service").read_bytes(), 0o644))
|
||||
files.append(("usr/lib/mission-core-node/uplink_helper.py", (p / "uplink_helper.py").read_bytes(), 0o644))
|
||||
files.append(("usr/lib/mission-core-node/qualify_uplink_namespace.py", (p / "qualify_uplink_namespace.py").read_bytes(), 0o644))
|
||||
files.append(("usr/lib/systemd/system/mission-core-uplink.service", (p / "mission-core-uplink.service").read_bytes(), 0o644))
|
||||
for path in sorted((p / "uplink").glob("*.py")):
|
||||
files.append(("usr/lib/mission-core-node/uplink/" + path.name, path.read_bytes(), 0o644))
|
||||
netbird = ROOT.parents[1] / "src/k1link/fleet/netbird"
|
||||
for name in ("client.py", "assets.py", "persistence.py", "clients.lock.json"):
|
||||
files.append(("usr/lib/mission-core-node/netbird/" + name, (netbird / name).read_bytes(), 0o644))
|
||||
@@ -64,7 +69,7 @@ Description: Mission Core onboard computer configuration
|
||||
raise ValueError("Bundled NetBird package changed")
|
||||
files.append(("usr/share/mission-core-node/netbird/" + row["filename"], data, 0o644))
|
||||
files.append(("usr/share/mission-core-node/netbird/clients.lock.json", (netbird / "clients.lock.json").read_bytes(), 0o644))
|
||||
for name in ("netbird_helper.py", "netbird_install.py"):
|
||||
for name in ("netbird_helper.py", "netbird_install.py", "netbird_monitor.py"):
|
||||
files.append(("usr/lib/mission-core-node/" + name, (p / name).read_bytes(), 0o644))
|
||||
files.append(("usr/lib/systemd/system/mission-core-node-netbird.service", (p / "mission-core-node-netbird.service").read_bytes(), 0o644))
|
||||
brand = (ROOT.parents[2] / "NODEDC_DESIGN_GUIDELINE/apps/catalog/public/nodedc-mark.svg").read_bytes()
|
||||
|
||||
@@ -265,7 +265,7 @@ def main():
|
||||
|
||||
run("node-environment-tests", ["/usr/bin/python3", "-m", "unittest", "test_environment_helper", "test_wifi_latency_trial", "test_usb_startup_recovery", "test_desktop_startup", "test_install_owner_release", "test_can_maintenance", "test_vesc_hall_recovery", "test_owner_dependencies", "test_build_source_reuse", "-v"], cwd=node / "packaging")
|
||||
run("owner-release-staging-tests", ["/usr/bin/python3", "plugins/insta360-x4/packaging/test_owner_release_entry.py"], cwd=repo)
|
||||
run("node-usb-unit-validation", ["/usr/bin/systemd-analyze", "verify", str(node / "packaging/mission-core-node-usb-startup.service"), str(node / "packaging/mission-core-node-wifi-trial.service"), str(node / "packaging/mission-core-node-netbird.service")], cwd=node)
|
||||
run("node-usb-unit-validation", ["/usr/bin/systemd-analyze", "verify", str(node / "packaging/mission-core-node-usb-startup.service"), str(node / "packaging/mission-core-node-wifi-trial.service"), str(node / "packaging/mission-core-node-netbird.service"), str(node / "packaging/mission-core-uplink.service")], cwd=node)
|
||||
run("vesc-reader-tests", ["/usr/bin/python3", "-m", "unittest", "discover", "-s", "plugins/vesc/tests", "-v"], cwd=repo)
|
||||
run("usb-can-native-abi", ["/usr/bin/python3", "-B", "-c",
|
||||
"from runtime.sdk import library; library('build/sdk/libcontrolcanfd.so'); print('Pinned SDK loaded; no USB open')"],
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
[Unit]
|
||||
Description=Mission Core physical uplink selection
|
||||
After=NetworkManager.service
|
||||
Wants=NetworkManager.service
|
||||
Before=mission-core-node.service
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/bin/python3 -I /usr/lib/mission-core-node/uplink_helper.py
|
||||
ExecStopPost=/usr/bin/python3 -I /usr/lib/mission-core-node/uplink_helper.py --restore
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
StateDirectory=mission-core-uplink
|
||||
StateDirectoryMode=0700
|
||||
RuntimeDirectory=mission-core-uplink
|
||||
RuntimeDirectoryMode=0755
|
||||
NoNewPrivileges=yes
|
||||
ProtectSystem=strict
|
||||
ProtectHome=yes
|
||||
PrivateTmp=yes
|
||||
RestrictAddressFamilies=AF_UNIX AF_NETLINK AF_INET AF_INET6 AF_PACKET
|
||||
CapabilityBoundingSet=CAP_CHOWN CAP_NET_ADMIN CAP_DAC_READ_SEARCH CAP_NET_RAW
|
||||
MemoryMax=64M
|
||||
TasksMax=16
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Plan-bound repair of the owned Linux NetBird monitor flag via its official CLI.
|
||||
|
||||
No routes, credentials, peer registration or network preference is changed.
|
||||
Only the named, already enrolled 0.82.0 profile is eligible. The installer carries
|
||||
this module so repair is reproducible; it never edits vendor configuration.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path('/var/lib/netbird')
|
||||
OWNER = Path('/var/lib/mission-core-netbird/networks/netbird.json')
|
||||
|
||||
|
||||
def invoke(*args):
|
||||
# The owner installer deliberately clears the login environment. NetBird's
|
||||
# explicit profile switch also maintains a local profile mirror; qualify
|
||||
# root's real config directory without inheriting another sudo user's state.
|
||||
environment = {k: v for k, v in os.environ.items()
|
||||
if not k.startswith(('NB_', 'SUDO_'))}
|
||||
environment['XDG_CONFIG_HOME'] = str(Path(pwd.getpwuid(0).pw_dir) / '.config')
|
||||
result = subprocess.run(['/usr/bin/netbird', *args], capture_output=True, text=True,
|
||||
timeout=45, check=False, env=environment)
|
||||
if result.returncode:
|
||||
log = OWNER.with_name('network-monitor-cli-error.json')
|
||||
private_receipt(log, dict(exit_code=result.returncode, stdout=result.stdout,
|
||||
stderr=result.stderr))
|
||||
raise RuntimeError('NetBird CLI failed; private details: ' + str(log))
|
||||
return result.stdout
|
||||
|
||||
|
||||
def private_receipt(path, value):
|
||||
old = os.umask(0o077)
|
||||
try:
|
||||
path.write_text(json.dumps(value, indent=2) + '\n')
|
||||
path.chmod(0o600)
|
||||
finally:
|
||||
os.umask(old)
|
||||
|
||||
|
||||
def fingerprint(value):
|
||||
return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
|
||||
|
||||
|
||||
def config():
|
||||
active = json.loads((ROOT/'active_profile.json').read_text())
|
||||
if active.get('username') != 'root' or not re.fullmatch(r'[a-f0-9]{32}', active.get('name','')):
|
||||
raise ValueError('Foreign active NetBird profile')
|
||||
path = ROOT/'root'/(active['name']+'.json')
|
||||
if path.is_symlink() or path.stat().st_uid != 0 or path.stat().st_size > 262144:
|
||||
raise ValueError('Foreign NetBird profile file')
|
||||
data = json.loads(path.read_text())
|
||||
if data.get('Name') != 'mission-core' or type(data.get('NetworkMonitor')) is not bool:
|
||||
raise ValueError('Foreign or unsupported NetBird profile')
|
||||
return data
|
||||
|
||||
|
||||
def plan():
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError('Run within the root owner installer')
|
||||
if not OWNER.exists():
|
||||
return dict(state='not-configured', changed=False)
|
||||
if invoke('version').strip() != '0.82.0':
|
||||
raise ValueError('Unsupported NetBird version')
|
||||
saved = json.loads(OWNER.read_text())
|
||||
status = json.loads(invoke('status','--json'))
|
||||
if (status.get('profileName') != 'mission-core'
|
||||
or status.get('management',{}).get('url') != saved['server_url']):
|
||||
raise ValueError('Foreign NetBird network')
|
||||
data = config()
|
||||
value = dict(schema='missioncore.netbird-monitor-plan/v1', version=2,
|
||||
profile='mission-core', before=data['NetworkMonitor'], after=False,
|
||||
changed=data['NetworkMonitor'], profile_sha256=fingerprint(data),
|
||||
server_url=saved['server_url'])
|
||||
value['plan_sha256'] = fingerprint(value)
|
||||
return value
|
||||
|
||||
|
||||
def apply(expected):
|
||||
proposal = plan()
|
||||
if proposal.get('plan_sha256') != expected:
|
||||
raise ValueError('NetBird monitor plan changed')
|
||||
if not proposal['changed']:
|
||||
return dict(state='ready', changed=False)
|
||||
before = config()
|
||||
# Persist enough to reverse this one flag; no private keys in the receipt.
|
||||
receipt = OWNER.with_name('network-monitor-repair.json')
|
||||
private_receipt(receipt, dict(plan=proposal, state='applying'))
|
||||
try:
|
||||
invoke('up','--profile','mission-core','--network-monitor=false','--management-url',proposal['server_url'],'--no-browser')
|
||||
after = config()
|
||||
if after != {**before,'NetworkMonitor':False}:
|
||||
raise ValueError('NetBird profile readback differs from the admitted change')
|
||||
deadline=time.monotonic()+30
|
||||
while True:
|
||||
status=json.loads(invoke('status','--json'))
|
||||
if (status.get('profileName')=='mission-core'
|
||||
and status.get('management',{}).get('url')==proposal['server_url']
|
||||
and status.get('management',{}).get('connected')
|
||||
and status.get('signal',{}).get('connected')):
|
||||
break
|
||||
if time.monotonic()>=deadline:
|
||||
raise ValueError('NetBird connection did not recover')
|
||||
time.sleep(.5)
|
||||
except Exception as error:
|
||||
state = 'unchanged'
|
||||
try:
|
||||
if config() != before:
|
||||
invoke('up','--profile','mission-core','--network-monitor=true',
|
||||
'--management-url',proposal['server_url'],'--no-browser')
|
||||
if config() != before:
|
||||
raise ValueError('NetBird rollback readback differs')
|
||||
state = 'rolled-back'
|
||||
except Exception:
|
||||
private_receipt(receipt, dict(plan=proposal,state='rollback-failed',
|
||||
error_type=type(error).__name__))
|
||||
raise
|
||||
private_receipt(receipt, dict(plan=proposal,state=state,
|
||||
error_type=type(error).__name__))
|
||||
raise
|
||||
result=dict(state='ready',changed=True,profile_preserved=True,network_monitor=False)
|
||||
private_receipt(receipt, dict(plan=proposal, **result))
|
||||
return result
|
||||
|
||||
|
||||
def repair():
|
||||
proposal=plan()
|
||||
if proposal.get('state')=='not-configured':
|
||||
return proposal
|
||||
return apply(proposal['plan_sha256'])
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
print(json.dumps(repair()))
|
||||
@@ -23,6 +23,10 @@ case "$1" in
|
||||
systemctl restart mission-core-node-netbird.service
|
||||
systemctl enable mission-core-node-wireguard.service
|
||||
systemctl restart mission-core-node-wireguard.service
|
||||
systemctl stop mission-core-uplink.service
|
||||
/usr/bin/python3 -I /usr/lib/mission-core-node/uplink_helper.py --migrate-native-fallback
|
||||
systemctl enable mission-core-uplink.service
|
||||
systemctl restart mission-core-uplink.service
|
||||
systemctl enable mission-core-node.service
|
||||
systemctl restart mission-core-node.service
|
||||
systemctl start mission-core-node-usb-can-prepare.service
|
||||
|
||||
@@ -135,3 +135,11 @@ if [ "$1" = remove ] || { [ "$1" = upgrade ] && [ -n "${2:-}" ] && dpkg --compar
|
||||
systemctl disable --now mission-core-node-netbird.service || true
|
||||
fi
|
||||
fi
|
||||
|
||||
# Retain the journal; NetworkManager owns the pending checkpoint timeout.
|
||||
if [ "$1" = remove ] || { [ "$1" = upgrade ] && [ -n "${2:-}" ] && dpkg --compare-versions "$2" lt 0.8.53-125; }; then
|
||||
if [ -d /run/systemd/system ]; then
|
||||
systemctl disable --now mission-core-uplink.service || true
|
||||
/usr/bin/python3 -I /usr/lib/mission-core-node/uplink_helper.py --release || true
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Check actual Linux outgoing UDP capture only in a disposable network namespace."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
from uplink.quic_path import observe_udp
|
||||
|
||||
|
||||
def main():
|
||||
if os.geteuid() or os.readlink("/proc/self/ns/net") == os.readlink("/proc/1/ns/net"):
|
||||
raise ValueError("Root in a new network namespace required")
|
||||
subprocess.run(["/usr/sbin/ip", "link", "set", "lo", "up"], check=True)
|
||||
with (
|
||||
socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as source,
|
||||
socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sink,
|
||||
):
|
||||
source.bind(("127.0.0.1", 0))
|
||||
sink.bind(("127.0.0.1", 0))
|
||||
sport, dport = source.getsockname()[1], sink.getsockname()[1]
|
||||
stop = threading.Event()
|
||||
|
||||
def emit():
|
||||
while not stop.wait(0.03):
|
||||
source.sendto(b"synthetic", ("127.0.0.1", dport))
|
||||
|
||||
sender = threading.Thread(target=emit)
|
||||
sender.start()
|
||||
try:
|
||||
assert observe_udp("lo", {"127.0.0.1"}, {"127.0.0.1"}, dport, {sport}) == (
|
||||
"127.0.0.1",
|
||||
"127.0.0.1",
|
||||
)
|
||||
started = time.monotonic()
|
||||
assert observe_udp("lo", {"127.0.0.1"}, {"127.0.0.1"}, dport, {sport + 1}) is None
|
||||
assert time.monotonic() - started < 1.2
|
||||
assert observe_udp("lo", {"192.0.2.1"}, {"127.0.0.1"}, dport, {sport}) is None
|
||||
finally:
|
||||
stop.set()
|
||||
sender.join(timeout=1)
|
||||
print(
|
||||
json.dumps(
|
||||
{"state": "complete", "isolated_namespace": True, "cases": 3, "live_interfaces": False}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Bounded prepared-Ubuntu package smoke check; never installs or opens hardware."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def qualify(package, expected):
|
||||
assert os.geteuid() != 0
|
||||
match = re.fullmatch(
|
||||
r"mission-core-node_([0-9]+\.[0-9]+\.[0-9]+-[1-9][0-9]*)_amd64\.deb", package.name)
|
||||
assert match, "Unexpected package identity"
|
||||
version = match[1]
|
||||
release = platform.freedesktop_os_release()
|
||||
assert (release["ID"], release["VERSION_ID"], platform.machine()) == (
|
||||
"ubuntu",
|
||||
"24.04",
|
||||
"x86_64",
|
||||
)
|
||||
raw = package.read_bytes()
|
||||
assert hashlib.sha256(raw).hexdigest() == expected
|
||||
report = dict(
|
||||
schema="missioncore.uplink.prepared-host-package-check/v1",
|
||||
session_id=uuid.uuid4().hex,
|
||||
started_at=datetime.now(UTC).isoformat(),
|
||||
monotonic_started=time.monotonic(),
|
||||
clean_image_qualified=False,
|
||||
hardware_access=False,
|
||||
checks=[],
|
||||
)
|
||||
|
||||
def run(name, args, allowed=(0,), **kwargs):
|
||||
result = subprocess.run(args, capture_output=True, timeout=60, **kwargs)
|
||||
assert result.returncode in allowed, name + ": " + result.stderr.decode()[:300]
|
||||
report["checks"].append(dict(id=name, exit_code=result.returncode))
|
||||
return result.stdout
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="router-api-package-", dir=package.parent) as scratch:
|
||||
root = Path(scratch)
|
||||
run("control", ["dpkg-deb", "-e", str(package), str(root / "control")])
|
||||
run("payload", ["dpkg-deb", "-x", str(package), str(root / "payload")])
|
||||
for name in ["postinst", "prerm"]:
|
||||
run("shell-" + name, ["/bin/sh", "-n", str(root / "control" / name)])
|
||||
control = (root / "control/control").read_text()
|
||||
assert "python3-dbus" in control and "bluez (>= 5.72)" in control
|
||||
assert f"Version: {version}\n" in control
|
||||
profile_path = root / "payload/usr/share/mission-core-node/router-observation-profile.json"
|
||||
profile = json.loads(profile_path.read_text())
|
||||
assert profile["network_changes"] is False
|
||||
assert any(
|
||||
a["id"] == "dexaflow-client-api/v1" and a["identity"] == "device_ca"
|
||||
for a in profile["adapters"]
|
||||
)
|
||||
report["checks"].append(dict(id="embedded-router-profile", exit_code=0))
|
||||
uplink_root = root / "payload/usr/lib/mission-core-node"
|
||||
for path in (uplink_root / "uplink").glob("*.py"):
|
||||
compile(path.read_text(), str(path), "exec")
|
||||
compile((uplink_root / "uplink_helper.py").read_text(), "uplink_helper.py", "exec")
|
||||
run("netbird-policy-imports", ["/usr/bin/python3", "-B", "-c",
|
||||
"import netbird_monitor; from netbird.client import safe_flags; "
|
||||
"assert '--network-monitor=false' in safe_flags()"], cwd=uplink_root)
|
||||
run(
|
||||
"uplink-readonly-inventory",
|
||||
[
|
||||
"/usr/bin/python3",
|
||||
"-B",
|
||||
"-c",
|
||||
"import json; from uplink.network_manager import NetworkManager; "
|
||||
"from uplink.preferences import choice; "
|
||||
"nm=NetworkManager(); state=nm.public(nm.inspect()); "
|
||||
"assert state['supported']; assert state['current_id']; "
|
||||
"assert len(state['candidates'])>=1; "
|
||||
"profiles=nm.profile_preferences(); assert len(profiles)>0; "
|
||||
"assert all(choice(p,p['id'],0)['metrics'][f]==p['saved']['metrics'][f] "
|
||||
"for p in profiles.values() for f in p.get('inactive_families',[])); "
|
||||
"print(json.dumps({'supported':state['supported'],'candidate_count':len(state['candidates'])}))",
|
||||
],
|
||||
cwd=uplink_root,
|
||||
)
|
||||
unit = root / "payload/usr/lib/systemd/system/mission-core-uplink.service"
|
||||
# Verify service syntax against staged executable; no system installation.
|
||||
text = unit.read_text().replace(
|
||||
"/usr/lib/mission-core-node/uplink_helper.py", str(uplink_root / "uplink_helper.py")
|
||||
)
|
||||
unit.write_text(text)
|
||||
run("uplink-unit-validation", ["systemd-analyze", "verify", str(unit)])
|
||||
runtime = root / "payload/usr/lib/mission-core-jk-bms"
|
||||
for path in runtime.rglob("*.py"):
|
||||
compile(path.read_text(), str(path), "exec")
|
||||
run(
|
||||
"python-imports",
|
||||
[
|
||||
"/usr/bin/python3",
|
||||
"-B",
|
||||
"-c",
|
||||
"import runtime.protocol, runtime.service, runtime.bluez, runtime.server; "
|
||||
"from gi.repository import GLib",
|
||||
],
|
||||
cwd=runtime,
|
||||
)
|
||||
vesc = root / "payload/usr/lib/mission-core-vesc"
|
||||
for path in (vesc / "runtime").glob("*.py"):
|
||||
compile(path.read_text(), str(path), "exec")
|
||||
run("vesc-recovery-imports", ["/usr/bin/python3", "-B", "-c",
|
||||
"from runtime.remote_control import RemoteControl; "
|
||||
"from runtime.preflight_recovery import PreflightRecovery; "
|
||||
"assert PreflightRecovery({'bindings': {}}, cancelled=True).cancelled"], cwd=vesc)
|
||||
help_text = run(
|
||||
"node-executable-help",
|
||||
[str(root / "payload/usr/lib/mission-core-node/node-agent"), "--help"],
|
||||
allowed=(0, 1, 2),
|
||||
)
|
||||
assert len(help_text) < 65536
|
||||
run("apt-simulation", ["apt-get", "--simulate", "--no-remove", "install", str(package)])
|
||||
report.update(
|
||||
state="complete",
|
||||
finished_at=datetime.now(UTC).isoformat(),
|
||||
duration_seconds=time.monotonic() - report["monotonic_started"],
|
||||
package_sha256=expected,
|
||||
version=version,
|
||||
)
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("package", type=Path)
|
||||
parser.add_argument("sha256")
|
||||
args = parser.parse_args()
|
||||
qualify(args.package.resolve(), args.sha256)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Kernel routing acceptance in a new network namespace; no live NIC access."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
from uplink.transport_route import RouteNotReady, TransportRoute
|
||||
|
||||
|
||||
def run(*args):
|
||||
return subprocess.run(args, text=True, capture_output=True, check=True, timeout=8).stdout
|
||||
|
||||
|
||||
def main():
|
||||
if os.geteuid() or os.readlink('/proc/self/ns/net') == os.readlink('/proc/1/ns/net'):
|
||||
raise ValueError('Run only as root inside unshare --net.')
|
||||
ip = '/usr/sbin/ip'
|
||||
# Disposable virtual links exist only in this namespace, never on the host.
|
||||
for name, address in [('ethernet-test', '192.0.2.2/24'), ('wifi-test', '198.51.100.2/24')]:
|
||||
run(ip, 'link', 'add', name, 'type', 'dummy')
|
||||
run(ip, 'link', 'set', name, 'up')
|
||||
run(ip, 'address', 'add', address, 'dev', name)
|
||||
run(ip, 'route', 'add', 'default', 'via', '192.0.2.1', 'dev', 'ethernet-test', 'metric', '10')
|
||||
run(ip, 'route', 'add', 'default', 'via', '198.51.100.1', 'dev', 'wifi-test', 'metric', '100')
|
||||
mark = 0x1bd00
|
||||
|
||||
def route(address, marked=False):
|
||||
args = [ip, '-j', '-4', 'route', 'get', address]
|
||||
if marked:
|
||||
args += ['mark', hex(mark)]
|
||||
return json.loads(run(*args))[0]['dev']
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix='mission-core-uplink-qualification-') as folder:
|
||||
steering = TransportRoute(run, Path(folder))
|
||||
assert route('192.0.2.20', True) == 'ethernet-test'
|
||||
steering.select(dict(interface='wifi-test', mark=mark))
|
||||
assert route('192.0.2.20', True) == 'wifi-test' # Original connected-LAN bug.
|
||||
assert route('192.0.2.20') == 'ethernet-test' # Router LAN remains accessible.
|
||||
assert route('203.0.113.8', True) == 'wifi-test'
|
||||
assert route('198.51.100.20', True) == 'wifi-test'
|
||||
steering.select(dict(interface='ethernet-test', mark=mark))
|
||||
assert route('203.0.113.8', True) == 'ethernet-test'
|
||||
steering.select(dict(interface='wifi-test', mark=mark))
|
||||
run(ip, 'link', 'del', 'wifi-test')
|
||||
assert route('203.0.113.8', True) == 'ethernet-test' # Missing NIC falls through.
|
||||
steering.release()
|
||||
assert not steering.rules() and not steering.routes()
|
||||
assert not steering.path.exists()
|
||||
def restore_wifi():
|
||||
run(ip, 'link', 'add', 'wifi-test', 'type', 'dummy')
|
||||
run(ip, 'link', 'set', 'wifi-test', 'up')
|
||||
run(ip, 'address', 'add', '198.51.100.2/24', 'dev', 'wifi-test')
|
||||
run(ip, 'route', 'add', 'default', 'via', '198.51.100.1',
|
||||
'dev', 'wifi-test', 'metric', '100')
|
||||
restore_wifi()
|
||||
strict = dict(interface='wifi-test', mark=mark, strict=True)
|
||||
steering.select(strict)
|
||||
assert route('203.0.113.8', True) == 'wifi-test'
|
||||
stamp = steering.path.stat().st_mtime_ns
|
||||
steering.select(strict)
|
||||
assert steering.path.stat().st_mtime_ns == stamp # No periodic journal writes.
|
||||
run(ip, 'link', 'del', 'wifi-test')
|
||||
blocked = subprocess.run([ip, '-4', 'route', 'get', '203.0.113.8', 'mark', hex(mark)],
|
||||
capture_output=True, timeout=5)
|
||||
assert blocked.returncode != 0, blocked.stdout
|
||||
assert any(r.get('type') == 'unreachable' for r in steering.routes())
|
||||
assert route('203.0.113.8') == 'ethernet-test' # Other traffic untouched.
|
||||
steering = TransportRoute(run, Path(folder)) # Restart preserves owned guard.
|
||||
steering.select(strict)
|
||||
restore_wifi()
|
||||
steering.select(strict)
|
||||
assert route('203.0.113.8', True) == 'wifi-test'
|
||||
steering.select(dict(interface='wifi-test', mark=mark)) # Enable fallback again.
|
||||
run(ip, 'link', 'del', 'wifi-test')
|
||||
assert route('203.0.113.8', True) == 'ethernet-test'
|
||||
steering.release()
|
||||
assert not steering.rules() and not steering.routes()
|
||||
restore_wifi()
|
||||
expired = [False]
|
||||
def race(*args):
|
||||
result = run(*args)
|
||||
if args[-3:] == ('show', 'table', 'main') and not expired[0]:
|
||||
expired[0] = True
|
||||
run(ip, 'address', 'del', '198.51.100.2/24', 'dev', 'wifi-test')
|
||||
return result
|
||||
racing = TransportRoute(race, Path(folder))
|
||||
try:
|
||||
racing.select(dict(interface='wifi-test', mark=mark))
|
||||
raise AssertionError('An expired DHCP source cannot be accepted')
|
||||
except RouteNotReady:
|
||||
pass
|
||||
assert not racing.rules() and not racing.routes()
|
||||
assert route('203.0.113.8', True) == 'ethernet-test'
|
||||
run(ip, 'address', 'add', '198.51.100.2/24', 'dev', 'wifi-test')
|
||||
run(ip, 'route', 'add', 'default', 'via', '198.51.100.1',
|
||||
'dev', 'wifi-test', 'metric', '100')
|
||||
racing.select(dict(interface='wifi-test', mark=mark))
|
||||
assert route('203.0.113.8', True) == 'wifi-test'
|
||||
racing.release()
|
||||
assert not racing.rules() and not racing.routes()
|
||||
print(json.dumps(dict(state='complete', isolated_network_namespace=True,
|
||||
live_interfaces_changed=False,
|
||||
cases=['connected-subnet-vpn', 'router-lan-preserved',
|
||||
'bidirectional-selection', 'physical-loss-fallback',
|
||||
'cleanup-after-device-loss', 'disabled-fallback-no-leak',
|
||||
'strict-device-return', 'strict-journal-idempotence',
|
||||
'reenabled-fallback', 'expired-dhcp-source-retry'])))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Explicit stationary-board qualification: pause only Node replies for 50 seconds.
|
||||
|
||||
No network configuration writes. The installed production helper must keep the accepted connection.
|
||||
A detached, PID/start-time-scoped guard resumes Node even if this test/SSH dies.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def command(*args):
|
||||
return subprocess.check_output(args, timeout=15, text=True).strip()
|
||||
|
||||
|
||||
def stamp(pid):
|
||||
return Path(f"/proc/{pid}/stat").read_text().split(") ", 1)[1].split()[19]
|
||||
|
||||
|
||||
def status():
|
||||
raw = command(
|
||||
"/usr/sbin/runuser",
|
||||
"-u",
|
||||
"mission-core-node",
|
||||
"--",
|
||||
"/usr/bin/python3",
|
||||
"-I",
|
||||
"-c",
|
||||
"import socket,json; s=socket.socket(socket.AF_UNIX); s.settimeout(12); "
|
||||
's.connect("/run/mission-core-uplink/control.sock"); '
|
||||
's.sendall(b\'{"action":"status"}\\n\'); '
|
||||
"print(s.makefile().readline(32769))",
|
||||
)
|
||||
return json.loads(raw)["result"]
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--pause-node-replies", action="store_true", required=True)
|
||||
args = parser.parse_args()
|
||||
assert args.pause_node_replies and os.geteuid() == 0
|
||||
assert command("dpkg-query", "-W", "-f", "${Version}", "mission-core-node") == "0.8.53-128"
|
||||
state = status()
|
||||
assert state["path_verified"] and state["operation"]["phase"] == "applied"
|
||||
pid = int(command("systemctl", "show", "mission-core-node.service", "-p", "MainPID", "--value"))
|
||||
assert pid > 1 and Path(f"/proc/{pid}/exe").resolve() == Path(
|
||||
"/usr/lib/mission-core-node/node-agent"
|
||||
)
|
||||
started = stamp(pid)
|
||||
|
||||
def resume():
|
||||
try:
|
||||
if stamp(pid) == started:
|
||||
os.kill(pid, signal.SIGCONT)
|
||||
except (ProcessLookupError, FileNotFoundError):
|
||||
pass
|
||||
|
||||
guard = os.fork()
|
||||
if guard == 0:
|
||||
os.setsid()
|
||||
signal.signal(signal.SIGHUP, signal.SIG_IGN)
|
||||
signal.signal(signal.SIGTERM, lambda *_: (resume(), os._exit(0)))
|
||||
with open(os.devnull, "r+") as null:
|
||||
for fd in (0, 1, 2):
|
||||
os.dup2(null.fileno(), fd)
|
||||
time.sleep(60)
|
||||
resume()
|
||||
os._exit(0)
|
||||
report = {
|
||||
"schema": "missioncore.uplink.manual-only-qualification/v1",
|
||||
"start": time.time(),
|
||||
"operation": state["operation"]["id"],
|
||||
"before": state["current_id"],
|
||||
"samples": [],
|
||||
}
|
||||
try:
|
||||
os.kill(pid, signal.SIGSTOP)
|
||||
end = time.monotonic() + 50
|
||||
while time.monotonic() < end:
|
||||
time.sleep(5)
|
||||
value = status()
|
||||
report["samples"].append(
|
||||
{
|
||||
"elapsed": round(time.time() - report["start"], 1),
|
||||
"current": value["current_id"],
|
||||
"phase": value["operation"]["phase"],
|
||||
}
|
||||
)
|
||||
finally:
|
||||
resume()
|
||||
os.kill(guard, signal.SIGTERM)
|
||||
os.waitpid(guard, 0)
|
||||
report["resumed_at"] = time.time()
|
||||
Path(__file__).with_suffix(".result.json").write_text(json.dumps(report, indent=2))
|
||||
assert all(
|
||||
s["current"] == report["before"] and s["phase"] == "applied" for s in report["samples"]
|
||||
)
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Exact qualified Node151 delta: passive QUIC path evidence and service capability.
|
||||
|
||||
No Node binary, UI, motor runtime, NetworkManager profile or route policy changes.
|
||||
Requires prepared-Ubuntu qualification before the owner installer can be built.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from node_package_delta import parts
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
BASE = "b91efd2c2af62cb2efe9709b96e62a1a02d62b058b561b5c3739d4f142fe76f4"
|
||||
VERSION = "0.8.53-152"
|
||||
FILES = {
|
||||
"uplink/netbird_path.py": "usr/lib/mission-core-node/uplink/netbird_path.py",
|
||||
"uplink/quic_path.py": "usr/lib/mission-core-node/uplink/quic_path.py",
|
||||
"mission-core-uplink.service": "usr/lib/systemd/system/mission-core-uplink.service",
|
||||
}
|
||||
|
||||
|
||||
def digest(raw):
|
||||
return hashlib.sha256(raw).hexdigest()
|
||||
|
||||
|
||||
def build(base, output):
|
||||
evidence = json.loads((base / "qualification.json").read_text())
|
||||
if evidence["state"] != "complete":
|
||||
raise ValueError("Qualified predecessor required")
|
||||
raw = (base / "mission-core-node_0.8.53-151_amd64.deb").read_bytes()
|
||||
if digest(raw) != BASE:
|
||||
raise ValueError("Qualified predecessor changed")
|
||||
archives = parts(raw)
|
||||
changes = {
|
||||
target: (REPO / "apps/node-agent/packaging" / source).read_bytes()
|
||||
for source, target in FILES.items()
|
||||
}
|
||||
for name, data in changes.items():
|
||||
if name.endswith(".py"):
|
||||
compile(data, name, "exec")
|
||||
provenance = dict(
|
||||
schema="missioncore.node.packaging-revision/v1",
|
||||
version=VERSION,
|
||||
base_sha256=BASE,
|
||||
changed_files={n: digest(v) for n, v in changes.items()},
|
||||
node_ui_motor_routing_policy_unchanged=True,
|
||||
added_service_capability="CAP_NET_RAW; AF_PACKET; owner approved 2026-11-14",
|
||||
base_qualification_sha256=digest((base / "qualification.json").read_bytes()),
|
||||
builder_sha256=digest(Path(__file__).read_bytes()),
|
||||
)
|
||||
changes["usr/share/doc/mission-core-node/quic-path-revision.json"] = (
|
||||
json.dumps(provenance, sort_keys=True) + "\n"
|
||||
).encode()
|
||||
controls = []
|
||||
for n, v, m in archives["control.tar.gz"]:
|
||||
if n == "control":
|
||||
if v.count(b"Version: 0.8.53-151\n") != 1:
|
||||
raise ValueError("Unexpected version")
|
||||
v = v.replace(b"Version: 0.8.53-151\n", b"Version: 0.8.53-152\n")
|
||||
controls.append((n, v, m))
|
||||
data = [(n, changes.get(n, v), m) for n, v, m in archives["data.tar.gz"]]
|
||||
old = {n for n, _, _ in data}
|
||||
data += [(n, v, 0o644) for n, v in changes.items() if n not in old]
|
||||
sys.path.insert(0, str(REPO / "scripts/packaging"))
|
||||
from debian import package
|
||||
|
||||
raw = package(controls, data)
|
||||
checked = parts(raw)
|
||||
if checked["control.tar.gz"] != sorted(controls) or checked["data.tar.gz"] != sorted(data):
|
||||
raise ValueError("Package delta differs")
|
||||
output.mkdir(mode=0o700)
|
||||
name = "mission-core-node_" + VERSION + "_amd64.deb"
|
||||
(output / name).write_bytes(raw)
|
||||
artifacts = {name: dict(bytes=len(raw), sha256=digest(raw))}
|
||||
for name, info in evidence["artifacts"].items():
|
||||
if name.startswith("mission-core-node_"):
|
||||
continue
|
||||
content = (base / name).read_bytes()
|
||||
if digest(content) != info["sha256"] or len(content) != info["bytes"]:
|
||||
raise ValueError("Dependency changed")
|
||||
os.link(base / name, output / name)
|
||||
artifacts[name] = info
|
||||
report = dict(
|
||||
schema="missioncore.node.runtime-qualification/v1",
|
||||
state="awaiting_prepared_host",
|
||||
clean_image_qualified=False,
|
||||
artifacts=artifacts,
|
||||
packaging_revision=provenance,
|
||||
scope="Passive QUIC physical path proof; existing TCP/P2P checks retained",
|
||||
)
|
||||
(output / "qualification.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--qualified", type=Path, required=True)
|
||||
p.add_argument("--output", type=Path, required=True)
|
||||
a = p.parse_args()
|
||||
build(a.qualified, a.output)
|
||||
@@ -0,0 +1,111 @@
|
||||
"""Bounded Node133 delta over qualified Node125, including owned service startup."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
NODE = REPO / "apps/node-agent"
|
||||
BASE_SHA = "d71c932e89ec15dd3ad7981ba401035f3c396a3d383f97668a2d78e53685f070"
|
||||
sys.path.insert(0, str(REPO / "scripts/packaging"))
|
||||
from debian import package # noqa: E402
|
||||
|
||||
|
||||
def build(binary, output):
|
||||
if output.exists():
|
||||
raise FileExistsError("Published releases are immutable")
|
||||
raw = (NODE / "build/uplink-125-qualified/mission-core-node_0.8.53-125_amd64.deb").read_bytes()
|
||||
assert hashlib.sha256(raw).hexdigest() == BASE_SHA
|
||||
stream, archives = io.BytesIO(raw), {}
|
||||
assert stream.read(8) == b"!<arch>\n"
|
||||
while header := stream.read(60):
|
||||
size = int(header[48:58])
|
||||
archives[header[:16].decode().strip().rstrip("/")] = stream.read(size)
|
||||
if size % 2:
|
||||
stream.read(1)
|
||||
|
||||
def members(name):
|
||||
with tarfile.open(fileobj=io.BytesIO(archives[name]), mode="r:gz") as archive:
|
||||
return [(m.name, archive.extractfile(m).read(), m.mode) for m in archive if m.isfile()]
|
||||
|
||||
controls, files = members("control.tar.gz"), members("data.tar.gz")
|
||||
old = {n: d for n, d, _ in files}
|
||||
compiled = binary.read_bytes()
|
||||
assert compiled[:6] == b"\x7fELF\x02\x01" and compiled[18:20] == b"\x3e\x00"
|
||||
p = NODE / "packaging"
|
||||
changes = {"usr/lib/mission-core-node/node-agent": compiled}
|
||||
additions = {
|
||||
"usr/lib/mission-core-node/uplink_helper.py": (p / "uplink_helper.py").read_bytes(),
|
||||
"usr/lib/systemd/system/mission-core-uplink.service": (
|
||||
p / "mission-core-uplink.service"
|
||||
).read_bytes(),
|
||||
}
|
||||
for path in sorted((p / "uplink").glob("*.py")):
|
||||
additions["usr/lib/mission-core-node/uplink/" + path.name] = path.read_bytes()
|
||||
changes.update({n: d for n, d in additions.items() if n in old})
|
||||
additions = {n: d for n, d in additions.items() if n not in old}
|
||||
provenance = {
|
||||
"schema": "missioncore.node.packaging-revision/v1",
|
||||
"version": "0.8.53-134",
|
||||
"qualified_base_sha256": BASE_SHA,
|
||||
"qualified_base_provenance": json.loads(
|
||||
old["usr/share/doc/mission-core-node/provenance.json"]
|
||||
),
|
||||
"scope": (
|
||||
"Native NetworkManager fallback, reversible manual preference "
|
||||
"and proven sticky recovery"
|
||||
),
|
||||
"binary_sha256": hashlib.sha256(compiled).hexdigest(),
|
||||
"sources": {
|
||||
str(path.relative_to(REPO)): hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for folder in (
|
||||
NODE / "internal/node",
|
||||
NODE / "internal/routers",
|
||||
p / "uplink",
|
||||
REPO / "packages/router-ui/src",
|
||||
)
|
||||
for path in sorted(folder.glob("*"))
|
||||
if path.is_file()
|
||||
},
|
||||
}
|
||||
changes["usr/share/doc/mission-core-node/provenance.json"] = (
|
||||
json.dumps(provenance, indent=2) + "\n"
|
||||
).encode()
|
||||
replaced = []
|
||||
for name, data, mode in controls:
|
||||
if name == "control":
|
||||
assert b"Version: 0.8.53-125\n" in data
|
||||
data = data.replace(b"Version: 0.8.53-125\n", b"Version: 0.8.53-134\n").replace(
|
||||
b"network-manager,", b"network-manager (>= 1.46),"
|
||||
)
|
||||
if name in ("postinst", "prerm"):
|
||||
data = (p / name).read_bytes()
|
||||
replaced.append((name, data, mode))
|
||||
payload = [(n, changes.get(n, d), m) for n, d, m in files]
|
||||
payload += [(n, d, 0o644) for n, d in additions.items()]
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_bytes(package(replaced, payload))
|
||||
report = dict(
|
||||
version="0.8.53-134",
|
||||
base_sha256=BASE_SHA,
|
||||
sha256=hashlib.sha256(output.read_bytes()).hexdigest(),
|
||||
bytes=output.stat().st_size,
|
||||
changed_controls=["control", "postinst", "prerm"],
|
||||
changed_payloads=list(changes),
|
||||
added_payloads=list(additions),
|
||||
retained_payload_count=len(files) - len(changes),
|
||||
)
|
||||
output.with_suffix(".json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--binary", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
build(args.binary, args.output)
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Synthetic official-CLI repair, no installed services or real network changes."""
|
||||
import copy
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
spec=importlib.util.spec_from_file_location('netbird_monitor',Path(__file__).with_name('netbird_monitor.py'))
|
||||
module=importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rig(tmp_path,monkeypatch):
|
||||
owner=tmp_path/'netbird.json'
|
||||
owner.write_text(json.dumps({'server_url':'https://vpn.example:8443'}))
|
||||
monkeypatch.setattr(module,'OWNER',owner)
|
||||
monkeypatch.setattr(module.os,'geteuid',lambda:0)
|
||||
data={'Name':'mission-core','PrivateKey':'synthetic-key','NetworkMonitor':True,'WgIface':'wt0'}
|
||||
monkeypatch.setattr(module,'config',lambda:copy.deepcopy(data))
|
||||
status={'profileName':'mission-core','management':{'url':'https://vpn.example:8443','connected':True},'signal':{'connected':True}}
|
||||
calls=[]
|
||||
def invoke(*args):
|
||||
calls.append(args)
|
||||
if args[0]=='version':return '0.82.0'
|
||||
if args[0]=='status':return json.dumps(status)
|
||||
assert args[0]=='up' and args[1:3]==('--profile','mission-core')
|
||||
data['NetworkMonitor']='--network-monitor=true' in args
|
||||
return ''
|
||||
monkeypatch.setattr(module,'invoke',invoke)
|
||||
return data,status,calls,owner
|
||||
|
||||
|
||||
def test_owned_policy_repair_preserves_keys_and_is_idempotent(rig):
|
||||
data,status,calls,owner=rig
|
||||
result=module.repair()
|
||||
assert result['changed'] and not data['NetworkMonitor']
|
||||
assert data['PrivateKey']=='synthetic-key'
|
||||
receipt=owner.with_name('network-monitor-repair.json').read_text()
|
||||
assert 'synthetic-key' not in receipt
|
||||
assert not module.repair()['changed']
|
||||
assert len([c for c in calls if c[0]=='up'])==1
|
||||
assert owner.with_name('network-monitor-repair.json').read_text()==receipt
|
||||
|
||||
|
||||
def test_foreign_profile_or_server_never_mutated(rig):
|
||||
data,status,calls,_=rig
|
||||
for key,value in [('profileName','other'),('management',{'url':'https://foreign.example'})]:
|
||||
old=status[key];status[key]=value
|
||||
with pytest.raises(ValueError,match='Foreign'):module.repair()
|
||||
status[key]=old
|
||||
assert not any(c[0]=='up' for c in calls)
|
||||
|
||||
|
||||
def test_plan_drift_and_unexpected_config_change_are_rejected(rig,monkeypatch):
|
||||
data,status,calls,_=rig
|
||||
proposal=module.plan();data['WgIface']='changed'
|
||||
with pytest.raises(ValueError,match='plan changed'):module.apply(proposal['plan_sha256'])
|
||||
original=module.invoke
|
||||
def mutate(*args):
|
||||
result=original(*args)
|
||||
if '--network-monitor=false' in args:data['WgIface']='foreign'
|
||||
return result
|
||||
monkeypatch.setattr(module,'invoke',mutate)
|
||||
with pytest.raises(ValueError,match='readback'):module.repair()
|
||||
assert data['NetworkMonitor'] is True
|
||||
assert calls[-1][3]=='--network-monitor=true'
|
||||
|
||||
|
||||
def test_lost_management_rolls_back_monitor_flag(rig,monkeypatch):
|
||||
data,status,calls,_=rig
|
||||
status['management']['connected']=False
|
||||
clock=iter([0,31]);monkeypatch.setattr(module.time,'monotonic',lambda:next(clock))
|
||||
with pytest.raises(ValueError,match='did not recover'):module.repair()
|
||||
assert data['NetworkMonitor'] is True
|
||||
|
||||
|
||||
def test_unenrolled_host_is_untouched(rig):
|
||||
_,_,calls,owner=rig;owner.unlink()
|
||||
assert module.repair()=={'state':'not-configured','changed':False}
|
||||
assert not calls
|
||||
|
||||
|
||||
def test_cli_runs_as_owned_root_profile_in_empty_installer_environment(rig,monkeypatch):
|
||||
import subprocess
|
||||
from types import SimpleNamespace
|
||||
# Keep the actual invoke function from a separate clean module instance.
|
||||
real = importlib.util.module_from_spec(spec);spec.loader.exec_module(real)
|
||||
real.OWNER=rig[3]
|
||||
monkeypatch.setattr(real.os,'environ',{'SUDO_USER':'other','NB_MANAGEMENT_URL':'foreign'})
|
||||
monkeypatch.setattr(real.pwd,'getpwuid',lambda _:SimpleNamespace(pw_dir='/root'))
|
||||
seen=[]
|
||||
def call(args,**kwargs):
|
||||
seen.append(kwargs['env'])
|
||||
return subprocess.CompletedProcess(args,0,'ok','')
|
||||
monkeypatch.setattr(real.subprocess,'run',call)
|
||||
assert real.invoke('version')=='ok'
|
||||
assert seen==[{'XDG_CONFIG_HOME':'/root/.config'}]
|
||||
|
||||
|
||||
def test_failed_cli_without_config_change_does_not_blindly_retry_rollback(rig,monkeypatch):
|
||||
data,_,calls,owner=rig
|
||||
original=module.invoke
|
||||
def fail(*args):
|
||||
if args[0]=='up':
|
||||
calls.append(args)
|
||||
raise RuntimeError('synthetic CLI failure')
|
||||
return original(*args)
|
||||
monkeypatch.setattr(module,'invoke',fail)
|
||||
with pytest.raises(RuntimeError,match='synthetic'):module.repair()
|
||||
assert len([c for c in calls if c[0]=='up'])==1
|
||||
assert json.loads(owner.with_name('network-monitor-repair.json').read_text())['state']=='unchanged'
|
||||
@@ -0,0 +1,80 @@
|
||||
"""Synthetic packet/socket checks; never open the host's real interfaces."""
|
||||
|
||||
import socket
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from uplink import quic_path as q
|
||||
|
||||
|
||||
def packet(src="192.0.2.12", dst="203.0.113.4", sport=35577, dport=8444):
|
||||
raw = bytearray(28)
|
||||
raw[0], raw[9] = 0x45, 17
|
||||
raw[12:16], raw[16:20] = socket.inet_aton(src), socket.inet_aton(dst)
|
||||
struct.pack_into("!HHH", raw, 20, sport, dport, 8)
|
||||
return bytes(raw)
|
||||
|
||||
|
||||
def test_parser_rejects_truncation_non_udp_and_fragments():
|
||||
p = packet()
|
||||
assert q.udp_header(p) == ("192.0.2.12", "203.0.113.4", 35577, 8444)
|
||||
for size in range(28):
|
||||
assert q.udp_header(p[:size]) is None
|
||||
for offset, value in [(0, 0x65), (0, 0x44), (9, 6), (6, 0x20), (7, 1), (25, 0)]:
|
||||
bad = bytearray(p)
|
||||
bad[offset] = value
|
||||
if offset == 25:
|
||||
bad[24:26] = b"\0\0"
|
||||
bad[26:28] = b"\0\0"
|
||||
struct.pack_into("!H", bad, 24, 0)
|
||||
assert q.udp_header(bad) is None
|
||||
|
||||
|
||||
def test_outgoing_matching_headers_only_and_resource_closed(monkeypatch):
|
||||
frames = [(packet(), 0), (packet(sport=9), 4), (packet(src="198.51.100.4"), 4), (packet(), 4)]
|
||||
|
||||
class Capture:
|
||||
closed = False
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
self.closed = True
|
||||
|
||||
def setsockopt(self, *args):
|
||||
pass
|
||||
|
||||
def bind(self, value):
|
||||
assert value == ("cable7", 0)
|
||||
|
||||
def settimeout(self, value):
|
||||
assert 0 < value <= 0.6
|
||||
|
||||
def recvfrom(self, size, flags=0):
|
||||
data, direction = frames[0]
|
||||
if not flags:
|
||||
frames.pop(0)
|
||||
assert size <= 28
|
||||
return data[:size], ("cable7", 0x0800, direction, 0, b"")
|
||||
|
||||
capture = Capture()
|
||||
monkeypatch.setattr(q.socket, "AF_PACKET", 17, raising=False)
|
||||
monkeypatch.setattr(q.socket, "PACKET_OUTGOING", 4, raising=False)
|
||||
monkeypatch.setattr(q.socket, "socket", lambda *a: capture)
|
||||
assert q.observe_udp("cable7", {"192.0.2.12"}, {"203.0.113.4"}, 8444, {35577}) == (
|
||||
"192.0.2.12",
|
||||
"203.0.113.4",
|
||||
)
|
||||
assert capture.closed and not frames
|
||||
|
||||
|
||||
def test_missing_capability_and_empty_owner_fail_closed(monkeypatch):
|
||||
def denied(*a):
|
||||
raise PermissionError()
|
||||
|
||||
monkeypatch.setattr(q.socket, "socket", denied)
|
||||
assert q.observe_udp("cable7", {"192.0.2.12"}, {"203.0.113.4"}, 8444, {35577}) is None
|
||||
assert q.observe_udp("cable7", {"192.0.2.12"}, {"203.0.113.4"}, 8444, set()) is None
|
||||
@@ -0,0 +1,524 @@
|
||||
"""Simulation only: fake NM adapter never opens a bus or mutates host networking."""
|
||||
|
||||
import copy
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from uplink.transaction import Controller, dispatch # noqa: E402
|
||||
|
||||
A, B = "a" * 36, "b" * 36
|
||||
|
||||
|
||||
class FakeNM:
|
||||
def __init__(self):
|
||||
self.generation = "boot:nm-1"
|
||||
self.current = A
|
||||
self.verified = True
|
||||
self.checkpoint_exists = False
|
||||
self.writes = []
|
||||
self.fail_apply = self.fail_rollback = False
|
||||
self.disconnected = set()
|
||||
self.profiles = {i: dict(id=i, kind=k, saved=dict(
|
||||
autoconnect=True, metrics={"ipv4": 50, "ipv6": 50},
|
||||
defaults={"ipv4": False, "ipv6": False})) for i,k in ((A,"wifi"),(B,"ethernet"))}
|
||||
|
||||
def epoch(self):
|
||||
return self.generation
|
||||
|
||||
def inspect(self, refresh=False, known=()):
|
||||
return dict(
|
||||
supported=True,
|
||||
revision="r1",
|
||||
current_id=self.current,
|
||||
candidates=[
|
||||
dict(id=i, verified=(i == A or self.verified), interface="nic" + i[0],
|
||||
kind=self.profiles[i]["kind"], saved=copy.deepcopy(self.profiles[i]["saved"]))
|
||||
for i in (A, B)
|
||||
if i not in self.disconnected
|
||||
],
|
||||
)
|
||||
|
||||
def public(self, value):
|
||||
return copy.deepcopy(value)
|
||||
|
||||
def checkpoint(self, entries):
|
||||
self.checkpoint_exists = True
|
||||
self.writes.append("checkpoint")
|
||||
return "/checkpoint/1"
|
||||
|
||||
def apply(self, entries, target):
|
||||
self.writes.append("apply")
|
||||
self.current = target
|
||||
if self.fail_apply:
|
||||
raise ValueError("simulated partial apply")
|
||||
|
||||
def checkpoints(self):
|
||||
return {"/checkpoint/1"} if self.checkpoint_exists else set()
|
||||
|
||||
def rollback(self, checkpoint):
|
||||
self.writes.append("rollback")
|
||||
if self.fail_rollback:
|
||||
raise ValueError("simulated rollback failure")
|
||||
self.current, self.checkpoint_exists = A, False
|
||||
self.disconnected = set()
|
||||
|
||||
def confirm(self, checkpoint):
|
||||
assert self.checkpoint_exists
|
||||
self.writes.append("confirm")
|
||||
self.checkpoint_exists = False
|
||||
|
||||
def select_only(self, entries, target):
|
||||
raise AssertionError('Never inhibit native autoconnect')
|
||||
|
||||
def locally_changed(self, entries, target):
|
||||
return any(e.get('planned') and self.profiles.get(e['id'], {}).get('saved')
|
||||
!= e['planned'] for e in entries if e['id'] in self.profiles)
|
||||
|
||||
def reserves(self, entries):
|
||||
return [e for e in entries if e["id"] in self.disconnected]
|
||||
|
||||
def activate(self, entry):
|
||||
self.disconnected.discard(entry["id"])
|
||||
|
||||
def profile_preferences(self):
|
||||
return copy.deepcopy(self.profiles)
|
||||
|
||||
def release_reserves(self, entries, target, resume_wifi=True):
|
||||
if resume_wifi:
|
||||
self.disconnected.clear()
|
||||
|
||||
def resume_autoconnect(self, entries):
|
||||
self.disconnected.clear()
|
||||
|
||||
def prefer_observed(self, entries, target, profiles):
|
||||
self.writes.append("adopt")
|
||||
self.current=target
|
||||
self.persist_choice(profiles, target)
|
||||
return profiles
|
||||
|
||||
def persist_choice(self, entries, target):
|
||||
self.persisted = target
|
||||
for entry in entries:
|
||||
self.profiles[entry["id"]]["saved"] = copy.deepcopy(entry["planned"])
|
||||
|
||||
def snapshot_profiles(self, entries, target):
|
||||
from uplink.preferences import choice
|
||||
result=copy.deepcopy(entries)
|
||||
for index,entry in enumerate(result):
|
||||
entry["saved"]=copy.deepcopy(self.profiles[entry["id"]]["saved"])
|
||||
entry["planned"]=choice(entry,target,index)
|
||||
return result
|
||||
|
||||
def restore_profiles(self, entries):
|
||||
self.persisted = A
|
||||
for entry in entries:
|
||||
if entry['id'] in self.profiles:
|
||||
self.profiles[entry['id']]['saved'] = copy.deepcopy(entry['saved'])
|
||||
|
||||
def restore_metrics(self, entries):
|
||||
self.current = A
|
||||
|
||||
|
||||
class FakePath:
|
||||
def __init__(self):
|
||||
self.valid = True
|
||||
self.selected = None
|
||||
|
||||
def select(self, policy):
|
||||
self.selected = policy.copy()
|
||||
|
||||
def release(self):
|
||||
self.selected = None
|
||||
|
||||
def prepare(self, peer, interface):
|
||||
return dict(peer=peer, interface=interface)
|
||||
|
||||
def evidence(self, policy):
|
||||
return self.valid
|
||||
|
||||
|
||||
def heartbeat(c):
|
||||
return dispatch(
|
||||
c, dict(action="heartbeat", binding="pairing:runtime", peer="10.42.0.1", provider="netbird")
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def setup(tmp_path):
|
||||
now, adapter = [1000], FakeNM()
|
||||
c = Controller(tmp_path, adapter, lambda: now[0], FakePath())
|
||||
heartbeat(c)
|
||||
return c, adapter, now
|
||||
|
||||
|
||||
def command(**changes):
|
||||
return dict(
|
||||
action="stage",
|
||||
id="a" * 32,
|
||||
binding="pairing:runtime",
|
||||
target=B,
|
||||
revision="r1",
|
||||
expires_at=1030,
|
||||
**changes,
|
||||
)
|
||||
|
||||
|
||||
def ack(c):
|
||||
return {"action": "confirm", **{k: c.operation[k] for k in ("id", "binding", "nonce")}}
|
||||
|
||||
|
||||
def test_read_only_start_and_status(setup):
|
||||
c, nm, _ = setup
|
||||
assert dispatch(c, {"action": "status"})["current_id"] == A
|
||||
assert nm.writes == []
|
||||
|
||||
|
||||
def test_confirm_keeps_selected_and_duplicate_never_reapplies(setup):
|
||||
c, nm, now = setup
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
dispatch(c, body)
|
||||
settle(c, now)
|
||||
assert c.operation["phase"] == "verifying"
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
dispatch(c, body)
|
||||
dispatch(c, ack(c))
|
||||
dispatch(c, ack(c))
|
||||
now[0] += 10
|
||||
heartbeat(c)
|
||||
c.tick()
|
||||
assert nm.current == B and nm.writes == ["checkpoint", "apply", "confirm"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"field,value",
|
||||
[("revision", "stale"), ("expires_at", 999), ("target", "unknown"), ("id", "malformed")],
|
||||
)
|
||||
def test_stale_invalid_commands_have_zero_writes(setup, field, value):
|
||||
c, nm, _ = setup
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
body[field] = value
|
||||
with pytest.raises(ValueError):
|
||||
dispatch(c, body)
|
||||
assert nm.writes == []
|
||||
|
||||
|
||||
def test_unverified_link_and_ambiguous_default_are_not_candidates(setup):
|
||||
c, nm, _ = setup
|
||||
nm.verified = False
|
||||
with pytest.raises(ValueError):
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
dispatch(c, body)
|
||||
nm.verified, nm.current = True, ""
|
||||
with pytest.raises(ValueError):
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
dispatch(c, body)
|
||||
assert not nm.writes
|
||||
|
||||
|
||||
def test_lost_core_rolls_back_without_ack(setup):
|
||||
c, nm, now = setup
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
dispatch(c, body)
|
||||
now[0] += 81
|
||||
c.tick()
|
||||
assert nm.current == A and c.operation["phase"] == "recovering"
|
||||
with pytest.raises(ValueError):
|
||||
dispatch(c, ack(c))
|
||||
|
||||
|
||||
def test_helper_restart_restores_pending_and_never_replays(setup):
|
||||
c, nm, now = setup
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
dispatch(c, body)
|
||||
recovered = Controller(c.root, nm, lambda: now[0], c.path_adapter)
|
||||
assert recovered.operation["phase"] == "recovering"
|
||||
heartbeat(recovered)
|
||||
dispatch(recovered, body)
|
||||
assert nm.writes.count("apply") == 1
|
||||
|
||||
|
||||
def test_partial_apply_rolls_back(setup):
|
||||
c, nm, _ = setup
|
||||
nm.fail_apply = True
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
dispatch(c, body)
|
||||
assert c.operation["phase"] == "recovering" and nm.current == A
|
||||
|
||||
|
||||
def test_changed_binding_nonce_and_target_loss_cannot_confirm(setup):
|
||||
c, nm, now = setup
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
dispatch(c, body)
|
||||
settle(c, now)
|
||||
for field in ("binding", "nonce", "id"):
|
||||
bad = ack(c)
|
||||
bad[field] = "x"
|
||||
with pytest.raises(ValueError):
|
||||
dispatch(c, bad)
|
||||
nm.verified = False
|
||||
dispatch(c, ack(c))
|
||||
assert c.operation["phase"] == "verifying"
|
||||
|
||||
|
||||
def test_rollback_failure_is_never_success_and_blocks_new_writes(setup):
|
||||
c, nm, now = setup
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
dispatch(c, body)
|
||||
nm.fail_rollback = True
|
||||
now[0] += 81
|
||||
c.tick()
|
||||
assert c.operation["phase"] == "rollback_failed"
|
||||
body = command()
|
||||
body.update(id="b" * 32, expires_at=1100)
|
||||
with pytest.raises(ValueError):
|
||||
dispatch(c, body)
|
||||
assert nm.writes.count("apply") == 1
|
||||
|
||||
|
||||
def test_automatic_nm_timeout_and_reboot_without_checkpoint(setup):
|
||||
c, nm, now = setup
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
dispatch(c, body)
|
||||
nm.current, nm.checkpoint_exists = A, False
|
||||
now[0] += 91
|
||||
c.tick()
|
||||
assert c.operation["phase"] == "recovering"
|
||||
|
||||
|
||||
def test_extra_fields_are_rejected(setup):
|
||||
c, nm, _ = setup
|
||||
for body in ({"action": "status", "shell": "x"}, {"action": "activate"}):
|
||||
with pytest.raises(ValueError):
|
||||
dispatch(c, body)
|
||||
assert not nm.writes
|
||||
|
||||
|
||||
def test_nm_reapply_changes_only_metrics_and_uses_version_cas():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from uplink.network_manager import NetworkManager
|
||||
|
||||
settings = {
|
||||
"connection": {"uuid": A},
|
||||
"ipv4": {"method": "auto", "route-metric": 70},
|
||||
"ipv6": {"method": "auto"},
|
||||
"802-11-wireless": {"ssid": b"example"},
|
||||
}
|
||||
original, writes = copy.deepcopy(settings), []
|
||||
device = SimpleNamespace(
|
||||
GetAppliedConnection=lambda *args, **kwargs: (copy.deepcopy(settings), 7),
|
||||
Reapply=lambda data, version, flags, **kwargs: writes.append((data, version)),
|
||||
)
|
||||
nm = NetworkManager.__new__(NetworkManager)
|
||||
nm.dbus = SimpleNamespace(Interface=lambda obj, _: obj, Int64=int, UInt32=int, Boolean=bool)
|
||||
nm.obj = lambda path: device
|
||||
nm.apply([{"id": A, "path": "/device/1", "version": 7}], A)
|
||||
sent, version = writes[0]
|
||||
assert version == 7 and sent["ipv4"]["route-metric"] == sent["ipv6"]["route-metric"] == 10
|
||||
for family in ("ipv4", "ipv6"):
|
||||
sent[family].pop("route-metric")
|
||||
assert sent[family].pop("never-default") is False
|
||||
original[family].pop("route-metric", None)
|
||||
assert sent == original
|
||||
with pytest.raises(ValueError):
|
||||
nm.apply([{"id": A, "path": "/device/1", "version": 8}], A)
|
||||
assert len(writes) == 1
|
||||
|
||||
|
||||
def test_restarted_nm_never_rolls_back_a_reused_foreign_checkpoint(setup):
|
||||
c, nm, now = setup
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
dispatch(c, body)
|
||||
nm.generation = "boot:nm-2"
|
||||
nm.current = A
|
||||
# Another owner can now have the same object path in the new NM instance.
|
||||
recovered = Controller(c.root, nm, lambda: now[0], c.path_adapter)
|
||||
assert recovered.operation["phase"] == "recovering"
|
||||
assert "rollback" not in nm.writes and nm.checkpoint_exists
|
||||
|
||||
|
||||
def settle(c, now):
|
||||
"""Next normal watchdog poll after asynchronous NM Reapply."""
|
||||
now[0] += 6
|
||||
c.tick()
|
||||
|
||||
|
||||
def select(c, now):
|
||||
body = command()
|
||||
body["revision"] = c.status()["revision"]
|
||||
dispatch(c, body)
|
||||
settle(c, now)
|
||||
return body
|
||||
|
||||
|
||||
def test_default_route_and_fresh_core_do_not_prove_vpn_path(setup):
|
||||
c, nm, now = setup
|
||||
select(c, now)
|
||||
c.path_adapter.valid = False
|
||||
assert nm.current == B
|
||||
heartbeat(c)
|
||||
dispatch(c, ack(c))
|
||||
assert c.operation["phase"] == "verifying"
|
||||
assert not c.status()["operation"]["path_verified"]
|
||||
now[0] += 81
|
||||
c.tick()
|
||||
assert nm.current == A and c.operation["phase"] == "recovering"
|
||||
|
||||
|
||||
def test_committed_selection_never_switches_after_lost_core(setup):
|
||||
c, nm, now = setup
|
||||
select(c, now)
|
||||
dispatch(c, ack(c))
|
||||
assert not nm.disconnected
|
||||
assert {e["id"] for e in c.status()["candidates"]} == {A, B}
|
||||
writes = list(nm.writes)
|
||||
now[0] += 3600
|
||||
c.tick()
|
||||
assert c.operation["phase"] == "applied"
|
||||
assert nm.current == B
|
||||
assert nm.writes == writes and not c.status()["path_verified"]
|
||||
|
||||
|
||||
def test_path_failure_enters_recovery_without_disconnecting(setup):
|
||||
c, nm, now = setup
|
||||
select(c, now)
|
||||
dispatch(c, ack(c))
|
||||
c.path_adapter.valid = False
|
||||
for _ in range(4):
|
||||
now[0] += 5
|
||||
heartbeat(c)
|
||||
assert c.operation["phase"] == "recovering" and nm.current == B
|
||||
assert not c.status()["path_verified"]
|
||||
|
||||
|
||||
def test_healthy_choice_does_not_promote_reserve(setup):
|
||||
c, nm, now = setup
|
||||
select(c, now)
|
||||
dispatch(c, ack(c))
|
||||
for _ in range(20):
|
||||
now[0] += 5
|
||||
heartbeat(c)
|
||||
assert nm.current == B and not nm.disconnected
|
||||
assert c.status()["path_verified"]
|
||||
|
||||
|
||||
def test_helper_restart_after_commit_does_not_switch(setup):
|
||||
c, nm, now = setup
|
||||
select(c, now)
|
||||
dispatch(c, ack(c))
|
||||
recovered = Controller(c.root, nm, lambda: now[0], c.path_adapter)
|
||||
assert recovered.operation["phase"] == "applied"
|
||||
assert nm.current == B
|
||||
assert not recovered.status()["path_verified"]
|
||||
|
||||
|
||||
def test_original_journal_and_vpn_state_never_leak_through_ipc(setup):
|
||||
c, _, now = setup
|
||||
select(c, now)
|
||||
op = c.status()["operation"]
|
||||
assert not {"baseline", "policy", "checkpoint", "epoch"} & op.keys()
|
||||
|
||||
|
||||
def test_switch_back_can_activate_saved_disconnected_reserve(setup):
|
||||
c, nm, now = setup
|
||||
select(c, now)
|
||||
dispatch(c, ack(c))
|
||||
now[0] += 5
|
||||
heartbeat(c)
|
||||
body = command()
|
||||
body.update(id="b" * 32, target=A, revision=c.status()["revision"])
|
||||
dispatch(c, body)
|
||||
settle(c, now)
|
||||
assert c.operation["phase"] == "verifying"
|
||||
dispatch(c, ack(c))
|
||||
assert nm.current == A and not nm.disconnected
|
||||
|
||||
|
||||
def test_upgrade_does_not_trust_legacy_metric_only_applied_receipt(tmp_path):
|
||||
import json
|
||||
|
||||
(tmp_path / "operation.json").write_text(
|
||||
json.dumps(dict(id="a" * 32, phase="applied", target=B))
|
||||
)
|
||||
nm = FakeNM()
|
||||
c = Controller(tmp_path, nm, lambda: 1000, FakePath())
|
||||
heartbeat(c)
|
||||
assert c.operation["phase"] == "superseded"
|
||||
assert not c.status()["path_verified"]
|
||||
assert not nm.writes
|
||||
|
||||
|
||||
def test_wifi_selection_keeps_ethernet_lan_and_does_not_mutate_addresses():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from uplink.network_manager import NetworkManager
|
||||
|
||||
writes = []
|
||||
states = {
|
||||
A: {"connection": {"uuid": A}, "ipv4": {"method": "auto", "address-data": ["lease"]}},
|
||||
B: {"connection": {"uuid": B}, "ipv4": {"method": "auto", "address-data": ["router-lan"]}},
|
||||
}
|
||||
devices = {
|
||||
identity: SimpleNamespace(
|
||||
GetAppliedConnection=lambda *a, i=identity, **k: (copy.deepcopy(states[i]), 1),
|
||||
Reapply=lambda data, *a, i=identity, **k: writes.append((i, data)),
|
||||
Disconnect=lambda *a, i=identity, **k: pytest.fail("Ethernet must stay connected"),
|
||||
) for identity in (A, B)
|
||||
}
|
||||
nm = NetworkManager.__new__(NetworkManager)
|
||||
nm.dbus = SimpleNamespace(Interface=lambda obj, _: obj, Int64=int, UInt32=int, Boolean=bool)
|
||||
nm.obj = lambda path: devices[path]
|
||||
entries = [dict(id=A, path=A, version=1, kind="wifi"),
|
||||
dict(id=B, path=B, version=1, kind="ethernet")]
|
||||
nm.apply(entries, A)
|
||||
assert writes[0][1]["ipv4"]["never-default"] is False
|
||||
assert writes[1][1]["ipv4"]["never-default"] is False
|
||||
assert writes[1][1]["ipv4"]["address-data"] == ["router-lan"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("target", [A, B])
|
||||
def test_saved_choice_retains_native_fallback(target):
|
||||
from uplink.network_manager import NetworkManager
|
||||
|
||||
nm = NetworkManager.__new__(NetworkManager)
|
||||
values = {}
|
||||
nm.set_preference = lambda entry, value: values.update({entry["id"]: value})
|
||||
nm.profile_preferences = lambda: {A: {"saved": {}}, B: {"saved": {}}}
|
||||
nm.persist_choice([dict(id=A, kind="wifi", saved={}),
|
||||
dict(id=B, kind="ethernet", saved={})], target)
|
||||
assert values[A]["autoconnect"] is True
|
||||
assert values[B]["autoconnect"] is True # Router LAN returns with its cable.
|
||||
assert values[B]["defaults"]["ipv4"] is False
|
||||
assert values[A]["defaults"]["ipv4"] is False
|
||||
|
||||
|
||||
def test_failed_manual_switch_returns_previous_and_then_stays_there(setup):
|
||||
c, nm, now = setup
|
||||
select(c, now)
|
||||
now[0] += 81
|
||||
c.tick()
|
||||
now[0] += 1
|
||||
heartbeat(c)
|
||||
now[0] += 11
|
||||
heartbeat(c)
|
||||
assert c.operation["phase"] == "rolled_back" and nm.current == A
|
||||
before = list(nm.writes)
|
||||
now[0] += 3600
|
||||
c.path_adapter.valid = False
|
||||
c.tick()
|
||||
assert nm.current == A and nm.writes == before
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Fallback permission must affect routing, survive restart and preserve manual rollback."""
|
||||
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
from test_uplink import A, B, FakeNM, FakePath, ack, heartbeat, select
|
||||
from uplink.transaction import Controller, dispatch
|
||||
|
||||
|
||||
def prepared(tmp_path):
|
||||
nm, clock, path = FakeNM(), [1000], FakePath()
|
||||
c = Controller(tmp_path, nm, lambda: clock[0], path)
|
||||
heartbeat(c)
|
||||
select(c, clock)
|
||||
c.confirm(ack(c))
|
||||
return c, nm, clock, path
|
||||
|
||||
|
||||
def setting(c, enabled, identity='e'*32):
|
||||
return dict(action='fallback', id=identity, binding='pairing:runtime', enabled=enabled,
|
||||
revision=c.fallback_setting['revision'], expires_at=int(c.clock())+30)
|
||||
|
||||
|
||||
def test_default_on_disable_is_durable_idempotent_and_never_switches(tmp_path):
|
||||
c, nm, clock, path = prepared(tmp_path)
|
||||
assert c.status()['fallback']['enabled'] is True
|
||||
writes = list(nm.writes)
|
||||
body = setting(c, False)
|
||||
dispatch(c, body)
|
||||
dispatch(c, body)
|
||||
assert c.status()['fallback']['revision'] == 1 and nm.writes == writes
|
||||
assert path.selected['strict'] and nm.current == B and not nm.disconnected
|
||||
restarted = Controller(tmp_path, nm, lambda: clock[0], path)
|
||||
assert not restarted.fallback_enabled() and path.selected['strict']
|
||||
path.valid = False
|
||||
for _ in range(100):
|
||||
clock[0] += 5
|
||||
restarted.tick()
|
||||
assert nm.current == B and nm.writes == writes
|
||||
assert restarted.operation['phase'] == 'applied'
|
||||
|
||||
|
||||
def test_disabled_does_not_adopt_an_unselected_path(tmp_path):
|
||||
c, nm, clock, path = prepared(tmp_path)
|
||||
dispatch(c, setting(c, False))
|
||||
nm.current = A
|
||||
path.evidence = lambda policy: policy['interface'] == 'nica'
|
||||
for _ in range(10):
|
||||
clock[0] += 10
|
||||
heartbeat(c)
|
||||
assert c.watched_target() == B
|
||||
assert not c.status()['path_verified']
|
||||
assert c.status()['current_id'] == B
|
||||
|
||||
|
||||
def test_enabled_restores_recovery_without_changing_current_choice(tmp_path):
|
||||
c, nm, clock, path = prepared(tmp_path)
|
||||
dispatch(c, setting(c, False))
|
||||
dispatch(c, setting(c, True, 'f'*32))
|
||||
assert not path.selected.get('strict') and nm.current == B
|
||||
path.valid = False
|
||||
for _ in range(18):
|
||||
clock[0] += 5
|
||||
c.tick()
|
||||
assert nm.current == A and c.operation['phase'] == 'recovering'
|
||||
path.valid = True
|
||||
heartbeat(c)
|
||||
clock[0] += 11
|
||||
heartbeat(c)
|
||||
event = c.status()['events'][-1]
|
||||
assert (event['kind'], event['source'], event['target']) == ('fallback', 'ethernet', 'wifi')
|
||||
for _ in range(5):
|
||||
clock[0] += 10
|
||||
heartbeat(c)
|
||||
assert c.status()['events'] == [event]
|
||||
|
||||
|
||||
def test_failed_manual_selection_rolls_back_even_with_fallback_disabled(tmp_path):
|
||||
c, nm, clock, path = prepared(tmp_path)
|
||||
dispatch(c, setting(c, False))
|
||||
command = dict(action='stage',id='f'*32,binding='pairing:runtime',target=A,
|
||||
revision=c.status()['revision'],expires_at=1030)
|
||||
# Fake checkpoint tracks A by default; adapt it to this transaction's B baseline.
|
||||
nm.rollback = lambda cp: (setattr(nm,'current',B),setattr(nm,'checkpoint_exists',False))
|
||||
nm.restore_metrics = lambda entries: setattr(nm,'current',B)
|
||||
dispatch(c, command)
|
||||
clock[0] += 81
|
||||
c.tick()
|
||||
assert nm.current == B and c.watched_target() == B and path.selected['strict']
|
||||
heartbeat(c)
|
||||
clock[0] += 11
|
||||
heartbeat(c)
|
||||
assert c.operation['phase'] == 'rolled_back'
|
||||
assert c.status()['events'][-1]['kind'] == 'manual_rollback'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('change',[{'enabled':'false'},{'revision':9},{'expires_at':999},{'binding':'wrong'}])
|
||||
def test_invalid_setting_has_no_effect(tmp_path,change):
|
||||
c,nm,clock,path=prepared(tmp_path)
|
||||
before=copy.deepcopy(path.selected)
|
||||
with pytest.raises(ValueError):
|
||||
dispatch(c,{**setting(c,False),**change})
|
||||
assert c.fallback_enabled() and path.selected==before
|
||||
|
||||
|
||||
def test_failed_setting_write_restores_previous_policy(tmp_path):
|
||||
c,nm,clock,path=prepared(tmp_path)
|
||||
c.save=lambda: (_ for _ in ()).throw(OSError('disk full'))
|
||||
with pytest.raises(OSError):
|
||||
dispatch(c,setting(c,False))
|
||||
assert c.fallback_enabled() and not path.selected.get('strict')
|
||||
|
||||
|
||||
|
||||
def test_proven_vpn_path_wins_over_unmarked_default_and_avoids_recovery(tmp_path):
|
||||
c, nm, clock, path = prepared(tmp_path)
|
||||
path.evidence = lambda policy: policy['interface'] == 'nicb'
|
||||
nm.current = A # Native connectivity penalty changes only the unmarked default.
|
||||
before = list(nm.writes)
|
||||
for _ in range(10):
|
||||
clock[0] += 6
|
||||
heartbeat(c)
|
||||
assert c.status()['path_verified'] and c.status()['current_id'] == B
|
||||
assert c.watched_target() == B and nm.writes == before
|
||||
|
||||
|
||||
def test_same_channel_recovery_does_not_reapply_dhcp(tmp_path):
|
||||
c, nm, clock, path = prepared(tmp_path)
|
||||
path.evidence = lambda policy: policy['interface'] == 'nicb'
|
||||
c.operation.update(phase='recovering', recovery_reason='automatic')
|
||||
before = list(nm.writes)
|
||||
heartbeat(c)
|
||||
clock[0] += 11
|
||||
heartbeat(c)
|
||||
assert c.status()['path_verified'] and c.watched_target() == B
|
||||
assert nm.writes == before and not c.status()['events']
|
||||
|
||||
|
||||
def test_disabled_ip_family_is_not_claimed_as_a_mutable_preference(monkeypatch):
|
||||
from uplink.preferences import Preferences, choice
|
||||
|
||||
calls = []
|
||||
monkeypatch.setattr('uplink.preferences.subprocess.run',
|
||||
lambda args, **kw: calls.append(args))
|
||||
entry = dict(id=A, inactive_families=['ipv6'], saved=dict(autoconnect=True,
|
||||
metrics={'ipv4':100, 'ipv6':-1}, defaults={'ipv4':False, 'ipv6':False}))
|
||||
planned = choice(entry, A, 0)
|
||||
assert planned['metrics'] == {'ipv4':10, 'ipv6':-1}
|
||||
Preferences().set_preference(entry, planned)
|
||||
assert 'ipv4.route-metric' in calls[0] and 'ipv6.route-metric' not in calls[0]
|
||||
@@ -0,0 +1,197 @@
|
||||
"""Both physical directions, native/marked divergence and failed guarded trials."""
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
from test_uplink import A, B, FakeNM, FakePath, ack, heartbeat, settle
|
||||
from test_uplink_fallback import setting
|
||||
from uplink.transaction import Controller, dispatch
|
||||
|
||||
|
||||
@pytest.fixture(params=[(A, B), (B, A)])
|
||||
def channel(tmp_path, request):
|
||||
previous, target = request.param
|
||||
nm, path, now = FakeNM(), FakePath(), [1000]
|
||||
nm.current = previous
|
||||
route = [previous]
|
||||
path.evidence = lambda p: p['interface'] == 'nic'+route[0][0] if route[0] else False
|
||||
c = Controller(tmp_path, nm, lambda: now[0], path)
|
||||
heartbeat(c)
|
||||
now[0] += 11
|
||||
heartbeat(c)
|
||||
assert c.status()['path_verified']
|
||||
return c, nm, path, now, route, previous, target
|
||||
|
||||
|
||||
def trial(c, target):
|
||||
return dict(action='stage', id='f'*32, binding='pairing:runtime', target=target,
|
||||
revision=c.status()['revision'], expires_at=int(c.clock())+30)
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled', [False, True])
|
||||
def test_toggle_uses_actual_transport_even_if_native_default_disagrees(channel, enabled):
|
||||
c, nm, path, now, route, previous, target = channel
|
||||
nm.current = target
|
||||
before = list(nm.writes)
|
||||
dispatch(c, setting(c, enabled))
|
||||
assert c.fallback_enabled() is enabled
|
||||
assert path.selected['interface'] == 'nic'+previous[0]
|
||||
assert c.status()['current_id'] == previous and nm.writes == before
|
||||
|
||||
|
||||
@pytest.mark.parametrize('enabled', [False, True])
|
||||
@pytest.mark.parametrize('restart', [False, True])
|
||||
def test_failed_trial_restores_baseline_and_notifies_after_proof(channel, enabled, restart):
|
||||
c, nm, path, now, route, previous, target = channel
|
||||
dispatch(c, setting(c, enabled))
|
||||
nm.current = target # Unmarked route differs from the proven selected VPN path.
|
||||
nm.restore_metrics = lambda entries: setattr(nm, 'current', target)
|
||||
nm.rollback = lambda cp: setattr(nm, 'checkpoint_exists', False)
|
||||
body = trial(c, target)
|
||||
dispatch(c, body)
|
||||
assert c.operation['previous'] == previous
|
||||
route[0] = '' # Cable/address exists but Core transport cannot pass.
|
||||
if restart:
|
||||
c = Controller(c.root, nm, lambda: now[0], path)
|
||||
else:
|
||||
now[0] += 81
|
||||
c.tick()
|
||||
assert c.operation['phase'] == 'recovering'
|
||||
assert c.watched_target() == previous
|
||||
assert path.selected['interface'] == 'nic'+previous[0]
|
||||
assert not c.status()['events'] and not c.status()['path_verified']
|
||||
route[0] = previous
|
||||
heartbeat(c)
|
||||
assert not c.status()['events']
|
||||
now[0] += 11
|
||||
heartbeat(c)
|
||||
assert c.operation['phase'] == 'rolled_back' and c.status()['path_verified']
|
||||
assert c.status()['current_id'] == previous
|
||||
event = c.status()['events'][-1]
|
||||
assert event['kind'] == 'manual_rollback'
|
||||
assert event['source'] == nm.profiles[target]['kind']
|
||||
assert event['target'] == nm.profiles[previous]['kind']
|
||||
saved = copy.deepcopy(c.status()['events'])
|
||||
heartbeat(c)
|
||||
assert c.status()['events'] == saved
|
||||
|
||||
|
||||
def test_successful_trial_requires_new_path_ack_and_retains_choice(channel):
|
||||
c, nm, path, now, route, previous, target = channel
|
||||
nm.current = target
|
||||
dispatch(c, trial(c, target))
|
||||
settle(c, now)
|
||||
c.confirm(ack(c)) # ACK arriving on the previous path is not acceptance.
|
||||
assert c.operation['phase'] == 'verifying'
|
||||
route[0] = target
|
||||
c.confirm(ack(c))
|
||||
assert c.operation['phase'] == 'applied'
|
||||
nm.current = previous
|
||||
for _ in range(4):
|
||||
now[0] += 6
|
||||
heartbeat(c)
|
||||
assert c.status()['path_verified'] and c.status()['current_id'] == target
|
||||
assert not c.status()['events']
|
||||
|
||||
|
||||
def test_no_proven_baseline_refuses_without_mutating_network(channel):
|
||||
c, nm, path, now, route, previous, target = channel
|
||||
route[0] = ''
|
||||
before = list(nm.writes)
|
||||
with pytest.raises(ValueError, match='не подтверждён'):
|
||||
dispatch(c, trial(c, target))
|
||||
assert nm.writes == before
|
||||
|
||||
|
||||
def test_restart_preserves_healthy_choice_against_native_default(channel):
|
||||
c, nm, path, now, route, previous, target = channel
|
||||
nm.current = target
|
||||
restarted = Controller(c.root, nm, lambda: now[0], path)
|
||||
assert path.selected['interface'] == 'nic'+previous[0]
|
||||
assert not restarted.status()['path_verified'] # Fresh Core reply still required.
|
||||
heartbeat(restarted)
|
||||
assert restarted.status()['path_verified']
|
||||
assert restarted.status()['current_id'] == previous
|
||||
|
||||
|
||||
def test_evidence_is_bounded_preserves_transitions_and_excludes_credentials(channel):
|
||||
c, nm, path, now, route, previous, target = channel
|
||||
for i in range(25):
|
||||
dispatch(c, setting(c, bool(i % 2), f'{i+1:032x}'))
|
||||
state = c.status()['diagnostic']
|
||||
assert len(state['events']) == 16
|
||||
assert state['events'][-1]['sequence'] > 16
|
||||
assert state['interface'] == 'nic'+previous[0]
|
||||
assert not {'nonce', 'binding', 'peer', 'baseline'} & state.keys()
|
||||
|
||||
|
||||
def test_async_dhcp_route_waits_without_reapplying_preferences(channel):
|
||||
from uplink.transport_route import RouteNotReady
|
||||
c, nm, path, now, route, previous, target = channel
|
||||
original = path.select
|
||||
calls = []
|
||||
def select(policy):
|
||||
calls.append(policy)
|
||||
if len(calls) == 1:
|
||||
raise RouteNotReady('DHCP is publishing the route')
|
||||
original(policy)
|
||||
path.select = select
|
||||
dispatch(c, trial(c, target))
|
||||
assert c.operation['phase'] == 'applying'
|
||||
assert c.operation['wait_reason'] == 'network_preferences_pending'
|
||||
assert not calls # No route mutation in the NM Reapply call.
|
||||
settle(c, now)
|
||||
assert c.operation['wait_reason'] == 'gateway_pending'
|
||||
writes = list(nm.writes)
|
||||
now[0] += 6
|
||||
c.tick()
|
||||
assert c.operation['phase'] == 'verifying'
|
||||
assert nm.writes == writes
|
||||
route[0] = target
|
||||
c.confirm(ack(c))
|
||||
assert c.operation['phase'] == 'applied'
|
||||
|
||||
|
||||
def test_nontransient_apply_error_is_recorded_without_secret_text(channel):
|
||||
c, nm, path, now, route, previous, target = channel
|
||||
def broken(*args):
|
||||
raise RuntimeError('private password text must never reach diagnostic')
|
||||
nm.apply = broken
|
||||
dispatch(c, trial(c, target))
|
||||
events = c.status()['diagnostic']['events']
|
||||
assert any(e['state'].get('failure') == {'step':'network_preferences',
|
||||
'error_type':'RuntimeError'} for e in events)
|
||||
assert 'private password' not in str(events)
|
||||
assert c.operation['phase'] == 'recovering'
|
||||
|
||||
|
||||
def test_ip_kernel_error_is_preserved_locally_for_failed_trial(channel):
|
||||
import subprocess
|
||||
c, nm, path, now, route, previous, target = channel
|
||||
def broken(policy):
|
||||
raise subprocess.CalledProcessError(2, ('/usr/sbin/ip', '-4', 'route', 'add'),
|
||||
stderr=b'RTNETLINK answers: test error')
|
||||
dispatch(c, trial(c, target))
|
||||
path.select = broken
|
||||
settle(c, now)
|
||||
failure = next(e['state']['failure'] for e in c.status()['diagnostic']['events']
|
||||
if e['state'].get('failure'))
|
||||
assert failure['step'] == 'transport_route'
|
||||
assert failure['command'] == ['/usr/sbin/ip', '-4', 'route', 'add']
|
||||
assert failure['exit_code'] == 2 and 'RTNETLINK' in failure['kernel_error']
|
||||
|
||||
|
||||
def test_trial_reads_cached_nm_readiness_without_global_connectivity_probe(channel):
|
||||
c, nm, path, now, route, previous, target = channel
|
||||
inspect = nm.inspect
|
||||
calls = []
|
||||
def readonly_inventory(*, known=()):
|
||||
calls.append(True)
|
||||
return inspect(known=known)
|
||||
nm.inspect = readonly_inventory # No refresh command/probe accepted.
|
||||
dispatch(c, trial(c, target))
|
||||
assert c.operation['wait_reason'] == 'network_preferences_pending'
|
||||
settle(c, now)
|
||||
assert calls and c.operation['phase'] == 'verifying'
|
||||
route[0] = target
|
||||
c.confirm(ack(c))
|
||||
assert c.operation['phase'] == 'applied'
|
||||
@@ -0,0 +1,133 @@
|
||||
"""Path proof must reject a healthy default when the VPN uses the reserve."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parent))
|
||||
from uplink import netbird_path as module # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def observer(monkeypatch):
|
||||
state = {
|
||||
"profileName": "mission-core",
|
||||
"daemonVersion": "0.82.0",
|
||||
"peers": {
|
||||
"details": [
|
||||
{
|
||||
"netbirdIp": "10.42.0.1",
|
||||
"status": "Connected",
|
||||
"connectionType": "Relayed",
|
||||
"relayAddress": "rels://vpn.example.test:8443",
|
||||
"publicKey": "public",
|
||||
"iceCandidateEndpoint": {"local": "192.0.2.12:5000"},
|
||||
"iceCandidateType": {"local": "host"},
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
facts = {
|
||||
"source": "192.0.2.12",
|
||||
"route": "cable7",
|
||||
"owner": "/system.slice/netbird.service",
|
||||
"socket": True,
|
||||
"quic": False,
|
||||
}
|
||||
|
||||
def run(*args):
|
||||
if args[0].endswith("netbird"):
|
||||
return json.dumps(state)
|
||||
if "address" in args:
|
||||
return json.dumps([{"addr_info": [{"family": "inet", "local": "192.0.2.12"}]}])
|
||||
if "route" in args:
|
||||
return json.dumps([{"dev": facts["route"]}])
|
||||
if args[0].endswith("getent"):
|
||||
return "203.0.113.4 STREAM vpn.example.test"
|
||||
if args[0].endswith("systemctl"):
|
||||
return "/system.slice/netbird.service"
|
||||
if args[0].endswith("ss"):
|
||||
if facts["quic"]:
|
||||
return f"udp UNCONN 0 0 *:35577 *:* cgroup:{facts['owner']}"
|
||||
return (
|
||||
f"tcp ESTAB 0 0 {facts['source']}:5000 203.0.113.4:8443 cgroup:{facts['owner']}"
|
||||
if facts["socket"]
|
||||
else ""
|
||||
)
|
||||
if args[0].endswith("wg"):
|
||||
return "public\t203.0.113.4:5000"
|
||||
raise AssertionError(args)
|
||||
|
||||
monkeypatch.setattr(module, "run", run)
|
||||
return module.NetBirdPath(), state, facts, dict(peer="10.42.0.1", interface="cable7")
|
||||
|
||||
|
||||
def test_actual_relay_socket_and_route_must_agree(observer):
|
||||
probe, state, facts, policy = observer
|
||||
assert probe.evidence(policy)
|
||||
for key, wrong in [
|
||||
("source", "198.51.100.5"),
|
||||
("route", "radio8"),
|
||||
("owner", "/system.slice/unrelated.service"),
|
||||
("socket", False),
|
||||
]:
|
||||
before = facts[key]
|
||||
facts[key] = wrong
|
||||
assert not probe.evidence(policy)
|
||||
facts[key] = before
|
||||
|
||||
|
||||
def test_connected_core_on_another_physical_ice_path_is_not_success(observer):
|
||||
probe, state, facts, policy = observer
|
||||
peer = state["peers"]["details"][0]
|
||||
peer["connectionType"] = "P2P"
|
||||
assert probe.evidence(policy)
|
||||
peer["iceCandidateEndpoint"]["local"] = "198.51.100.5:5000"
|
||||
assert not probe.evidence(policy)
|
||||
|
||||
|
||||
def test_unknown_transport_or_other_profile_never_inferred_from_default(observer):
|
||||
probe, state, facts, policy = observer
|
||||
state["peers"]["details"][0]["connectionType"] = "unknown"
|
||||
assert not probe.evidence(policy)
|
||||
state["profileName"] = "other"
|
||||
with pytest.raises(ValueError):
|
||||
probe.evidence(policy)
|
||||
|
||||
|
||||
def test_marked_kernel_path_does_not_use_stale_ice_interface_as_current_proof(observer):
|
||||
probe, state, facts, policy = observer
|
||||
peer = state["peers"]["details"][0]
|
||||
peer["connectionType"] = "P2P"
|
||||
peer["iceCandidateEndpoint"]["local"] = "198.51.100.5:5000"
|
||||
policy["mark"] = 0x1BD00
|
||||
assert probe.evidence(policy)
|
||||
facts["route"] = "radio8"
|
||||
assert not probe.evidence(policy)
|
||||
|
||||
|
||||
def test_quic_requires_owned_observed_packet_and_matching_route(observer, monkeypatch):
|
||||
probe, state, facts, policy = observer
|
||||
facts["quic"] = True
|
||||
state["relays"] = {
|
||||
"details": [{"uri": "rels://vpn.example.test:8443", "available": True, "transport": "quic"}]
|
||||
}
|
||||
observed = []
|
||||
|
||||
def capture(interface, sources, ips, port, owned):
|
||||
observed.append((interface, sources, ips, port, owned))
|
||||
return ("192.0.2.12", "203.0.113.4") if owned == {35577} else None
|
||||
|
||||
monkeypatch.setattr(module, "observe_udp", capture)
|
||||
assert probe.evidence(policy)
|
||||
assert observed[0][0] == "cable7"
|
||||
facts["route"] = "radio8"
|
||||
assert not probe.evidence(policy)
|
||||
facts["route"] = "cable7"
|
||||
facts["owner"] = "/foreign.service"
|
||||
assert not probe.evidence(policy)
|
||||
facts["owner"] = "/system.slice/netbird.service"
|
||||
monkeypatch.setattr(module, "observe_udp", lambda *args: None)
|
||||
assert not probe.evidence(policy)
|
||||
@@ -0,0 +1,265 @@
|
||||
"""Native NM reconnection, sticky recovery and local-operator ownership."""
|
||||
import copy
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from test_uplink import A, B, FakeNM, FakePath, ack, heartbeat, select
|
||||
from uplink.migration import migrate
|
||||
from uplink.transaction import Controller
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rig(tmp_path):
|
||||
nm, now = FakeNM(), [1000]
|
||||
c = Controller(tmp_path, nm, lambda: now[0], FakePath())
|
||||
heartbeat(c)
|
||||
select(c, now)
|
||||
c.confirm(ack(c))
|
||||
return c,nm,now
|
||||
|
||||
|
||||
def test_all_offline_waits_for_nm_and_requires_new_core_evidence(rig):
|
||||
c,nm,now=rig
|
||||
before=list(nm.writes)
|
||||
nm.current=""
|
||||
nm.disconnected={A,B}
|
||||
now[0]+=120
|
||||
c.tick()
|
||||
assert nm.writes==before and not c.status()["path_verified"]
|
||||
# NetworkManager, not our controller, reconnects a saved Wi-Fi.
|
||||
nm.current=A
|
||||
nm.disconnected={B}
|
||||
now[0]+=20
|
||||
c.tick()
|
||||
assert nm.writes==before
|
||||
heartbeat(c)
|
||||
assert nm.writes==before
|
||||
now[0]+=11
|
||||
heartbeat(c)
|
||||
assert nm.writes==before+["adopt"]
|
||||
assert c.watched_target()==A and c.status()["path_verified"]
|
||||
assert nm.profiles[A]["saved"]["metrics"]["ipv4"]==10
|
||||
|
||||
|
||||
def test_returning_ethernet_does_not_steal_recovered_wifi(rig):
|
||||
c,nm,now=rig
|
||||
nm.current=A
|
||||
nm.disconnected.clear()
|
||||
heartbeat(c)
|
||||
now[0]+=11
|
||||
heartbeat(c)
|
||||
before=list(nm.writes)
|
||||
nm.disconnected.clear()
|
||||
for _ in range(6):
|
||||
now[0]+=10
|
||||
heartbeat(c)
|
||||
assert c.watched_target()==A and nm.writes==before
|
||||
assert nm.profiles[B]["saved"]["metrics"]["ipv4"]>nm.profiles[A]["saved"]["metrics"]["ipv4"]
|
||||
|
||||
|
||||
def test_old_vpn_path_or_single_heartbeat_cannot_latch(rig):
|
||||
c,nm,now=rig
|
||||
nm.current=A
|
||||
c.path_adapter.valid=False
|
||||
before=list(nm.writes)
|
||||
for _ in range(4):
|
||||
now[0]+=20
|
||||
heartbeat(c)
|
||||
assert nm.writes==before and c.watched_target()==B
|
||||
c.path_adapter.valid=True
|
||||
heartbeat(c)
|
||||
assert nm.writes==before
|
||||
|
||||
|
||||
def test_ubuntu_profile_changes_are_observed_without_rewriting(rig):
|
||||
c,nm,now=rig
|
||||
nm.current=A
|
||||
nm.disconnected.clear()
|
||||
nm.profiles[A]["saved"]["metrics"]["ipv4"]=7
|
||||
before=copy.deepcopy(nm.profiles)
|
||||
writes=list(nm.writes)
|
||||
heartbeat(c)
|
||||
now[0]+=11
|
||||
heartbeat(c)
|
||||
assert nm.profiles==before and nm.writes==writes
|
||||
assert c.watched_target()==A and c.status()["path_verified"]
|
||||
|
||||
|
||||
def test_loss_of_core_alone_never_disconnects_a_network(rig):
|
||||
c,nm,now=rig
|
||||
before=list(nm.writes)
|
||||
now[0]+=3600
|
||||
c.tick()
|
||||
now[0]+=16
|
||||
c.tick()
|
||||
assert nm.current==B and not nm.disconnected and nm.writes==before
|
||||
|
||||
|
||||
def test_failed_release_rolls_back_instead_of_committing(tmp_path):
|
||||
nm,now=FakeNM(),[1000]
|
||||
c=Controller(tmp_path,nm,lambda:now[0],FakePath())
|
||||
heartbeat(c)
|
||||
select(c, now)
|
||||
nm.release_reserves=lambda *_, **kw: (_ for _ in ()).throw(ValueError("changed locally"))
|
||||
c.confirm(ack(c))
|
||||
assert c.operation["phase"]=="recovering" and nm.current==A
|
||||
assert "confirm" not in nm.writes
|
||||
|
||||
|
||||
class MigrationNM(FakeNM):
|
||||
def set_preference(self,entry,value):
|
||||
self.profiles[entry["id"]]["saved"]=copy.deepcopy(value)
|
||||
def restore_profiles(self,entries):
|
||||
for entry in entries:
|
||||
if self.profiles[entry["id"]]["saved"]==entry["planned"]:
|
||||
self.set_preference(entry,entry["saved"])
|
||||
|
||||
|
||||
def test_installer_undoes_only_owned_bans_and_is_repeatable(tmp_path):
|
||||
nm=MigrationNM()
|
||||
entries=nm.inspect()["candidates"]
|
||||
nm.profiles[A]["saved"]=dict(autoconnect=False,metrics={"ipv4":100,"ipv6":100},defaults={"ipv4":True,"ipv6":True})
|
||||
nm.profiles[B]["saved"]["metrics"]={"ipv4":10,"ipv6":10}
|
||||
(tmp_path/"operation.json").write_text(json.dumps(dict(phase="applied",target=B,baseline=entries)))
|
||||
migrate(tmp_path,nm)
|
||||
assert nm.profiles[A]["saved"]["autoconnect"]
|
||||
assert not nm.profiles[A]["saved"]["defaults"]["ipv4"]
|
||||
after=copy.deepcopy(nm.profiles)
|
||||
migrate(tmp_path,nm)
|
||||
assert nm.profiles==after
|
||||
|
||||
|
||||
def test_migration_preserves_later_manual_edits(tmp_path):
|
||||
nm=MigrationNM()
|
||||
entries=nm.inspect()["candidates"]
|
||||
nm.profiles[A]["saved"]["metrics"]["ipv4"]=444
|
||||
before=copy.deepcopy(nm.profiles)
|
||||
(tmp_path/"operation.json").write_text(json.dumps(dict(phase="applied",target=B,baseline=entries)))
|
||||
migrate(tmp_path,nm)
|
||||
assert nm.profiles==before
|
||||
|
||||
|
||||
def test_offline_previous_profile_is_demoted_when_recovery_is_latched(rig):
|
||||
c,nm,now=rig
|
||||
nm.current=A
|
||||
nm.disconnected={B}
|
||||
heartbeat(c)
|
||||
now[0]+=11
|
||||
heartbeat(c)
|
||||
assert nm.profiles[B]["saved"]["metrics"]["ipv4"]>10
|
||||
|
||||
|
||||
def test_core_service_outage_does_not_disable_reserves_after_rollback(rig):
|
||||
c,nm,now=rig
|
||||
nm.current=A
|
||||
nm.disconnected.clear()
|
||||
c.operation.update(phase="recovering",previous=B,recovery_started=now[0])
|
||||
now[0]+=1
|
||||
heartbeat(c)
|
||||
now[0]+=11
|
||||
heartbeat(c)
|
||||
assert c.operation["phase"]=="superseded"
|
||||
assert c.watched_target()==A and not nm.disconnected
|
||||
|
||||
|
||||
def test_connected_backup_is_released_without_changing_addresses_or_credentials():
|
||||
from types import SimpleNamespace
|
||||
|
||||
from uplink.network_manager import NetworkManager
|
||||
nm=NetworkManager.__new__(NetworkManager)
|
||||
writes=[]
|
||||
settings={"connection":{"uuid":A},"ipv4":{"never-default":True,"address-data":["lease"]}}
|
||||
dev=SimpleNamespace(GetAppliedConnection=lambda *a,**kw:(copy.deepcopy(settings),9),
|
||||
Reapply=lambda s,v,f,**kw:writes.append((s,v,f)))
|
||||
nm.obj=lambda _:dev
|
||||
nm.dbus=SimpleNamespace(Interface=lambda obj,_:obj,Boolean=bool,UInt32=int,Int64=int)
|
||||
nm.same_device=lambda *args:True
|
||||
nm.props=lambda *args:{"State":100}
|
||||
nm.profile_preferences=lambda:{A:{"saved":{"defaults":{"ipv4":False},"metrics":{"ipv4":100}}}}
|
||||
nm.release_reserves([dict(id=A,path="/a",kind="wifi")],B)
|
||||
assert writes[0][0]["ipv4"]=={"never-default":False,"route-metric":100,"address-data":["lease"]}
|
||||
assert writes[0][2]==1 # Preserve external IP addresses and routes.
|
||||
|
||||
|
||||
def test_installer_failure_restores_owned_saved_profile(tmp_path):
|
||||
nm=MigrationNM()
|
||||
entries=nm.inspect()["candidates"]
|
||||
nm.profiles[A]["saved"]=dict(autoconnect=False,metrics={"ipv4":100,"ipv6":100},defaults={"ipv4":True,"ipv6":True})
|
||||
before=copy.deepcopy(nm.profiles)
|
||||
(tmp_path/"operation.json").write_text(json.dumps(dict(phase="applied",target=B,baseline=entries)))
|
||||
nm.release_reserves=lambda *_: (_ for _ in ()).throw(ValueError("reapply failed"))
|
||||
with pytest.raises(ValueError):
|
||||
migrate(tmp_path,nm)
|
||||
assert nm.profiles==before
|
||||
assert not (tmp_path/"native-fallback-v1.json").exists()
|
||||
|
||||
|
||||
def test_local_ubuntu_selection_is_adopted_by_actual_vpn_path(rig):
|
||||
c,nm,now=rig
|
||||
nm.disconnected.clear() # Local Ubuntu GUI activated Wi-Fi.
|
||||
c.path_adapter.evidence=lambda policy: policy["interface"]=="nica"
|
||||
heartbeat(c)
|
||||
now[0]+=11
|
||||
heartbeat(c)
|
||||
assert nm.current==A and c.watched_target()==A
|
||||
assert c.status()["path_verified"]
|
||||
|
||||
|
||||
def test_failed_channel_releases_paused_wifi_to_nm_without_core(rig):
|
||||
c,nm,now=rig
|
||||
assert not nm.disconnected
|
||||
c.path_adapter.valid=False
|
||||
now[0]+=5
|
||||
c.tick()
|
||||
assert not nm.disconnected
|
||||
now[0]+=16
|
||||
c.tick()
|
||||
assert not nm.disconnected
|
||||
assert not c.operation.get("paused_reserves")
|
||||
assert nm.current==B # No invented claim or forced selection of another network.
|
||||
|
||||
|
||||
def test_fresh_heartbeats_on_selected_channel_keep_preference(rig):
|
||||
c,nm,now=rig
|
||||
for _ in range(12):
|
||||
now[0]+=10
|
||||
heartbeat(c)
|
||||
assert nm.current==B and not nm.disconnected
|
||||
assert not any(w=="adopt" for w in nm.writes)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("wifi_metric,expected", [(100, "eth"), (10, "wifi")])
|
||||
def test_ipv4_wifi_not_rejected_by_other_interfaces_ipv6_route(wifi_metric, expected):
|
||||
from types import SimpleNamespace
|
||||
|
||||
from uplink.network_manager import ROOT, NetworkManager
|
||||
|
||||
nm = NetworkManager.__new__(NetworkManager)
|
||||
settings = {
|
||||
kind: {"connection": {"uuid": kind, "id": kind}, "ipv4": {"method": "auto"}}
|
||||
for kind in ("eth", "wifi")
|
||||
}
|
||||
devices = {
|
||||
kind: dict(DeviceType=1 if kind == "eth" else 2, State=100,
|
||||
Managed=True, Interface=kind, ActiveConnection="active-"+kind,
|
||||
Ip4Connectivity=4)
|
||||
for kind in settings
|
||||
}
|
||||
def props(path, interface):
|
||||
if path == ROOT:
|
||||
return dict(Version="1.46.0", Devices=list(devices),
|
||||
ConnectivityCheckEnabled=True, ConnectivityCheckAvailable=True)
|
||||
if path.startswith("active-"):
|
||||
return {"Connection": path.removeprefix("active-")}
|
||||
return devices[path]
|
||||
nm.props = props
|
||||
nm.obj = lambda path: SimpleNamespace(GetAppliedConnection=lambda *a, **kw: (settings[path], 1))
|
||||
nm.dbus = SimpleNamespace(Interface=lambda obj, _: obj)
|
||||
nm.device_identity = lambda path, props: path
|
||||
nm.saved = lambda path: settings[path]
|
||||
nm.epoch = lambda: "synthetic-boot"
|
||||
nm.routes = lambda family: ([dict(dev="eth", metric=50), dict(dev="wifi", metric=wifi_metric)]
|
||||
if family == 4 else [dict(dev="eth", metric=1024)])
|
||||
state = nm.inspect()
|
||||
assert state["current_id"] == expected
|
||||
assert all(entry["verified"] for entry in state["candidates"])
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Read-only audit: synthetic adapters, no D-Bus, SSH or network mutations."""
|
||||
|
||||
import copy
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from test_board_uplinks import OP, PAYLOAD, REV, ROW
|
||||
from test_uplink import A, B, FakeNM, FakePath, ack, heartbeat, select
|
||||
from uplink.network_manager import ROOT as NM_ROOT
|
||||
from uplink.network_manager import NetworkManager
|
||||
from uplink.transaction import Controller, dispatch
|
||||
|
||||
from k1link.fleet.uplinks import Uplinks
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rig(tmp_path):
|
||||
nm, now = FakeNM(), [1000]
|
||||
c = Controller(tmp_path, nm, lambda: now[0], FakePath())
|
||||
heartbeat(c)
|
||||
return c, nm, now
|
||||
|
||||
|
||||
def test_rollback_attempts_runtime_restore_even_when_saved_profile_restore_fails(rig):
|
||||
c, nm, now = rig
|
||||
select(c, now)
|
||||
c.operation["profiles_pending"] = True
|
||||
|
||||
def fail(_):
|
||||
raise ValueError("profile no longer exists")
|
||||
|
||||
nm.restore_profiles = fail
|
||||
c.rollback("failed save")
|
||||
assert "rollback" in nm.writes
|
||||
|
||||
|
||||
def test_core_guard_covers_recovery_until_terminal_outcome():
|
||||
events = []
|
||||
u = Uplinks(lambda: 1000, guard=lambda node, active: events.append((node, active)))
|
||||
u.heartbeat(ROW, PAYLOAD)
|
||||
u.start(ROW, B, REV, "runtime", OP)
|
||||
p = copy.deepcopy(PAYLOAD)
|
||||
p["uplink"]["operation"] = dict(id=OP, binding="pair:runtime", target=B, phase="recovering")
|
||||
u.heartbeat(ROW, p)
|
||||
assert events[-1] == ("board", True)
|
||||
assert u.busy("board")
|
||||
|
||||
|
||||
def test_changing_core_peer_invalidates_old_proof_without_switching(rig):
|
||||
c, nm, now = rig
|
||||
select(c, now)
|
||||
dispatch(c, ack(c))
|
||||
old_policy = copy.deepcopy(c.operation["policy"])
|
||||
seen = []
|
||||
c.path_adapter.evidence = lambda policy: seen.append(policy.copy()) or policy == old_policy
|
||||
now[0] += 5
|
||||
result = dispatch(
|
||||
c,
|
||||
dict(
|
||||
action="heartbeat", binding="another-pair:runtime", peer="10.42.0.2", provider="netbird"
|
||||
),
|
||||
)
|
||||
assert seen[-1]["peer"] == "10.42.0.2"
|
||||
assert not result["path_verified"]
|
||||
|
||||
|
||||
def test_transaction_does_not_write_absent_historical_profiles(rig):
|
||||
c, nm, now = rig
|
||||
removed = "c" * 36
|
||||
c.operation = dict(
|
||||
id="d" * 32,
|
||||
phase="applied",
|
||||
target=A,
|
||||
policy={},
|
||||
baseline=[dict(id=removed, verified=True, interface="old-radio")],
|
||||
)
|
||||
select(c, now)
|
||||
sent = []
|
||||
nm.persist_choice = lambda entries, target: sent.extend(e["id"] for e in entries)
|
||||
dispatch(c, ack(c))
|
||||
assert removed not in sent
|
||||
|
||||
|
||||
def test_reserve_preserves_explicitly_verified_radio_identity():
|
||||
nm = NetworkManager.__new__(NetworkManager)
|
||||
nm.dbus = SimpleNamespace(Interface=lambda obj, _: obj)
|
||||
nm.props = lambda path, _: (
|
||||
{"Devices": ["/device/new"]}
|
||||
if path == NM_ROOT
|
||||
else {
|
||||
"DeviceType": 2,
|
||||
"Managed": True,
|
||||
"AvailableConnections": ["/profile/a"],
|
||||
"Interface": "radio-new",
|
||||
}
|
||||
)
|
||||
nm.obj = lambda path: SimpleNamespace(
|
||||
GetSettings=lambda **kw: {
|
||||
"connection": {"uuid": A, "id": "example"},
|
||||
"ipv4": {},
|
||||
"ipv6": {},
|
||||
}
|
||||
)
|
||||
entries = nm.reserves(
|
||||
[
|
||||
dict(
|
||||
id=A,
|
||||
verified=True,
|
||||
interface="radio-original",
|
||||
path="/device/original",
|
||||
kind="wifi",
|
||||
)
|
||||
]
|
||||
)
|
||||
assert not entries or all(e["interface"] == "radio-original" for e in entries)
|
||||
|
||||
|
||||
def test_policy_preserves_inactive_profiles_and_native_fallback():
|
||||
nm = NetworkManager.__new__(NetworkManager)
|
||||
other_wifi, vpn = "c" * 36, "d" * 36
|
||||
before = dict(
|
||||
autoconnect=True, metrics={"ipv4": -1, "ipv6": -1}, defaults={"ipv4": False, "ipv6": False}
|
||||
)
|
||||
profiles = {
|
||||
i: dict(id=i, kind=k, saved=copy.deepcopy(before))
|
||||
for i, k in [(A, "wifi"), (B, "other"), (other_wifi, "wifi"), (vpn, "other")]
|
||||
}
|
||||
nm.profile_preferences = lambda: copy.deepcopy(profiles)
|
||||
saved = {}
|
||||
nm.set_preference = lambda e, value: saved.update({e["id"]: value})
|
||||
entries = nm.snapshot_profiles([dict(id=A, kind="wifi"), dict(id=B, kind="ethernet")], B)
|
||||
nm.persist_choice(entries, B)
|
||||
assert other_wifi not in saved
|
||||
assert saved[A]["autoconnect"]
|
||||
assert saved[B]["autoconnect"]
|
||||
assert vpn not in saved
|
||||
|
||||
|
||||
def test_lost_path_proof_does_not_return_an_unqualified_success_message(rig):
|
||||
c, nm, now = rig
|
||||
select(c, now)
|
||||
dispatch(c, ack(c))
|
||||
c.path_adapter.valid = False
|
||||
now[0] += 5
|
||||
state = heartbeat(c)
|
||||
assert not state["path_verified"]
|
||||
# BoardUplinkControl renders operation.message without checking path_verified.
|
||||
assert "Путь к Core подтверждён" not in state["operation"]["message"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phase", ["recovering", "rolling_back", "rollback_failed"])
|
||||
def test_restarted_core_adopts_guard_and_releases_only_terminal_report(phase):
|
||||
events = []
|
||||
u = Uplinks(lambda: 1000, guard=lambda n, active: events.append(active))
|
||||
p = copy.deepcopy(PAYLOAD)
|
||||
p["uplink"]["operation"] = dict(id=OP, binding="pair:old-runtime", target=B, phase=phase)
|
||||
assert u.heartbeat(ROW, p) == {}
|
||||
assert u.busy("board") and events == [True]
|
||||
p["execution_binding"]["agent_instance_id"] = "next-runtime"
|
||||
p["uplink"]["operation"]["phase"] = "rolled_back"
|
||||
assert u.heartbeat(ROW, p) == {}
|
||||
assert not u.busy("board") and events == [True, False]
|
||||
|
||||
|
||||
def test_restarted_core_cannot_ack_unowned_selection():
|
||||
u = Uplinks(lambda: 1000)
|
||||
p = copy.deepcopy(PAYLOAD)
|
||||
p["uplink"]["operation"] = dict(
|
||||
id=OP,
|
||||
binding="pair:runtime",
|
||||
target=B,
|
||||
phase="verifying",
|
||||
nonce="f" * 32,
|
||||
path_verified=True,
|
||||
)
|
||||
assert u.heartbeat(ROW, p) == {}
|
||||
assert u.busy("board")
|
||||
|
||||
|
||||
def test_profile_restore_continues_after_failure_and_preserves_foreign_edits():
|
||||
nm = NetworkManager.__new__(NetworkManager)
|
||||
entries = [dict(id=i, saved={"v": 0}, planned={"v": 1}) for i in "abcd"]
|
||||
nm.profile_preferences = lambda: {
|
||||
"a": {"saved": {"v": 1}},
|
||||
"b": {"saved": {"v": 1}},
|
||||
"c": {"saved": {"v": 99}},
|
||||
}
|
||||
writes = []
|
||||
|
||||
def write(entry, value):
|
||||
writes.append(entry["id"])
|
||||
if entry["id"] == "a":
|
||||
raise ValueError("unavailable")
|
||||
|
||||
nm.set_preference = write
|
||||
with pytest.raises(ValueError):
|
||||
nm.restore_profiles(entries)
|
||||
assert writes == ["a", "b"]
|
||||
|
||||
|
||||
def test_adapter_replug_matches_permanent_identity_not_another_radio():
|
||||
old = dict(interface="radio0", hardware="aa:bb:cc:dd:ee:ff")
|
||||
nm = NetworkManager.__new__(NetworkManager)
|
||||
nm.device_identity = lambda path, props: path
|
||||
assert nm.same_device(old, "aa:bb:cc:dd:ee:ff", {"Interface": "radio9"})
|
||||
assert not nm.same_device(old, "00:11:22:33:44:55", {"Interface": "radio0"})
|
||||
|
||||
|
||||
def test_new_core_peer_is_revalidated_without_network_mutations(rig):
|
||||
c, nm, now = rig
|
||||
select(c, now)
|
||||
dispatch(c, ack(c))
|
||||
writes = copy.deepcopy(nm.writes)
|
||||
c.path_adapter.evidence = lambda policy: policy["peer"] == "10.42.0.2"
|
||||
now[0] += 5
|
||||
result = dispatch(
|
||||
c,
|
||||
dict(action="heartbeat", binding="new-pair:runtime", peer="10.42.0.2", provider="netbird"),
|
||||
)
|
||||
assert result["path_verified"]
|
||||
assert nm.writes == writes
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Regressions for the field failure: no manual disconnect and no stale proof."""
|
||||
|
||||
import copy
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from test_uplink import A, FakeNM, FakePath, ack, heartbeat, select, settle
|
||||
from uplink.network_manager import NetworkManager
|
||||
from uplink.transaction import Controller
|
||||
from uplink.transport_route import PRIORITY, TABLE, TransportRoute
|
||||
|
||||
|
||||
def test_fallback_tries_another_checked_channel_and_latches_it(tmp_path):
|
||||
nm, clock, path = FakeNM(), [1000], FakePath()
|
||||
c = Controller(tmp_path, nm, lambda: clock[0], path)
|
||||
heartbeat(c)
|
||||
select(c, clock)
|
||||
c.confirm(ack(c))
|
||||
path.valid = False
|
||||
for _ in range(18):
|
||||
clock[0] += 5
|
||||
c.tick()
|
||||
assert nm.current == A and not nm.disconnected
|
||||
assert not c.status()['path_verified']
|
||||
path.valid = True
|
||||
heartbeat(c)
|
||||
clock[0] += 11
|
||||
heartbeat(c)
|
||||
assert c.status()['path_verified'] and c.watched_target() == A
|
||||
writes = list(nm.writes)
|
||||
for _ in range(20):
|
||||
clock[0] += 10
|
||||
heartbeat(c)
|
||||
assert nm.current == A and nm.writes == writes
|
||||
|
||||
|
||||
def test_new_reserve_activation_survives_rollback_without_autoconnect_inhibition():
|
||||
nm = NetworkManager.__new__(NetworkManager)
|
||||
calls = []
|
||||
nm.dbus = SimpleNamespace(Array=lambda value, **kw: value, ObjectPath=str, UInt32=int)
|
||||
nm.manager = lambda: SimpleNamespace(CheckpointCreate=lambda paths, *a, **kw:
|
||||
calls.append(paths) or '/checkpoint')
|
||||
nm.checkpoint([dict(path='/working', active=True), dict(path='/reserve', active=False)])
|
||||
assert calls == [['/working']]
|
||||
|
||||
|
||||
def test_available_saved_profile_is_not_a_currently_verified_channel(tmp_path):
|
||||
nm, clock = FakeNM(), [1000]
|
||||
c = Controller(tmp_path, nm, lambda: clock[0], FakePath())
|
||||
heartbeat(c)
|
||||
select(c, clock)
|
||||
c.confirm(ack(c))
|
||||
nm.disconnected = {A}
|
||||
nm.reserves = lambda entries: [dict(next(e for e in entries if e['id'] == A),
|
||||
verified=False, active=False, available=True)]
|
||||
state = c.status()
|
||||
candidate = next(e for e in state['candidates'] if e['id'] == A)
|
||||
assert candidate['available'] and not candidate['verified']
|
||||
body = dict(action='stage', id='c' * 32, binding='pairing:runtime', target=A,
|
||||
revision=state['revision'], expires_at=1030)
|
||||
c.stage(body)
|
||||
settle(c, clock)
|
||||
assert c.operation['phase'] == 'verifying' and nm.current == A
|
||||
assert not c.status()['path_verified'] # Requires Core acknowledgement.
|
||||
|
||||
|
||||
def test_foreign_rule_or_route_is_never_removed(tmp_path):
|
||||
calls = []
|
||||
def run(*args):
|
||||
calls.append(args)
|
||||
if 'rule' in args:
|
||||
return json.dumps([dict(priority=PRIORITY, table=TABLE, fwmark='0x99')])
|
||||
return '[]'
|
||||
route = TransportRoute(run, tmp_path)
|
||||
with pytest.raises(ValueError):
|
||||
route.release()
|
||||
route.record(dict(mark=0x1bd00, routes=[]))
|
||||
with pytest.raises(ValueError):
|
||||
route.release()
|
||||
assert not any('del' in c or 'flush' in c for c in calls)
|
||||
|
||||
|
||||
def test_local_profile_change_releases_transport_without_rewriting_ubuntu(tmp_path):
|
||||
nm, clock, path = FakeNM(), [1000], FakePath()
|
||||
c = Controller(tmp_path, nm, lambda: clock[0], path)
|
||||
heartbeat(c)
|
||||
select(c, clock)
|
||||
c.confirm(ack(c))
|
||||
nm.profiles[A]['saved']['metrics']['ipv4'] = 3
|
||||
before = copy.deepcopy(nm.profiles)
|
||||
clock[0] += 5
|
||||
c.tick()
|
||||
assert path.selected is None and nm.profiles == before
|
||||
assert c.operation['local_override'] and not nm.disconnected
|
||||
|
||||
|
||||
@pytest.mark.parametrize('already_absent', [False, True])
|
||||
def test_route_disappearing_during_release_is_only_ignored_if_absent(tmp_path, already_absent):
|
||||
import subprocess
|
||||
row = dict(dst='198.51.100.0/24', dev='radio-test', prefsrc='198.51.100.2',
|
||||
table=TABLE, protocol='242')
|
||||
queries = []
|
||||
def run(*args):
|
||||
if 'del' in args:
|
||||
raise subprocess.CalledProcessError(2, args, stderr=b'route deletion failed')
|
||||
if 'rule' in args:
|
||||
return '[]'
|
||||
queries.append(args)
|
||||
return json.dumps([] if len(queries)>1 and already_absent else [row])
|
||||
steering = TransportRoute(run, tmp_path)
|
||||
steering.record(dict(mark=0x1bd00, routes=[steering.route_key(row)]))
|
||||
if already_absent:
|
||||
steering.release()
|
||||
assert not steering.path.exists()
|
||||
else:
|
||||
with pytest.raises(subprocess.CalledProcessError):
|
||||
steering.release()
|
||||
assert steering.path.exists() # Ownership retained; do not hide other failures.
|
||||
@@ -0,0 +1 @@
|
||||
"""Board-owned physical uplink control. No Core address or hardware constants."""
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Bounded local controller evidence. Never sent as periodic WAN telemetry."""
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
|
||||
class Evidence:
|
||||
def record_error(self, error):
|
||||
# Class/step are sufficient to locate the failing boundary. Never copy
|
||||
# exception text or subprocess arguments, which may contain secrets.
|
||||
self.operation['failure'] = dict(
|
||||
step=self.operation.get('apply_step', self.operation.get('phase', 'unknown')),
|
||||
error_type=type(error).__name__[:80])
|
||||
if callable(getattr(error, 'get_dbus_name', None)):
|
||||
name = error.get_dbus_name()
|
||||
if isinstance(name, str) and re.fullmatch(r'[A-Za-z0-9_.]{1,160}', name):
|
||||
self.operation['failure']['dbus_error'] = name
|
||||
if isinstance(error, subprocess.CalledProcessError):
|
||||
cmd = error.cmd
|
||||
if isinstance(cmd, (tuple, list)) and list(cmd[:1]) == ['/usr/sbin/ip']:
|
||||
# ip route/rule commands contain no authentication material.
|
||||
# Preserve the actual kernel failure locally for diagnosis.
|
||||
self.operation['failure']['command'] = [str(v)[:128] for v in cmd[:32]]
|
||||
self.operation['failure']['exit_code'] = error.returncode
|
||||
raw = error.stderr or b''
|
||||
self.operation['failure']['kernel_error'] = (
|
||||
raw.decode(errors='replace') if isinstance(raw, bytes) else raw)[:512]
|
||||
self.save()
|
||||
|
||||
def record_transition(self):
|
||||
op = self.operation
|
||||
state = dict(operation_id=op['id'], phase=op['phase'], target=op.get('target'),
|
||||
previous=op.get('previous'), selected=self.watched_target(),
|
||||
fallback_enabled=self.fallback_enabled(),
|
||||
local_override=bool(op.get('local_override')),
|
||||
reason=op.get('recovery_reason', ''), message=op.get('message', ''),
|
||||
wait_reason=op.get('wait_reason', ''), failure=op.get('failure'))
|
||||
prior = op.get('diagnostic_events', [])
|
||||
if prior and prior[-1]['state'] == state:
|
||||
return
|
||||
sequence = op.get('diagnostic_sequence', 0) + 1
|
||||
op['diagnostic_sequence'] = sequence
|
||||
op['diagnostic_events'] = [*prior, dict(
|
||||
sequence=sequence, at=self.wall_clock(), monotonic_ms=self.clock()*1000,
|
||||
helper_instance=self.helper_instance, state=state)][-16:]
|
||||
|
||||
def local_evidence(self, state):
|
||||
op = self.operation or {}
|
||||
policy = op.get('watch_policy') or op.get('policy', {})
|
||||
return dict(
|
||||
schema='missioncore.uplink-evidence/v1', helper_instance=self.helper_instance,
|
||||
sampled_at=self.wall_clock(), monotonic_ms=self.clock()*1000,
|
||||
native_current_id=state.get('current_id', ''),
|
||||
selected_id=self.watched_target() if op else '',
|
||||
interface=policy.get('interface', ''), transport_mark=policy.get('mark'),
|
||||
path_proven=self.path_ok, proof_age_ms=max(0, self.clock()-self.last_probe)*1000,
|
||||
core_reply_age_ms=max(0, self.clock()-self.last_core)*1000,
|
||||
fallback_enabled=self.fallback_enabled(), phase=op.get('phase', 'unselected'),
|
||||
local_override=bool(op.get('local_override')),
|
||||
events=op.get('diagnostic_events', [])[-16:])
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Board-owned fallback permission, independent of a particular switch command."""
|
||||
|
||||
import copy
|
||||
import re
|
||||
|
||||
|
||||
class FallbackPolicy:
|
||||
def load_fallback(self):
|
||||
value = (self.operation or {}).get('fallback', dict(
|
||||
enabled=True, revision=0, operation_id=''))
|
||||
if (type(value.get('enabled')) is not bool
|
||||
or type(value.get('revision')) is not int or value['revision'] < 0):
|
||||
raise ValueError('Повреждена настройка резервного подключения.')
|
||||
self.fallback_setting = value
|
||||
|
||||
def fallback_enabled(self):
|
||||
return self.fallback_setting['enabled']
|
||||
|
||||
def select_path(self, policy):
|
||||
strict = {} if self.fallback_enabled() else {'strict': True}
|
||||
self.path_adapter.select({**policy, **strict})
|
||||
|
||||
def retain_path(self):
|
||||
op = self.operation or {}
|
||||
if self.fallback_enabled() or op.get('local_override') or not op.get('policy'):
|
||||
return
|
||||
policy = op.get('watch_policy') or op['policy']
|
||||
self.select_path(policy)
|
||||
self.transport_ready = True
|
||||
|
||||
def fallback(self, body):
|
||||
if (not re.fullmatch(r'[a-f0-9]{32}', str(body['id']))
|
||||
or type(body['enabled']) is not bool or type(body['revision']) is not int):
|
||||
raise ValueError('Некорректная настройка резервного подключения.')
|
||||
if (not self.context or body['binding'] != self.context['binding']
|
||||
or self.clock() - self.last_core > 20
|
||||
or type(body['expires_at']) is not int
|
||||
or not self.wall_clock() < body['expires_at'] <= self.wall_clock() + 60):
|
||||
raise ValueError('Нет свежего подтверждения Core.')
|
||||
old = self.fallback_setting
|
||||
if body['id'] == old['operation_id']:
|
||||
if body['enabled'] != old['enabled']:
|
||||
raise ValueError('Конфликт настройки резервного подключения.')
|
||||
return self.status()
|
||||
if body['revision'] != old['revision']:
|
||||
raise ValueError('Настройка изменилась. Обновите состояние борта.')
|
||||
self.tick()
|
||||
op = self.operation
|
||||
if (not op or op['phase'] not in ('applied', 'rolled_back', 'superseded')
|
||||
or not self.path_ok or self.clock() - self.last_core > 20):
|
||||
raise ValueError('Дождитесь подтверждения текущего подключения.')
|
||||
state = self.adapter.inspect(known=self.known())
|
||||
chosen, policy = self.proven_current(state)
|
||||
updated = dict(enabled=body['enabled'], revision=old['revision'] + 1,
|
||||
operation_id=body['id'])
|
||||
self.path_adapter.select({**policy, **({} if updated['enabled'] else {'strict': True})})
|
||||
before = copy.deepcopy(op)
|
||||
self.fallback_setting = updated
|
||||
# This explicit Core choice owns the current path, never an alternative.
|
||||
op.update(network_policy='native-fallback-v2', local_override=False,
|
||||
watch_policy=policy, watch_target=chosen['id'])
|
||||
op['profile_baseline'] = [dict(e, planned=e['saved']) for e in state['candidates']]
|
||||
self.transport_ready = True
|
||||
try:
|
||||
self.save() # Policy and selected-path ownership commit atomically.
|
||||
except Exception:
|
||||
self.operation, self.fallback_setting = before, old
|
||||
self.select_path(policy)
|
||||
raise
|
||||
return self.status()
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Installer migration from owned manual-only preferences to normal NM fallback."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
FAMILIES = ("ipv4", "ipv6")
|
||||
|
||||
|
||||
def migrate(root: Path, adapter):
|
||||
path = root / "operation.json"
|
||||
receipt = root / "native-fallback-v1.json"
|
||||
if not path.exists():
|
||||
return
|
||||
op = json.loads(path.read_text())
|
||||
if op.get("network_policy") in ("native-fallback-v1", "native-fallback-v2"):
|
||||
return
|
||||
if op.get("phase") not in ("applied", "rolled_back", "superseded"):
|
||||
raise ValueError("Завершите текущую операцию переключения перед обновлением.")
|
||||
entries = sorted(op.get("profile_baseline") or op.get("baseline", []), key=lambda e: e["id"])
|
||||
pending = root / "native-fallback-v1.pending.json"
|
||||
if pending.exists():
|
||||
adapter.restore_profiles(json.loads(pending.read_text())["changes"])
|
||||
current = adapter.profile_preferences()
|
||||
changes, skipped = [], []
|
||||
for index, entry in enumerate(entries):
|
||||
saved = entry.get("saved")
|
||||
value = current.get(entry["id"], {}).get("saved")
|
||||
if not saved or value is None or entry.get("kind") not in ("ethernet", "wifi"):
|
||||
continue
|
||||
old = entry.get("planned") or dict(
|
||||
autoconnect=entry["kind"] == "ethernet" or entry["id"] == op["target"],
|
||||
metrics={f: 10 if entry["id"] == op["target"] else 100 + index for f in FAMILIES},
|
||||
defaults={f: entry["id"] != op["target"] for f in FAMILIES},
|
||||
)
|
||||
restored = dict(value, autoconnect=saved["autoconnect"], defaults=saved["defaults"])
|
||||
if value != old and value != saved:
|
||||
skipped.append(entry["id"])
|
||||
continue
|
||||
if value == restored:
|
||||
continue
|
||||
changes.append(dict(entry, saved=value, planned=restored))
|
||||
# Persist the exact undo record before the first write. A failed installation
|
||||
# restores already changed profiles and can retry; unrelated edits survive.
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with pending.open("w") as stream:
|
||||
os.chmod(pending, 0o600)
|
||||
json.dump(dict(changes=changes, skipped=skipped), stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
live = None
|
||||
try:
|
||||
for entry in changes:
|
||||
adapter.set_preference(entry, entry["planned"])
|
||||
live = adapter.inspect(known=entries)
|
||||
for entry in live["candidates"]:
|
||||
if entry["id"] in {e["id"] for e in changes}:
|
||||
adapter.release_reserves([entry], "")
|
||||
except Exception:
|
||||
adapter.restore_profiles(changes)
|
||||
if live:
|
||||
adapter.restore_metrics(live["candidates"])
|
||||
raise
|
||||
# Keep priorities, but take ownership only of profiles proved by this journal.
|
||||
updated = adapter.profile_preferences()
|
||||
op["profile_baseline"] = [
|
||||
dict(e, saved=updated[e["id"]]["saved"], planned=updated[e["id"]]["saved"])
|
||||
for e in entries if e["id"] in updated and e["id"] not in skipped
|
||||
]
|
||||
op["network_policy"] = "native-fallback-v1"
|
||||
temporary = path.with_suffix(".migration.tmp")
|
||||
with temporary.open("w") as stream:
|
||||
os.chmod(temporary, 0o600)
|
||||
json.dump(op, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
temporary.replace(path)
|
||||
pending.replace(receipt)
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Read-only physical-path evidence for the qualified NetBird transport.
|
||||
|
||||
NetworkManager exclusively owns connection switching. No VPN configuration edits.
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from .quic_path import observe_udp
|
||||
from .transport_route import TransportRoute
|
||||
|
||||
NAME = re.compile(r"^[a-zA-Z0-9_.-]{1,64}$")
|
||||
|
||||
|
||||
def run(*args):
|
||||
result = subprocess.run(args, capture_output=True, timeout=8, check=True)
|
||||
if len(result.stdout) > 262144:
|
||||
raise ValueError("Слишком большой ответ сетевой службы.")
|
||||
return result.stdout.decode()
|
||||
|
||||
|
||||
def private_peer(value):
|
||||
address = ipaddress.IPv4Address(value)
|
||||
if (
|
||||
(not address.is_private and address not in ipaddress.ip_network("100.64.0.0/10"))
|
||||
or address.is_loopback
|
||||
or address.is_link_local
|
||||
):
|
||||
raise ValueError("Некорректный адрес Core.")
|
||||
return str(address)
|
||||
|
||||
|
||||
def endpoint(value):
|
||||
host, port = value.rsplit(":", 1)
|
||||
return str(ipaddress.ip_address(host.strip("[]").split("%", 1)[0])), int(port)
|
||||
|
||||
|
||||
class NetBirdPath:
|
||||
def __init__(self, root=None):
|
||||
self.routing = TransportRoute(run) if root is None else TransportRoute(run, root)
|
||||
|
||||
def status(self):
|
||||
state = json.loads(run("/usr/bin/netbird", "status", "--json"))
|
||||
if state.get("profileName") != "mission-core" or state.get("daemonVersion") != "0.82.0":
|
||||
raise ValueError("Для выбора пути нужен профиль Mission Core и NetBird 0.82.0.")
|
||||
return state
|
||||
|
||||
def prepare(self, peer, interface):
|
||||
private_peer(peer)
|
||||
self.status()
|
||||
if not NAME.fullmatch(interface):
|
||||
raise ValueError("Некорректный сетевой интерфейс.")
|
||||
route = json.loads(run("/usr/sbin/ip", "-j", "-4", "route", "get", peer))
|
||||
vpn_interface = route[0].get("dev", "") if len(route) == 1 else ""
|
||||
if not NAME.fullmatch(vpn_interface):
|
||||
raise ValueError("Не определён интерфейс VPN до Core.")
|
||||
mark = int(run("/usr/bin/wg", "show", vpn_interface, "fwmark").strip(), 0)
|
||||
if mark <= 0 or mark > 0xFFFFFFFF or mark & 0xFF:
|
||||
raise ValueError("Не подтверждена штатная метка транспорта NetBird.")
|
||||
return dict(interface=interface, peer=peer, mark=mark)
|
||||
|
||||
def select(self, policy):
|
||||
self.routing.select(policy)
|
||||
|
||||
def release(self):
|
||||
self.routing.release()
|
||||
|
||||
def route(self, address, interface, source="", mark=None):
|
||||
args = ["/usr/sbin/ip", "-j", "-4", "route", "get", address]
|
||||
if source:
|
||||
args += ["from", source]
|
||||
if mark:
|
||||
args += ["mark", hex(mark)]
|
||||
routes = json.loads(run(*args))
|
||||
return (
|
||||
len(routes) == 1
|
||||
and routes[0].get("dev") == interface
|
||||
and (not source or routes[0].get("prefsrc", routes[0].get("src", source)) == source)
|
||||
)
|
||||
|
||||
def evidence(self, policy):
|
||||
interface, peer_ip = policy["interface"], policy["peer"]
|
||||
state = self.status()
|
||||
peer = next(
|
||||
(p for p in state.get("peers", {}).get("details", []) if p.get("netbirdIp") == peer_ip),
|
||||
None,
|
||||
)
|
||||
if not peer or peer.get("status") != "Connected":
|
||||
return False
|
||||
addresses = json.loads(run("/usr/sbin/ip", "-j", "-4", "address", "show", "dev", interface))
|
||||
sources = {
|
||||
a["local"]
|
||||
for e in addresses
|
||||
for a in e.get("addr_info", [])
|
||||
if a.get("family") == "inet"
|
||||
}
|
||||
if not sources:
|
||||
return False
|
||||
if peer.get("connectionType") == "P2P":
|
||||
# The kernel's current peer endpoint, not a remembered ICE candidate.
|
||||
peer_route = json.loads(run("/usr/sbin/ip", "-j", "-4", "route", "get", peer_ip))
|
||||
iface = peer_route[0].get("dev", "") if len(peer_route) == 1 else ""
|
||||
if not NAME.fullmatch(iface):
|
||||
return False
|
||||
entries = [
|
||||
line.split() for line in run("/usr/bin/wg", "show", iface, "endpoints").splitlines()
|
||||
]
|
||||
value = next((v for k, v in entries if k == peer.get("publicKey")), "")
|
||||
destination, _ = endpoint(value)
|
||||
local, _ = endpoint(peer["iceCandidateEndpoint"]["local"])
|
||||
# A kernel WireGuard socket uses its current fwmark route. ICE's
|
||||
# remembered local candidate may predate that route change.
|
||||
if (
|
||||
not policy.get("mark")
|
||||
and peer.get("iceCandidateType", {}).get("local") == "host"
|
||||
and local not in sources
|
||||
):
|
||||
return False
|
||||
return not ipaddress.ip_address(destination).is_loopback and self.route(
|
||||
destination, interface, mark=policy.get("mark")
|
||||
)
|
||||
if peer.get("connectionType") != "Relayed":
|
||||
return False
|
||||
relay = urlsplit(peer.get("relayAddress", ""))
|
||||
if relay.scheme not in ("rel", "rels") or not relay.hostname or not relay.port:
|
||||
return False
|
||||
# Bound DNS subprocess; a failed resolver cannot stall the watchdog.
|
||||
ips = {
|
||||
line.split()[0]
|
||||
for line in run("/usr/bin/getent", "ahostsv4", relay.hostname).splitlines()
|
||||
}
|
||||
cgroup = run(
|
||||
"/usr/bin/systemctl", "show", "netbird.service", "--property=ControlGroup", "--value"
|
||||
).strip()
|
||||
if not cgroup.startswith("/") or any(c.isspace() for c in cgroup):
|
||||
return False
|
||||
quic = any(
|
||||
r.get("uri") == peer.get("relayAddress")
|
||||
and r.get("available")
|
||||
and r.get("transport") == "quic"
|
||||
for r in state.get("relays", {}).get("details", [])
|
||||
)
|
||||
sockets = []
|
||||
udp_ports = set()
|
||||
# SOCK_DIAG supplies the socket's cgroup without /proc/PID inspection.
|
||||
# The restricted service deliberately has no CAP_SYS_PTRACE.
|
||||
for line in run("/usr/bin/ss", "-Hntua", "--cgroup").splitlines():
|
||||
fields = line.split()
|
||||
if len(fields) < 7 or "cgroup:" + cgroup not in fields[6:]:
|
||||
continue
|
||||
if quic and fields[0] == "udp" and fields[1] in ("UNCONN", "ESTAB"):
|
||||
try:
|
||||
local, local_port = fields[4].rsplit(":", 1)
|
||||
local = local.strip("[]").split("%", 1)[0]
|
||||
if local in sources or local in ("*", "0.0.0.0", "::"):
|
||||
udp_ports.add(int(local_port))
|
||||
except ValueError:
|
||||
pass
|
||||
if fields[0] != "tcp" or fields[1] != "ESTAB":
|
||||
continue
|
||||
try:
|
||||
destination, port = endpoint(fields[5])
|
||||
source, _ = endpoint(fields[4])
|
||||
except ValueError:
|
||||
continue
|
||||
if destination in ips and port == relay.port:
|
||||
sockets.append(
|
||||
source in sources
|
||||
and self.route(destination, interface, source, policy.get("mark"))
|
||||
)
|
||||
if quic:
|
||||
# Upstream QUIC has an unconnected, wildcard-source UDP socket.
|
||||
# A route alone cannot prove its live path. Require an outgoing
|
||||
# header from an owned socket on the selected physical interface.
|
||||
packet = observe_udp(interface, sources, ips, relay.port, udp_ports)
|
||||
return bool(packet) and self.route(packet[1], interface, packet[0], policy.get("mark"))
|
||||
return bool(sockets) and all(sockets)
|
||||
@@ -0,0 +1,423 @@
|
||||
"""Narrow NetworkManager adapter; imports D-Bus only on the supported Linux host."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from .preferences import Preferences
|
||||
|
||||
SERVICE = "org.freedesktop.NetworkManager"
|
||||
ROOT = "/org/freedesktop/NetworkManager"
|
||||
DEVICE = SERVICE + ".Device"
|
||||
|
||||
|
||||
class NetworkManager(Preferences):
|
||||
def __init__(self):
|
||||
import dbus
|
||||
|
||||
self.dbus = dbus
|
||||
self.bus = dbus.SystemBus(private=True)
|
||||
self.activation_attempts = {}
|
||||
|
||||
def epoch(self):
|
||||
return (
|
||||
Path("/proc/sys/kernel/random/boot_id").read_text().strip()
|
||||
+ ":"
|
||||
+ str(self.bus.get_name_owner(SERVICE))
|
||||
)
|
||||
|
||||
def obj(self, path):
|
||||
return self.bus.get_object(SERVICE, path)
|
||||
|
||||
def props(self, path, interface):
|
||||
return dict(
|
||||
self.dbus.Interface(self.obj(path), "org.freedesktop.DBus.Properties").GetAll(
|
||||
interface, timeout=5
|
||||
)
|
||||
)
|
||||
|
||||
def manager(self):
|
||||
return self.dbus.Interface(self.obj(ROOT), SERVICE)
|
||||
|
||||
def device_identity(self, path, props):
|
||||
kind = "Wireless" if int(props["DeviceType"]) == 2 else "Wired"
|
||||
value = self.props(path, DEVICE + "." + kind).get("PermHwAddress", "")
|
||||
return str(value).lower()
|
||||
|
||||
def same_device(self, entry, path, props):
|
||||
expected = entry.get("hardware", "")
|
||||
return (
|
||||
self.device_identity(path, props) == expected
|
||||
if expected
|
||||
else str(props["Interface"]) == entry["interface"]
|
||||
)
|
||||
|
||||
def routes(self, family):
|
||||
raw = subprocess.run(
|
||||
["/usr/sbin/ip", "-j", f"-{family}", "route", "show", "default"],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=3,
|
||||
).stdout
|
||||
if len(raw) > 32768:
|
||||
raise ValueError("Слишком сложная таблица маршрутов.")
|
||||
return json.loads(raw)
|
||||
|
||||
@staticmethod
|
||||
def preference(settings):
|
||||
return dict(
|
||||
autoconnect=bool(settings["connection"].get("autoconnect", True)),
|
||||
metrics={f: int(settings.get(f, {}).get("route-metric", -1)) for f in ("ipv4", "ipv6")},
|
||||
defaults={
|
||||
f: bool(settings.get(f, {}).get("never-default", False)) for f in ("ipv4", "ipv6")
|
||||
},
|
||||
)
|
||||
|
||||
def saved(self, connection):
|
||||
return self.dbus.Interface(
|
||||
self.obj(connection), SERVICE + ".Settings.Connection"
|
||||
).GetSettings(timeout=5)
|
||||
|
||||
def inspect(self, known=()):
|
||||
# Per-device NM status is readiness, not proof of the new Core path.
|
||||
# A global synchronous CheckConnectivity can block on another interface;
|
||||
# fresh authenticated Core/path evidence commits the guarded trial.
|
||||
global_props = self.props(ROOT, SERVICE)
|
||||
version = tuple(int(x) for x in str(global_props["Version"]).split(".")[:2])
|
||||
if version < (1, 46):
|
||||
raise ValueError("Для выбора подключения нужен NetworkManager 1.46 или новее.")
|
||||
if not (
|
||||
global_props.get("ConnectivityCheckEnabled")
|
||||
and global_props.get("ConnectivityCheckAvailable")
|
||||
):
|
||||
raise ValueError("На борту отключена проверка доступности интернета.")
|
||||
routes4, routes6 = self.routes(4), self.routes(6)
|
||||
paths = list(global_props["Devices"])
|
||||
if len(paths) > 64:
|
||||
raise ValueError("Слишком много сетевых интерфейсов.")
|
||||
entries = []
|
||||
for path in paths:
|
||||
p = self.props(path, DEVICE)
|
||||
if int(p["DeviceType"]) not in (1, 2) or int(p["State"]) != 100 or not p["Managed"]:
|
||||
continue
|
||||
name = str(p["Interface"])
|
||||
has_default = any(r.get("dev") == name for r in routes4)
|
||||
dev = self.dbus.Interface(self.obj(path), DEVICE)
|
||||
settings, applied_version = dev.GetAppliedConnection(0, timeout=5)
|
||||
identity = str(settings["connection"]["uuid"])
|
||||
admitted = any(e["id"] == identity for e in known)
|
||||
if (
|
||||
not has_default
|
||||
and not admitted
|
||||
and (
|
||||
int(p["DeviceType"]) != 2
|
||||
or (
|
||||
settings.get("ipv4", {}).get("never-default")
|
||||
or settings.get("ipv4", {}).get("method") != "auto"
|
||||
)
|
||||
)
|
||||
):
|
||||
continue
|
||||
connection = str(
|
||||
self.props(p["ActiveConnection"], SERVICE + ".Connection.Active")["Connection"]
|
||||
)
|
||||
for family in ("ipv4", "ipv6"):
|
||||
part = settings.get(family, {})
|
||||
if part.get("route-table", 0) not in (0, 254) or part.get("routing-rules"):
|
||||
raise ValueError(
|
||||
"Выбор подключения недоступен при нестандартной маршрутизации."
|
||||
)
|
||||
if any(
|
||||
int(r.get("prefix", -1)) == 0 for r in part.get("route-data", [])
|
||||
) or part.get("routes"):
|
||||
raise ValueError("Выбор подключения недоступен при ручных маршрутах.")
|
||||
entries.append(
|
||||
dict(
|
||||
id=identity,
|
||||
connection=connection,
|
||||
saved=self.preference(self.saved(connection)),
|
||||
label=str(settings["connection"]["id"])[:160],
|
||||
interface=name,
|
||||
kind="wifi" if int(p["DeviceType"]) == 2 else "ethernet",
|
||||
hardware=self.device_identity(path, p),
|
||||
verified=has_default and int(p["Ip4Connectivity"]) == 4,
|
||||
available=True,
|
||||
active=True,
|
||||
local_only=not has_default and admitted,
|
||||
path=str(path),
|
||||
version=int(applied_version),
|
||||
ipv6=any(r.get("dev") == name for r in routes6),
|
||||
metrics={
|
||||
f: int(settings.get(f, {}).get("route-metric", -1))
|
||||
for f in ("ipv4", "ipv6")
|
||||
},
|
||||
defaults=self.preference(settings)["defaults"],
|
||||
)
|
||||
)
|
||||
names = {e["interface"] for e in entries}
|
||||
if any(r.get("dev") not in names or "nexthops" in r for r in routes4 + routes6):
|
||||
raise ValueError("Основной маршрут не принадлежит управляемому Wi-Fi или Ethernet.")
|
||||
if len(entries) > 16 or len({e["id"] for e in entries}) != len(entries):
|
||||
raise ValueError("Неоднозначная привязка сетевых профилей.")
|
||||
minimum = min((int(r.get("metric", 0)) for r in routes4), default=0)
|
||||
primary = {r["dev"] for r in routes4 if int(r.get("metric", 0)) == minimum}
|
||||
current = next((e["id"] for e in entries if primary == {e["interface"]}), "")
|
||||
# The admitted Core peer and physical-path proof use IPv4. A native
|
||||
# IPv6 route on another NIC must not hide a working IPv4-only uplink.
|
||||
# IPv6 remains under NetworkManager's independent family policy.
|
||||
revision = hashlib.sha256(
|
||||
json.dumps(
|
||||
[
|
||||
self.epoch(),
|
||||
entries,
|
||||
[
|
||||
{k: r.get(k) for k in ("dev", "gateway", "metric")}
|
||||
for r in routes4 + routes6
|
||||
],
|
||||
],
|
||||
sort_keys=True,
|
||||
).encode()
|
||||
).hexdigest()
|
||||
return {
|
||||
"supported": True,
|
||||
"revision": revision,
|
||||
"current_id": current,
|
||||
"candidates": entries,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def public(state):
|
||||
return {
|
||||
**state,
|
||||
"candidates": [
|
||||
{k: e[k] for k in ("id", "label", "interface", "kind",
|
||||
"verified", "available", "active")}
|
||||
for e in state["candidates"]
|
||||
],
|
||||
}
|
||||
|
||||
def checkpoint(self, entries):
|
||||
return str(
|
||||
self.manager().CheckpointCreate(
|
||||
# Do not checkpoint an initially disconnected reserve: NM's
|
||||
# rollback would Disconnect(USER_REQUESTED) it and inhibit its
|
||||
# saved profile. Only the existing working devices need undo.
|
||||
self.dbus.Array([self.dbus.ObjectPath(path) for path in sorted({
|
||||
e['path'] for e in entries if e.get('active', True)
|
||||
})], signature="o"),
|
||||
self.dbus.UInt32(90),
|
||||
self.dbus.UInt32(0),
|
||||
timeout=5,
|
||||
)
|
||||
)
|
||||
|
||||
def apply(self, entries, target):
|
||||
# Priority only. Both networks retain addresses, defaults and native
|
||||
# autoconnect. VPN transport routing is separately scoped to its mark.
|
||||
for index, e in enumerate(sorted(entries, key=lambda x: x["id"])):
|
||||
dev = self.dbus.Interface(self.obj(e["path"]), DEVICE)
|
||||
settings, version = dev.GetAppliedConnection(0, timeout=5)
|
||||
if int(version) != e["version"] or str(settings["connection"]["uuid"]) != e["id"]:
|
||||
raise ValueError("Настройки сети изменились. Повторите выбор.")
|
||||
for family in ("ipv4", "ipv6"):
|
||||
if family in settings and settings[family].get("method") not in (
|
||||
"disabled",
|
||||
"ignore",
|
||||
):
|
||||
settings[family]["route-metric"] = self.dbus.Int64(
|
||||
10 if e["id"] == target else 100 + index
|
||||
)
|
||||
settings[family]["never-default"] = self.dbus.Boolean(
|
||||
e.get('saved', {}).get('defaults', {}).get(family, False))
|
||||
dev.Reapply(settings, version, self.dbus.UInt32(1), timeout=8)
|
||||
|
||||
def checkpoints(self):
|
||||
return {str(p) for p in self.props(ROOT, SERVICE)["Checkpoints"]}
|
||||
|
||||
def rollback(self, checkpoint):
|
||||
result = self.manager().CheckpointRollback(self.dbus.ObjectPath(checkpoint), timeout=15)
|
||||
if not result or any(int(status) != 0 for status in result.values()):
|
||||
raise ValueError("Борт не подтвердил восстановление всех сетевых интерфейсов.")
|
||||
|
||||
def confirm(self, checkpoint):
|
||||
self.manager().CheckpointDestroy(self.dbus.ObjectPath(checkpoint), timeout=5)
|
||||
|
||||
def restore_metrics(self, entries):
|
||||
# Restore only owned metrics on the same live UUID; missing hardware is
|
||||
# allowed. Saved profiles/passwords and foreign reconfiguration are untouched.
|
||||
live = {str(p): self.props(p, DEVICE) for p in self.props(ROOT, SERVICE)["Devices"]}
|
||||
for e in entries:
|
||||
props = live.get(e["path"], {})
|
||||
if props.get("Interface") != e["interface"] or int(props.get("State", 0)) != 100:
|
||||
continue
|
||||
dev = self.dbus.Interface(self.obj(e["path"]), DEVICE)
|
||||
settings, version = dev.GetAppliedConnection(0, timeout=5)
|
||||
if str(settings["connection"]["uuid"]) != e["id"]:
|
||||
continue
|
||||
for family, metric in e["metrics"].items():
|
||||
if family in settings and settings[family].get("method") not in (
|
||||
"disabled",
|
||||
"ignore",
|
||||
):
|
||||
current = int(settings[family].get("route-metric", -1))
|
||||
if current not in {10, *range(100, 116), metric}:
|
||||
raise ValueError("Приоритет сети изменён другим владельцем.")
|
||||
settings[family]["route-metric"] = self.dbus.Int64(metric)
|
||||
settings[family]["never-default"] = self.dbus.Boolean(
|
||||
e.get("defaults", {}).get(family, False)
|
||||
)
|
||||
dev.Reapply(settings, version, self.dbus.UInt32(1), timeout=8)
|
||||
|
||||
def release_reserves(self, entries, target, resume_wifi=True):
|
||||
"""End temporary path isolation; restore normal NM fallback immediately."""
|
||||
saved = self.profile_preferences()
|
||||
for entry in entries:
|
||||
if entry["id"] == target:
|
||||
continue
|
||||
profile = saved.get(entry["id"])
|
||||
if profile is None:
|
||||
continue
|
||||
props = self.props(entry["path"], DEVICE)
|
||||
if not self.same_device(entry, entry["path"], props):
|
||||
raise ValueError("Сетевой интерфейс изменился во время переключения.")
|
||||
if int(props["State"]) == 100:
|
||||
dev = self.dbus.Interface(self.obj(entry["path"]), DEVICE)
|
||||
settings, version = dev.GetAppliedConnection(0, timeout=5)
|
||||
if str(settings["connection"]["uuid"]) != entry["id"]:
|
||||
raise ValueError("Подключение изменено средствами Ubuntu.")
|
||||
for family in ("ipv4", "ipv6"):
|
||||
if family in settings:
|
||||
settings[family]["never-default"] = self.dbus.Boolean(
|
||||
profile["saved"]["defaults"][family]
|
||||
)
|
||||
settings[family]["route-metric"] = self.dbus.Int64(
|
||||
profile["saved"]["metrics"][family]
|
||||
)
|
||||
dev.Reapply(settings, version, self.dbus.UInt32(1), timeout=8)
|
||||
elif resume_wifi and entry["kind"] == "wifi" and profile["saved"]["autoconnect"]:
|
||||
# Disconnect() temporarily inhibits autoconnect. Release only
|
||||
# the Wi-Fi reserve that this transaction disconnected.
|
||||
self.dbus.Interface(self.obj(entry["path"]), "org.freedesktop.DBus.Properties").Set(
|
||||
DEVICE, "Autoconnect", self.dbus.Boolean(True), timeout=5
|
||||
)
|
||||
|
||||
def resume_autoconnect(self, entries):
|
||||
profiles = self.profile_preferences()
|
||||
devices = {str(p) for p in self.props(ROOT, SERVICE)["Devices"]}
|
||||
for entry in entries:
|
||||
if entry["path"] not in devices:
|
||||
continue # A replugged device has a new native autoconnect state.
|
||||
props = self.props(entry["path"], DEVICE)
|
||||
profile = profiles.get(entry["id"], {})
|
||||
if (
|
||||
not self.same_device(entry, entry["path"], props)
|
||||
or not profile.get("saved", {}).get("autoconnect")
|
||||
or int(props["State"]) >= 40
|
||||
or not props.get("Managed")
|
||||
):
|
||||
continue
|
||||
self.dbus.Interface(self.obj(entry["path"]), "org.freedesktop.DBus.Properties").Set(
|
||||
DEVICE, "Autoconnect", self.dbus.Boolean(True), timeout=5
|
||||
)
|
||||
|
||||
def prefer_observed(self, entries, target, profiles):
|
||||
"""Latch a proven NM failover using metrics only; keep all reserves."""
|
||||
try:
|
||||
self.persist_choice(profiles, target)
|
||||
for entry in entries:
|
||||
dev = self.dbus.Interface(self.obj(entry["path"]), DEVICE)
|
||||
settings, version = dev.GetAppliedConnection(0, timeout=5)
|
||||
if (
|
||||
int(version) != entry["version"]
|
||||
or str(settings["connection"]["uuid"]) != entry["id"]
|
||||
):
|
||||
raise ValueError("Подключение изменено средствами Ubuntu.")
|
||||
pref = next(e["planned"] for e in profiles if e["id"] == entry["id"])
|
||||
for family in ("ipv4", "ipv6"):
|
||||
if (family in settings
|
||||
and settings[family].get('method') not in ('disabled', 'ignore')):
|
||||
settings[family]["route-metric"] = self.dbus.Int64(pref["metrics"][family])
|
||||
dev.Reapply(settings, version, self.dbus.UInt32(1), timeout=8)
|
||||
except Exception:
|
||||
self.restore_profiles(profiles)
|
||||
self.restore_metrics(entries)
|
||||
raise
|
||||
return profiles
|
||||
|
||||
def reserves(self, baseline):
|
||||
result = []
|
||||
for path in self.props(ROOT, SERVICE)["Devices"]:
|
||||
props = self.props(path, DEVICE)
|
||||
if int(props["DeviceType"]) not in (1, 2) or not props["Managed"]:
|
||||
continue
|
||||
for connection in props.get("AvailableConnections", []):
|
||||
settings = self.dbus.Interface(
|
||||
self.obj(connection), SERVICE + ".Settings.Connection"
|
||||
).GetSettings(timeout=5)
|
||||
identity = str(settings["connection"]["uuid"])
|
||||
old = next((e for e in baseline if e["id"] == identity), None)
|
||||
if old and self.same_device(old, path, props):
|
||||
result.append(
|
||||
{
|
||||
**old,
|
||||
'verified': False,
|
||||
'active': False,
|
||||
'available': True,
|
||||
"path": str(path),
|
||||
"interface": str(props["Interface"]),
|
||||
"connection": str(connection),
|
||||
"hardware": self.device_identity(path, props),
|
||||
"saved": self.preference(settings),
|
||||
"metrics": self.preference(settings)["metrics"],
|
||||
"defaults": self.preference(settings)["defaults"],
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
def locally_changed(self, entries, target):
|
||||
"""An Ubuntu disconnect/profile edit wins over our pending operation."""
|
||||
profiles = self.profile_preferences()
|
||||
for entry in entries:
|
||||
current = profiles.get(entry['id'])
|
||||
if current and entry.get('planned') and current['saved'] != entry['planned']:
|
||||
return True
|
||||
for path in self.props(ROOT, SERVICE)['Devices']:
|
||||
p = self.props(path, DEVICE)
|
||||
if str(p.get('Interface')) != target:
|
||||
continue
|
||||
# USER_REQUESTED is different from carrier/DHCP loss. A disabled
|
||||
# device must remain disabled, even when a cable is still present.
|
||||
reason = p.get('StateReason', (0, 0))
|
||||
if int(p.get('State', 0)) != 100 and int(reason[1]) == 39:
|
||||
return True
|
||||
return False
|
||||
|
||||
def activate(self, entry):
|
||||
props = self.props(entry["path"], DEVICE)
|
||||
if str(props["Interface"]) != entry["interface"]:
|
||||
raise ValueError("Сетевой интерфейс изменился.")
|
||||
if int(props["State"]) == 100:
|
||||
dev = self.dbus.Interface(self.obj(entry["path"]), DEVICE)
|
||||
settings, version = dev.GetAppliedConnection(0, timeout=5)
|
||||
if str(settings["connection"]["uuid"]) == entry["id"]:
|
||||
changed = False
|
||||
for family in ("ipv4", "ipv6"):
|
||||
if settings.get(family, {}).get("never-default"):
|
||||
settings[family]["never-default"] = self.dbus.Boolean(False)
|
||||
changed = True
|
||||
if changed:
|
||||
dev.Reapply(settings, version, self.dbus.UInt32(1), timeout=8)
|
||||
return
|
||||
if 40 <= int(props["State"]) < 100:
|
||||
return
|
||||
if time.monotonic() - self.activation_attempts.get(entry["id"], 0) < 20:
|
||||
return
|
||||
self.activation_attempts[entry["id"]] = time.monotonic()
|
||||
self.manager().ActivateConnection(
|
||||
self.dbus.ObjectPath(entry["connection"]),
|
||||
self.dbus.ObjectPath(entry["path"]),
|
||||
self.dbus.ObjectPath("/"),
|
||||
timeout=8,
|
||||
)
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Observe NM recovery; latch only a fresh, proven Core path. Never scan or disconnect."""
|
||||
|
||||
import secrets
|
||||
import time
|
||||
|
||||
TERMINAL = {"applied", "rolled_back", "superseded", "recovering"}
|
||||
|
||||
|
||||
class Observation:
|
||||
def restore_adoption(self):
|
||||
pending = (self.operation or {}).get("adoption")
|
||||
if not pending:
|
||||
return
|
||||
self.adapter.restore_profiles(pending["profiles"])
|
||||
if pending["epoch"] == self.adapter.epoch():
|
||||
self.adapter.restore_metrics(pending["entries"])
|
||||
self.operation.pop("adoption")
|
||||
self.save()
|
||||
|
||||
def observe(self):
|
||||
op = self.operation
|
||||
if not self.context or not self.path_adapter or (op and op["phase"] not in TERMINAL):
|
||||
return
|
||||
if op and op.get('profiles_pending'):
|
||||
return # Restoring profiles must complete before any recovery receipt.
|
||||
try:
|
||||
state = self.adapter.inspect(known=self.known())
|
||||
candidates = sorted(state["candidates"], key=lambda e: e["id"] != state["current_id"])
|
||||
chosen, policy = None, None
|
||||
for candidate in candidates:
|
||||
if (op and not self.fallback_enabled() and not op.get('local_override')
|
||||
and candidate['id'] != self.watched_target()):
|
||||
continue
|
||||
proof = self.path_adapter.prepare(self.context["peer"], candidate["interface"])
|
||||
if self.path_adapter.evidence(proof):
|
||||
chosen, policy = candidate, proof
|
||||
break
|
||||
if chosen is None:
|
||||
self.observed_candidate = None
|
||||
return
|
||||
if (
|
||||
op and op["phase"] != "recovering" and chosen["id"] == self.watched_target()
|
||||
and op.get("proof_context") == self.context
|
||||
and op.get("watch_policy", op.get("policy")) == policy
|
||||
):
|
||||
self.observed_candidate = None
|
||||
return
|
||||
# Two separate authenticated Core replies, with a stable physical path.
|
||||
key = (chosen["id"], self.adapter.epoch(), str(self.context))
|
||||
pending = getattr(self, "observed_candidate", None)
|
||||
if not pending or pending[0] != key:
|
||||
self.observed_candidate = (key, self.clock())
|
||||
return
|
||||
if self.clock() - pending[1] < 10:
|
||||
return
|
||||
# A local operator owns later profile edits. We observe these without
|
||||
# rewriting them. Health/lease changes alone do not alter saved settings.
|
||||
owned = {e["id"]: e.get("planned") for e in (op or {}).get("profile_baseline", [])}
|
||||
current = self.adapter.profile_preferences()
|
||||
foreign = bool((op or {}).get("local_override")) or any(
|
||||
identity in current and current[identity]["saved"] != expected
|
||||
for identity, expected in owned.items() if expected is not None
|
||||
)
|
||||
profiles = []
|
||||
# A recovered exchange on the same physical channel requires no
|
||||
# NetworkManager reapply (which can renew DHCP and change addresses).
|
||||
if op and owned and not foreign and chosen['id'] != self.watched_target():
|
||||
affected = {e["id"]: e for e in op["profile_baseline"] if e["id"] in current}
|
||||
affected.update({e["id"]: e for e in state["candidates"]})
|
||||
profiles = self.adapter.snapshot_profiles(list(affected.values()), chosen["id"])
|
||||
for entry in profiles:
|
||||
entry["planned"]["autoconnect"] = entry["saved"]["autoconnect"]
|
||||
op["adoption"] = dict(
|
||||
profiles=profiles, entries=state["candidates"], epoch=self.adapter.epoch()
|
||||
)
|
||||
self.save()
|
||||
try:
|
||||
self.adapter.prefer_observed(state["candidates"], chosen["id"], profiles)
|
||||
except Exception:
|
||||
self.restore_adoption()
|
||||
raise
|
||||
op.pop("adoption")
|
||||
if op is None:
|
||||
self.operation = op = dict(
|
||||
network_policy="native-fallback-v2",
|
||||
id=secrets.token_hex(16), binding=self.context["binding"],
|
||||
target=chosen["id"], previous=chosen["id"], baseline=state["candidates"],
|
||||
policy=policy, known=state["candidates"], profile_baseline=[
|
||||
dict(e, planned=e["saved"]) for e in state["candidates"]
|
||||
],
|
||||
)
|
||||
if op.get('phase') == 'recovering':
|
||||
reason = op.get('recovery_reason', 'automatic')
|
||||
previous = op['target'] if reason == 'manual_rollback' else self.watched_target()
|
||||
old = next((e for e in self.known() if e['id'] == previous), None)
|
||||
if old and (previous != chosen['id'] or reason == 'manual_rollback'):
|
||||
event = dict(id=secrets.token_hex(16), at=time.time(),
|
||||
kind=('manual_rollback' if reason == 'manual_rollback'
|
||||
else 'fallback'),
|
||||
source=old['kind'], target=chosen['kind'])
|
||||
op['events'] = [*op.get('events', []), event][-8:]
|
||||
op.update(
|
||||
network_policy="native-fallback-v2",
|
||||
phase=('rolled_back' if op.get('phase') == 'recovering'
|
||||
and chosen['id'] == op['previous'] else 'superseded'),
|
||||
watch_target=chosen["id"], watch_policy=policy,
|
||||
proof_context=self.context.copy(),
|
||||
message="Связь восстановлена. Используется текущее подключение.",
|
||||
)
|
||||
if profiles:
|
||||
op["profile_baseline"] = profiles
|
||||
elif foreign:
|
||||
op["profile_baseline"] = [] # Do not resume ownership after a local edit.
|
||||
if not foreign:
|
||||
self.select_path(policy)
|
||||
op.pop('recovery_tried', None)
|
||||
op.pop('recovery_attempt_at', None)
|
||||
self.path_ok = True
|
||||
self.observed_candidate = None
|
||||
self.save()
|
||||
except Exception:
|
||||
self.observed_candidate = None
|
||||
# Never turn a failed observation into a network operation.
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Saved station-profile policy, scoped to an explicit manual transaction."""
|
||||
|
||||
import subprocess
|
||||
|
||||
SERVICE = "org.freedesktop.NetworkManager"
|
||||
|
||||
|
||||
def choice(entry, target, index):
|
||||
"""Preference is a route priority, never a ban on another connection."""
|
||||
saved = entry["saved"]
|
||||
return dict(
|
||||
autoconnect=True if entry["id"] == target else saved.get("autoconnect", True),
|
||||
metrics={f: (saved["metrics"][f] if f in entry.get("inactive_families", ())
|
||||
else 10 if entry["id"] == target else 100 + index)
|
||||
for f in ("ipv4", "ipv6")},
|
||||
defaults=dict(saved.get("defaults", {"ipv4": False, "ipv6": False})),
|
||||
)
|
||||
|
||||
|
||||
class Preferences:
|
||||
def profile_preferences(self):
|
||||
settings = self.dbus.Interface(
|
||||
self.obj("/org/freedesktop/NetworkManager/Settings"), SERVICE + ".Settings"
|
||||
)
|
||||
paths = settings.ListConnections(timeout=5)
|
||||
if len(paths) > 128:
|
||||
raise ValueError("Слишком много сетевых профилей.")
|
||||
result = {}
|
||||
for path in paths:
|
||||
data = self.saved(path)
|
||||
connection, radio = data["connection"], data.get("802-11-wireless", {})
|
||||
station = (
|
||||
connection.get("type") == "802-11-wireless"
|
||||
and radio.get("mode", "infrastructure") == "infrastructure"
|
||||
and not connection.get("master")
|
||||
and not connection.get("controller")
|
||||
and data.get("ipv4", {}).get("method") != "shared"
|
||||
)
|
||||
identity = str(connection["uuid"])
|
||||
result[identity] = dict(
|
||||
id=identity,
|
||||
connection=str(path),
|
||||
kind="wifi" if station else "other",
|
||||
saved=self.preference(data),
|
||||
inactive_families=[f for f in ('ipv4', 'ipv6')
|
||||
if data.get(f, {}).get('method') in ('disabled', 'ignore')],
|
||||
)
|
||||
return result
|
||||
|
||||
def snapshot_profiles(self, entries, target):
|
||||
# Only admitted uplinks participate. Inactive Wi-Fi profiles, local LANs,
|
||||
# VPNs, passwords and the operator's autoconnect settings stay untouched.
|
||||
profiles = self.profile_preferences()
|
||||
result = {}
|
||||
for entry in entries:
|
||||
if entry["id"] not in profiles:
|
||||
raise ValueError("Сетевой профиль изменился. Повторите выбор.")
|
||||
result[entry["id"]] = {
|
||||
**profiles[entry["id"]],
|
||||
"kind": entry["kind"],
|
||||
}
|
||||
values = sorted(result.values(), key=lambda e: e["id"])
|
||||
for index, entry in enumerate(values):
|
||||
entry["planned"] = choice(entry, target, index)
|
||||
return values
|
||||
|
||||
def set_preference(self, entry, value):
|
||||
args = [
|
||||
"/usr/bin/nmcli",
|
||||
"--wait",
|
||||
"8",
|
||||
"connection",
|
||||
"modify",
|
||||
"uuid",
|
||||
entry["id"],
|
||||
"connection.autoconnect",
|
||||
"yes" if value["autoconnect"] else "no",
|
||||
]
|
||||
for family in ("ipv4", "ipv6"):
|
||||
if family in entry.get('inactive_families', ()):
|
||||
continue
|
||||
args += [
|
||||
family + ".route-metric",
|
||||
str(value["metrics"][family]),
|
||||
family + ".never-default",
|
||||
"yes" if value["defaults"][family] else "no",
|
||||
]
|
||||
subprocess.run(args, check=True, capture_output=True, timeout=10)
|
||||
|
||||
def persist_choice(self, entries, target):
|
||||
current = self.profile_preferences()
|
||||
for entry in entries:
|
||||
if current.get(entry["id"], {}).get("saved") != entry["saved"]:
|
||||
raise ValueError("Сохранённые настройки сети изменились. Возвращаем прежнее.")
|
||||
for index, entry in enumerate(entries):
|
||||
self.set_preference(entry, entry.get("planned") or choice(entry, target, index))
|
||||
|
||||
def restore_profiles(self, entries):
|
||||
current, errors = self.profile_preferences(), []
|
||||
for entry in entries:
|
||||
value = current.get(entry["id"], {}).get("saved")
|
||||
if value is None or value == entry.get("saved"):
|
||||
continue # Deleted profiles are not recreated; unchanged ones need no write.
|
||||
if "planned" in entry and value != entry["planned"]:
|
||||
errors.append(entry["id"])
|
||||
continue # Preserve concurrent edits by another owner.
|
||||
try:
|
||||
self.set_preference(entry, entry["saved"])
|
||||
except Exception:
|
||||
errors.append(entry["id"])
|
||||
if errors:
|
||||
raise ValueError("Не все сохранённые настройки сети восстановлены.")
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Bounded passive QUIC path proof. No probes or persistent packet capture."""
|
||||
|
||||
import socket
|
||||
import struct
|
||||
import time
|
||||
|
||||
|
||||
def udp_header(data):
|
||||
if len(data) < 28 or data[0] >> 4 != 4 or data[9] != 17:
|
||||
return None
|
||||
size = (data[0] & 15) * 4
|
||||
if size < 20 or len(data) < size + 8 or struct.unpack_from("!H", data, 6)[0] & 0x3FFF:
|
||||
return None
|
||||
src, dst = socket.inet_ntoa(data[12:16]), socket.inet_ntoa(data[16:20])
|
||||
sport, dport, length = struct.unpack_from("!HHH", data, size)
|
||||
if length < 8:
|
||||
return None
|
||||
return src, dst, sport, dport
|
||||
|
||||
|
||||
def observe_udp(interface, sources, destinations, port, owned_ports):
|
||||
if not owned_ports or not destinations:
|
||||
return None
|
||||
try:
|
||||
# SOCK_DGRAM removes Ethernet framing. Peek the IPv4 length, then read
|
||||
# only IPv4+UDP headers;
|
||||
# no promiscuous mode, sending or disk output. Ignore payload bytes.
|
||||
with socket.socket(socket.AF_PACKET, socket.SOCK_DGRAM, socket.htons(0x0003)) as capture:
|
||||
capture.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 16384)
|
||||
capture.bind((interface, 0))
|
||||
deadline = time.monotonic() + 0.6
|
||||
for _ in range(512):
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
break
|
||||
capture.settimeout(remaining)
|
||||
prefix, _ = capture.recvfrom(20, socket.MSG_PEEK)
|
||||
header_size = (prefix[0] & 15) * 4 if prefix and prefix[0] >> 4 == 4 else 20
|
||||
data, address = capture.recvfrom(min(max(header_size, 20), 60) + 8)
|
||||
if address[1] != 0x0800 or address[2] != socket.PACKET_OUTGOING:
|
||||
continue
|
||||
header = udp_header(data)
|
||||
if header is None:
|
||||
continue
|
||||
src, dst, sport, dport = header
|
||||
if (
|
||||
src in sources
|
||||
and dst in destinations
|
||||
and sport in owned_ports
|
||||
and dport == port
|
||||
):
|
||||
return src, dst
|
||||
except (OSError, AttributeError):
|
||||
pass
|
||||
return None
|
||||
@@ -0,0 +1,565 @@
|
||||
"""Bounded manual selection and observation of native NetworkManager recovery."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from .evidence import Evidence
|
||||
from .fallback import FallbackPolicy
|
||||
from .netbird_path import private_peer
|
||||
from .observation import Observation
|
||||
from .transport_route import RouteNotReady
|
||||
|
||||
IDENTITY = re.compile(r"^[a-f0-9]{32}$")
|
||||
BUSY = {"applying", "verifying", "rolling_back"}
|
||||
|
||||
|
||||
class Controller(Observation, FallbackPolicy, Evidence):
|
||||
def __init__(self, root: Path, adapter, clock=time.monotonic, path_adapter=None):
|
||||
self.root, self.adapter, self.clock, self.path_adapter = root, adapter, clock, path_adapter
|
||||
self.wall_clock = time.time if clock is time.monotonic else clock
|
||||
self.context = None
|
||||
self.helper_instance = secrets.token_hex(16)
|
||||
self.last_core = 0
|
||||
self.last_probe = 0
|
||||
self.path_ok = False
|
||||
self.path_failed_since = None
|
||||
self.transport_ready = False
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
self.path = root / "operation.json"
|
||||
self.operation = json.loads(self.path.read_text()) if self.path.exists() else None
|
||||
self.load_fallback()
|
||||
self.restore_adoption()
|
||||
if (
|
||||
self.operation
|
||||
and self.operation["phase"] == "applied"
|
||||
and "policy" not in self.operation
|
||||
):
|
||||
self.operation.update(
|
||||
phase="superseded", message="Повторите выбор подключения для проверки пути к Core."
|
||||
)
|
||||
self.save()
|
||||
if self.operation and self.operation["phase"] in BUSY:
|
||||
self.rollback("Переключение прервано. Возвращаем прежнее подключение.")
|
||||
if self.operation and self.operation['phase'] == 'recovering':
|
||||
# Monotonic deadlines are local to this boot, not durable leases.
|
||||
self.operation.pop('recovery_attempt_at', None)
|
||||
self.operation.pop('recovery_tried', None)
|
||||
self.save()
|
||||
op = self.operation or {}
|
||||
policy = op.get('watch_policy') or op.get('policy')
|
||||
if (policy and op.get('phase') in ('applied', 'rolled_back', 'superseded')
|
||||
and not op.get('local_override')):
|
||||
try:
|
||||
if self.adapter.locally_changed(op.get('profile_baseline', []),
|
||||
policy.get('interface', '')):
|
||||
op['local_override'] = True
|
||||
self.path_adapter.release()
|
||||
self.save()
|
||||
else:
|
||||
# A service/package restart must not abandon a healthy chosen
|
||||
# transport merely because NM has another unmarked default.
|
||||
self.select_path(policy)
|
||||
self.transport_ready = True
|
||||
except Exception:
|
||||
self.transport_ready = False
|
||||
elif self.path_adapter and (not policy or op.get('local_override')):
|
||||
self.path_adapter.release()
|
||||
self.retain_path()
|
||||
|
||||
def save(self):
|
||||
self.operation['fallback'] = dict(self.fallback_setting)
|
||||
self.record_transition()
|
||||
path = self.path.with_suffix(".tmp")
|
||||
with path.open("w", encoding="utf8") as stream:
|
||||
os.chmod(path, 0o600)
|
||||
json.dump(self.operation, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
path.replace(self.path)
|
||||
fd = os.open(self.root, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
def inventory(self):
|
||||
catalog = self.known()
|
||||
state = self.adapter.inspect(known=catalog)
|
||||
active = {e["id"] for e in state["candidates"]}
|
||||
state["candidates"] += [e for e in self.adapter.reserves(catalog) if e["id"] not in active]
|
||||
state["revision"] = hashlib.sha256(
|
||||
json.dumps([state["revision"], state["candidates"]], sort_keys=True).encode()
|
||||
).hexdigest()
|
||||
return state
|
||||
|
||||
def known(self):
|
||||
op = self.operation or {}
|
||||
return op.get("known", op.get("baseline", []))
|
||||
|
||||
def finish_apply(self):
|
||||
op = self.operation
|
||||
entry = next(e for e in self.inventory()["candidates"] if e["id"] == op["target"])
|
||||
op["apply_step"] = "candidate_readiness"
|
||||
self.adapter.activate(entry)
|
||||
state = self.adapter.inspect(known=op["baseline"])
|
||||
target = next(
|
||||
(
|
||||
e
|
||||
for e in state["candidates"]
|
||||
if e["id"] == self.operation["target"] and e["verified"]
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not target:
|
||||
return
|
||||
if not op.get('metrics_applied'):
|
||||
op['apply_step'] = 'network_preferences'
|
||||
self.adapter.apply(state["candidates"], target["id"])
|
||||
op['metrics_applied'] = True
|
||||
op.update(wait_reason='network_preferences_pending',
|
||||
message='Ожидаем готовность подключения.')
|
||||
# NM returns before DHCP/ACD finishes republishing addresses/routes.
|
||||
# Advance on the next normal watchdog sample, never in the same call.
|
||||
self.last_probe = self.clock()
|
||||
self.save()
|
||||
return
|
||||
op['apply_step'] = 'transport_route'
|
||||
try:
|
||||
self.select_path(op["policy"])
|
||||
except RouteNotReady:
|
||||
# Reapply returns before NM republishes DHCP routes. Do not reapply
|
||||
# again on every poll: it would keep restarting the same lease.
|
||||
op.update(wait_reason='gateway_pending', message='Ожидаем готовность подключения.')
|
||||
self.save()
|
||||
return
|
||||
op.pop('wait_reason', None)
|
||||
self.transport_ready = True
|
||||
self.operation.update(phase="verifying", message="Проверяем путь связи с Core.")
|
||||
self.save()
|
||||
|
||||
def watched_target(self):
|
||||
return self.operation.get("watch_target", self.operation["target"])
|
||||
|
||||
def proven_current(self, state):
|
||||
"""Resolve the rollback baseline from the Core transport, not NM's default."""
|
||||
if not self.context or self.clock() - self.last_core > 20:
|
||||
raise ValueError("Нет свежего подтверждения Core.")
|
||||
op = self.operation
|
||||
if op and not op.get('local_override') and op.get('proof_context') == self.context:
|
||||
identity = self.watched_target()
|
||||
else:
|
||||
identity = state['current_id']
|
||||
chosen = next((e for e in state['candidates'] if e['id'] == identity), None)
|
||||
if chosen:
|
||||
policy = self.path_adapter.prepare(self.context['peer'], chosen['interface'])
|
||||
if self.path_adapter.evidence(policy):
|
||||
return chosen, policy
|
||||
raise ValueError("Текущий путь связи с Core не подтверждён. "
|
||||
"Повторите после восстановления связи.")
|
||||
|
||||
def probe(self):
|
||||
op = self.operation
|
||||
state = self.adapter.inspect(known=self.known())
|
||||
chosen = next((e for e in state["candidates"] if e["id"] == self.watched_target()), None)
|
||||
return bool(
|
||||
op.get("network_policy") == "native-fallback-v2"
|
||||
and (op["phase"] not in BUSY or op["epoch"] == self.adapter.epoch())
|
||||
and chosen
|
||||
and (chosen["verified"] or op["phase"] not in BUSY)
|
||||
and op.get("proof_context") == self.context
|
||||
and self.path_adapter.evidence(op.get("watch_policy") or op.get("policy", {}))
|
||||
)
|
||||
|
||||
def tick(self):
|
||||
op, now = self.operation, self.clock()
|
||||
if not op:
|
||||
return
|
||||
if op["phase"] in BUSY and now >= op["deadline"]:
|
||||
self.rollback("Новое подключение не подтверждено. Возвращаем прежнее.")
|
||||
if now - self.last_probe < 5:
|
||||
return
|
||||
self.last_probe = now
|
||||
if op["phase"] == "applying":
|
||||
try:
|
||||
self.finish_apply()
|
||||
except Exception as error:
|
||||
self.record_error(error)
|
||||
self.rollback("Подключение не выполнено. Возвращаем прежнее.")
|
||||
if op["phase"] in ("verifying", "applied", "superseded") or (
|
||||
op["phase"] == "rolled_back" and op.get("watch_policy")
|
||||
):
|
||||
try:
|
||||
if op['phase'] not in BUSY:
|
||||
policy = op.get('watch_policy') or op.get('policy', {})
|
||||
if self.adapter.locally_changed(op.get('profile_baseline', []),
|
||||
policy.get('interface', '')):
|
||||
self.path_adapter.release()
|
||||
op['local_override'] = True
|
||||
self.save()
|
||||
elif (not self.transport_ready and not op.get('local_override')
|
||||
and op.get('network_policy') == 'native-fallback-v2'
|
||||
and self.context):
|
||||
state = self.adapter.inspect(known=self.known())
|
||||
selected = next((e for e in state['candidates']
|
||||
if e['id'] == self.watched_target()
|
||||
and e['verified']), None)
|
||||
if selected and selected['id'] == state['current_id']:
|
||||
policy = self.path_adapter.prepare(self.context['peer'],
|
||||
selected['interface'])
|
||||
self.select_path(policy)
|
||||
self.transport_ready = True
|
||||
self.retain_path()
|
||||
self.path_ok = self.probe()
|
||||
except Exception:
|
||||
self.path_ok = False
|
||||
if op["phase"] not in BUSY:
|
||||
if self.path_ok and now - self.last_core <= 35:
|
||||
self.path_failed_since = None
|
||||
else:
|
||||
if self.path_failed_since is None:
|
||||
self.path_failed_since = now
|
||||
if now - self.path_failed_since >= 15 and self.fallback_enabled():
|
||||
self.path_adapter.release()
|
||||
self.transport_ready = False
|
||||
self.release_paused()
|
||||
if not op.get('local_override'):
|
||||
policy = op.get('watch_policy') or op.get('policy', {})
|
||||
if self.adapter.locally_changed(
|
||||
op.get('profile_baseline', []), policy.get('interface', '')
|
||||
):
|
||||
op['local_override'] = True
|
||||
self.save()
|
||||
else:
|
||||
op.update(phase='recovering', recovery_started=now,
|
||||
recovery_reason='automatic',
|
||||
message='Восстанавливаем связь с Core.')
|
||||
self.save()
|
||||
self.recover()
|
||||
elif op["phase"] == "recovering":
|
||||
self.recover()
|
||||
|
||||
def status(self):
|
||||
self.tick()
|
||||
try:
|
||||
result = self.adapter.public(self.inventory())
|
||||
except Exception as error:
|
||||
result = dict(
|
||||
supported=False,
|
||||
reason=str(error) if isinstance(error, ValueError) else "Сведения сети недоступны.",
|
||||
candidates=[],
|
||||
current_id="",
|
||||
revision="",
|
||||
)
|
||||
result["protocol"] = 2
|
||||
result['diagnostic'] = self.local_evidence(result)
|
||||
result['fallback'] = dict(self.fallback_setting)
|
||||
result['events'] = (self.operation or {}).get('events', [])[-8:]
|
||||
if (self.operation and not self.fallback_enabled()
|
||||
and not self.operation.get('local_override')):
|
||||
result['current_id'] = self.watched_target()
|
||||
result["path_verified"] = bool(
|
||||
self.operation
|
||||
and self.operation["phase"] in ("applied", "rolled_back", "superseded")
|
||||
and self.path_ok
|
||||
and self.clock() - self.last_core <= 35
|
||||
)
|
||||
if result['path_verified']:
|
||||
result['current_id'] = self.watched_target()
|
||||
if not self.context or self.context["provider"] != "netbird" or not self.path_adapter:
|
||||
result.update(
|
||||
supported=False, reason="Выбор пути доступен для подключения Core через NetBird."
|
||||
)
|
||||
# No private journal/profile snapshots cross the root IPC boundary.
|
||||
result["operation"] = {
|
||||
k: v
|
||||
for k, v in (self.operation or {}).items()
|
||||
if k in {"id", "binding", "target", "previous", "nonce", "phase", "deadline", "message"}
|
||||
} or None
|
||||
if result["operation"]:
|
||||
result["operation"]["path_verified"] = self.path_ok and self.operation["phase"] in (
|
||||
"verifying",
|
||||
"applied",
|
||||
)
|
||||
return result
|
||||
|
||||
def heartbeat(self, body):
|
||||
binding = body["binding"]
|
||||
if (
|
||||
not isinstance(binding, str)
|
||||
or not 1 <= len(binding) <= 160
|
||||
or body["provider"] not in ("netbird", "wireguard", "tailscale")
|
||||
):
|
||||
raise ValueError("Некорректная привязка Core.")
|
||||
private_peer(body["peer"])
|
||||
context = {k: body[k] for k in ("binding", "provider", "peer")}
|
||||
if (
|
||||
self.operation
|
||||
and self.operation["phase"] in BUSY
|
||||
and self.context
|
||||
and self.context != context
|
||||
):
|
||||
self.rollback("Привязка Core изменилась. Снято ограничение сетевого пути.")
|
||||
changed = self.context != context
|
||||
if changed or self.clock() - self.last_core > 35:
|
||||
self.observed_candidate = None
|
||||
self.context, self.last_core = context, self.clock()
|
||||
if changed and self.operation and self.operation["phase"] in (
|
||||
"applied", "rolled_back", "superseded"
|
||||
):
|
||||
self.path_ok = False
|
||||
self.operation.pop("proof_context", None)
|
||||
try:
|
||||
chosen = next(
|
||||
e for e in self.inventory()["candidates"] if e["id"] == self.watched_target()
|
||||
)
|
||||
self.operation["watch_policy"] = self.path_adapter.prepare(
|
||||
context["peer"], chosen["interface"]
|
||||
)
|
||||
self.operation["proof_context"] = context.copy()
|
||||
self.last_probe = 0
|
||||
except Exception:
|
||||
pass
|
||||
self.save()
|
||||
self.observe()
|
||||
return self.status()
|
||||
|
||||
def stage(self, body):
|
||||
identity, binding = body["id"], body["binding"]
|
||||
if (
|
||||
not IDENTITY.fullmatch(identity)
|
||||
or not self.context
|
||||
or self.context["binding"] != binding
|
||||
or self.context["provider"] != "netbird"
|
||||
or self.clock() - self.last_core > 20
|
||||
):
|
||||
raise ValueError("Нет свежего подтверждения привязки Core.")
|
||||
if (
|
||||
not isinstance(body["expires_at"], int)
|
||||
or not self.wall_clock() < body["expires_at"] <= self.wall_clock() + 60
|
||||
):
|
||||
raise ValueError("Команда переключения устарела.")
|
||||
self.tick()
|
||||
if self.operation and self.operation["id"] == identity:
|
||||
if self.operation["binding"] != binding or self.operation["target"] != body["target"]:
|
||||
raise ValueError("Конфликт команды переключения.")
|
||||
return self.status()
|
||||
if self.operation and self.operation["phase"] in BUSY | {"rollback_failed", "recovering"}:
|
||||
raise ValueError("Дождитесь завершения восстановления связи.")
|
||||
state = self.inventory()
|
||||
if state["revision"] != body["revision"]:
|
||||
raise ValueError("Подключения изменились. Обновите выбор.")
|
||||
target = next(
|
||||
(e for e in state["candidates"] if e["id"] == body["target"]
|
||||
and (e.get("available") or e["verified"])), None
|
||||
)
|
||||
if target is None:
|
||||
raise ValueError("Борт не подтвердил доступность выбранного подключения.")
|
||||
previous, previous_policy = self.proven_current(state)
|
||||
known = {e["id"]: e for e in self.known()}
|
||||
for entry in state["candidates"]:
|
||||
known[entry["id"]] = {
|
||||
**entry,
|
||||
"verified": entry["verified"] or known.get(entry["id"], {}).get("verified", False),
|
||||
}
|
||||
if len(known) > 64:
|
||||
raise ValueError("Слишком много сохранённых подключений.")
|
||||
profiles = self.adapter.snapshot_profiles(state["candidates"], target["id"])
|
||||
policy = self.path_adapter.prepare(self.context["peer"], target["interface"])
|
||||
checkpoint = self.adapter.checkpoint(state["candidates"])
|
||||
self.observed_candidate = None
|
||||
self.operation = dict(
|
||||
network_policy="native-fallback-v2",
|
||||
id=identity,
|
||||
binding=binding,
|
||||
target=target["id"],
|
||||
previous=previous['id'],
|
||||
previous_policy=previous_policy,
|
||||
checkpoint=checkpoint,
|
||||
epoch=self.adapter.epoch(),
|
||||
nonce=secrets.token_hex(16),
|
||||
phase="applying",
|
||||
deadline=int(self.clock()) + 80,
|
||||
message="Проверяем путь связи с Core.",
|
||||
policy=policy,
|
||||
proof_context=self.context.copy(),
|
||||
baseline=state["candidates"],
|
||||
profile_baseline=profiles,
|
||||
known=list(known.values()),
|
||||
events=(self.operation or {}).get('events', [])[-8:],
|
||||
diagnostic_events=(self.operation or {}).get('diagnostic_events', [])[-16:],
|
||||
diagnostic_sequence=(self.operation or {}).get('diagnostic_sequence', 0),
|
||||
)
|
||||
self.path_ok = False
|
||||
self.save()
|
||||
try:
|
||||
self.finish_apply()
|
||||
except Exception as error:
|
||||
self.record_error(error)
|
||||
self.rollback("Переключение не завершено. Восстанавливаем прежнее подключение.")
|
||||
return self.status()
|
||||
|
||||
def confirm(self, body):
|
||||
self.tick()
|
||||
op = self.operation
|
||||
if not op or any(body[k] != op[k] for k in ("id", "binding", "nonce")):
|
||||
raise ValueError("Подтверждение относится к другому переключению.")
|
||||
if op["phase"] == "applied":
|
||||
return self.status()
|
||||
if op["phase"] != "verifying":
|
||||
raise ValueError("Время подтверждения истекло.")
|
||||
if not self.probe():
|
||||
# A route change between report and acknowledgement cannot commit.
|
||||
self.path_ok = False
|
||||
return self.status()
|
||||
# Save only after the new physical path and authenticated Core reply agree.
|
||||
# The checkpoint and journal remain available if persistence is interrupted.
|
||||
op["profiles_pending"] = True
|
||||
self.save()
|
||||
try:
|
||||
self.adapter.persist_choice(op["profile_baseline"], op["target"])
|
||||
self.adapter.release_reserves(op["baseline"], op["target"], resume_wifi=False)
|
||||
if not self.probe():
|
||||
raise ValueError("Путь изменился после восстановления резервных подключений.")
|
||||
self.adapter.confirm(op["checkpoint"])
|
||||
except Exception as error:
|
||||
self.record_error(error)
|
||||
self.rollback("Не удалось сохранить выбор. Возвращаем прежнее подключение.")
|
||||
return self.status()
|
||||
op.pop("profiles_pending", None)
|
||||
op.update(phase="applied", message="Подключение выбрано.")
|
||||
self.path_ok, self.last_core = True, self.clock()
|
||||
self.save()
|
||||
return self.status()
|
||||
|
||||
def rollback(self, message):
|
||||
op = self.operation
|
||||
op["phase"] = "rolling_back"
|
||||
self.path_ok = False
|
||||
self.save()
|
||||
errors = []
|
||||
try:
|
||||
self.path_adapter.release()
|
||||
except Exception:
|
||||
errors.append("routes")
|
||||
if op.get("profiles_pending"):
|
||||
try:
|
||||
self.adapter.restore_profiles(op.get("profile_baseline", op["baseline"]))
|
||||
op.pop("profiles_pending", None)
|
||||
except Exception:
|
||||
errors.append("profiles")
|
||||
try:
|
||||
if op["epoch"] == self.adapter.epoch():
|
||||
if op["checkpoint"] in self.adapter.checkpoints():
|
||||
self.adapter.rollback(op["checkpoint"])
|
||||
if op.get("baseline"):
|
||||
self.adapter.restore_metrics(op["baseline"])
|
||||
except Exception:
|
||||
errors.append("routes")
|
||||
if "routes" in errors:
|
||||
op.update(
|
||||
phase="rollback_failed",
|
||||
message="Не удалось восстановить настройки сети. Требуется проверка борта.",
|
||||
)
|
||||
else:
|
||||
op.update(phase="recovering", message=message, recovery_started=self.clock(),
|
||||
recovery_reason='manual_rollback')
|
||||
# Restore the actual previous transport first in BOTH reserve modes.
|
||||
# NM checkpoint/metric restoration alone cannot restore a VPN fwmark path.
|
||||
previous = next(e for e in op['baseline'] if e['id'] == op['previous'])
|
||||
policy = op.get('previous_policy') or {
|
||||
**op['policy'], 'interface': previous['interface']}
|
||||
op.update(watch_target=previous['id'], watch_policy=policy)
|
||||
try:
|
||||
self.select_path(policy)
|
||||
self.transport_ready = True
|
||||
op.update(recovery_attempt_at=self.clock(), recovery_tried=[previous['id']])
|
||||
except Exception:
|
||||
self.transport_ready = False # Retry recovery; never report success here.
|
||||
for entry in op.get('profile_baseline', []):
|
||||
entry['planned'] = entry['saved']
|
||||
self.save()
|
||||
if "routes" not in errors:
|
||||
self.release_paused()
|
||||
self.recover()
|
||||
|
||||
def release_paused(self):
|
||||
op = self.operation or {}
|
||||
if op.get("paused_reserves"):
|
||||
try:
|
||||
self.adapter.resume_autoconnect(op["paused_reserves"])
|
||||
op.pop("paused_reserves")
|
||||
self.save()
|
||||
except Exception:
|
||||
pass # Retry the bounded release, never disconnect another network.
|
||||
|
||||
def recover(self):
|
||||
# Native NM owns association, DHCP and saved-network discovery. Try only
|
||||
# currently active, internet-checked channels, without disconnecting any
|
||||
# interface. No old success receipt is evidence for a recovery candidate.
|
||||
op, now = self.operation, self.clock()
|
||||
try:
|
||||
if op.get('profiles_pending'):
|
||||
self.adapter.restore_profiles(op.get('profile_baseline', []))
|
||||
op.pop('profiles_pending', None)
|
||||
self.save()
|
||||
policy = op.get('watch_policy') or op.get('policy', {})
|
||||
if self.adapter.locally_changed(op.get('profile_baseline', []),
|
||||
policy.get('interface', '')):
|
||||
self.path_adapter.release()
|
||||
op.update(local_override=True, phase='superseded',
|
||||
message='Подключение изменено средствами Ubuntu.')
|
||||
self.save()
|
||||
return
|
||||
if now - op.get('recovery_attempt_at', -60) < 60:
|
||||
return
|
||||
state = self.adapter.inspect(known=self.known())
|
||||
candidates = [e for e in state['candidates'] if e['verified']]
|
||||
if not self.fallback_enabled():
|
||||
self.retain_path()
|
||||
return
|
||||
# Let native route selection recover first. On a later attempt,
|
||||
# move to the next checked channel if Core is still unreachable.
|
||||
candidates.sort(key=lambda e: (e['id'] != state['current_id'], e['id']))
|
||||
if not candidates:
|
||||
self.path_adapter.release()
|
||||
return
|
||||
tried = op.get('recovery_tried', [])
|
||||
fresh = [e for e in candidates if e['id'] not in tried]
|
||||
if not fresh:
|
||||
tried, fresh = [], candidates
|
||||
chosen = fresh[0]
|
||||
proof = self.path_adapter.prepare(op['policy']['peer'], chosen['interface'])
|
||||
op.update(recovery_attempt_at=now, recovery_tried=[*tried, chosen['id']])
|
||||
self.save()
|
||||
if chosen['id'] != state['current_id']:
|
||||
self.adapter.apply(state['candidates'], chosen['id'])
|
||||
self.select_path(proof)
|
||||
except Exception:
|
||||
# A failed trial never tears down another network. Durable operation
|
||||
# remains recovering; the next bounded attempt can use native NM.
|
||||
if self.fallback_enabled():
|
||||
self.path_adapter.release()
|
||||
|
||||
|
||||
def dispatch(controller, body):
|
||||
shapes = {
|
||||
"status": {"action"},
|
||||
"heartbeat": {"action", "binding", "provider", "peer"},
|
||||
"stage": {"action", "id", "binding", "target", "revision", "expires_at"},
|
||||
"confirm": {"action", "id", "binding", "nonce"},
|
||||
"fallback": {"action", "id", "binding", "enabled", "revision", "expires_at"},
|
||||
}
|
||||
if (
|
||||
not isinstance(body, dict)
|
||||
or body.get("action") not in shapes
|
||||
or set(body) != shapes[body["action"]]
|
||||
):
|
||||
raise ValueError("Некорректная команда сетевой службы.")
|
||||
if body["action"] == "status":
|
||||
return controller.status()
|
||||
return getattr(controller, body["action"])(body)
|
||||
@@ -0,0 +1,164 @@
|
||||
"""A reversible route for NetBird's existing socket mark, not a second network manager.
|
||||
|
||||
Only the qualified transport's outer packets use this table. LAN traffic, DHCP,
|
||||
Ubuntu's connections and other VPNs keep their own routing and autoconnect policy.
|
||||
An empty table falls through to native routes; it never blackholes recovery.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
TABLE, PRIORITY, PROTOCOL = 51001, 5100, 242
|
||||
|
||||
|
||||
class RouteNotReady(ValueError):
|
||||
"""The selected connection is still publishing its DHCP default route."""
|
||||
|
||||
|
||||
class TransportRoute:
|
||||
def __init__(self, run, root=Path('/var/lib/mission-core-uplink')):
|
||||
self.run = run
|
||||
self.path = root / 'transport-route.json'
|
||||
|
||||
def ip(self, *args):
|
||||
return self.run('/usr/sbin/ip', '-4', *map(str, args))
|
||||
|
||||
def routes(self):
|
||||
# "table all" also works before our private table exists.
|
||||
return [r for r in json.loads(self.ip('-j', 'route', 'show', 'table', 'all'))
|
||||
if str(r.get('table')) == str(TABLE)]
|
||||
|
||||
def rules(self):
|
||||
return [r for r in json.loads(self.ip('-j', 'rule', 'show'))
|
||||
if r.get('priority') == PRIORITY or str(r.get('table')) == str(TABLE)]
|
||||
|
||||
@staticmethod
|
||||
def route_key(row):
|
||||
keys = ('dst', 'gateway', 'dev', 'prefsrc')
|
||||
if row.get('type') == 'unreachable':
|
||||
keys += ('type', 'metric')
|
||||
return {k: row[k] for k in keys if k in row}
|
||||
|
||||
def record(self, value):
|
||||
self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
temporary = self.path.with_suffix('.tmp')
|
||||
with temporary.open('w') as stream:
|
||||
os.chmod(temporary, 0o600)
|
||||
json.dump(value, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
temporary.replace(self.path)
|
||||
|
||||
def owned(self):
|
||||
if not self.path.exists():
|
||||
if self.routes() or self.rules():
|
||||
raise ValueError('Таблица пути Core занята другой настройкой сети.')
|
||||
return [], []
|
||||
record = json.loads(self.path.read_text())
|
||||
routes, rules = self.routes(), self.rules()
|
||||
for rule in rules:
|
||||
if not (rule.get('priority') == PRIORITY
|
||||
and str(rule.get('table')) == str(TABLE)
|
||||
and int(rule.get('fwmark', '0'), 0) == record['mark']
|
||||
and str(rule.get('protocol')) == str(PROTOCOL)
|
||||
and not rule.get('fwmask')):
|
||||
raise ValueError('Правило пути Core изменено другим владельцем.')
|
||||
for row in routes:
|
||||
if (str(row.get('protocol')) != str(PROTOCOL)
|
||||
or self.route_key(row) not in record['routes']):
|
||||
raise ValueError('Маршрут пути Core изменён другим владельцем.')
|
||||
return routes, rules
|
||||
|
||||
def change_route(self, action, row):
|
||||
args = ['route', action, 'table', TABLE]
|
||||
if row.get('type'):
|
||||
args.append(row['type'])
|
||||
args.append(row['dst'])
|
||||
if row.get('gateway'):
|
||||
args += ['via', row['gateway'], 'onlink']
|
||||
if row.get('dev'):
|
||||
args += ['dev', row['dev']]
|
||||
if row.get('metric') is not None:
|
||||
args += ['metric', row['metric']]
|
||||
if row.get('prefsrc'):
|
||||
args += ['src', row['prefsrc']]
|
||||
self.ip(*args, 'protocol', PROTOCOL)
|
||||
|
||||
def release(self):
|
||||
routes, rules = self.owned()
|
||||
if not self.path.exists():
|
||||
return
|
||||
record = json.loads(self.path.read_text())
|
||||
for _ in rules:
|
||||
self.ip('rule', 'del', 'priority', PRIORITY, 'fwmark', hex(record['mark']),
|
||||
'table', TABLE, 'protocol', PROTOCOL)
|
||||
for row in routes:
|
||||
try:
|
||||
self.change_route('del', self.route_key(row))
|
||||
except subprocess.CalledProcessError:
|
||||
# DHCP may remove an address and its owned route after the snapshot.
|
||||
# Only absence of this exact row makes deletion already complete.
|
||||
if any(self.route_key(live) == self.route_key(row) for live in self.routes()):
|
||||
raise
|
||||
self.path.unlink()
|
||||
|
||||
def select(self, policy):
|
||||
interface, mark = policy['interface'], policy['mark']
|
||||
main = json.loads(self.ip('-j', 'route', 'show', 'table', 'main'))
|
||||
defaults = [r for r in main if r.get('dst') == 'default' and r.get('dev') == interface]
|
||||
strict = policy.get('strict', False)
|
||||
if (len(defaults) != 1 or not defaults[0].get('gateway')) and not strict:
|
||||
raise RouteNotReady('У выбранного подключения нет однозначного шлюза.')
|
||||
routes = [self.route_key(r) for r in main if r.get('dev') == interface
|
||||
and r.get('scope') == 'link' and r.get('dst') != 'default']
|
||||
if len(defaults) == 1 and defaults[0].get('gateway'):
|
||||
routes.append(self.route_key(defaults[0]))
|
||||
if len(routes) > 32:
|
||||
raise ValueError('Слишком сложная маршрутизация выбранного подключения.')
|
||||
if strict:
|
||||
self.retain_selected(mark, routes)
|
||||
return
|
||||
self.release()
|
||||
self.record(dict(mark=mark, routes=routes)) # Undo is durable before the first write.
|
||||
try:
|
||||
for row in routes:
|
||||
self.change_route('add', row)
|
||||
self.ip('rule', 'add', 'priority', PRIORITY, 'fwmark', hex(mark),
|
||||
'table', TABLE, 'protocol', PROTOCOL)
|
||||
except Exception as error:
|
||||
self.release()
|
||||
if isinstance(error, subprocess.CalledProcessError):
|
||||
detail = (error.stderr or b'')
|
||||
if isinstance(detail, bytes):
|
||||
detail = detail.decode(errors='replace')
|
||||
if 'Invalid prefsrc address' in detail or 'Cannot find device' in detail:
|
||||
raise RouteNotReady('Адрес выбранного подключения обновляется.') from error
|
||||
raise
|
||||
|
||||
def retain_selected(self, mark, routes):
|
||||
# When fallback is disabled, a missing selected NIC must not fall through
|
||||
# to another default. Keep the guard while refreshing DHCP/kernel routes.
|
||||
guard = dict(dst='default', type='unreachable', metric=32760)
|
||||
desired = [*routes, guard]
|
||||
live, rules = self.owned()
|
||||
if rules and int(rules[0]['fwmark'], 0) != mark:
|
||||
raise ValueError('Метка транспорта изменилась. Повторите выбор подключения.')
|
||||
current = [self.route_key(row) for row in live]
|
||||
if len(current) == len(desired) and all(row in desired for row in current) and rules:
|
||||
return
|
||||
journal = current + [row for row in desired if row not in current]
|
||||
self.record(dict(mark=mark, routes=journal))
|
||||
if guard not in current:
|
||||
self.change_route('add', guard)
|
||||
if not rules:
|
||||
self.ip('rule', 'add', 'priority', PRIORITY, 'fwmark', hex(mark),
|
||||
'table', TABLE, 'protocol', PROTOCOL)
|
||||
for row in current:
|
||||
if row not in desired:
|
||||
self.change_route('del', row)
|
||||
for row in routes:
|
||||
if row not in current:
|
||||
self.change_route('add', row)
|
||||
self.record(dict(mark=mark, routes=desired))
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Root-owned IPC service. No shell command or arbitrary profile data accepted."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import socket
|
||||
import socketserver
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from uplink.migration import migrate # noqa: E402
|
||||
from uplink.netbird_path import NetBirdPath # noqa: E402
|
||||
from uplink.network_manager import NetworkManager # noqa: E402
|
||||
from uplink.transaction import Controller, dispatch # noqa: E402
|
||||
|
||||
SOCKET = Path("/run/mission-core-uplink/control.sock")
|
||||
|
||||
|
||||
class Handler(socketserver.StreamRequestHandler):
|
||||
def handle(self):
|
||||
self.connection.settimeout(30)
|
||||
_, uid, _ = struct.unpack(
|
||||
"3i", self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)
|
||||
)
|
||||
if uid != self.server.uid:
|
||||
return
|
||||
try:
|
||||
raw = self.rfile.readline(4097)
|
||||
if len(raw) > 4096 or not raw.endswith(b"\n"):
|
||||
return
|
||||
result = {"ok": True, "result": dispatch(self.server.controller, json.loads(raw))}
|
||||
except ValueError as error:
|
||||
result = {"ok": False, "error": str(error)}
|
||||
except Exception:
|
||||
result = {"ok": False, "error": "Сетевая служба не подтвердила операцию."}
|
||||
self.wfile.write(json.dumps(result).encode() + b"\n")
|
||||
|
||||
|
||||
class Server(socketserver.UnixStreamServer):
|
||||
def service_actions(self):
|
||||
self.controller.tick()
|
||||
|
||||
|
||||
def main():
|
||||
os.umask(0o077)
|
||||
if sys.argv[1:] == ["--migrate-native-fallback"]:
|
||||
migrate(Path("/var/lib/mission-core-uplink"), NetworkManager())
|
||||
return
|
||||
user = pwd.getpwnam("mission-core-node")
|
||||
controller = Controller(
|
||||
Path("/var/lib/mission-core-uplink"), NetworkManager(), path_adapter=NetBirdPath()
|
||||
)
|
||||
if sys.argv[1:] == ['--release']:
|
||||
controller.path_adapter.release()
|
||||
controller.release_paused()
|
||||
return
|
||||
if sys.argv[1:] == ["--restore"]:
|
||||
if controller.fallback_enabled():
|
||||
controller.path_adapter.release()
|
||||
else:
|
||||
controller.retain_path()
|
||||
controller.release_paused()
|
||||
return
|
||||
SOCKET.unlink(missing_ok=True)
|
||||
with Server(str(SOCKET), Handler) as server:
|
||||
server.uid, server.controller = user.pw_uid, controller
|
||||
os.chown(SOCKET, 0, user.pw_gid)
|
||||
os.chmod(SOCKET, 0o660)
|
||||
server.serve_forever(poll_interval=1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user