feat(router): confirm DexaFlow modes and expose the paired admin interface

This commit is contained in:
DCCONSTRUCTIONS
2026-11-21 20:58:25 +03:00
parent bed1db3508
commit 3ff43dd2af
37 changed files with 1462 additions and 63 deletions
@@ -48,6 +48,10 @@ func recoveryPeer(state tls.ConnectionState, coreID string) bool {
func (p *Pairing) recoveryHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/v1/router/admin" {
p.routerAdmin(w, r)
return
}
w.Header().Set("Cache-Control", "no-store")
host, _, err := net.SplitHostPort(r.RemoteAddr)
p.mu.Lock()
@@ -0,0 +1,48 @@
package node
import (
"encoding/json"
"net"
"net/http"
"nodedc.local/mission-core/node-agent/internal/routers"
"time"
)
func (p *Pairing) routerAdmin(w http.ResponseWriter, r *http.Request) {
host, _, err := net.SplitHostPort(r.RemoteAddr)
var body routers.AdminRequest
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 2*1048576))
decoder.DisallowUnknownFields()
if r.Method != "POST" || err != nil || r.TLS == nil || decoder.Decode(&body) != nil || !body.Valid() {
http.Error(w, "Invalid request", 400)
return
}
p.mu.Lock()
b := p.state.Binding
allowed := p.state.Phase == "paired" && b != nil && p.networkPeerLocked(host) && recoveryPeer(*r.TLS, b.CoreID) && body.BindingID == b.BindingID
collector := p.Routers
p.mu.Unlock()
if !allowed {
http.Error(w, "Binding unavailable", 403)
return
}
if collector == nil {
http.Error(w, "Router unavailable", 503)
return
}
if body.Method == "POST" {
// Extend only an authenticated admin request, not the shared listener.
if err := http.NewResponseController(w).SetWriteDeadline(time.Now().Add(100 * time.Second)); err != nil {
http.Error(w, "Router response deadline unavailable", 503)
return
}
}
result, err := collector.Admin(r.Context(), body)
if err != nil {
http.Error(w, "Router request failed", 502)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
json.NewEncoder(w).Encode(result)
}
@@ -0,0 +1,65 @@
package node
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"net/http/httptest"
"nodedc.local/mission-core/node-agent/internal/routers"
"strings"
"testing"
"time"
)
type adminDeadlineRecorder struct {
*httptest.ResponseRecorder
deadline time.Time
}
func (w *adminDeadlineRecorder) SetWriteDeadline(t time.Time) error { w.deadline = t; return nil }
func TestRouterAdminLongDeadlineRequiresAuthenticatedWrite(t *testing.T) {
p, client := recoveryFixture(t)
p.Routers = routers.Open(t.TempDir())
cert, _ := x509.ParseCertificate(client.Certificate[0])
for _, tc := range []struct {
binding, method string
status int
extended bool
}{
{"old", "POST", 403, false},
{p.state.Binding.BindingID, "GET", 502, false},
{p.state.Binding.BindingID, "POST", 502, true},
} {
body, _ := json.Marshal(map[string]any{"binding_id": tc.binding, "device_id": "router", "method": tc.method, "path": "/cgi-bin/dexaflow_manual"})
r := httptest.NewRequest("POST", "/v1/router/admin", strings.NewReader(string(body)))
r.RemoteAddr = "100.64.10.5:42000"
r.TLS = &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{cert}}, PeerCertificates: []*x509.Certificate{cert}}
w := &adminDeadlineRecorder{ResponseRecorder: httptest.NewRecorder()}
p.recoveryHandler().ServeHTTP(w, r)
if w.Code != tc.status || !w.deadline.IsZero() != tc.extended {
t.Fatalf("%s: code %d deadline %v", tc.method, w.Code, w.deadline)
}
if tc.extended && time.Until(w.deadline) < 90*time.Second {
t.Fatal("native command inherits the short shared-listener deadline")
}
}
}
func TestRouterAdminRequiresCurrentBinding(t *testing.T) {
p, client := recoveryFixture(t)
body := map[string]any{"binding_id": "old", "device_id": "router", "method": "GET", "path": "/"}
if out := recoveryCall(p, client, "/v1/router/admin", body); out.Code != 403 {
t.Fatal(out.Code)
}
body["binding_id"] = p.state.Binding.BindingID
if out := recoveryCall(p, client, "/v1/router/admin", body); out.Code != 503 {
t.Fatal(out.Code)
}
if e := p.cancel(); e != nil {
t.Fatal(e)
}
if out := recoveryCall(p, client, "/v1/router/admin", body); out.Code != 403 {
t.Fatal(out.Code)
}
}
+101
View File
@@ -0,0 +1,101 @@
package routers
// Browser forwarding is scoped to a freshly observed Ethernet router. It has
// no arbitrary destination, credential injection, redirects or host route edits.
import (
"bytes"
"context"
"errors"
"io"
"net/http"
"net/url"
"strings"
"time"
)
type AdminRequest struct {
BindingID string `json:"binding_id"`
DeviceID string `json:"device_id"`
Method string `json:"method"`
Path string `json:"path"`
Headers map[string]string `json:"headers"`
Body []byte `json:"body"`
}
type AdminResponse struct {
Status int `json:"status"`
Headers map[string][]string `json:"headers"`
Body []byte `json:"body"`
}
func (r AdminRequest) Valid() bool {
u, e := url.ParseRequestURI(r.Path)
return e == nil && strings.HasPrefix(r.Path, "/") && !strings.HasPrefix(r.Path, "//") && u.Host == "" && u.Scheme == "" && !strings.ContainsAny(r.Path, "\r\n\\") && len(r.Path) <= 8192 && len(r.Body) <= 1048576 && len(r.Headers) <= 8 && (r.Method == "GET" || r.Method == "POST" || r.Method == "HEAD")
}
func (c *Collector) Admin(ctx context.Context, in AdminRequest) (AdminResponse, error) {
if !in.Valid() {
return AdminResponse{}, errProtocol
}
var chosen *Device
for _, d := range c.Snapshot().Items {
if d.ID == in.DeviceID && d.Attached && d.Connection == "ethernet" && d.State == "ready" && time.Now().Unix()-d.ObservedAt < 40 {
copy := d
chosen = &copy
break
}
}
if chosen == nil {
return AdminResponse{}, errors.New("router not available")
}
d := chosen
candidate := Candidate{Address: d.Address, Interface: d.Interface, LocalIP: d.LocalIP, MAC: c.neighbor(d.Interface, d.Address)}
if candidate.MAC == "" {
return AdminResponse{}, errLink
}
a := newAPI(candidate)
a.client.Jar = nil
a.client.Timeout = 8 * time.Second
if in.Method == "POST" {
// Native mode changes and diagnostics synchronously wait for the router.
a.client.Timeout = 90 * time.Second
}
a.client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
defer a.client.CloseIdleConnections()
req, e := http.NewRequestWithContext(ctx, in.Method, "http://"+d.Address+in.Path, bytes.NewReader(in.Body))
if e != nil {
return AdminResponse{}, e
}
for _, key := range []string{"Cookie", "Content-Type", "Accept", "Accept-Encoding"} {
if v := in.Headers[key]; len(v) <= 16384 {
req.Header.Set(key, v)
}
}
req.Header.Set("Origin", "http://"+d.Address)
req.Header.Set("Referer", "http://"+d.Address+"/cgi-bin/luci/dexaflow")
if !a.check() {
return AdminResponse{}, errLink
}
response, e := a.client.Do(req)
if e != nil {
return AdminResponse{}, e
}
defer response.Body.Close()
body, e := io.ReadAll(io.LimitReader(response.Body, 8*1048576+1))
if e != nil || len(body) > 8*1048576 {
return AdminResponse{}, errProtocol
}
out := AdminResponse{Status: response.StatusCode, Body: body, Headers: map[string][]string{}}
for _, key := range []string{"Content-Type", "Content-Encoding", "Set-Cookie", "Location", "Content-Disposition"} {
values := response.Header.Values(key)
if key == "Location" && len(values) > 0 {
u, e := url.Parse(values[0])
if e != nil || (u.Host != "" && u.Host != d.Address) {
return AdminResponse{}, errProtocol
}
values = []string{u.RequestURI()}
}
if len(values) > 0 {
out.Headers[key] = values
}
}
return out, nil
}
@@ -0,0 +1,17 @@
package routers
import "testing"
func TestAdminRequestRejectsDestinationEscapes(t *testing.T) {
for _, path := range []string{"https://other/", "//other/path", "/bad\nheader", "/back\\slash"} {
if (AdminRequest{Method: "GET", Path: path}).Valid() {
t.Fatal("accepted", path)
}
}
if !(AdminRequest{Method: "GET", Path: "/cgi-bin/luci/dexaflow?x=1"}).Valid() {
t.Fatal("native path rejected")
}
if (AdminRequest{Method: "CONNECT", Path: "/"}).Valid() {
t.Fatal("tunnel accepted")
}
}
@@ -0,0 +1,52 @@
package routers
import (
"encoding/json"
"testing"
)
func TestClientAPIConfirmationFollowsFreshActiveMode(t *testing.T) {
caps := []byte(`{"api_version":"1","schema_version":"1.1","rights":["read"]}`)
for _, tc := range []struct {
name, observed, effective string
wanVerified bool
server string
internet string
}{
{"aggregation-with-inactive-vpn", `{"active":"aggregation","stale":false,"aggregate_checked":true,"aggregate_verified":true,"vpn_verified":false}`, "", false, "true", "verified"},
{"aggregation-failed-vpn-healthy", `{"active":"aggregation","stale":false,"aggregate_checked":true,"aggregate_verified":false,"vpn_verified":true}`, "", true, "false", "unknown"},
{"aggregation-not-checked", `{"active":"aggregation","stale":false,"aggregate_checked":false,"aggregate_verified":false}`, "", false, "null", "unknown"},
{"aggregation-missing-proof", `{"active":"aggregation","stale":false}`, "", false, "null", "unknown"},
{"aggregation-null-proof", `{"active":"aggregation","stale":false,"aggregate_verified":null}`, "", false, "null", "unknown"},
{"aggregation-invalid-proof", `{"active":"aggregation","stale":false,"aggregate_verified":"true"}`, "", false, "null", "unknown"},
{"aggregation-stale", `{"active":"aggregation","stale":true,"aggregate_verified":true}`, "", true, "null", "unknown"},
{"freshness-missing", `{"active":"aggregation","aggregate_verified":true}`, "", true, "null", "unknown"},
{"vpn-confirmed", `{"active":"vpn","stale":false,"aggregate_verified":false,"vpn_verified":true}`, "", false, "true", "verified"},
{"vpn-failed-aggregation-healthy", `{"active":"vpn","stale":false,"aggregate_verified":true,"vpn_verified":false}`, "", true, "false", "unknown"},
{"direct-does-not-inherit-server-proof", `{"active":"direct","stale":false,"aggregate_verified":true,"vpn_verified":true}`, "wan1", false, "null", "unknown"},
{"direct-selected-wan-verified", `{"active":"direct","stale":false}`, "wan1", true, "null", "verified"},
{"direct-other-wan-verified", `{"active":"direct","stale":false}`, "wan2", true, "null", "unknown"},
{"direct-missing-effective-wan", `{"active":"direct","stale":false}`, "", true, "null", "unknown"},
{"unknown-mode", `{"active":"future","stale":false,"aggregate_verified":true,"vpn_verified":true}`, "wan1", true, "null", "unknown"},
} {
t.Run(tc.name, func(t *testing.T) {
var observed map[string]any
if err := json.Unmarshal([]byte(tc.observed), &observed); err != nil {
t.Fatal(err)
}
status := map[string]any{"boot_id": "synthetic-boot", "uptime": 100, "revision": "r1", "observed": observed,
"desired_policy": map[string]any{"mode": "aggregation"}, "persisted_policy": map[string]any{"mode": "aggregation"},
"effective_wan": tc.effective, "vpn": map[string]any{"verified": false},
"wan": []any{map[string]any{"slot": "M1", "wan": "wan1", "up": true, "internet_verified": tc.wanVerified}}, "modems": []any{}}
raw, _ := json.Marshal(status)
d, err := normalizeClientAPI(caps, raw)
if err != nil {
t.Fatal(err)
}
server, _ := json.Marshal(d.VPSUp)
if string(server) != tc.server || d.Internet != tc.internet {
t.Fatalf("server=%s internet=%s; want %s/%s", server, d.Internet, tc.server, tc.internet)
}
})
}
}
@@ -104,7 +104,7 @@ func (c *Collector) verifyClientControl(ctx context.Context, candidates []Candid
result.VendorID = pending.OperationID
c.results[pending.Command.ID] = result
c.mu.Unlock()
c.event(pending.Command.DeviceID, code, 0, pending.Command.Action, "")
c.event(pending.Command.DeviceID, code, 0, pending.Command.Action, reason)
c.clientControl = nil
}
if !time.Now().Before(pending.Until) {
@@ -131,6 +131,7 @@ func (c *Collector) verifyClientControl(ctx context.Context, candidates []Candid
ID string `json:"operation_id"`
State string `json:"state"`
Kind string `json:"kind"`
Error string `json:"error"`
Result struct {
Persisted *bool `json:"persisted"`
Applied *bool `json:"applied"`
@@ -148,7 +149,7 @@ func (c *Collector) verifyClientControl(ctx context.Context, candidates []Candid
}
finish("complete", "", "command_complete")
case "failed":
finish("error", "command_rejected", "command_failed")
finish("error", clientOperationError(op.Error), "command_failed")
case "interrupted", "unknown":
finish("unknown", "confirmation_timeout", "command_unconfirmed")
}
@@ -161,3 +162,16 @@ func sameClientPolicy(a, b clientPolicy) bool {
y, _ := json.Marshal(b)
return string(x) == string(y)
}
// Only documented public codes may leave the vendor boundary. A failed async
// operation is not equivalent to an HTTP rejection of its initial request.
func clientOperationError(code string) string {
switch code {
case "busy":
return "router_busy"
case "revision_conflict", "superseded", "boot_id_mismatch":
return "router_conflict"
default:
return "command_rejected"
}
}
@@ -115,11 +115,21 @@ func normalizeClientAPI(capsRaw, statusRaw []byte) (Device, error) {
d.ActiveMode = text(observed["active"])
d.ManualMode = d.SelectedMode
d.ActiveWAN = text(status["effective_wan"])
if observed["stale"] == false && (observed["aggregate_verified"] == true || observed["vpn_verified"] == true) {
d.Internet = "verified"
// Confirmation belongs to the observed path, never the configured policy or
// a different (possibly inactive) VPN. Missing/stale proof remains unknown.
if observed["stale"] == false {
switch d.ActiveMode {
case "aggregation":
if observed["aggregate_checked"] != false {
d.VPSUp = boolValue(observed["aggregate_verified"])
}
case "vpn":
d.VPSUp = boolValue(observed["vpn_verified"])
}
if d.VPSUp != nil && *d.VPSUp {
d.Internet = "verified"
}
}
vpn := object(status["vpn"])
d.VPSUp = boolValue(vpn["verified"])
recovery := object(status["recovery"])
detail.RecoveryPhase = text(recovery["phase"])
detail.RecoveryReason = text(recovery["reason_code"])
@@ -143,7 +153,8 @@ func normalizeClientAPI(capsRaw, statusRaw []byte) (Device, error) {
}
}
detail.WAN = append(detail.WAN, clientWAN{Slot: slot, WAN: text(w["wan"]), Interface: text(w["interface"]), Up: boolValue(w["up"]), SIMPresent: boolValue(w["sim_present"]), ModemPresent: boolValue(w["modem_present"]), Registration: text(registration["registration_state"]), FailureReason: failure, Fresh: boolValue(registration["fresh"]), AgeSeconds: number(registration["age_s"], 0, 1e12), Traffic: readTraffic(w["traffic"]), ObservedUptime: number(w["observed_uptime"], 0, 1e12), SessionUptime: number(w["uptime_s"], 0, 1e12)})
if observed["stale"] == false && w["internet_verified"] == true {
if observed["stale"] == false && d.ActiveMode == "direct" && d.ActiveWAN != "" &&
(d.ActiveWAN == w["wan"] || d.ActiveWAN == w["slot"]) && w["internet_verified"] == true {
d.Internet = "verified"
}
// A slot being up does not prove it participates in aggregation. Only a
@@ -195,12 +206,18 @@ func (c *Collector) pollClientAPI(ctx context.Context, candidates []Candidate, s
if candidate.Address == r.Device.Address && c.neighbor(candidate.Interface, candidate.Address) == r.MAC {
handled[candidate.Address] = true
seen[id] = true
r.Device.Attached = true
r.Device.Connection = "ethernet"
c.state.Records[id] = r
if r.Rejected {
seen[id] = true
r.Device.ObservedAt = time.Now().Unix()
// A remembered ARP entry alone cannot prove current presence.
// Recheck the public panel without retrying rejected credentials.
old := r.Device
r.Device.Attached = c.client(candidate).family(ctx)
if r.Device.Attached {
r.Device.State = "access_rejected"
r.Device.ObservedAt = time.Now().Unix()
} else {
r.Device.State = "unreachable"
}
c.transitions(old, r.Device)
c.state.Records[id] = r
break
}
@@ -218,6 +235,7 @@ func (c *Collector) pollClientAPI(ctx context.Context, candidates []Candidate, s
if err != nil && !(errors.As(err, &apiErr) && (apiErr.Status == 401 || apiErr.Status == 403)) {
if seen[id] {
r.Device.State = "unreachable"
r.Device.Attached = false
c.state.Records[id] = r
}
delete(c.traffic, id)
@@ -306,3 +306,71 @@ func TestClientAPIControlAcceptedIsNotComplete(t *testing.T) {
t.Fatal("operation verification failed")
}
}
func TestClientPolicyAsyncOutcome(t *testing.T) {
for _, tc := range []struct {
name, state, code, wantState, wantError string
persisted, applied, observed bool
}{
{"busy", "failed", "busy", "error", "router_busy", false, false, false},
{"changed", "failed", "superseded", "error", "router_conflict", false, false, false},
{"private-error", "failed", "secret-token-or-response", "error", "command_rejected", false, false, false},
{"interrupted", "interrupted", "", "unknown", "confirmation_timeout", false, false, false},
{"not-persisted", "succeeded", "", "applying", "", false, true, true},
{"not-applied", "succeeded", "", "applying", "", true, false, true},
{"stale-readback", "succeeded", "", "applying", "", true, true, false},
{"confirmed", "succeeded", "", "complete", "", true, true, true},
} {
t.Run(tc.name, func(t *testing.T) {
var writes atomic.Int32
a, ca := clientAPIFixture(t, func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/client/v1/status":
io.WriteString(w, `{"boot_id":"boot-1","revision":"r1"}`)
case "/api/client/v1/policy":
writes.Add(1)
w.WriteHeader(202)
io.WriteString(w, `{"operation_id":"policy-1","kind":"policy","state":"accepted"}`)
case "/api/client/v1/operations/policy-1":
json.NewEncoder(w).Encode(map[string]any{"operation_id": "policy-1", "kind": "policy", "state": tc.state, "error": tc.code, "result": map[string]bool{"persisted": tc.persisted, "applied": tc.applied}})
default:
t.Error("unexpected path", r.URL.Path)
w.WriteHeader(404)
}
})
c := Open(t.TempDir())
candidate := Candidate{Address: "192.168.1.1", LocalIP: "192.168.1.2", Interface: "eth-test"}
c.discover = func(context.Context, []Candidate) []Candidate { return []Candidate{candidate} }
c.apiClient = func(Candidate, clientAPIAccess) (*clientAPI, error) { return a, nil }
expected := clientPolicy{Mode: "direct", PreferredSIM: "M1", AllowFallback: true, ReturnToPreferred: true, Persist: true, FailSeconds: 60, RecoverSeconds: 60, MinVPNSeconds: 120}
r := record{Device: Device{ID: a.identity, Address: candidate.Address, Interface: candidate.Interface, State: "ready", ClientAPI: &clientPublic{Rights: []string{"read", "policy"}}}, Access: &credential{ClientAPI: &clientAPIAccess{Token: "synthetic-private-key", CA: ca}}}
if tc.observed {
r.Device.ClientAPI.Policy = expected
}
c.state.Records[a.identity] = r
cmd := Command{ID: "op_0123456789abcdef0123456789abcdef", RuntimeID: c.runtime, DeviceID: a.identity, Action: "policy", ExpectedBootID: "boot-1", ExpectedRevision: "r1", Deadline: time.Now().Add(time.Minute).Unix(), Policy: &expected}
c.applyClientControl(context.Background(), cmd, r)
if writes.Load() != 1 || c.results[cmd.ID].State != "applying" {
t.Fatal("HTTP 202 was not pending", c.results[cmd.ID])
}
c.verifyClientControl(context.Background(), []Candidate{candidate})
result := c.results[cmd.ID]
if result.State != tc.wantState || result.Error != tc.wantError || writes.Load() != 1 {
t.Fatal("wrong terminal outcome or replay", result, writes.Load())
}
if tc.wantState != "applying" {
if result.VendorID != "policy-1" {
t.Fatal("vendor correlation lost")
}
event := c.state.Events[len(c.state.Events)-1]
if event.After != tc.wantError {
t.Fatal("reason lost in journal", event)
}
c.verifyClientControl(context.Background(), []Candidate{candidate})
if writes.Load() != 1 {
t.Fatal("terminal failure was retried")
}
}
})
}
}
+24 -2
View File
@@ -16,6 +16,13 @@ import (
)
type Collector struct {
devUntil atomic.Int64
devSequence uint64
devRows []DiagnosticEvent
devEventsAt map[string]time.Time
devSeen map[string]bool
devCursors map[string]string
devBoots map[string]string
speedUpdates chan struct{}
speedCancel context.CancelFunc
speedOperation, speedDevice string
@@ -86,6 +93,13 @@ func (c *Collector) Snapshot() Snapshot {
data, _ := json.Marshal(c.view.Load().(Snapshot))
var s Snapshot
_ = json.Unmarshal(data, &s)
for i := range s.Items {
age := time.Now().Unix() - s.Items[i].ObservedAt
if age >= 40 || age < -30 {
s.Items[i].Attached = false
s.Items[i].State = "unreachable"
}
}
c.mu.Lock()
s.Results = []Result{}
for _, r := range c.results {
@@ -151,7 +165,7 @@ func (c *Collector) Submit(cmd Command) error {
}
select {
case c.commands <- cmd:
c.results[cmd.ID] = Result{ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: "queued"}
c.results[cmd.ID] = Result{At: now.Unix(), ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: "queued"}
c.resultTimes[cmd.ID] = now
return nil
default:
@@ -164,7 +178,7 @@ func (c *Collector) publish() {
c.evidenceCache = nil
c.evidence = nil
}
s := Snapshot{SpeedtestVersion: 1, ReadVersion: 1, Evidence: c.evidence, ControlVersion: 1, Schema: Schema, RuntimeID: c.runtime, Available: !c.blocked, ObservedAt: time.Now().Unix(), Items: []Device{}, Events: append([]Event{}, c.state.Events...), Results: []Result{}, Journal: Journal{Last: c.state.Sequence, Dropped: c.state.Dropped, Limit: maxEvents, RetentionDays: 7, Error: c.storageError}}
s := Snapshot{AdminVersion: 1, SpeedtestVersion: 1, ReadVersion: 1, Evidence: c.evidence, ControlVersion: 1, Schema: Schema, RuntimeID: c.runtime, Available: !c.blocked, ObservedAt: time.Now().Unix(), Items: []Device{}, Events: append([]Event{}, c.state.Events...), Results: []Result{}, Journal: Journal{Last: c.state.Sequence, Dropped: c.state.Dropped, Limit: maxEvents, RetentionDays: 7, Error: c.storageError}}
if len(s.Events) > 0 {
s.Journal.First = s.Events[0].Sequence
}
@@ -227,7 +241,13 @@ func (c *Collector) Run(ctx context.Context) {
if c.blocked {
return
}
c.devEventsAt = map[string]time.Time{}
c.devSeen = map[string]bool{}
c.devCursors = map[string]string{}
c.devBoots = map[string]string{}
c.poll(ctx)
diagnosticTicker := time.NewTicker(time.Second)
defer diagnosticTicker.Stop()
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for {
@@ -249,6 +269,8 @@ func (c *Collector) Run(ctx context.Context) {
c.applyControl(ctx, cmd)
}
c.publish()
case <-diagnosticTicker.C:
c.pollDiagnostic(ctx)
case <-ticker.C:
c.poll(ctx)
}
@@ -0,0 +1,161 @@
package routers
// Opt-in, expiring DEV interest: GETs only, no modem commands or recovery jobs.
import (
"context"
"encoding/json"
"errors"
"time"
)
type DiagnosticEvent struct {
Sequence uint64
DeviceID, Event, At string
Data map[string]any
}
func (c *Collector) DiagnosticInterest() {
c.devUntil.Store(time.Now().Add(3 * time.Second).UnixNano())
}
func (c *Collector) DiagnosticTail(after uint64) []DiagnosticEvent {
c.mu.Lock()
defer c.mu.Unlock()
out := []DiagnosticEvent{}
for _, row := range c.devRows {
if row.Sequence > after {
out = append(out, row)
}
}
return out
}
func (c *Collector) devRecord(id, event string, data map[string]any) {
raw, e := json.Marshal(data)
if e != nil {
return
}
if len(raw) > 6500 {
data = map[string]any{"state": "record_omitted", "reason": "size_bound", "bytes": len(raw)}
}
c.mu.Lock()
defer c.mu.Unlock()
c.devSequence++
c.devRows = append(c.devRows, DiagnosticEvent{c.devSequence, id, event, time.Now().UTC().Format(time.RFC3339Nano), data})
if len(c.devRows) > 128 {
c.devRows = c.devRows[len(c.devRows)-128:]
}
}
func diagnosticFields(source map[string]any, keys ...string) map[string]any {
out := map[string]any{}
for _, k := range keys {
if v, ok := source[k]; ok {
out[k] = v
}
}
return out
}
func (c *Collector) pollDiagnostic(ctx context.Context) {
if time.Now().UnixNano() > c.devUntil.Load() {
return
}
for id, r := range c.state.Records {
if r.Access == nil || r.Access.ClientAPI == nil || r.Rejected {
continue
}
if !r.Device.Attached {
continue
}
a, e := c.apiClient(Candidate{Address: r.Device.Address, Interface: r.Device.Interface, LocalIP: r.Device.LocalIP}, *r.Access.ClientAPI)
if e != nil || a.identity != id {
continue
}
call, cancel := context.WithTimeout(ctx, 650*time.Millisecond)
raw, _, e := a.readResource(call, "status", "", "", 0)
cancel()
if e != nil {
c.devRecord(id, "router_sample", map[string]any{"state": "read_failed"})
continue
}
projected, e := projectEvidence("status", raw, r.Access.ClientAPI.Token)
var safe struct {
Data map[string]any `json:"data"`
}
if e != nil || json.Unmarshal(projected, &safe) != nil {
c.devRecord(id, "router_sample", map[string]any{"state": "unsupported_response"})
continue
}
d := safe.Data
if c.devCursors == nil {
c.devCursors = map[string]string{}
c.devBoots = map[string]string{}
}
if boot, ok := d["boot_id"].(string); ok && c.devBoots[id] != boot {
c.devBoots[id] = boot
delete(c.devCursors, id)
}
summary := diagnosticFields(d, "boot_id", "uptime", "revision", "clock_quality", "firmware_version", "desired_policy", "persisted_policy", "observed", "effective_wan", "recovery", "traffic", "vpn")
summary["state"] = "read"
summary["sample_interval_s"] = 1
summary["slot_map"] = r.Device.SlotMap
c.devRecord(id, "router_sample", summary)
for _, kind := range []string{"wan", "modems"} {
rows, _ := d[kind].([]any)
for i, row := range rows {
if i >= 8 {
break
}
v, _ := row.(map[string]any)
if v == nil {
continue
}
c.devRecord(id, "router_"+kind, map[string]any{"boot_id": d["boot_id"], "router_uptime": d["uptime"], "sample": v})
}
}
// Preserve vendor-origin event times; repeated tail reads are deduplicated.
if time.Since(c.devEventsAt[id]) < 5*time.Second {
continue
}
c.devEventsAt[id] = time.Now()
call, cancel = context.WithTimeout(ctx, 650*time.Millisecond)
raw, _, e = a.readResource(call, "events", "", c.devCursors[id], 50)
cancel()
if e != nil {
var apiErr *clientAPIError
if errors.As(e, &apiErr) && (apiErr.Status == 400 || apiErr.Status == 409 || apiErr.Status == 410 || apiErr.Status == 422) && c.devCursors[id] != "" {
delete(c.devCursors, id)
c.devRecord(id, "router_event_cursor_reset", map[string]any{"state": "cursor_rejected", "http_status": apiErr.Status})
}
c.devRecord(id, "router_events_unavailable", map[string]any{"state": "read_failed"})
continue
}
projected, e = projectEvidence("events", raw, r.Access.ClientAPI.Token)
if e != nil || json.Unmarshal(projected, &safe) != nil {
continue
}
if cursor, ok := safe.Data["cursor"].(string); ok && len(cursor) <= 512 {
c.devCursors[id] = cursor
}
rows, _ := safe.Data["events"].([]any)
if len(rows) >= 50 && c.devCursors[id] != "" {
// Catch up one bounded page per poll, without blocking other work.
c.devEventsAt[id] = time.Now().Add(-4 * time.Second)
}
c.devRecord(id, "router_event_page", map[string]any{"events": len(rows), "cursor_present": c.devCursors[id] != "", "page_full": len(rows) >= 50, "router_boot_id": d["boot_id"]})
for _, row := range rows {
v, _ := row.(map[string]any)
if v == nil {
continue
}
value := diagnosticFields(v, "sequence", "source", "boot", "boot_id", "clock_quality", "epoch", "at", "at_utc", "observed_utc", "uptime", "topic", "category", "code", "recorded_code", "action", "recorded_action", "state", "reason", "operation_id", "initiator_kind", "actor_inferred", "causal_link_proven", "slot")
keyBytes, _ := json.Marshal(value)
key := id + string(keyBytes)
if c.devSeen[key] {
continue
}
if len(c.devSeen) >= 256 {
c.devSeen = map[string]bool{}
}
c.devSeen[key] = true
c.devRecord(id, "router_event", value)
}
}
}
@@ -0,0 +1,64 @@
package routers
import (
"context"
"encoding/json"
"io"
"net/http"
"strings"
"testing"
"time"
)
func TestDiagnosticRouterReadsExpireAndPreserveSourceTimes(t *testing.T) {
calls := 0
eventCalls := 0
a, _ := clientAPIFixture(t, func(w http.ResponseWriter, r *http.Request) {
calls++
if r.Method != "GET" {
t.Fatal("DEV mutated router")
}
if r.URL.Path == "/api/client/v1/status" {
io.WriteString(w, `{"boot_id":"boot-a","uptime":120,"clock_quality":"unverified","token":"secret","desired_policy":{"mode":"direct"},"observed":{"active":"direct"},"modems":[{"slot":"M1","operator":"Carrier","imei":"secret","radio":{"rsrp_dbm":-90,"age_s":12}}]}`)
} else if r.URL.Path == "/api/client/v1/events" {
eventCalls++
if eventCalls > 1 && r.URL.Query().Get("after") != "next-page" {
t.Fatal("event cursor did not advance")
}
io.WriteString(w, `{"cursor":"next-page","events":[{"sequence":5,"boot_id":"boot-a","at_utc":"2026-11-13T10:00:00Z","code":"modem_connected","password":"secret"}]}`)
} else {
t.Error("unexpected resource", r.URL.Path)
}
})
c := Open(t.TempDir())
id := a.identity
c.state.Records[id] = record{Device: Device{ID: id, Attached: true, State: "ready"}, Access: &credential{ClientAPI: &clientAPIAccess{Token: "secret"}}}
c.apiClient = func(Candidate, clientAPIAccess) (*clientAPI, error) { return a, nil }
c.devEventsAt = map[string]time.Time{}
c.devSeen = map[string]bool{}
c.pollDiagnostic(context.Background())
if calls != 0 {
t.Fatal("inactive source performed I/O")
}
c.DiagnosticInterest()
c.pollDiagnostic(context.Background())
first := c.DiagnosticTail(0)
if len(first) != 4 {
t.Fatal(len(first))
}
data, _ := json.Marshal(first)
if strings.Contains(string(data), "secret") || !strings.Contains(string(data), "2026-11-13T10:00:00Z") || !strings.Contains(string(data), `"age_s":12`) {
t.Fatal(string(data))
}
c.devEventsAt[id] = time.Time{}
c.pollDiagnostic(context.Background())
if len(c.DiagnosticTail(first[len(first)-1].Sequence)) != 3 {
t.Fatal("vendor event repeated")
}
c.devUntil.Store(time.Now().Add(-time.Second).UnixNano())
before := calls
c.pollDiagnostic(context.Background())
if calls != before {
t.Fatal("interest did not expire")
}
}
@@ -12,6 +12,7 @@ import (
// are omitted, never forwarded as telemetry or interpreted as instructions.
// Dynamic vendor dictionaries, credentials and request bodies are not admitted.
var evidenceFields = strings.Fields(`
at at_utc timestamp timestamp_utc
new_probe_started active_modem_query network_command_sent external_probe_started_by_get vpn_auto chain expression_types oif fwmark dstlen iif network_registration_scope
request expected_boot_id deadline_uptime
report shared_component_version shared_queue operation operation_id kind state accepted_boot_id accepted_uptime accepted_utc updated_utc actor result
@@ -70,7 +70,7 @@ func applyInventory(d *Device, status map[string]any) {
func (c *Collector) decorate(r *record, candidate Candidate) {
r.Device.Name = r.Name
r.Device.Attached = true
r.Device.Attached = r.Device.State != "unreachable"
r.Device.Connection = "ethernet"
r.Device.WebUsername = ""
if r.WebAccess != nil {
@@ -0,0 +1,102 @@
package routers
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
)
func TestPresenceExpiresWithoutDiscardingInstanceSettings(t *testing.T) {
c := Open(t.TempDir())
c.state.Records["a"] = record{Name: "Saved name", Device: Device{ID: "a", State: "ready", Attached: true, ObservedAt: time.Now().Add(-time.Minute).Unix()}}
c.state.Records["b"] = record{Device: Device{ID: "b", State: "ready", Attached: true, ObservedAt: time.Now().Unix()}}
c.publish()
s := c.Snapshot()
if s.Items[0].Attached || s.Items[0].State != "unreachable" || !s.Items[1].Attached {
t.Fatal("fresh heartbeat revived an expired instance", s.Items)
}
if c.state.Records["a"].Name != "Saved name" || len(c.state.Records) != 2 {
t.Fatal("presence expiry discarded enrollment")
}
}
func TestDecoratingUnreachableRouterCannotRestorePresence(t *testing.T) {
c := Open(t.TempDir())
r := record{Device: Device{State: "unreachable"}}
c.decorate(&r, Candidate{})
if r.Device.Attached {
t.Fatal("decoration changed failed observation into attachment")
}
}
func TestRememberedARPDoesNotKeepFailedClientAPIConnected(t *testing.T) {
a, ca := clientAPIFixture(t, func(w http.ResponseWriter, _ *http.Request) {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
})
c := Open(t.TempDir())
candidate := Candidate{Address: "192.168.1.1", Interface: "test-lan", MAC: "02:00:00:00:00:01"}
c.discover = func(context.Context, []Candidate) []Candidate { return []Candidate{candidate} }
c.neighbor = func(string, string) string { return candidate.MAC }
c.apiClient = func(Candidate, clientAPIAccess) (*clientAPI, error) { return a, nil }
c.client = func(Candidate) *api { t.Fatal("failed paired device must not become another instance"); return nil }
c.state.Records[a.identity] = record{MAC: candidate.MAC, Access: &credential{ClientAPI: &clientAPIAccess{Token: "synthetic", CA: ca}}, Device: Device{ID: a.identity, Address: candidate.Address, State: "ready", Attached: true, ObservedAt: time.Now().Unix()}}
c.poll(context.Background())
d := c.Snapshot().Items[0]
if d.Attached || d.State != "unreachable" || len(c.state.Records) != 1 {
t.Fatal("remembered ARP revived failed API", d)
}
}
func TestTwoRoutersDisconnectAndReturnIndependently(t *testing.T) {
online := map[string]*atomic.Bool{"192.168.20.1": {}, "192.168.30.1": {}}
servers := map[string]*httptest.Server{}
for address := range online {
address := address
online[address].Store(true)
servers[address] = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !online[address].Load() {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
return
}
fmt.Fprint(w, loginPageFixture)
}))
defer servers[address].Close()
}
c := Open(t.TempDir())
c.discover = func(context.Context, []Candidate) []Candidate {
return []Candidate{{Address: "192.168.20.1", Interface: "eth0"}, {Address: "192.168.30.1", Interface: "eth1"}}
}
c.neighbor = func(_, address string) string {
if address == "192.168.20.1" {
return "02:00:00:00:00:01"
}
return "02:00:00:00:00:02"
}
c.client = func(candidate Candidate) *api { return testAPI(servers[candidate.Address]) }
c.poll(context.Background())
first := c.Snapshot()
if len(first.Items) != 2 || !first.Items[0].Attached || !first.Items[1].Attached {
t.Fatal("multiple instances were collapsed", first.Items)
}
online["192.168.20.1"].Store(false)
c.poll(context.Background())
count := 0
for _, d := range c.Snapshot().Items {
if d.Attached {
count++
}
}
if count != 1 {
t.Fatal("disconnect affected the wrong instance", count)
}
online["192.168.20.1"].Store(true)
c.poll(context.Background())
last := c.Snapshot()
if len(last.Items) != 2 || !last.Items[0].Attached || !last.Items[1].Attached || last.Items[0].ID != first.Items[0].ID || last.Items[1].ID != first.Items[1].ID {
t.Fatal("reconnect lost identity or created duplicates", last.Items)
}
}
@@ -106,6 +106,7 @@ type Result struct {
}
type Snapshot struct {
SpeedtestVersion int `json:"speedtest_version"`
AdminVersion int `json:"admin_version"`
ReadVersion int `json:"read_version"`
Evidence *EvidenceChunk `json:"evidence,omitempty"`
ControlVersion int `json:"control_version"`