feat(routers): integrate Banana Pi Client API and onboard LibreSpeed measurements
Discover Ethernet routers under the board, map physical SIM slots, expose vendor controls and real telemetry, and provide packaged VPS speed tests with a live monochrome gauge. Enforce compact typography across Core and Node UI.
This commit is contained in:
@@ -307,6 +307,10 @@ func (p *Pairing) sendEncoded(ctx context.Context, b CoreBinding, path string, p
|
||||
func (p *Pairing) channel(ctx context.Context) {
|
||||
instance := "agent_" + token()
|
||||
var changed <-chan struct{}
|
||||
var speedChanged <-chan struct{}
|
||||
if p.Routers != nil {
|
||||
speedChanged = p.Routers.SpeedtestUpdates()
|
||||
}
|
||||
if p.Sensors != nil {
|
||||
var unsubscribe func()
|
||||
changed, unsubscribe = p.Sensors.events.subscribe()
|
||||
@@ -473,6 +477,7 @@ func (p *Pairing) channel(ctx context.Context) {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
case <-speedChanged:
|
||||
case <-changed:
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
package node
|
||||
|
||||
import (
|
||||
"nodedc.local/mission-core/node-agent/internal/routers"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRouterReadEndpointCannotDispatchWrites(t *testing.T) {
|
||||
read := routers.Command{Action: "inspect", Query: &routers.EvidenceQuery{Resource: "events"}}
|
||||
for _, action := range []string{"reboot", "recovery", "policy", "diagnostics", ""} {
|
||||
if routerRouteMatches("inspect", routers.Command{Action: action}) {
|
||||
t.Fatal("read endpoint admitted", action)
|
||||
}
|
||||
}
|
||||
if !routerRouteMatches("inspect", read) || routerRouteMatches("control", read) || routerRouteMatches("access", read) {
|
||||
t.Fatal("read route boundary")
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func (p *Pairing) applyRouterCommands(raw json.RawMessage) {
|
||||
if p.Routers == nil || len(raw) > 4096 {
|
||||
if p.Routers == nil || len(raw) > 32768 {
|
||||
return
|
||||
}
|
||||
var commands []routers.Command
|
||||
@@ -33,7 +33,7 @@ func (s *Server) routerRoutes(mux *http.ServeMux) {
|
||||
}
|
||||
json.NewEncoder(w).Encode(s.Pairing.Routers.Snapshot())
|
||||
})
|
||||
submit := func(control bool) http.HandlerFunc {
|
||||
submit := func(kind string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorized(w, r) {
|
||||
return
|
||||
@@ -42,7 +42,7 @@ func (s *Server) routerRoutes(mux *http.ServeMux) {
|
||||
if !decode(w, r, &command) {
|
||||
return
|
||||
}
|
||||
if (control != (command.Action != "")) || s.Pairing == nil || s.Pairing.Routers == nil || s.Pairing.Routers.Submit(command) != nil {
|
||||
if (!routerRouteMatches(kind, command)) || s.Pairing == nil || s.Pairing.Routers == nil || s.Pairing.Routers.Submit(command) != nil {
|
||||
http.Error(w, "Router unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
@@ -51,6 +51,11 @@ func (s *Server) routerRoutes(mux *http.ServeMux) {
|
||||
json.NewEncoder(w).Encode(routers.Result{ID: command.ID, State: "queued"})
|
||||
}
|
||||
}
|
||||
mux.HandleFunc("POST /api/routers/access", submit(false))
|
||||
mux.HandleFunc("POST /api/routers/control", submit(true))
|
||||
mux.HandleFunc("POST /api/routers/access", submit("access"))
|
||||
mux.HandleFunc("POST /api/routers/control", submit("control"))
|
||||
mux.HandleFunc("POST /api/routers/inspect", submit("inspect"))
|
||||
}
|
||||
|
||||
func routerRouteMatches(kind string, command routers.Command) bool {
|
||||
return ((kind != "access") == (command.Action != "")) && ((kind == "inspect") == (command.Query != nil))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
package routers
|
||||
|
||||
// Client API v1 is a separate firmware adapter. It never falls back to HTTP,
|
||||
// shares web-panel credentials, changes host networking or retries a write.
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const clientAPIAdapter = "dexaflow-client-api/v1"
|
||||
const bananaPiModel = "bananapi.bpi-r4-pro"
|
||||
const bananaPiName = "Banana Pi BPI-R4 Pro"
|
||||
const clientAPIResponseLimit = 2 * 1024 * 1024
|
||||
|
||||
var errClientTLS = errors.New("router_certificate_rejected")
|
||||
var apiIdentifier = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,80}$`)
|
||||
var revisionIdentifier = regexp.MustCompile(`^[a-zA-Z0-9_.:-]{1,128}$`)
|
||||
|
||||
// API credentials are private Node configuration, never public telemetry.
|
||||
type clientAPIAccess struct {
|
||||
Token string `json:"token"`
|
||||
CA string `json:"ca"`
|
||||
}
|
||||
|
||||
type clientAPI struct {
|
||||
client *http.Client
|
||||
base, token, identity string
|
||||
check func(context.Context) bool
|
||||
}
|
||||
|
||||
// Each device ships its own CA. Fingerprint DER, not PEM formatting, address,
|
||||
// boot_id, slot or SIM identity. Certificate renewal under that CA preserves ID.
|
||||
func clientAPIRoot(value string) (*x509.CertPool, string, error) {
|
||||
if len(value) > 8192 {
|
||||
return nil, "", errClientTLS
|
||||
}
|
||||
block, rest := pem.Decode([]byte(value))
|
||||
if block == nil || block.Type != "CERTIFICATE" || len(bytes.TrimSpace(rest)) != 0 {
|
||||
return nil, "", errClientTLS
|
||||
}
|
||||
cert, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil || !cert.IsCA || !cert.BasicConstraintsValid {
|
||||
return nil, "", errClientTLS
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
pool.AddCert(cert)
|
||||
sum := sha256.Sum256(cert.Raw)
|
||||
return pool, "router_" + hex.EncodeToString(sum[:12]), nil
|
||||
}
|
||||
|
||||
func newClientAPI(c Candidate, access clientAPIAccess) (*clientAPI, error) {
|
||||
root, id, err := clientAPIRoot(access.CA)
|
||||
ip, local := net.ParseIP(c.Address), net.ParseIP(c.LocalIP)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ip == nil || ip.To4() == nil || !ip.IsPrivate() || local == nil || local.To4() == nil || !local.IsPrivate() || len(access.Token) < 1 || len(access.Token) > 4096 || strings.ContainsAny(access.Token, " \r\n\t") {
|
||||
return nil, errProtocol
|
||||
}
|
||||
check := func(ctx context.Context) bool {
|
||||
if !physical(c.Interface) {
|
||||
return false
|
||||
}
|
||||
source, ok := onLink(c.Interface, c.Address)
|
||||
if !ok || source != c.LocalIP {
|
||||
return false
|
||||
}
|
||||
var routes []route
|
||||
return commandJSON(ctx, []string{"-j", "-4", "route", "get", c.Address}, &routes) && len(routes) == 1 && routes[0].Dev == c.Interface && routes[0].Gateway == ""
|
||||
}
|
||||
transport := &http.Transport{
|
||||
Proxy: nil, DisableKeepAlives: true, DisableCompression: true,
|
||||
MaxResponseHeaderBytes: 16384, TLSHandshakeTimeout: 3 * time.Second,
|
||||
TLSClientConfig: &tls.Config{RootCAs: root, MinVersion: tls.VersionTLS12, ServerName: c.Address},
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if address != net.JoinHostPort(c.Address, "9443") || !check(ctx) {
|
||||
return nil, errLink
|
||||
}
|
||||
return (&net.Dialer{Timeout: 3 * time.Second, LocalAddr: &net.TCPAddr{IP: local}}).DialContext(ctx, network, address)
|
||||
},
|
||||
}
|
||||
return &clientAPI{base: "https://" + c.Address + ":9443/api/client/v1", token: access.Token, identity: id, check: check,
|
||||
client: &http.Client{Timeout: 12 * time.Second, Transport: transport,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return errProtocol }}}, nil
|
||||
}
|
||||
|
||||
// Errors are fixed public codes. Never include response bodies, URLs, tokens or
|
||||
// arbitrary firmware error strings in an operator receipt or log.
|
||||
type clientAPIError struct {
|
||||
Status int
|
||||
Code string
|
||||
}
|
||||
|
||||
func (e *clientAPIError) Error() string { return e.Code }
|
||||
func clientAPIErrorCode(status int) string {
|
||||
switch status {
|
||||
case 401, 403:
|
||||
return "access_rejected"
|
||||
case 409:
|
||||
return "router_conflict"
|
||||
case 410:
|
||||
return "result_expired"
|
||||
case 422, 428:
|
||||
return "command_rejected"
|
||||
case 429:
|
||||
return "router_busy"
|
||||
case 503:
|
||||
return "router_unavailable"
|
||||
default:
|
||||
return "unsupported_response"
|
||||
}
|
||||
}
|
||||
|
||||
func (a *clientAPI) request(ctx context.Context, method, path string, body []byte, headers http.Header) (json.RawMessage, http.Header, error) {
|
||||
if !a.check(ctx) {
|
||||
return nil, nil, errLink
|
||||
}
|
||||
if len(body) > 4096 {
|
||||
return nil, nil, errProtocol
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, a.base+path, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, nil, errProtocol
|
||||
}
|
||||
req.Header = headers.Clone()
|
||||
if req.Header == nil {
|
||||
req.Header = make(http.Header)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+a.token)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
// No GetBody: even a future transport with keep-alive cannot replay writes.
|
||||
req.GetBody = nil
|
||||
response, err := a.client.Do(req)
|
||||
if err != nil {
|
||||
var certificate *tls.CertificateVerificationError
|
||||
if errors.As(err, &certificate) {
|
||||
return nil, nil, errClientTLS
|
||||
}
|
||||
return nil, nil, errors.New("router_unavailable")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusAccepted {
|
||||
return nil, nil, &clientAPIError{response.StatusCode, clientAPIErrorCode(response.StatusCode)}
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(response.Body, clientAPIResponseLimit+1))
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("router_unavailable")
|
||||
}
|
||||
if len(raw) > clientAPIResponseLimit || !json.Valid(raw) {
|
||||
return nil, nil, errProtocol
|
||||
}
|
||||
return json.RawMessage(raw), response.Header.Clone(), nil
|
||||
}
|
||||
|
||||
// Fixed read selectors cover the supplied API, including bounded passive
|
||||
// history. Callers cannot supply URLs, arbitrary paths, probes or shell commands.
|
||||
func clientAPIReadPath(resource, id, after string, limit int) (string, error) {
|
||||
static := map[string]string{"capabilities": "/capabilities", "status": "/status", "policy": "/policy", "modems": "/modems", "events": "/events", "recovery_history": "/recovery/history", "diagnostics_latest": "/diagnostics/latest", "targets": "/targets", "recordings": "/recordings", "schema": "/openapi.json"}
|
||||
path, ok := static[resource]
|
||||
if !ok {
|
||||
if !apiIdentifier.MatchString(id) {
|
||||
return "", errProtocol
|
||||
}
|
||||
switch resource {
|
||||
case "operation":
|
||||
path = "/operations/" + id
|
||||
case "diagnostic":
|
||||
path = "/diagnostics/" + id
|
||||
case "bundle":
|
||||
path = "/diagnostics/" + id + "/bundle"
|
||||
case "recording":
|
||||
path = "/recordings/" + id
|
||||
default:
|
||||
return "", errProtocol
|
||||
}
|
||||
} else if id != "" {
|
||||
return "", errProtocol
|
||||
}
|
||||
if limit != 0 || after != "" {
|
||||
if (resource != "events" && resource != "recovery_history") || limit < 0 || limit > 500 || len(after) > 512 {
|
||||
return "", errProtocol
|
||||
}
|
||||
query := url.Values{}
|
||||
if limit != 0 {
|
||||
query.Set("limit", fmt.Sprint(limit))
|
||||
}
|
||||
if after != "" {
|
||||
query.Set("after", after)
|
||||
}
|
||||
path += "?" + query.Encode()
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
func (a *clientAPI) readResource(ctx context.Context, resource, id, after string, limit int) (json.RawMessage, http.Header, error) {
|
||||
path, err := clientAPIReadPath(resource, id, after, limit)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return a.request(ctx, http.MethodGet, path, nil, nil)
|
||||
}
|
||||
|
||||
type clientPolicy struct {
|
||||
Mode string `json:"mode"`
|
||||
PreferredSIM string `json:"preferred_sim,omitempty"`
|
||||
AllowFallback bool `json:"allow_fallback"`
|
||||
ReturnToPreferred bool `json:"return_to_preferred"`
|
||||
Persist bool `json:"persist"`
|
||||
FailSeconds int `json:"fail_seconds"`
|
||||
RecoverSeconds int `json:"recover_seconds"`
|
||||
MinVPNSeconds int `json:"min_vpn_seconds"`
|
||||
FallbackSIMs []string `json:"fallback_sims,omitempty"`
|
||||
}
|
||||
|
||||
func simSlot(slot string) int {
|
||||
switch slot {
|
||||
case "M1":
|
||||
return 1
|
||||
case "M2":
|
||||
return 2
|
||||
case "M3":
|
||||
return 3
|
||||
}
|
||||
return 0
|
||||
}
|
||||
func (p clientPolicy) valid() bool {
|
||||
if !p.AllowFallback || !p.ReturnToPreferred || !p.Persist || p.FailSeconds < 15 || p.FailSeconds > 300 || p.RecoverSeconds < 30 || p.RecoverSeconds > 600 || p.MinVPNSeconds < 60 || p.MinVPNSeconds > 900 {
|
||||
return false
|
||||
}
|
||||
// Restricted fallback sets are explicitly unsupported by Client API v1.
|
||||
if len(p.FallbackSIMs) != 0 {
|
||||
return false
|
||||
}
|
||||
switch p.Mode {
|
||||
case "direct":
|
||||
return simSlot(p.PreferredSIM) != 0
|
||||
case "vpn", "aggregation", "whitelist":
|
||||
return p.PreferredSIM == ""
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type clientGuard struct {
|
||||
BootID string `json:"expected_boot_id"`
|
||||
DeadlineUptime int64 `json:"deadline_uptime"`
|
||||
}
|
||||
type clientAction struct {
|
||||
clientGuard
|
||||
Policy *clientPolicy `json:"policy,omitempty"`
|
||||
Action string `json:"action,omitempty"`
|
||||
SIM string `json:"sim,omitempty"`
|
||||
}
|
||||
type clientObservation struct {
|
||||
BootID string `json:"boot_id"`
|
||||
Uptime float64 `json:"uptime"`
|
||||
Revision string `json:"revision"`
|
||||
Firmware string `json:"firmware_version"`
|
||||
PersistedPolicy clientPolicy `json:"persisted_policy"`
|
||||
DesiredPolicy clientPolicy `json:"desired_policy"`
|
||||
}
|
||||
type clientEnvelope struct {
|
||||
Method, Path, BootID, Revision, Key string
|
||||
Body []byte
|
||||
Expires time.Time
|
||||
}
|
||||
|
||||
// Prepare binds a command to one fresh boot/revision. Callers persist intent
|
||||
// before send and poll the accepted operation; neither method loops or retries.
|
||||
func prepareClientAction(kind, key string, status clientObservation, action clientAction, now time.Time) (clientEnvelope, error) {
|
||||
if !operationID.MatchString(key) || status.BootID == "" || len(status.BootID) > 128 || !revisionIdentifier.MatchString(status.Revision) || math.IsNaN(status.Uptime) || math.IsInf(status.Uptime, 0) || status.Uptime < 0 || status.Uptime > 1e12 {
|
||||
return clientEnvelope{}, errProtocol
|
||||
}
|
||||
method := http.MethodPost
|
||||
switch kind {
|
||||
case "policy":
|
||||
if action.Policy == nil || !action.Policy.valid() || action.Action != "" || action.SIM != "" {
|
||||
return clientEnvelope{}, errProtocol
|
||||
}
|
||||
method = http.MethodPut
|
||||
case "recovery":
|
||||
if action.Policy != nil {
|
||||
return clientEnvelope{}, errProtocol
|
||||
}
|
||||
switch action.Action {
|
||||
case "wan_reconnect":
|
||||
if simSlot(action.SIM) == 0 {
|
||||
return clientEnvelope{}, errProtocol
|
||||
}
|
||||
case "vpn_reconnect", "dns_restart":
|
||||
if action.SIM != "" {
|
||||
return clientEnvelope{}, errProtocol
|
||||
}
|
||||
default:
|
||||
return clientEnvelope{}, errProtocol
|
||||
}
|
||||
case "reboot", "diagnostics":
|
||||
if action.Policy != nil || action.Action != "" || action.SIM != "" {
|
||||
return clientEnvelope{}, errProtocol
|
||||
}
|
||||
default:
|
||||
return clientEnvelope{}, errProtocol
|
||||
}
|
||||
action.clientGuard = clientGuard{status.BootID, int64(status.Uptime) + 90}
|
||||
body, err := json.Marshal(action)
|
||||
if err != nil || len(body) > 4096 {
|
||||
return clientEnvelope{}, errProtocol
|
||||
}
|
||||
return clientEnvelope{method, "/" + kind, status.BootID, status.Revision, key, body, now.Add(85 * time.Second)}, nil
|
||||
}
|
||||
func (a *clientAPI) sendAction(ctx context.Context, e clientEnvelope) (json.RawMessage, error) {
|
||||
if !time.Now().Before(e.Expires) {
|
||||
return nil, errors.New("expired")
|
||||
}
|
||||
if !operationID.MatchString(e.Key) || !revisionIdentifier.MatchString(e.Revision) || !((e.Method == http.MethodPut && e.Path == "/policy") || (e.Method == http.MethodPost && (e.Path == "/recovery" || e.Path == "/reboot" || e.Path == "/diagnostics"))) {
|
||||
return nil, errProtocol
|
||||
}
|
||||
headers := http.Header{"Idempotency-Key": {e.Key}}
|
||||
if e.Path != "/diagnostics" {
|
||||
headers.Set("If-Match", `"`+e.Revision+`"`)
|
||||
}
|
||||
raw, _, err := a.request(ctx, e.Method, e.Path, e.Body, headers)
|
||||
return raw, err
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
type clientVerification struct {
|
||||
Command Command
|
||||
OperationID string
|
||||
Until time.Time
|
||||
}
|
||||
|
||||
func (c *Collector) applyClientControl(ctx context.Context, cmd Command, r record) {
|
||||
reason := "router_unavailable"
|
||||
sent := false
|
||||
defer func() {
|
||||
if !sent {
|
||||
c.setControlResult(cmd, "error", reason)
|
||||
}
|
||||
}()
|
||||
if !slices.Contains([]string{"policy", "recovery", "reboot", "diagnostics"}, cmd.Action) || r.Device.ClientAPI == nil || !slices.Contains(r.Device.ClientAPI.Rights, cmd.Action) {
|
||||
reason = "command_rejected"
|
||||
return
|
||||
}
|
||||
for _, candidate := range c.candidates(ctx) {
|
||||
if candidate.Address != r.Device.Address || candidate.Interface != r.Device.Interface {
|
||||
continue
|
||||
}
|
||||
a, err := c.apiClient(candidate, *r.Access.ClientAPI)
|
||||
if err != nil || a.identity != cmd.DeviceID {
|
||||
return
|
||||
}
|
||||
raw, _, err := a.readResource(ctx, "status", "", "", 0)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var status clientObservation
|
||||
if json.Unmarshal(raw, &status) != nil {
|
||||
reason = "unsupported_response"
|
||||
return
|
||||
}
|
||||
if status.BootID != cmd.ExpectedBootID || status.Revision != cmd.ExpectedRevision {
|
||||
reason = "router_conflict"
|
||||
return
|
||||
}
|
||||
envelope, err := prepareClientAction(cmd.Action, cmd.ID, status, clientAction{Policy: cmd.Policy, Action: cmd.Recovery, SIM: cmd.SIM}, time.Now())
|
||||
if err != nil {
|
||||
reason = "command_rejected"
|
||||
return
|
||||
}
|
||||
c.event(cmd.DeviceID, "command_requested", 0, cmd.Action, cmd.Mode)
|
||||
c.persist()
|
||||
if c.storageError {
|
||||
reason = "storage_error"
|
||||
return
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
reason = "expired"
|
||||
return
|
||||
}
|
||||
sent = true
|
||||
raw, err = a.sendAction(ctx, envelope)
|
||||
if err != nil {
|
||||
var rejected *clientAPIError
|
||||
if errors.As(err, &rejected) {
|
||||
c.setControlResult(cmd, "error", rejected.Code)
|
||||
c.event(cmd.DeviceID, "command_failed", 0, cmd.Action, rejected.Code)
|
||||
} else {
|
||||
c.setControlResult(cmd, "unknown", "confirmation_timeout")
|
||||
c.event(cmd.DeviceID, "command_unconfirmed", 0, cmd.Action, "")
|
||||
}
|
||||
c.persist()
|
||||
return
|
||||
}
|
||||
var accepted struct {
|
||||
ID string `json:"operation_id"`
|
||||
State string `json:"state"`
|
||||
Kind string `json:"kind"`
|
||||
}
|
||||
if json.Unmarshal(raw, &accepted) != nil || !apiIdentifier.MatchString(accepted.ID) || accepted.Kind != cmd.Action {
|
||||
c.setControlResult(cmd, "unknown", "confirmation_timeout")
|
||||
c.event(cmd.DeviceID, "command_unconfirmed", 0, cmd.Action, "")
|
||||
c.persist()
|
||||
return
|
||||
}
|
||||
c.clientControl = &clientVerification{cmd, accepted.ID, time.Now().Add(180 * time.Second)}
|
||||
c.setControlResult(cmd, "applying", "")
|
||||
return
|
||||
}
|
||||
}
|
||||
func (c *Collector) verifyClientControl(ctx context.Context, candidates []Candidate) {
|
||||
pending := c.clientControl
|
||||
if pending == nil {
|
||||
return
|
||||
}
|
||||
finish := func(state, reason, code string) {
|
||||
c.setControlResult(pending.Command, state, reason)
|
||||
c.mu.Lock()
|
||||
result := c.results[pending.Command.ID]
|
||||
result.VendorID = pending.OperationID
|
||||
c.results[pending.Command.ID] = result
|
||||
c.mu.Unlock()
|
||||
c.event(pending.Command.DeviceID, code, 0, pending.Command.Action, "")
|
||||
c.clientControl = nil
|
||||
}
|
||||
if !time.Now().Before(pending.Until) {
|
||||
finish("unknown", "confirmation_timeout", "command_unconfirmed")
|
||||
return
|
||||
}
|
||||
r, ok := c.state.Records[pending.Command.DeviceID]
|
||||
if !ok || r.Access == nil || r.Access.ClientAPI == nil || r.Device.State != "ready" {
|
||||
return
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
if candidate.Address != r.Device.Address || candidate.Interface != r.Device.Interface {
|
||||
continue
|
||||
}
|
||||
a, err := c.apiClient(candidate, *r.Access.ClientAPI)
|
||||
if err != nil || a.identity != pending.Command.DeviceID {
|
||||
return
|
||||
}
|
||||
raw, _, err := a.readResource(ctx, "operation", pending.OperationID, "", 0)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var op struct {
|
||||
ID string `json:"operation_id"`
|
||||
State string `json:"state"`
|
||||
Kind string `json:"kind"`
|
||||
Result struct {
|
||||
Persisted *bool `json:"persisted"`
|
||||
Applied *bool `json:"applied"`
|
||||
} `json:"result"`
|
||||
}
|
||||
if json.Unmarshal(raw, &op) != nil || op.ID != pending.OperationID || op.Kind != pending.Command.Action {
|
||||
return
|
||||
}
|
||||
switch op.State {
|
||||
case "succeeded":
|
||||
if op.Kind == "policy" {
|
||||
if op.Result.Persisted == nil || !*op.Result.Persisted || op.Result.Applied == nil || !*op.Result.Applied || r.Device.ClientAPI == nil || !sameClientPolicy(r.Device.ClientAPI.Policy, *pending.Command.Policy) {
|
||||
return
|
||||
}
|
||||
}
|
||||
finish("complete", "", "command_complete")
|
||||
case "failed":
|
||||
finish("error", "command_rejected", "command_failed")
|
||||
case "interrupted", "unknown":
|
||||
finish("unknown", "confirmation_timeout", "command_unconfirmed")
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func sameClientPolicy(a, b clientPolicy) bool {
|
||||
x, _ := json.Marshal(a)
|
||||
y, _ := json.Marshal(b)
|
||||
return string(x) == string(y)
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package routers
|
||||
|
||||
type clientVPN struct {
|
||||
Selected *bool `json:"selected"`
|
||||
Active *bool `json:"active"`
|
||||
Verified *bool `json:"verified"`
|
||||
SIM string `json:"sim"`
|
||||
Server string `json:"server"`
|
||||
WatchState string `json:"watch_state"`
|
||||
WatchAge *float64 `json:"watch_age"`
|
||||
ProofAge *float64 `json:"proof_age"`
|
||||
LastSuccessAge *float64 `json:"last_success_age"`
|
||||
}
|
||||
type reservePair struct {
|
||||
SIM string `json:"sim"`
|
||||
Server string `json:"server"`
|
||||
Transport string `json:"transport"`
|
||||
Age *float64 `json:"age"`
|
||||
}
|
||||
type clientReserve struct {
|
||||
Available *bool `json:"available"`
|
||||
Running *bool `json:"running"`
|
||||
Count *float64 `json:"count"`
|
||||
Target *float64 `json:"target"`
|
||||
DistinctSIMs *float64 `json:"distinct_sims"`
|
||||
Age *float64 `json:"age"`
|
||||
TTL *float64 `json:"ttl"`
|
||||
Phase string `json:"phase"`
|
||||
Pairs []reservePair `json:"pairs"`
|
||||
}
|
||||
type clientDetails struct {
|
||||
VPN clientVPN `json:"vpn"`
|
||||
Reserve clientReserve `json:"reserve"`
|
||||
Pending *bool `json:"pending"`
|
||||
Fallback *bool `json:"fallback"`
|
||||
FallbackReason string `json:"fallback_reason"`
|
||||
RecoveryAge *float64 `json:"recovery_age"`
|
||||
LastAttemptCurrent *bool `json:"last_attempt_current"`
|
||||
}
|
||||
|
||||
func readClientDetails(status map[string]any) *clientDetails {
|
||||
vpn, reserve, recovery := object(status["vpn"]), object(status["reserve"]), object(status["recovery"])
|
||||
d := &clientDetails{VPN: clientVPN{Selected: boolValue(vpn["selected"]), Active: boolValue(vpn["active"]), Verified: boolValue(vpn["verified"]), SIM: text(vpn["sim"]), Server: text(vpn["server_reference"]), WatchState: text(vpn["watch_state"]), WatchAge: number(vpn["watch_age_s"], 0, 1e12), ProofAge: number(vpn["proof_age_s"], 0, 1e12), LastSuccessAge: number(vpn["last_success_age_s"], 0, 1e12)}, Reserve: clientReserve{Available: boolValue(reserve["available"]), Running: boolValue(reserve["running"]), Count: number(reserve["count"], 0, 1000), Target: number(reserve["target"], 0, 1000), DistinctSIMs: number(reserve["distinct_sim_count"], 0, 3), Age: number(reserve["state_age_s"], 0, 1e12), TTL: number(reserve["fresh_seconds"], 0, 1e12), Phase: text(reserve["phase"]), Pairs: []reservePair{}}, Pending: boolValue(recovery["pending"]), Fallback: boolValue(status["fallback_active"]), FallbackReason: text(status["fallback_reason"]), RecoveryAge: number(recovery["state_age_s"], 0, 1e12), LastAttemptCurrent: boolValue(object(recovery["last_attempt"])["matches_current_policy_epoch"])}
|
||||
pairs, _ := reserve["pairs"].([]any)
|
||||
for _, raw := range pairs[:min(len(pairs), 12)] {
|
||||
p := object(raw)
|
||||
d.Reserve.Pairs = append(d.Reserve.Pairs, reservePair{SIM: text(p["sim"]), Server: text(p["server_reference"]), Transport: text(p["transport"]), Age: number(p["age_s"], 0, 1e12)})
|
||||
}
|
||||
return d
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
type clientWAN struct {
|
||||
Slot int `json:"slot"`
|
||||
WAN string `json:"wan"`
|
||||
Interface string `json:"interface"`
|
||||
Up *bool `json:"up"`
|
||||
SIMPresent *bool `json:"sim_present"`
|
||||
ModemPresent *bool `json:"modem_present"`
|
||||
Registration string `json:"registration"`
|
||||
FailureReason string `json:"failure_reason"`
|
||||
Fresh *bool `json:"fresh"`
|
||||
AgeSeconds *float64 `json:"age_seconds"`
|
||||
Traffic *wanTraffic `json:"traffic"`
|
||||
ObservedUptime *float64 `json:"observed_uptime"`
|
||||
SessionUptime *float64 `json:"session_uptime"`
|
||||
}
|
||||
type clientCheck struct {
|
||||
ID string `json:"id"`
|
||||
State string `json:"state"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
type clientPublic struct {
|
||||
Details *clientDetails `json:"details,omitempty"`
|
||||
ModuleVersion string `json:"module_version"`
|
||||
SchemaVersion string `json:"schema_version"`
|
||||
ClockQuality string `json:"clock_quality"`
|
||||
BootID string `json:"boot_id"`
|
||||
Revision string `json:"revision"`
|
||||
Rights []string `json:"rights"`
|
||||
Policy clientPolicy `json:"policy"`
|
||||
WAN []clientWAN `json:"wan"`
|
||||
RecoveryPhase string `json:"recovery_phase"`
|
||||
RecoveryReason string `json:"recovery_reason"`
|
||||
Checks []clientCheck `json:"checks"`
|
||||
}
|
||||
|
||||
func object(value any) map[string]any { m, _ := value.(map[string]any); return m }
|
||||
func boolValue(value any) *bool {
|
||||
v, ok := value.(bool)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
return &v
|
||||
}
|
||||
func (a *clientAPI) readDevice(ctx context.Context) (Device, error) {
|
||||
caps, _, err := a.readResource(ctx, "capabilities", "", "", 0)
|
||||
if err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
status, _, err := a.readResource(ctx, "status", "", "", 0)
|
||||
if err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
d, err := normalizeClientAPI(caps, status)
|
||||
if err != nil {
|
||||
return Device{}, err
|
||||
}
|
||||
if raw, _, e := a.readResource(ctx, "diagnostics_latest", "", "", 0); e == nil {
|
||||
var report map[string]any
|
||||
if json.Unmarshal(raw, &report) == nil {
|
||||
checks, _ := object(report["report"])["checks"].([]any)
|
||||
for i, v := range checks {
|
||||
if i >= 32 {
|
||||
break
|
||||
}
|
||||
check := object(v)
|
||||
state := text(check["state"])
|
||||
if slices.Contains([]string{"ok", "error", "warn", "unknown", "na"}, state) {
|
||||
d.ClientAPI.Checks = append(d.ClientAPI.Checks, clientCheck{ID: text(check["id"]), State: state, Code: text(check["code"])})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
func normalizeClientAPI(capsRaw, statusRaw []byte) (Device, error) {
|
||||
var caps, status map[string]any
|
||||
if json.Unmarshal(capsRaw, &caps) != nil || json.Unmarshal(statusRaw, &status) != nil || caps["api_version"] != "1" || caps["schema_version"] != "1.1" {
|
||||
return Device{}, errProtocol
|
||||
}
|
||||
var observation clientObservation
|
||||
if json.Unmarshal(statusRaw, &observation) != nil || observation.BootID == "" || len(observation.BootID) > 128 || !revisionIdentifier.MatchString(observation.Revision) {
|
||||
return Device{}, errProtocol
|
||||
}
|
||||
uptime := number(status["uptime"], 0, 1e12)
|
||||
if uptime == nil {
|
||||
return Device{}, errProtocol
|
||||
}
|
||||
detail := &clientPublic{Details: readClientDetails(status), ModuleVersion: text(caps["module_version"]), SchemaVersion: "1.1", ClockQuality: text(status["clock_quality"]), BootID: observation.BootID, Revision: observation.Revision, Policy: observation.PersistedPolicy, Rights: []string{}, WAN: []clientWAN{}, Checks: []clientCheck{}}
|
||||
if rights, ok := caps["rights"].([]any); ok {
|
||||
for _, right := range rights {
|
||||
if v, ok := right.(string); ok && slices.Contains([]string{"read", "policy", "recovery", "reboot", "diagnostics", "bundle"}, v) && !slices.Contains(detail.Rights, v) {
|
||||
detail.Rights = append(detail.Rights, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !slices.Contains(detail.Rights, "read") {
|
||||
return Device{}, errAccess
|
||||
}
|
||||
d := Device{Family: "DexaFlow", Identity: "device_ca", Adapter: clientAPIAdapter, State: "ready", Firmware: text(status["firmware_version"]), Uptime: uptime, Internet: "unknown", Modems: []Modem{}, ActiveSlots: []int{}, ClientAPI: detail, SelectedMode: observation.DesiredPolicy.Mode, PersistedMode: observation.PersistedPolicy.Mode}
|
||||
observed := object(status["observed"])
|
||||
if observed == nil {
|
||||
return Device{}, errProtocol
|
||||
}
|
||||
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"
|
||||
}
|
||||
vpn := object(status["vpn"])
|
||||
d.VPSUp = boolValue(vpn["verified"])
|
||||
recovery := object(status["recovery"])
|
||||
detail.RecoveryPhase = text(recovery["phase"])
|
||||
detail.RecoveryReason = text(recovery["reason_code"])
|
||||
wan, ok := status["wan"].([]any)
|
||||
if !ok || len(wan) > 3 {
|
||||
return Device{}, errProtocol
|
||||
}
|
||||
bySlot := map[int]map[string]any{}
|
||||
for _, v := range wan {
|
||||
w := object(v)
|
||||
slot := simSlot(text(w["slot"]))
|
||||
if slot == 0 || bySlot[slot] != nil {
|
||||
return Device{}, errProtocol
|
||||
}
|
||||
bySlot[slot] = w
|
||||
registration := object(w["network_registration"])
|
||||
failure := text(registration["failure_reason"])
|
||||
if failure == "" {
|
||||
if failures, ok := w["errors"].([]any); ok && len(failures) > 0 {
|
||||
failure = text(object(failures[0])["code"])
|
||||
}
|
||||
}
|
||||
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 {
|
||||
d.Internet = "verified"
|
||||
}
|
||||
// A slot being up does not prove it participates in aggregation. Only a
|
||||
// firmware-declared effective WAN establishes the direct active slot.
|
||||
if d.ActiveMode == "direct" && d.ActiveWAN != "" && (d.ActiveWAN == w["wan"] || d.ActiveWAN == w["slot"]) && w["up"] == true {
|
||||
d.ActiveSlots = append(d.ActiveSlots, slot)
|
||||
}
|
||||
}
|
||||
modems, ok := status["modems"].([]any)
|
||||
if !ok || len(modems) > 3 {
|
||||
return Device{}, errProtocol
|
||||
}
|
||||
seen := map[int]bool{}
|
||||
for _, v := range modems {
|
||||
m := object(v)
|
||||
slot := simSlot(text(m["slot"]))
|
||||
if slot == 0 || seen[slot] || bySlot[slot] == nil {
|
||||
return Device{}, errProtocol
|
||||
}
|
||||
seen[slot] = true
|
||||
w := bySlot[slot]
|
||||
radio := object(m["radio"])
|
||||
registration := object(m["network_registration"])
|
||||
modem := Modem{RadioAge: number(radio["age_s"], 0, 1e12), EARFCN: number(radio["earfcn"], 0, 1e7), TAC: text(radio["tac"]), Slot: slot, Operator: text(m["operator"]), Radio: text(m["modem_state"]), Technology: text(radio["technology"]), Band: text(radio["band"]), CellID: text(radio["cell_id"]), Bandwidth: number(radio["bandwidth_mhz"], 0, 1000), RSRP: number(radio["rsrp_dbm"], -160, -20), RSRQ: number(radio["rsrq_db"], -50, 20), SINR: number(radio["sinr_db"], -40, 60), RSSI: number(radio["rssi_dbm"], -160, 0), PCI: number(radio["pci"], 0, 1007)}
|
||||
if ip := net.ParseIP(text(m["ipv4"])); ip != nil {
|
||||
modem.IP = ip.String()
|
||||
}
|
||||
if w["up"] == true {
|
||||
modem.Connectivity = "online"
|
||||
} else if w["up"] == false {
|
||||
modem.Connectivity = "offline"
|
||||
}
|
||||
if registration["failure_reason"] == "sim-missing" || m["sim_present"] == false {
|
||||
modem.Radio = "NOSIM"
|
||||
}
|
||||
// A numeric zero is a measurement. Missing/invalid values remain null.
|
||||
d.Modems = append(d.Modems, modem)
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func (c *Collector) pollClientAPI(ctx context.Context, candidates []Candidate, seen map[string]bool) map[string]bool {
|
||||
handled := map[string]bool{}
|
||||
for id, r := range c.state.Records {
|
||||
if r.Access == nil || r.Access.ClientAPI == nil {
|
||||
continue
|
||||
}
|
||||
for _, candidate := range candidates {
|
||||
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()
|
||||
c.state.Records[id] = r
|
||||
break
|
||||
}
|
||||
}
|
||||
if r.Rejected {
|
||||
continue
|
||||
}
|
||||
// TLS identity, not MAC or address, authorizes this instance after pairing.
|
||||
a, err := c.apiClient(candidate, *r.Access.ClientAPI)
|
||||
if err != nil || a.identity != id {
|
||||
continue
|
||||
}
|
||||
d, err := a.readDevice(ctx)
|
||||
var apiErr *clientAPIError
|
||||
if err != nil && !(errors.As(err, &apiErr) && (apiErr.Status == 401 || apiErr.Status == 403)) {
|
||||
if seen[id] {
|
||||
r.Device.State = "unreachable"
|
||||
c.state.Records[id] = r
|
||||
}
|
||||
delete(c.traffic, id)
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
handled[candidate.Address] = true
|
||||
old := r.Device
|
||||
if old.Address != candidate.Address || old.Interface != candidate.Interface {
|
||||
delete(c.clients, id)
|
||||
}
|
||||
if err != nil {
|
||||
r.Device.State = "access_rejected"
|
||||
r.Rejected = true
|
||||
r.Device.ObservedAt = time.Now().Unix()
|
||||
} else {
|
||||
d.ID = id
|
||||
d.Address = candidate.Address
|
||||
d.Interface = candidate.Interface
|
||||
d.LocalIP = candidate.LocalIP
|
||||
d.ObservedAt = time.Now().Unix()
|
||||
d.BoardID, d.ModelName, d.ModelID, d.SlotMap = old.BoardID, old.ModelName, old.ModelID, old.SlotMap
|
||||
r.Device = d
|
||||
r.MAC = c.neighbor(candidate.Interface, candidate.Address)
|
||||
r.Rejected = false
|
||||
}
|
||||
if err == nil {
|
||||
c.enrichPanel(ctx, candidate, &r)
|
||||
c.rates(&r.Device)
|
||||
}
|
||||
c.decorate(&r, candidate)
|
||||
c.transitions(old, r.Device)
|
||||
c.state.Records[id] = r
|
||||
break
|
||||
}
|
||||
}
|
||||
return handled
|
||||
}
|
||||
func (c *Collector) authorizeClientAPI(ctx context.Context, cmd Command, r record) Result {
|
||||
result := Result{ID: cmd.ID, DeviceID: cmd.DeviceID, State: "error", Error: "router_unavailable"}
|
||||
for _, candidate := range c.candidates(ctx) {
|
||||
if candidate.Address != r.Device.Address || candidate.Interface != r.Device.Interface {
|
||||
continue
|
||||
}
|
||||
a, err := c.apiClient(candidate, *cmd.ClientAPI)
|
||||
if err != nil {
|
||||
result.Error = "unsupported_response"
|
||||
return result
|
||||
}
|
||||
d, err := a.readDevice(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, errClientTLS) {
|
||||
result.Error = "router_certificate_rejected"
|
||||
} else {
|
||||
result.Error = "access_rejected"
|
||||
}
|
||||
return result
|
||||
}
|
||||
if existing, ok := c.state.Records[a.identity]; ok && a.identity != cmd.DeviceID && existing.Access != nil {
|
||||
result.Error = "command_rejected"
|
||||
return result
|
||||
}
|
||||
d.ID = a.identity
|
||||
d.Address = candidate.Address
|
||||
d.Interface = candidate.Interface
|
||||
d.LocalIP = candidate.LocalIP
|
||||
d.ObservedAt = time.Now().Unix()
|
||||
oldEvents := append([]Event{}, c.state.Events...)
|
||||
oldSequence, oldDropped := c.state.Sequence, c.state.Dropped
|
||||
delete(c.state.Records, cmd.DeviceID)
|
||||
d.BoardID, d.ModelName, d.ModelID, d.SlotMap = r.Device.BoardID, r.Device.ModelName, r.Device.ModelID, r.Device.SlotMap
|
||||
next := record{Device: d, MAC: c.neighbor(candidate.Interface, candidate.Address), Access: &credential{ClientAPI: cmd.ClientAPI}, Name: r.Name, WebAccess: r.WebAccess}
|
||||
if next.WebAccess == nil && r.Access != nil && r.Access.Username != "" {
|
||||
next.WebAccess = r.Access
|
||||
}
|
||||
c.decorate(&next, candidate)
|
||||
c.state.Records[d.ID] = next
|
||||
// Keep the provisional discovery history attached to the enrolled instance.
|
||||
for i := range c.state.Events {
|
||||
if c.state.Events[i].DeviceID == cmd.DeviceID {
|
||||
c.state.Events[i].DeviceID = d.ID
|
||||
}
|
||||
}
|
||||
c.event(d.ID, "access_granted", 0, "", "")
|
||||
c.persist()
|
||||
if c.storageError {
|
||||
delete(c.state.Records, d.ID)
|
||||
c.state.Records[cmd.DeviceID] = r
|
||||
c.state.Events = oldEvents
|
||||
c.state.Sequence, c.state.Dropped = oldSequence, oldDropped
|
||||
result.Error = "storage_error"
|
||||
return result
|
||||
}
|
||||
delete(c.clients, cmd.DeviceID)
|
||||
result.DeviceID = d.ID
|
||||
result.State = "complete"
|
||||
result.Error = ""
|
||||
return result
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func clientAPIFixture(t *testing.T, handler http.HandlerFunc) (*clientAPI, string) {
|
||||
t.Helper()
|
||||
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
cert := &x509.Certificate{SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, IPAddresses: []net.IP{net.ParseIP("192.168.1.1")}}
|
||||
der, err := x509.CreateCertificate(rand.Reader, cert, cert, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ca := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}))
|
||||
server := httptest.NewUnstartedServer(handler)
|
||||
server.Config.ErrorLog = log.New(io.Discard, "", 0)
|
||||
server.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}}
|
||||
server.StartTLS()
|
||||
t.Cleanup(server.Close)
|
||||
a, err := newClientAPI(Candidate{Address: "192.168.1.1", LocalIP: "192.168.1.2", Interface: "test-lan"}, clientAPIAccess{Token: "synthetic-private-key", CA: ca})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Only the physical socket is substituted. Actual TLS verification and the
|
||||
// adapter's HTTP policy remain exercised against a real TLS server.
|
||||
a.check = func(context.Context) bool { return true }
|
||||
a.client.Transport.(*http.Transport).DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
return (&net.Dialer{}).DialContext(ctx, network, server.Listener.Addr().String())
|
||||
}
|
||||
return a, ca
|
||||
}
|
||||
|
||||
func TestClientAPITrustBeforeBearerAndNoRedirect(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
a, ca := clientAPIFixture(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
if r.Header.Get("Authorization") != "Bearer synthetic-private-key" {
|
||||
t.Error("missing bearer")
|
||||
}
|
||||
http.Redirect(w, r, "https://example.invalid/steal", http.StatusTemporaryRedirect)
|
||||
})
|
||||
_, id1, e := clientAPIRoot(ca)
|
||||
_, id2, e2 := clientAPIRoot("\n" + ca + "\n")
|
||||
if e != nil || e2 != nil || id1 != id2 {
|
||||
t.Fatal("PEM whitespace changed identity")
|
||||
}
|
||||
if _, _, e := clientAPIRoot(ca + ca); e == nil {
|
||||
t.Fatal("multiple trust roots admitted")
|
||||
}
|
||||
transport := a.client.Transport.(*http.Transport)
|
||||
roots := transport.TLSClientConfig.RootCAs
|
||||
transport.TLSClientConfig.RootCAs = x509.NewCertPool()
|
||||
_, _, e = a.readResource(context.Background(), "status", "", "", 0)
|
||||
if !errors.Is(e, errClientTLS) || calls.Load() != 0 {
|
||||
t.Fatal("untrusted server received bearer", e, calls.Load())
|
||||
}
|
||||
transport.TLSClientConfig.RootCAs = roots
|
||||
transport.TLSClientConfig.ServerName = "192.168.1.3"
|
||||
_, _, e = a.readResource(context.Background(), "status", "", "", 0)
|
||||
if !errors.Is(e, errClientTLS) || calls.Load() != 0 {
|
||||
t.Fatal("wrong IP certificate admitted")
|
||||
}
|
||||
transport.TLSClientConfig.ServerName = "192.168.1.1"
|
||||
_, _, e = a.readResource(context.Background(), "status", "", "", 0)
|
||||
if e == nil || calls.Load() != 1 {
|
||||
t.Fatal("redirect accepted", e, calls.Load())
|
||||
}
|
||||
a.check = func(context.Context) bool { return false }
|
||||
_, _, e = a.readResource(context.Background(), "status", "", "", 0)
|
||||
if !errors.Is(e, errLink) || calls.Load() != 1 {
|
||||
t.Fatal("link guard bypassed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientAPIReadSelectorsAndBounds(t *testing.T) {
|
||||
for _, v := range []struct {
|
||||
resource, id, after string
|
||||
limit int
|
||||
}{
|
||||
{"https://example.invalid", "", "", 0}, {"operation", "../status", "", 0},
|
||||
{"status", "", "cursor", 1}, {"status", "id", "", 0}, {"events", "", "", 501},
|
||||
{"events", "", "", -1},
|
||||
} {
|
||||
if _, e := clientAPIReadPath(v.resource, v.id, v.after, v.limit); e == nil {
|
||||
t.Fatal("invalid read admitted", v)
|
||||
}
|
||||
}
|
||||
path, e := clientAPIReadPath("events", "", "abc&after=other", 100)
|
||||
if e != nil || path != "/events?after=abc%26after%3Dother&limit=100" {
|
||||
t.Fatal(path, e)
|
||||
}
|
||||
a, _ := clientAPIFixture(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/client/v1/status" {
|
||||
io.WriteString(w, `{"padding":"`+strings.Repeat("x", clientAPIResponseLimit)+`"}`)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(403)
|
||||
io.WriteString(w, `{"secret":"do-not-echo-this"}`)
|
||||
})
|
||||
if _, _, e := a.readResource(context.Background(), "status", "", "", 0); !errors.Is(e, errProtocol) {
|
||||
t.Fatal("unbounded response accepted", e)
|
||||
}
|
||||
if _, _, e := a.readResource(context.Background(), "policy", "", "", 0); e == nil || e.Error() != "access_rejected" {
|
||||
t.Fatal("private error escaped", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientAPIBootRevisionAndExactlyOneWrite(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
a, _ := clientAPIFixture(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
if r.Method != "PUT" || r.URL.Path != "/api/client/v1/policy" || r.Header.Get("If-Match") != `"revision-1"` || r.Header.Get("Idempotency-Key") != "op_0123456789abcdef0123456789abcdef" {
|
||||
t.Error("wrong command envelope")
|
||||
}
|
||||
var body clientAction
|
||||
if json.NewDecoder(r.Body).Decode(&body) != nil || body.BootID != "boot-1" || body.DeadlineUptime != 190 || body.Policy.PreferredSIM != "M3" {
|
||||
t.Error("boot/deadline/SIM changed")
|
||||
}
|
||||
// Ambiguous network failure after reading the write must not replay it.
|
||||
conn, _, err := w.(http.Hijacker).Hijack()
|
||||
if err == nil {
|
||||
conn.Close()
|
||||
}
|
||||
})
|
||||
status := clientObservation{BootID: "boot-1", Revision: "revision-1", Uptime: 100.5}
|
||||
policy := clientPolicy{Mode: "direct", PreferredSIM: "M3", AllowFallback: true, ReturnToPreferred: true, Persist: true, FailSeconds: 60, RecoverSeconds: 60, MinVPNSeconds: 120}
|
||||
key := "op_0123456789abcdef0123456789abcdef"
|
||||
envelope, e := prepareClientAction("policy", key, status, clientAction{Policy: &policy}, time.Now())
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = a.sendAction(context.Background(), envelope); e == nil || calls.Load() != 1 {
|
||||
t.Fatal("write was replayed or loss reported complete", e, calls.Load())
|
||||
}
|
||||
envelope.Expires = time.Now().Add(-time.Second)
|
||||
if _, e = a.sendAction(context.Background(), envelope); e == nil || calls.Load() != 1 {
|
||||
t.Fatal("expired write sent")
|
||||
}
|
||||
policy.AllowFallback = false
|
||||
if _, e = prepareClientAction("policy", key, status, clientAction{Policy: &policy}, time.Now()); e == nil {
|
||||
t.Fatal("unsupported strict-SIM policy admitted")
|
||||
}
|
||||
policy.AllowFallback = true
|
||||
policy.Mode = "aggregation"
|
||||
if policy.valid() {
|
||||
t.Fatal("direct preference leaked into aggregation")
|
||||
}
|
||||
policy.PreferredSIM = ""
|
||||
if !policy.valid() {
|
||||
t.Fatal("documented aggregation rejected")
|
||||
}
|
||||
policy.FallbackSIMs = []string{"M1"}
|
||||
if policy.valid() {
|
||||
t.Fatal("unsupported restricted fallback admitted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientAPISlotsNullsAndProjection(t *testing.T) {
|
||||
caps := []byte(`{"api_version":"1","schema_version":"1.1","module_version":"synthetic","rights":["read","policy"]}`)
|
||||
status := []byte(`{"boot_id":"test-boot","uptime":100,"revision":"r1","firmware_version":"test","clock_quality":"unverified","persisted_policy":{"mode":"direct","preferred_sim":"M3","allow_fallback":true,"return_to_preferred":true,"persist":true,"fail_seconds":60,"recover_seconds":60,"min_vpn_seconds":120},"desired_policy":{"mode":"direct"},"observed":{"active":"direct","stale":false},"effective_wan":"wwan","wan":[{"slot":"M3","wan":"wwan","up":true,"sim_present":null,"network_registration":{"registration_state":"home","fresh":true,"age_s":0}}],"modems":[{"slot":"M3","wan":"wwan","modem_state":"connected","operator":"Test Carrier","ipv4":"10.1.2.3","sim_present":null,"radio":{"rsrp_dbm":null,"sinr_db":0,"rssi_dbm":null}}],"token":"must-not-escape","imei":"must-not-escape"}`)
|
||||
d, e := normalizeClientAPI(caps, status)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if d.ActiveWAN != "wwan" || len(d.ActiveSlots) != 1 || d.ActiveSlots[0] != 3 || d.Modems[0].Slot != 3 {
|
||||
t.Fatal("M3 wrongly treated as WAN3", d)
|
||||
}
|
||||
if d.Modems[0].RSRP != nil || d.Modems[0].SINR == nil || *d.Modems[0].SINR != 0 || d.ClientAPI.WAN[0].SIMPresent != nil {
|
||||
t.Fatal("unknown converted to zero or false")
|
||||
}
|
||||
raw, _ := json.Marshal(d)
|
||||
if strings.Contains(string(raw), "must-not-escape") || strings.Contains(string(raw), "imei") || strings.Contains(string(raw), "token") {
|
||||
t.Fatal("private vendor fields escaped")
|
||||
}
|
||||
if d.Internet != "unknown" {
|
||||
t.Fatal("WAN link mistaken for internet proof")
|
||||
}
|
||||
var bad map[string]any
|
||||
json.Unmarshal(status, &bad)
|
||||
bad["modems"] = append(bad["modems"].([]any), bad["modems"].([]any)[0])
|
||||
raw, _ = json.Marshal(bad)
|
||||
if _, e = normalizeClientAPI(caps, raw); e == nil {
|
||||
t.Fatal("duplicate slot accepted")
|
||||
}
|
||||
if _, e = normalizeClientAPI([]byte(`{"api_version":"2","schema_version":"1.1"}`), status); e == nil {
|
||||
t.Fatal("unknown API version accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientAPIEnrollmentSurvivesLANAndSIMChanges(t *testing.T) {
|
||||
status := `{"boot_id":"boot-a","uptime":20,"revision":"r1","persisted_policy":{"mode":"aggregation","allow_fallback":true,"return_to_preferred":true,"persist":true,"fail_seconds":60,"recover_seconds":60,"min_vpn_seconds":120},"desired_policy":{"mode":"aggregation"},"observed":{"active":"direct","stale":false},"wan":[],"modems":[]}`
|
||||
a, ca := clientAPIFixture(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/api/client/v1/capabilities":
|
||||
io.WriteString(w, `{"api_version":"1","schema_version":"1.1","rights":["read","policy"]}`)
|
||||
case "/api/client/v1/status":
|
||||
io.WriteString(w, status)
|
||||
case "/api/client/v1/diagnostics/latest":
|
||||
io.WriteString(w, `{"report":{"checks":[{"id":"lan","state":"ok"},{"id":"sim","state":"warn"}]}}`)
|
||||
default:
|
||||
t.Error("unexpected endpoint", r.URL.Path)
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
})
|
||||
root := t.TempDir()
|
||||
c := Open(root)
|
||||
candidate := Candidate{Address: "192.168.1.1", LocalIP: "192.168.1.2", Interface: "eth-test", 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("paired API device sent to legacy CGI"); return nil }
|
||||
provisional := identity(candidate.MAC)
|
||||
c.state.Records[provisional] = record{MAC: candidate.MAC, Device: Device{ID: provisional, Address: candidate.Address, Interface: candidate.Interface, State: "access_required", ObservedAt: time.Now().Unix()}}
|
||||
cmd := Command{ID: "op_0123456789abcdef0123456789abcdef", RuntimeID: c.runtime, DeviceID: provisional, Deadline: time.Now().Add(time.Minute).Unix(), ModelID: bananaPiModel, ClientAPI: &clientAPIAccess{Token: "synthetic-private-key", CA: ca}}
|
||||
c.authorize(context.Background(), cmd)
|
||||
if c.results[cmd.ID].State != "complete" || len(c.state.Records) != 1 || c.state.Records[a.identity].Device.Identity != "device_ca" {
|
||||
t.Fatal("enrollment not atomic", c.results[cmd.ID])
|
||||
}
|
||||
raw, e := os.ReadFile(filepath.Join(root, "routers-v1.json"))
|
||||
if e != nil || !strings.Contains(string(raw), "synthetic-private-key") {
|
||||
t.Fatal("private credential not retained", e)
|
||||
}
|
||||
info, _ := os.Stat(filepath.Join(root, "routers-v1.json"))
|
||||
if info.Mode().Perm()&0077 != 0 {
|
||||
t.Fatal("private state is public")
|
||||
}
|
||||
candidate.Address = "192.168.1.9"
|
||||
candidate.MAC = "02:00:00:00:00:09"
|
||||
c.poll(context.Background())
|
||||
d := c.Snapshot().Items[0]
|
||||
if d.ID != a.identity || d.Address != candidate.Address || len(c.Snapshot().Items) != 1 {
|
||||
t.Fatal("LAN change created another instance", d)
|
||||
}
|
||||
if len(d.ClientAPI.Checks) != 2 || d.ClientAPI.Checks[1].ID != "sim" {
|
||||
t.Fatal("latest service report not projected")
|
||||
}
|
||||
public, _ := json.Marshal(c.Snapshot())
|
||||
if strings.Contains(string(public), "synthetic-private-key") || strings.Contains(string(public), "BEGIN CERTIFICATE") {
|
||||
t.Fatal("access escaped into telemetry")
|
||||
}
|
||||
restarted := Open(root)
|
||||
if restarted.state.Records[a.identity].Access.ClientAPI == nil || restarted.Submit(cmd) == nil {
|
||||
t.Fatal("restart lost identity or admitted old runtime")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientAPIControlAcceptedIsNotComplete(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","uptime":30}`)
|
||||
case "/api/client/v1/diagnostics":
|
||||
writes.Add(1)
|
||||
if r.Method != "POST" || r.Header.Get("If-Match") != "" {
|
||||
t.Error("wrong diagnostic method/guard")
|
||||
}
|
||||
w.WriteHeader(202)
|
||||
io.WriteString(w, `{"operation_id":"diagnostic-1","kind":"diagnostics","state":"accepted"}`)
|
||||
case "/api/client/v1/operations/diagnostic-1":
|
||||
io.WriteString(w, `{"operation_id":"diagnostic-1","kind":"diagnostics","state":"succeeded"}`)
|
||||
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 }
|
||||
r := record{Device: Device{ID: a.identity, Address: candidate.Address, Interface: candidate.Interface, State: "ready", ClientAPI: &clientPublic{Rights: []string{"read", "diagnostics"}}}, Access: &credential{ClientAPI: &clientAPIAccess{Token: "synthetic-private-key", CA: ca}}}
|
||||
c.state.Records[a.identity] = r
|
||||
cmd := Command{ID: "op_0123456789abcdef0123456789abcdef", RuntimeID: c.runtime, DeviceID: a.identity, Action: "diagnostics", ExpectedBootID: "boot-1", ExpectedRevision: "old", Deadline: time.Now().Add(time.Minute).Unix()}
|
||||
c.applyClientControl(context.Background(), cmd, r)
|
||||
if writes.Load() != 0 || c.results[cmd.ID].Error != "router_conflict" {
|
||||
t.Fatal("stale revision sent")
|
||||
}
|
||||
cmd.ExpectedRevision = "r1"
|
||||
c.applyClientControl(context.Background(), cmd, r)
|
||||
if writes.Load() != 1 || c.results[cmd.ID].State != "applying" || c.clientControl == nil {
|
||||
t.Fatal("accepted confused with complete")
|
||||
}
|
||||
c.verifyClientControl(context.Background(), []Candidate{candidate})
|
||||
if writes.Load() != 1 || c.results[cmd.ID].State != "complete" || c.clientControl != nil {
|
||||
t.Fatal("operation verification failed")
|
||||
}
|
||||
}
|
||||
@@ -16,29 +16,37 @@ import (
|
||||
)
|
||||
|
||||
type Collector struct {
|
||||
path, runtime string
|
||||
started time.Time
|
||||
state state // Owned exclusively by Run, not by heartbeat or HTTP handlers.
|
||||
storageError bool
|
||||
control *verification
|
||||
blocked bool
|
||||
view atomic.Value
|
||||
commands chan Command
|
||||
mu sync.Mutex
|
||||
results map[string]Result
|
||||
resultTimes map[string]time.Time
|
||||
clients map[string]*api
|
||||
weak map[string]int
|
||||
discover func(context.Context, []Candidate) []Candidate
|
||||
client func(Candidate) *api
|
||||
neighbor func(string, string) string
|
||||
speedUpdates chan struct{}
|
||||
speedCancel context.CancelFunc
|
||||
speedOperation, speedDevice string
|
||||
evidenceCache *evidenceCache
|
||||
evidence *EvidenceChunk
|
||||
path, runtime string
|
||||
started time.Time
|
||||
state state // Owned exclusively by Run, not by heartbeat or HTTP handlers.
|
||||
storageError bool
|
||||
control *verification
|
||||
clientControl *clientVerification
|
||||
blocked bool
|
||||
view atomic.Value
|
||||
commands chan Command
|
||||
mu sync.Mutex
|
||||
results map[string]Result
|
||||
resultTimes map[string]time.Time
|
||||
clients map[string]*api
|
||||
weak map[string]int
|
||||
traffic map[string]trafficSample
|
||||
discover func(context.Context, []Candidate) []Candidate
|
||||
client func(Candidate) *api
|
||||
apiClient func(Candidate, clientAPIAccess) (*clientAPI, error)
|
||||
neighbor func(string, string) string
|
||||
}
|
||||
|
||||
func Open(root string) *Collector {
|
||||
b := make([]byte, 16)
|
||||
_, err := rand.Read(b)
|
||||
c := &Collector{path: filepath.Join(root, "routers-v1.json"), runtime: hex.EncodeToString(b), started: time.Now(),
|
||||
commands: make(chan Command, 4), results: map[string]Result{}, resultTimes: map[string]time.Time{}, clients: map[string]*api{}, weak: map[string]int{}, discover: discover, client: newAPI, neighbor: neighbor,
|
||||
speedUpdates: make(chan struct{}, 1), commands: make(chan Command, 4), results: map[string]Result{}, resultTimes: map[string]time.Time{}, clients: map[string]*api{}, weak: map[string]int{}, traffic: map[string]trafficSample{}, discover: discover, client: newAPI, apiClient: newClientAPI, neighbor: neighbor,
|
||||
state: state{Schema: Schema, Records: map[string]record{}, Events: []Event{}}}
|
||||
if err != nil || !profileValid() {
|
||||
c.blocked = true
|
||||
@@ -61,7 +69,11 @@ func Open(root string) *Collector {
|
||||
c.storageError = true
|
||||
}
|
||||
for id, r := range c.state.Records {
|
||||
if r.WebAccess == nil && r.Access != nil && r.Access.ClientAPI == nil {
|
||||
r.WebAccess = r.Access
|
||||
}
|
||||
r.Device.State = "unreachable"
|
||||
r.Device.Attached = false
|
||||
c.state.Records[id] = r
|
||||
}
|
||||
c.publish()
|
||||
@@ -74,6 +86,12 @@ func (c *Collector) Snapshot() Snapshot {
|
||||
data, _ := json.Marshal(c.view.Load().(Snapshot))
|
||||
var s Snapshot
|
||||
_ = json.Unmarshal(data, &s)
|
||||
c.mu.Lock()
|
||||
s.Results = []Result{}
|
||||
for _, r := range c.results {
|
||||
s.Results = append(s.Results, r)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
return s
|
||||
}
|
||||
|
||||
@@ -92,11 +110,15 @@ func (c *Collector) Submit(cmd Command) error {
|
||||
}
|
||||
found := false
|
||||
for _, d := range c.Snapshot().Items {
|
||||
if cmd.Settings != nil && d.ID == cmd.DeviceID {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
if d.ID == cmd.DeviceID && time.Now().Unix()-d.ObservedAt < 40 && ((cmd.Action == "" && (d.State == "access_required" || d.State == "access_rejected")) || d.State == "ready") {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
if !found && cmd.Action != "speedtest_cancel" {
|
||||
return errors.New("router_unavailable")
|
||||
}
|
||||
c.mu.Lock()
|
||||
@@ -111,10 +133,19 @@ func (c *Collector) Submit(cmd Command) error {
|
||||
return nil
|
||||
}
|
||||
for _, result := range c.results {
|
||||
if result.State == "queued" || result.State == "applying" {
|
||||
if (result.State == "queued" || result.State == "applying") && cmd.Action != "speedtest_cancel" {
|
||||
return errors.New("router_requests_busy")
|
||||
}
|
||||
}
|
||||
// Read receipts are ephemeral and never consume the write receipt budget.
|
||||
if cmd.Query != nil {
|
||||
for id, r := range c.results {
|
||||
if r.Action == "inspect" && r.State != "queued" && r.State != "applying" {
|
||||
delete(c.results, id)
|
||||
delete(c.resultTimes, id)
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(c.results) >= 32 {
|
||||
return errors.New("router_requests_busy")
|
||||
}
|
||||
@@ -129,7 +160,11 @@ func (c *Collector) Submit(cmd Command) error {
|
||||
}
|
||||
|
||||
func (c *Collector) publish() {
|
||||
s := Snapshot{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 c.evidenceCache != nil && time.Since(c.evidenceCache.At) > 10*time.Minute {
|
||||
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}}
|
||||
if len(s.Events) > 0 {
|
||||
s.Journal.First = s.Events[0].Sequence
|
||||
}
|
||||
@@ -200,7 +235,15 @@ func (c *Collector) Run(ctx context.Context) {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case cmd := <-c.commands:
|
||||
if cmd.Action == "" {
|
||||
if cmd.Action == "speedtest" || cmd.Action == "speedtest_cancel" {
|
||||
c.runSpeedtest(ctx, cmd)
|
||||
} else if cmd.Query != nil {
|
||||
deadline, cancel := context.WithDeadline(ctx, time.Unix(cmd.Deadline, 0))
|
||||
c.readEvidence(deadline, cmd)
|
||||
cancel()
|
||||
} else if cmd.Settings != nil {
|
||||
c.configure(ctx, cmd)
|
||||
} else if cmd.Action == "" {
|
||||
c.authorize(ctx, cmd)
|
||||
} else {
|
||||
c.applyControl(ctx, cmd)
|
||||
@@ -222,7 +265,12 @@ func (c *Collector) candidates(ctx context.Context) []Candidate {
|
||||
|
||||
func (c *Collector) poll(ctx context.Context) {
|
||||
seen := map[string]bool{}
|
||||
for _, candidate := range c.candidates(ctx) {
|
||||
candidates := c.candidates(ctx)
|
||||
handled := c.pollClientAPI(ctx, candidates, seen)
|
||||
for _, candidate := range candidates {
|
||||
if handled[candidate.Address] {
|
||||
continue
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
break
|
||||
}
|
||||
@@ -277,12 +325,15 @@ func (c *Collector) poll(ctx context.Context) {
|
||||
r.Device.State = "incompatible"
|
||||
} else if err != nil {
|
||||
r.Device.State = "unreachable"
|
||||
r.Device.Attached = false
|
||||
} else {
|
||||
d.ID, d.Address, d.Interface, d.LocalIP = id, candidate.Address, candidate.Interface, candidate.LocalIP
|
||||
d.ObservedAt = time.Now().Unix()
|
||||
d.WebAccess = r.WebAccess != nil
|
||||
r.Device = d
|
||||
}
|
||||
}
|
||||
c.decorate(&r, candidate)
|
||||
c.transitions(old, r.Device)
|
||||
c.state.Records[id] = r
|
||||
}
|
||||
@@ -290,11 +341,14 @@ func (c *Collector) poll(ctx context.Context) {
|
||||
if !seen[id] {
|
||||
old := r.Device
|
||||
r.Device.State = "unreachable"
|
||||
r.Device.Attached = false
|
||||
c.transitions(old, r.Device)
|
||||
c.state.Records[id] = r
|
||||
delete(c.traffic, id)
|
||||
}
|
||||
}
|
||||
c.verifyControl()
|
||||
c.verifyClientControl(ctx, candidates)
|
||||
c.persist()
|
||||
c.publish()
|
||||
}
|
||||
@@ -312,6 +366,14 @@ func (c *Collector) authorize(ctx context.Context, cmd Command) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if cmd.ClientAPI != nil {
|
||||
result = c.authorizeClientAPI(ctx, cmd, r)
|
||||
return
|
||||
}
|
||||
if r.Access != nil && r.Access.ClientAPI != nil {
|
||||
result.Error = "command_rejected"
|
||||
return
|
||||
}
|
||||
for _, candidate := range c.candidates(ctx) {
|
||||
if c.neighbor(candidate.Interface, candidate.Address) != r.MAC {
|
||||
continue
|
||||
@@ -336,7 +398,8 @@ func (c *Collector) authorize(ctx context.Context, cmd Command) {
|
||||
d.ID, d.Address, d.Interface, d.LocalIP = cmd.DeviceID, candidate.Address, candidate.Interface, candidate.LocalIP
|
||||
d.ObservedAt = time.Now().Unix()
|
||||
before := r
|
||||
r.Device, r.Access, r.Rejected = d, &access, false
|
||||
r.Device, r.Access, r.WebAccess, r.Rejected = d, &access, &access, false
|
||||
c.decorate(&r, candidate)
|
||||
c.state.Records[cmd.DeviceID] = r
|
||||
c.event(cmd.DeviceID, "access_granted", 0, "", "")
|
||||
c.persist()
|
||||
@@ -350,3 +413,6 @@ func (c *Collector) authorize(ctx context.Context, cmd Command) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// SpeedtestUpdates wakes the existing authenticated channel only for measured progress.
|
||||
func (c *Collector) SpeedtestUpdates() <-chan struct{} { return c.speedUpdates }
|
||||
|
||||
@@ -25,13 +25,48 @@ type verification struct {
|
||||
}
|
||||
|
||||
func validCommand(c Command) bool {
|
||||
if c.Action == "" {
|
||||
return c.Mode == "" && len(c.Slots) == 0 && len(c.Username) > 0 && len(c.Username) <= 64 && len(c.Password) > 0 && len(c.Password) <= 256
|
||||
if c.Speedtest != nil || c.SpeedtestCancel != "" || c.Action == "speedtest" || c.Action == "speedtest_cancel" {
|
||||
return validSpeedtest(c)
|
||||
}
|
||||
if c.Username != "" || c.Password != "" {
|
||||
if c.Query != nil || c.Action == "inspect" {
|
||||
return validEvidence(c)
|
||||
}
|
||||
if c.Settings != nil {
|
||||
return validSettings(c)
|
||||
}
|
||||
|
||||
if c.Action == "" {
|
||||
if c.ExpectedBootID != "" || c.ExpectedRevision != "" {
|
||||
return false
|
||||
}
|
||||
if c.Policy != nil || c.Recovery != "" || c.SIM != "" || c.Mode != "" || len(c.Slots) != 0 {
|
||||
return false
|
||||
}
|
||||
if c.ClientAPI != nil {
|
||||
return (c.ModelID == "" || c.ModelID == bananaPiModel) && c.Username == "" && c.Password == "" && len(c.ClientAPI.Token) > 0 && len(c.ClientAPI.Token) <= 4096 && len(c.ClientAPI.CA) > 0 && len(c.ClientAPI.CA) <= 8192
|
||||
}
|
||||
return c.ModelID == "" && len(c.Username) > 0 && len(c.Username) <= 64 && len(c.Password) > 0 && len(c.Password) <= 256
|
||||
}
|
||||
if c.Username != "" || c.Password != "" || c.ClientAPI != nil || c.ModelID != "" {
|
||||
return false
|
||||
}
|
||||
if c.Action == "reboot" {
|
||||
if c.Action == "policy" || c.Action == "recovery" || c.Action == "diagnostics" || (c.Action == "reboot" && c.ExpectedBootID != "") {
|
||||
if c.ExpectedBootID == "" || len(c.ExpectedBootID) > 128 || !revisionIdentifier.MatchString(c.ExpectedRevision) {
|
||||
return false
|
||||
}
|
||||
} else if c.ExpectedBootID != "" || c.ExpectedRevision != "" {
|
||||
return false
|
||||
}
|
||||
if c.Action == "policy" {
|
||||
return c.Mode == "" && len(c.Slots) == 0 && c.Policy != nil && c.Policy.valid() && c.Recovery == "" && c.SIM == ""
|
||||
}
|
||||
if c.Action == "recovery" {
|
||||
return c.Mode == "" && len(c.Slots) == 0 && c.Policy == nil && ((c.Recovery == "wan_reconnect" && simSlot(c.SIM) != 0) || ((c.Recovery == "vpn_reconnect" || c.Recovery == "dns_restart") && c.SIM == ""))
|
||||
}
|
||||
if c.Policy != nil || c.Recovery != "" || c.SIM != "" {
|
||||
return false
|
||||
}
|
||||
if c.Action == "reboot" || c.Action == "diagnostics" {
|
||||
return c.Mode == "" && len(c.Slots) == 0
|
||||
}
|
||||
if c.Action != "mode" || (c.Mode != "direct" && c.Mode != "aggregation") || len(c.Slots) < 1 || len(c.Slots) > 3 || (c.Mode == "direct" && len(c.Slots) != 1) {
|
||||
@@ -126,7 +161,7 @@ func controlForm(cmd Command, manual map[string]any) (url.Values, string, error)
|
||||
|
||||
func (c *Collector) setControlResult(cmd Command, state, reason string) {
|
||||
c.mu.Lock()
|
||||
c.results[cmd.ID] = Result{ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: state, Error: reason}
|
||||
c.results[cmd.ID] = Result{At: time.Now().Unix(), ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: state, Error: reason}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
@@ -148,6 +183,15 @@ func (c *Collector) applyControl(parent context.Context, cmd Command) {
|
||||
if !ok || r.Access == nil || r.Rejected || r.Device.State != "ready" {
|
||||
return
|
||||
}
|
||||
if r.Access.ClientAPI != nil {
|
||||
c.applyClientControl(ctx, cmd, r)
|
||||
sent = true
|
||||
return
|
||||
}
|
||||
if cmd.Action != "mode" && cmd.Action != "reboot" {
|
||||
result = "command_rejected"
|
||||
return
|
||||
}
|
||||
for _, candidate := range c.candidates(ctx) {
|
||||
if c.neighbor(candidate.Interface, candidate.Address) != r.MAC {
|
||||
continue
|
||||
|
||||
@@ -108,7 +108,7 @@ func TestCommandIsNotReplayedAfterAmbiguousWrite(t *testing.T) {
|
||||
c := Open(t.TempDir())
|
||||
mac := "02:00:00:00:00:01"
|
||||
id := identity(mac)
|
||||
c.state.Records[id] = record{MAC: mac, Access: &credential{"operator", "synthetic"}, Device: Device{ID: id, State: "ready", ObservedAt: time.Now().Unix()}}
|
||||
c.state.Records[id] = record{MAC: mac, Access: &credential{Username: "operator", Password: "synthetic"}, Device: Device{ID: id, State: "ready", ObservedAt: time.Now().Unix()}}
|
||||
c.discover = func(context.Context, []Candidate) []Candidate {
|
||||
return []Candidate{{Address: "192.168.50.1", Interface: "eth0", LocalIP: "192.168.50.2"}}
|
||||
}
|
||||
|
||||
@@ -252,6 +252,7 @@ func normalize(status, manual, internet, me map[string]any) (Device, error) {
|
||||
d.Modems = append(d.Modems, Modem{Slot: int(*slot), Operator: text(m["operator"]), Connectivity: text(m["connectivity"]), Radio: text(m["radio"]), IP: ip(m["ip"]), Technology: text(m["tech"]), Band: text(m["band"]), Bandwidth: bandwidth(m["bandwidth"]),
|
||||
RSRP: number(m["rsrp"], -160, -20), RSRQ: number(m["rsrq"], -50, 20), SINR: number(m["sinr"], -40, 60), RSSI: number(m["rssi"], -160, 0), CellID: text(m["cell_id"]), PCI: number(m["pci"], 0, 1007), DownKbps: number(m["dl"], 0, 1e9), UpKbps: number(m["ul"], 0, 1e9)})
|
||||
}
|
||||
applyInventory(&d, status)
|
||||
return d, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -31,7 +31,16 @@ func physical(name string) bool {
|
||||
return false
|
||||
}
|
||||
_, err := os.Stat(filepath.Join("/sys/class/net", name, "device"))
|
||||
return err == nil
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
// These routers attach to Node by Ethernet. Wireless/default uplinks are
|
||||
// not router discovery targets, even though they also have physical devices.
|
||||
if _, err := os.Stat(filepath.Join("/sys/class/net", name, "wireless")); err == nil {
|
||||
return false
|
||||
}
|
||||
carrier, err := os.ReadFile(filepath.Join("/sys/class/net", name, "carrier"))
|
||||
return err == nil && strings.TrimSpace(string(carrier)) == "1"
|
||||
}
|
||||
|
||||
func onLink(iface, address string) (string, bool) {
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
const evidenceChunkSize = 32768
|
||||
const evidenceMaxSize = 2 * 1024 * 1024
|
||||
const evidenceRetention = 20 * time.Minute
|
||||
|
||||
type EvidenceQuery struct {
|
||||
Resource string `json:"resource"`
|
||||
ID string `json:"id"`
|
||||
After string `json:"after"`
|
||||
Transfer string `json:"transfer"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
type EvidenceChunk struct {
|
||||
OperationID string `json:"operation_id"`
|
||||
DeviceID string `json:"device_id"`
|
||||
BootID string `json:"boot_id"`
|
||||
Resource string `json:"resource"`
|
||||
ID string `json:"id"`
|
||||
Transfer string `json:"transfer"`
|
||||
Offset int `json:"offset"`
|
||||
Total int `json:"total"`
|
||||
At int64 `json:"at"`
|
||||
Data string `json:"data"`
|
||||
}
|
||||
type evidenceCache struct {
|
||||
DeviceID, BootID, Resource, ID, After, Transfer string
|
||||
Data []byte
|
||||
At time.Time
|
||||
}
|
||||
|
||||
func validEvidence(cmd Command) bool {
|
||||
q := cmd.Query
|
||||
if q == nil || cmd.Action != "inspect" || cmd.Settings != nil || cmd.ClientAPI != nil || cmd.Username != "" || cmd.Password != "" || cmd.ModelID != "" || cmd.Policy != nil || cmd.Recovery != "" || cmd.SIM != "" || cmd.Mode != "" || len(cmd.Slots) != 0 || cmd.ExpectedRevision != "" || cmd.ExpectedBootID == "" || len(cmd.ExpectedBootID) > 128 {
|
||||
return false
|
||||
}
|
||||
if !slices.Contains([]string{"diagnostics_latest", "diagnostic", "bundle", "events", "recovery_history", "recordings", "recording", "targets"}, q.Resource) {
|
||||
return false
|
||||
}
|
||||
limit := 0
|
||||
if q.Resource == "events" || q.Resource == "recovery_history" {
|
||||
limit = 50
|
||||
}
|
||||
if _, err := clientAPIReadPath(q.Resource, q.ID, q.After, limit); err != nil {
|
||||
return false
|
||||
}
|
||||
if q.Transfer == "" {
|
||||
return q.Offset == 0
|
||||
}
|
||||
if len(q.Transfer) != 64 || q.Offset < 0 || q.Offset >= evidenceMaxSize || q.Offset%evidenceChunkSize != 0 {
|
||||
return false
|
||||
}
|
||||
_, err := hex.DecodeString(q.Transfer)
|
||||
return err == nil
|
||||
}
|
||||
func (c *Collector) readEvidence(ctx context.Context, cmd Command) {
|
||||
q := cmd.Query
|
||||
reason := "router_unavailable"
|
||||
defer func() {
|
||||
if reason != "" {
|
||||
c.setControlResult(cmd, "error", reason)
|
||||
}
|
||||
}()
|
||||
r, ok := c.state.Records[cmd.DeviceID]
|
||||
if !ok || r.Access == nil || r.Access.ClientAPI == nil || r.Device.State != "ready" || r.Device.ClientAPI == nil {
|
||||
return
|
||||
}
|
||||
if cmd.ExpectedBootID != r.Device.ClientAPI.BootID {
|
||||
reason = "router_conflict"
|
||||
return
|
||||
}
|
||||
right := "read"
|
||||
if q.Resource == "bundle" {
|
||||
right = "bundle"
|
||||
}
|
||||
if !slices.Contains(r.Device.ClientAPI.Rights, right) {
|
||||
reason = "access_rejected"
|
||||
return
|
||||
}
|
||||
cache := c.evidenceCache
|
||||
if q.Transfer != "" {
|
||||
if cache == nil || cache.Transfer != q.Transfer || cache.DeviceID != cmd.DeviceID || cache.BootID != cmd.ExpectedBootID || cache.Resource != q.Resource || cache.ID != q.ID || cache.After != q.After || time.Since(cache.At) > evidenceRetention {
|
||||
reason = "result_expired"
|
||||
return
|
||||
}
|
||||
} else {
|
||||
found := false
|
||||
for _, candidate := range c.candidates(ctx) {
|
||||
if candidate.Address != r.Device.Address || candidate.Interface != r.Device.Interface {
|
||||
continue
|
||||
}
|
||||
a, err := c.apiClient(candidate, *r.Access.ClientAPI)
|
||||
if err != nil || a.identity != cmd.DeviceID {
|
||||
return
|
||||
}
|
||||
raw, _, err := a.readResource(ctx, "status", "", "", 0)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
var status clientObservation
|
||||
if json.Unmarshal(raw, &status) != nil {
|
||||
reason = "unsupported_response"
|
||||
return
|
||||
}
|
||||
if status.BootID != cmd.ExpectedBootID {
|
||||
reason = "router_conflict"
|
||||
return
|
||||
}
|
||||
limit := 0
|
||||
if q.Resource == "events" || q.Resource == "recovery_history" {
|
||||
limit = 50
|
||||
}
|
||||
raw, _, err = a.readResource(ctx, q.Resource, q.ID, q.After, limit)
|
||||
if err != nil {
|
||||
var e *clientAPIError
|
||||
if errors.As(err, &e) {
|
||||
reason = e.Code
|
||||
}
|
||||
return
|
||||
}
|
||||
data, err := projectEvidence(q.Resource, raw, r.Access.ClientAPI.Token)
|
||||
if err != nil {
|
||||
reason = "unsupported_response"
|
||||
return
|
||||
}
|
||||
sum := sha256.Sum256(data)
|
||||
cache = &evidenceCache{DeviceID: cmd.DeviceID, BootID: cmd.ExpectedBootID, Resource: q.Resource, ID: q.ID, After: q.After, Transfer: hex.EncodeToString(sum[:]), Data: data, At: time.Now()}
|
||||
c.evidenceCache = cache
|
||||
found = true
|
||||
break
|
||||
}
|
||||
if !found {
|
||||
return
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil || time.Now().Unix() >= cmd.Deadline {
|
||||
reason = "expired"
|
||||
return
|
||||
}
|
||||
if q.Offset >= len(cache.Data) {
|
||||
reason = "result_expired"
|
||||
return
|
||||
}
|
||||
end := min(q.Offset+evidenceChunkSize, len(cache.Data))
|
||||
c.evidence = &EvidenceChunk{OperationID: cmd.ID, DeviceID: cmd.DeviceID, BootID: cmd.ExpectedBootID, Resource: q.Resource, ID: q.ID, Transfer: cache.Transfer, Offset: q.Offset, Total: len(cache.Data), At: cache.At.Unix(), Data: base64.StdEncoding.EncodeToString(cache.Data[q.Offset:end])}
|
||||
c.setControlResult(cmd, "complete", "")
|
||||
reason = ""
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"math"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// Document fields admitted from Client API v1 schema 1.1. Unknown extensions
|
||||
// are omitted, never forwarded as telemetry or interpreted as instructions.
|
||||
// Dynamic vendor dictionaries, credentials and request bodies are not admitted.
|
||||
var evidenceFields = strings.Fields(`
|
||||
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
|
||||
id schema_version diagnostic_profile service_run service_report machine_checks checks check_id code checked checked_utc title summary facts scope impact cause
|
||||
boot_id clock_quality started_utc finished_utc observed_utc generated_utc uptime started finished duration_ms limit_seconds done total step version component_version counts ok error warn unknown na
|
||||
joined_existing_job lan_client_tested client_path_verified installed_sim path path_changed_during_run repairs_performed result_available snapshot snapshot_scope snapshot_error snapshot_omitted
|
||||
target_probe_count target_probes target_id label success stages dns tcp tls http latency_ms duration_ms status http_status reason address port family resolved_addresses addresses host server_name certificate_verified
|
||||
captured_snapshot captured_snapshot_scope current_snapshot firewall_summary firewall_values_omitted secrets_included routes routing_rules handle hook name policy prio table type dev dst flags metric protocol src priority gateway prefsrc scope target nexthop mask source
|
||||
observed_state observed active selected pending phase reason_code policy_epoch stale aggregate_verified aggregate_checked aggregate_reason vpn_verified direct_applied direct_wan control_plane_only checked settings
|
||||
desired_policy persisted_policy mode preferred_sim allow_fallback return_to_preferred persist fail_seconds recover_seconds min_vpn_seconds fallback_sims revision firmware_version effective_wan fallback_active fallback_reason
|
||||
vpn sim server_reference verified last_success_age_s last_success_utc proof_age_s proof_scope watch_age_s watch_state context_fingerprint
|
||||
reserve available count target pairs distinct_sim_count fresh_seconds refresh_seconds running state_age_s operator_whitelist_verified transport age_s expires_in_s expires_utc tested_utc
|
||||
recovery automation_owner last_attempt matches_current_policy_epoch state_checked_utc full_cause_not_assumed
|
||||
wan modems slot interface up modem_present sim_present modem_state registration network_registration operator_network_registration operator operator_code operator_name packet_service_state registration_state roaming failure_reason network_rejection_access_technology network_rejection_code network_rejection_operator
|
||||
fresh sample_interval_s cache_age_s modem_cache_age_s modem_cache_fresh sim_cache_age_s radio technology band bandwidth_mhz cell_id earfcn pci rsrp_dbm rsrq_db rssi_dbm sinr_db tac bearer ipv4
|
||||
snapshot_available observed_uptime uptime_s connected_since_uptime link_state netdev_matches_inventory internet_verified internet_verification_scope role autostart dynamic availability_reason ip4table ipv4_addresses ipv6_addresses dns_servers errors subsystem
|
||||
traffic rx_bytes tx_bytes rx_packets tx_packets rx_errors tx_errors rx_dropped tx_dropped
|
||||
cursor persisted_cursor retention ram_tail_is_durable sequence_gaps_may_be_reservations events sequence source boot epoch level topic message category severity initiator_kind actor_key_id actor_inferred causal_link_proven recorded_code entries operations operation_order event_order unrecorded_actors_are_unknown error_code action recorded_action
|
||||
recordings enabled after_samples_max before_samples_max cause_inference external_probes_in_background last_error power_loss_tail_may_be_missing record_bytes_max retained_max sample_interval_s samples trigger_codes truncated context
|
||||
targets paths arbitrary_url_requests configuration_owner recorder_enabled
|
||||
`)
|
||||
|
||||
func projectEvidence(resource string, raw json.RawMessage, secret string) ([]byte, error) {
|
||||
var source map[string]any
|
||||
if len(raw) > evidenceMaxSize || json.Unmarshal(raw, &source) != nil {
|
||||
return nil, errProtocol
|
||||
}
|
||||
allowed := map[string]bool{}
|
||||
for _, key := range evidenceFields {
|
||||
allowed[key] = true
|
||||
}
|
||||
omitted, nodes := 0, 0
|
||||
var visit func(any, int) (any, error)
|
||||
visit = func(v any, depth int) (any, error) {
|
||||
nodes++
|
||||
if nodes > 50000 || depth > 18 {
|
||||
return nil, errProtocol
|
||||
}
|
||||
switch x := v.(type) {
|
||||
case map[string]any:
|
||||
out := map[string]any{}
|
||||
for k, v := range x {
|
||||
if !allowed[k] {
|
||||
omitted++
|
||||
continue
|
||||
}
|
||||
p, e := visit(v, depth+1)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out[k] = p
|
||||
}
|
||||
return out, nil
|
||||
case []any:
|
||||
if len(x) > 1000 {
|
||||
return nil, errProtocol
|
||||
}
|
||||
out := make([]any, 0, len(x))
|
||||
for _, v := range x {
|
||||
p, e := visit(v, depth+1)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out, nil
|
||||
case string:
|
||||
if len(x) > 8192 {
|
||||
return nil, errProtocol
|
||||
}
|
||||
if secret != "" {
|
||||
x = strings.ReplaceAll(x, secret, "[redacted]")
|
||||
}
|
||||
x = strings.Map(func(r rune) rune {
|
||||
if unicode.IsControl(r) && r != '\n' && r != '\t' {
|
||||
return -1
|
||||
}
|
||||
return r
|
||||
}, x)
|
||||
return x, nil
|
||||
case float64:
|
||||
if math.IsNaN(x) || math.IsInf(x, 0) || math.Abs(x) > 9007199254740991 {
|
||||
return nil, errProtocol
|
||||
}
|
||||
return x, nil
|
||||
case bool, nil:
|
||||
return x, nil
|
||||
default:
|
||||
return nil, errProtocol
|
||||
}
|
||||
}
|
||||
data, err := visit(source, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
projected := map[string]any{"schema": "missioncore.router-evidence/v1", "resource": resource, "omitted_fields": omitted, "data": data}
|
||||
result, err := json.Marshal(projected)
|
||||
if err != nil || len(result) > evidenceMaxSize {
|
||||
return nil, errors.New("unsupported_response")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestEvidenceReadIsBoundedImmutableAndNeverWrites(t *testing.T) {
|
||||
calls := 0
|
||||
a, ca := clientAPIFixture(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if r.Method != "GET" {
|
||||
t.Fatal("unexpected write")
|
||||
}
|
||||
if strings.HasSuffix(r.URL.Path, "/status") {
|
||||
w.Write([]byte(`{"boot_id":"boot"}`))
|
||||
return
|
||||
}
|
||||
json.NewEncoder(w).Encode(map[string]any{"report": map[string]any{"facts": []string{strings.Repeat("a", 8000), strings.Repeat("b", 8000), strings.Repeat("c", 8000), strings.Repeat("d", 8000), strings.Repeat("e", 8000)}, "password": "must-not-leave-router", "token": "synthetic-private-key"}})
|
||||
})
|
||||
c := Open(t.TempDir())
|
||||
candidate := Candidate{Address: "192.168.1.1", Interface: "test-lan", LocalIP: "192.168.1.2"}
|
||||
c.discover = func(context.Context, []Candidate) []Candidate { return []Candidate{candidate} }
|
||||
c.apiClient = func(Candidate, clientAPIAccess) (*clientAPI, error) { return a, nil }
|
||||
c.state.Records[a.identity] = record{Access: &credential{ClientAPI: &clientAPIAccess{Token: "synthetic-private-key", CA: ca}}, Device: Device{ID: a.identity, State: "ready", Address: candidate.Address, Interface: candidate.Interface, ClientAPI: &clientPublic{BootID: "boot", Rights: []string{"read"}}}}
|
||||
cmd := Command{ID: "op_" + strings.Repeat("a", 32), DeviceID: a.identity, Action: "inspect", ExpectedBootID: "boot", Deadline: time.Now().Unix() + 80, Query: &EvidenceQuery{Resource: "diagnostics_latest"}}
|
||||
c.readEvidence(context.Background(), cmd)
|
||||
if c.results[cmd.ID].State != "complete" || c.evidence == nil {
|
||||
t.Fatalf("%+v", c.results[cmd.ID])
|
||||
}
|
||||
first := *c.evidence
|
||||
raw, _ := base64.StdEncoding.DecodeString(first.Data)
|
||||
if len(raw) != evidenceChunkSize || first.Total <= len(raw) {
|
||||
t.Fatal("not chunked")
|
||||
}
|
||||
cmd.Query.Transfer = first.Transfer
|
||||
cmd.Query.Offset = evidenceChunkSize
|
||||
c.readEvidence(context.Background(), cmd)
|
||||
tail, _ := base64.StdEncoding.DecodeString(c.evidence.Data)
|
||||
if calls != 2 || c.evidence.Transfer != first.Transfer || c.evidence.At != first.At {
|
||||
t.Fatal("refetched mutable document")
|
||||
}
|
||||
whole := append(raw, tail...)
|
||||
if !json.Valid(whole) || strings.Contains(string(whole), "must-not-leave") || strings.Contains(string(whole), "synthetic-private-key") {
|
||||
t.Fatal("unsafe projection")
|
||||
}
|
||||
cmd.ExpectedBootID = "other"
|
||||
c.readEvidence(context.Background(), cmd)
|
||||
if c.results[cmd.ID].Error != "router_conflict" {
|
||||
t.Fatal("cross-boot read")
|
||||
}
|
||||
cmd.ExpectedBootID = "boot"
|
||||
c.evidenceCache.At = time.Now().Add(-21 * time.Minute)
|
||||
c.readEvidence(context.Background(), cmd)
|
||||
if c.results[cmd.ID].Error != "result_expired" {
|
||||
t.Fatal("expired chunk")
|
||||
}
|
||||
}
|
||||
func TestEvidenceSelectorsRejectActionsAndPathInjection(t *testing.T) {
|
||||
base := Command{Action: "inspect", ExpectedBootID: "boot", Query: &EvidenceQuery{Resource: "events"}}
|
||||
if !validCommand(base) {
|
||||
t.Fatal("valid read rejected")
|
||||
}
|
||||
for _, resource := range []string{"status", "schema", "reboot", "http://bad", "../policy"} {
|
||||
c := base
|
||||
q := *base.Query
|
||||
q.Resource = resource
|
||||
c.Query = &q
|
||||
if validCommand(c) {
|
||||
t.Fatal(resource)
|
||||
}
|
||||
}
|
||||
for _, id := range []string{"../file", "a?x=y", "/reboot"} {
|
||||
c := base
|
||||
c.Query = &EvidenceQuery{Resource: "bundle", ID: id}
|
||||
if validCommand(c) {
|
||||
t.Fatal(id)
|
||||
}
|
||||
}
|
||||
c := base
|
||||
c.Policy = &clientPolicy{}
|
||||
if validCommand(c) {
|
||||
t.Fatal("mixed mutation")
|
||||
}
|
||||
c = base
|
||||
c.Query = &EvidenceQuery{Resource: "events", Transfer: strings.Repeat("a", 64), Offset: 1}
|
||||
if validCommand(c) {
|
||||
t.Fatal("unaligned chunk")
|
||||
}
|
||||
}
|
||||
func TestEvidenceProjectionKeepsZeroNullAndFiltersUnknownExtensions(t *testing.T) {
|
||||
result, err := projectEvidence("recording", []byte(`{"samples":[{"state":{"vpn":{"verified":false},"wan":[{"radio":{"sinr_db":0,"rsrp_dbm":null},"password":"secret"}]}}],"token":"secret","unknown_extension":{"x":"secret"}}`), "secret")
|
||||
if err != nil || strings.Contains(string(result), "secret") || !strings.Contains(string(result), `"sinr_db":0`) || !strings.Contains(string(result), `"rsrp_dbm":null`) {
|
||||
t.Fatal(string(result), err)
|
||||
}
|
||||
d := readClientDetails(map[string]any{"reserve": map[string]any{"count": float64(0), "running": true}, "vpn": map[string]any{}})
|
||||
if d.Reserve.Count == nil || *d.Reserve.Count != 0 || d.VPN.Verified != nil || d.Reserve.DistinctSIMs != nil {
|
||||
t.Fatal("invented confirmation")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Board wiring is a versioned plugin profile, independent of the instance,
|
||||
// address, SIM/operator and mutable M-number assignment in the firmware.
|
||||
func applyInventory(d *Device, status map[string]any) {
|
||||
registry := object(status["slot_registry"])
|
||||
board := text(registry["board"])
|
||||
if board == "" {
|
||||
return
|
||||
}
|
||||
d.BoardID, d.ModelID, d.ModelName, d.SlotMap = board, "", "", nil
|
||||
var profiles struct {
|
||||
Boards []struct {
|
||||
Board string `json:"board_id"`
|
||||
Model string `json:"model_id"`
|
||||
Name string `json:"model_name"`
|
||||
Ports map[string]int `json:"sim_usb_ports"`
|
||||
Positions map[string]string `json:"sim_positions"`
|
||||
} `json:"board_profiles"`
|
||||
}
|
||||
if json.Unmarshal(profileJSON, &profiles) != nil {
|
||||
return
|
||||
}
|
||||
for _, p := range profiles.Boards {
|
||||
if board != p.Board {
|
||||
continue
|
||||
}
|
||||
d.ModelID, d.ModelName = p.Model, p.Name
|
||||
slots, ok := registry["slots"].([]any)
|
||||
if !ok || len(slots) != 3 {
|
||||
return
|
||||
}
|
||||
seenSIM, seenSlot := map[int]bool{}, map[int]bool{}
|
||||
bindings := []SlotBinding{}
|
||||
hub := ""
|
||||
for _, raw := range slots {
|
||||
s := object(raw)
|
||||
n := number(s["slot"], 1, 3)
|
||||
usb := text(s["usb"])
|
||||
cut := strings.LastIndex(usb, ".")
|
||||
if n == nil || cut < 1 || float64(int(*n)) != *n {
|
||||
return
|
||||
}
|
||||
if hub != "" && hub != usb[:cut] {
|
||||
return
|
||||
}
|
||||
hub = usb[:cut]
|
||||
sim, slot := p.Ports[usb[cut+1:]], int(*n)
|
||||
if sim == 0 || seenSIM[sim] || seenSlot[slot] {
|
||||
return
|
||||
}
|
||||
seenSIM[sim], seenSlot[slot] = true, true
|
||||
bindings = append(bindings, SlotBinding{Slot: slot, SIM: sim, Position: p.Positions[strconv.Itoa(sim)]})
|
||||
}
|
||||
d.SlotMap = bindings
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Collector) decorate(r *record, candidate Candidate) {
|
||||
r.Device.Name = r.Name
|
||||
r.Device.Attached = true
|
||||
r.Device.Connection = "ethernet"
|
||||
r.Device.WebUsername = ""
|
||||
if r.WebAccess != nil {
|
||||
r.Device.WebUsername = r.WebAccess.Username
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Collector) enrichPanel(ctx context.Context, candidate Candidate, r *record) {
|
||||
if r.WebAccess == nil || r.WebRejected {
|
||||
return
|
||||
}
|
||||
candidate.MAC = r.MAC
|
||||
a := c.clients[r.Device.ID]
|
||||
if a == nil {
|
||||
a = c.client(candidate)
|
||||
c.clients[r.Device.ID] = a
|
||||
}
|
||||
status, err := a.json(ctx, "dexaflow_status", nil)
|
||||
if err == errAccess {
|
||||
err = a.login(ctx, *r.WebAccess)
|
||||
if err == nil {
|
||||
status, err = a.json(ctx, "dexaflow_status", nil)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
r.Device.WebAccess = false
|
||||
if err == errAccess {
|
||||
r.WebRejected = true
|
||||
delete(c.clients, r.Device.ID)
|
||||
}
|
||||
return
|
||||
}
|
||||
r.Device.WebAccess = true
|
||||
applyInventory(&r.Device, status)
|
||||
}
|
||||
|
||||
type routerSettings struct {
|
||||
Name string `json:"name"`
|
||||
Address string `json:"address"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func validSettings(cmd Command) bool {
|
||||
s := cmd.Settings
|
||||
if s == nil || cmd.Action != "" || cmd.ClientAPI != nil || cmd.Policy != nil || cmd.ModelID != "" || cmd.Username != "" || cmd.Password != "" || cmd.Mode != "" || len(cmd.Slots) > 0 || cmd.SIM != "" || cmd.Recovery != "" || cmd.ExpectedBootID != "" || cmd.ExpectedRevision != "" {
|
||||
return false
|
||||
}
|
||||
if utf8.RuneCountInString(s.Name) > 128 || strings.IndexFunc(s.Name, unicode.IsControl) >= 0 {
|
||||
return false
|
||||
}
|
||||
ip := net.ParseIP(s.Address)
|
||||
return ip != nil && ip.To4() != nil && ip.IsPrivate() && len(s.Username) <= 64 && len(s.Password) <= 256 && ((s.Username == "" && s.Password == "") || (s.Username != "" && s.Password != ""))
|
||||
}
|
||||
|
||||
// Instance settings are stored on Node. Name changes never write the router;
|
||||
// web credentials authorize reads only, while Client API remains the write owner.
|
||||
func (c *Collector) configure(parent context.Context, cmd Command) {
|
||||
result := Result{ID: cmd.ID, DeviceID: cmd.DeviceID, State: "error", Error: "router_unavailable"}
|
||||
defer func() { c.mu.Lock(); c.results[cmd.ID] = result; c.mu.Unlock() }()
|
||||
if time.Now().Unix() >= cmd.Deadline {
|
||||
result.Error = "expired"
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithDeadline(parent, time.Unix(cmd.Deadline, 0))
|
||||
defer cancel()
|
||||
before, ok := c.state.Records[cmd.DeviceID]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
r := before
|
||||
s := cmd.Settings
|
||||
changedAddress := s.Address != r.Device.Address
|
||||
if changedAddress || s.Password != "" {
|
||||
candidates := c.discover(ctx, []Candidate{{Address: s.Address, Interface: r.Device.Interface}})
|
||||
found := false
|
||||
for _, candidate := range candidates {
|
||||
if candidate.Address != s.Address {
|
||||
continue
|
||||
}
|
||||
// Verify the enrolled identity before forwarding either credential.
|
||||
a := c.client(candidate)
|
||||
if r.Access != nil && r.Access.ClientAPI != nil {
|
||||
client, err := c.apiClient(candidate, *r.Access.ClientAPI)
|
||||
if err != nil || client.identity != r.Device.ID {
|
||||
continue
|
||||
}
|
||||
if _, err = client.readDevice(ctx); err != nil {
|
||||
continue
|
||||
}
|
||||
} else {
|
||||
if !a.family(ctx) || c.neighbor(candidate.Interface, candidate.Address) != r.MAC {
|
||||
continue
|
||||
}
|
||||
}
|
||||
candidate.MAC = c.neighbor(candidate.Interface, candidate.Address)
|
||||
if candidate.MAC == "" {
|
||||
continue
|
||||
}
|
||||
a = c.client(candidate)
|
||||
if s.Password != "" {
|
||||
access := &credential{Username: s.Username, Password: s.Password}
|
||||
if err := a.login(ctx, *access); err != nil {
|
||||
result.Error = "access_rejected"
|
||||
return
|
||||
}
|
||||
status, err := a.json(ctx, "dexaflow_status", nil)
|
||||
if err != nil {
|
||||
result.Error = "unsupported_response"
|
||||
return
|
||||
}
|
||||
applyInventory(&r.Device, status)
|
||||
r.WebAccess, r.WebRejected = access, false
|
||||
r.Device.WebAccess = true
|
||||
if r.Access == nil || r.Access.ClientAPI == nil {
|
||||
r.Access = access
|
||||
r.Rejected = false
|
||||
}
|
||||
}
|
||||
r.Device.Address, r.Device.Interface, r.Device.LocalIP = candidate.Address, candidate.Interface, candidate.LocalIP
|
||||
r.MAC = candidate.MAC
|
||||
c.clients[r.Device.ID] = a
|
||||
c.decorate(&r, candidate)
|
||||
found = true
|
||||
break
|
||||
}
|
||||
if !found {
|
||||
return
|
||||
}
|
||||
}
|
||||
r.Name = strings.TrimSpace(s.Name)
|
||||
r.Device.Name = r.Name
|
||||
if r.WebAccess != nil {
|
||||
r.Device.WebUsername = r.WebAccess.Username
|
||||
}
|
||||
c.state.Records[cmd.DeviceID] = r
|
||||
c.persist()
|
||||
if c.storageError {
|
||||
c.state.Records[cmd.DeviceID] = before
|
||||
delete(c.clients, cmd.DeviceID)
|
||||
result.Error = "storage_error"
|
||||
return
|
||||
}
|
||||
result.State, result.Error = "complete", ""
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func inventoryFixture(t *testing.T, board, slots string) map[string]any {
|
||||
t.Helper()
|
||||
var m map[string]any
|
||||
if json.Unmarshal([]byte(`{"slot_registry":{"board":"`+board+`","slots":`+slots+`}}`), &m) != nil {
|
||||
t.Fatal("fixture")
|
||||
}
|
||||
return m
|
||||
}
|
||||
func TestPhysicalSIMMappingUsesBoardWiringAndLiveUSBRegistry(t *testing.T) {
|
||||
d := Device{}
|
||||
applyInventory(&d, inventoryFixture(t, "bananapi,bpi-r4-pro-8x", `[{"slot":1,"usb":"4-1.4"},{"slot":2,"usb":"4-1.1"},{"slot":3,"usb":"4-1.2","physical_sim_slot":1}]`))
|
||||
if d.ModelName != "Banana Pi BPI-R4 Pro (8X)" || len(d.SlotMap) != 3 {
|
||||
t.Fatal(d)
|
||||
}
|
||||
if d.SlotMap[0].SIM != 3 || d.SlotMap[1].SIM != 1 || d.SlotMap[1].Position != "right" || d.SlotMap[2].SIM != 2 {
|
||||
t.Fatal(d.SlotMap)
|
||||
}
|
||||
// Another board instance can enumerate M IDs in a different order.
|
||||
applyInventory(&d, inventoryFixture(t, "bananapi,bpi-r4-pro-8x", `[{"slot":1,"usb":"5-2.1"},{"slot":2,"usb":"5-2.2"},{"slot":3,"usb":"5-2.4"}]`))
|
||||
if d.SlotMap[0].SIM != 1 || d.SlotMap[2].SIM != 3 {
|
||||
t.Fatal("instance mapping was hardcoded")
|
||||
}
|
||||
applyInventory(&d, inventoryFixture(t, "bananapi,bpi-r4-pro-4e", `[]`))
|
||||
if d.ModelName != "" || len(d.SlotMap) != 0 {
|
||||
t.Fatal("unknown board inherited a profile")
|
||||
}
|
||||
applyInventory(&d, inventoryFixture(t, "bananapi,bpi-r4-pro-8x", `[{"slot":1,"usb":"4-1.1"},{"slot":2,"usb":"4-1.1"},{"slot":3,"usb":"4-1.4"}]`))
|
||||
if len(d.SlotMap) != 0 {
|
||||
t.Fatal("duplicate physical SIM accepted")
|
||||
}
|
||||
}
|
||||
func TestInstanceNameAndDisconnectedIdentitySurviveRestart(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
c := Open(root)
|
||||
id := identity("02:00:00:00:00:01")
|
||||
c.state.Records[id] = record{Device: Device{ID: id, Address: "192.168.10.1", State: "unreachable"}}
|
||||
cmd := Command{ID: "op_0123456789abcdef0123456789abcdef", RuntimeID: c.runtime, DeviceID: id, Deadline: time.Now().Add(time.Minute).Unix(), Settings: &routerSettings{Name: "Rover uplink", Address: "192.168.10.1"}}
|
||||
if !validCommand(cmd) {
|
||||
t.Fatal("settings rejected")
|
||||
}
|
||||
c.configure(context.Background(), cmd)
|
||||
if c.results[cmd.ID].State != "complete" {
|
||||
t.Fatal(c.results)
|
||||
}
|
||||
reopened := Open(root)
|
||||
if reopened.state.Records[id].Name != "Rover uplink" || reopened.Snapshot().Items[0].Attached {
|
||||
t.Fatal("name or lifecycle lost")
|
||||
}
|
||||
reopened.discover = func(context.Context, []Candidate) []Candidate { return nil }
|
||||
reopened.poll(context.Background())
|
||||
if len(reopened.state.Records) != 1 || reopened.Snapshot().Items[0].Attached {
|
||||
t.Fatal("disconnection deleted identity")
|
||||
}
|
||||
cmd.Settings.Password = "secret"
|
||||
if validCommand(cmd) {
|
||||
t.Fatal("password without username")
|
||||
}
|
||||
cmd.Settings.Username = "operator"
|
||||
cmd.Settings.Address = "8.8.8.8"
|
||||
if validCommand(cmd) {
|
||||
t.Fatal("remote endpoint")
|
||||
}
|
||||
raw, _ := os.ReadFile(filepath.Join(root, "routers-v1.json"))
|
||||
if strings.Contains(string(raw), "secret") {
|
||||
t.Fatal("rejected secret persisted")
|
||||
}
|
||||
}
|
||||
func testTrafficDevice(boot string, at, count float64) Device {
|
||||
b := true
|
||||
return Device{ID: "router-test", ClientAPI: &clientPublic{BootID: boot, WAN: []clientWAN{{Slot: 2, Interface: "wwan0", Up: &b, ObservedUptime: &at, Traffic: &wanTraffic{RX: &count, TX: &count}}}}, Modems: []Modem{{Slot: 2}}}
|
||||
}
|
||||
func TestClientTrafficRatesResetOnMissingCounterBootAndDevice(t *testing.T) {
|
||||
c := Open(t.TempDir())
|
||||
d := testTrafficDevice("a", 100, 1000)
|
||||
c.rates(&d)
|
||||
if d.DownKbps != nil {
|
||||
t.Fatal("first sample invented speed")
|
||||
}
|
||||
d = testTrafficDevice("a", 110, 11000)
|
||||
c.rates(&d)
|
||||
if d.DownKbps == nil || *d.DownKbps != 8 || *d.Modems[0].UpKbps != 8 {
|
||||
t.Fatal("wrong bit rate", d)
|
||||
}
|
||||
d = testTrafficDevice("a", 120, 11000)
|
||||
c.rates(&d)
|
||||
if d.DownKbps == nil || *d.DownKbps != 0 {
|
||||
t.Fatal("real zero lost")
|
||||
}
|
||||
d = testTrafficDevice("a", 130, 100)
|
||||
c.rates(&d)
|
||||
if d.DownKbps != nil {
|
||||
t.Fatal("counter reset spike")
|
||||
}
|
||||
d = testTrafficDevice("b", 140, 100000)
|
||||
c.rates(&d)
|
||||
if d.DownKbps != nil {
|
||||
t.Fatal("reboot spike")
|
||||
}
|
||||
d = testTrafficDevice("b", 150, 110000)
|
||||
d.ClientAPI.WAN[0].Interface = "wwan2"
|
||||
c.rates(&d)
|
||||
if d.DownKbps != nil {
|
||||
t.Fatal("interface change spike")
|
||||
}
|
||||
d = testTrafficDevice("b", 160, 120000)
|
||||
d.ClientAPI.WAN[0].Traffic = nil
|
||||
c.rates(&d)
|
||||
if d.DownKbps != nil {
|
||||
t.Fatal("missing treated as zero")
|
||||
}
|
||||
d = testTrafficDevice("b", 170, 130000)
|
||||
c.rates(&d)
|
||||
if d.DownKbps != nil {
|
||||
t.Fatal("missing source retained baseline")
|
||||
}
|
||||
d = testTrafficDevice("b", 240, 140000)
|
||||
c.rates(&d)
|
||||
if d.DownKbps != nil {
|
||||
t.Fatal("long gap extrapolated")
|
||||
}
|
||||
}
|
||||
func TestClientEffectiveWANCanBeLogicalSIMIdentifier(t *testing.T) {
|
||||
caps := []byte(`{"api_version":"1","schema_version":"1.1","rights":["read"]}`)
|
||||
status := []byte(`{"boot_id":"boot","uptime":100,"revision":"r1","observed":{"active":"direct","stale":false},"effective_wan":"M2","wan":[{"slot":"M2","wan":"wan2","up":true}],"modems":[{"slot":"M2","operator":"Synthetic carrier","radio":{}}]}`)
|
||||
d, e := normalizeClientAPI(caps, status)
|
||||
if e != nil || len(d.ActiveSlots) != 1 || d.ActiveSlots[0] != 2 {
|
||||
t.Fatal("active channel lost", d, e)
|
||||
}
|
||||
if d.ModelID != "" || d.ModelName != "" {
|
||||
t.Fatal("API contract mistaken for hardware model")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGeneralWebAccessIsExplicitAndRetainsInstanceConfiguration(t *testing.T) {
|
||||
password := "synthetic-web-only-secret"
|
||||
logins := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/cgi-bin/luci/dexaflow":
|
||||
fmt.Fprint(w, loginPageFixture)
|
||||
case "/cgi-bin/dexaflow_auth":
|
||||
logins++
|
||||
r.ParseForm()
|
||||
if r.Form.Get("password") != password {
|
||||
w.WriteHeader(403)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"ok":true}`)
|
||||
case "/cgi-bin/dexaflow_status":
|
||||
fmt.Fprint(w, `{"slot_registry":{"board":"bananapi,bpi-r4-pro-8x","slots":[{"slot":2,"usb":"4-1.1"},{"slot":3,"usb":"4-1.2"},{"slot":1,"usb":"4-1.4"}]}}`)
|
||||
default:
|
||||
t.Error("unexpected router mutation", r.Method, r.URL.Path)
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
root := t.TempDir()
|
||||
c := Open(root)
|
||||
mac := "02:00:00:00:00:01"
|
||||
id := identity(mac)
|
||||
candidate := Candidate{Address: "192.168.10.1", Interface: "eth0", LocalIP: "192.168.10.2", MAC: mac}
|
||||
c.discover = func(context.Context, []Candidate) []Candidate { return []Candidate{candidate} }
|
||||
c.neighbor = func(string, string) string { return mac }
|
||||
c.client = func(Candidate) *api { return testAPI(server) }
|
||||
c.state.Records[id] = record{MAC: mac, Name: "Retained", Device: Device{ID: id, Address: candidate.Address, Interface: candidate.Interface}}
|
||||
cmd := Command{ID: "op_0123456789abcdef0123456789abcdef", DeviceID: id, Deadline: time.Now().Add(time.Minute).Unix(), Settings: &routerSettings{Name: "Owner alias", Address: candidate.Address, Username: "operator", Password: password}}
|
||||
c.configure(context.Background(), cmd)
|
||||
c.publish()
|
||||
if c.results[cmd.ID].State != "complete" || logins != 1 {
|
||||
t.Fatal(c.results, logins)
|
||||
}
|
||||
d := c.Snapshot().Items[0]
|
||||
if d.ModelName != "Banana Pi BPI-R4 Pro (8X)" || d.Name != "Owner alias" || len(d.SlotMap) != 3 {
|
||||
t.Fatal(d)
|
||||
}
|
||||
raw, _ := json.Marshal(c.Snapshot())
|
||||
if strings.Contains(string(raw), password) {
|
||||
t.Fatal("secret escaped")
|
||||
}
|
||||
reopened := Open(root)
|
||||
if reopened.state.Records[id].WebAccess.Password != password {
|
||||
t.Fatal("credentials not retained")
|
||||
}
|
||||
// A different MAC at an edited address must receive no password.
|
||||
c.neighbor = func(string, string) string { return "02:00:00:00:00:02" }
|
||||
cmd.Settings.Password = "replacement"
|
||||
cmd.Settings.Name = "Rejected change"
|
||||
c.configure(context.Background(), cmd)
|
||||
if logins != 1 || c.state.Records[id].Name != "Owner alias" {
|
||||
t.Fatal("credential sent to another identity")
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,69 @@
|
||||
{
|
||||
"schema": "missioncore.router-observation-profile/v1",
|
||||
"revision": "dexaflow-lan/3",
|
||||
"revision": "dexaflow-lan/6",
|
||||
"adapter": "dexaflow-cgi/v1",
|
||||
"discovery": "physical-private-ipv4-gateways",
|
||||
"discovery": "wired-private-ipv4-gateways",
|
||||
"poll_seconds": 10,
|
||||
"max_devices": 4,
|
||||
"journal_events": 256,
|
||||
"journal_days": 7,
|
||||
"network_changes": false,
|
||||
"router_changes": true,
|
||||
"router_actions": ["mode", "reboot"],
|
||||
"router_actions": [
|
||||
"mode",
|
||||
"reboot"
|
||||
],
|
||||
"command_replay": false,
|
||||
"credentials": "local-private-store",
|
||||
"wifi_required": false
|
||||
"wifi_required": false,
|
||||
"adapters": [
|
||||
{
|
||||
"id": "dexaflow-cgi/v1",
|
||||
"family": "DexaFlow",
|
||||
"identity": "local_mac"
|
||||
},
|
||||
{
|
||||
"id": "dexaflow-client-api/v1",
|
||||
"model_id": "bananapi.bpi-r4-pro",
|
||||
"name": "Dexaflow Client API v1",
|
||||
"class": "network-router",
|
||||
"identity": "device_ca",
|
||||
"trust": "per-instance-ca-and-token"
|
||||
}
|
||||
],
|
||||
"board_profiles": [
|
||||
{
|
||||
"board_id": "bananapi,bpi-r4-pro-8x",
|
||||
"model_id": "bananapi.bpi-r4-pro",
|
||||
"model_name": "Banana Pi BPI-R4 Pro (8X)",
|
||||
"sim_usb_ports": {
|
||||
"1": 1,
|
||||
"2": 2,
|
||||
"4": 3
|
||||
},
|
||||
"sim_positions": {
|
||||
"1": "right",
|
||||
"2": "center",
|
||||
"3": "left"
|
||||
},
|
||||
"source": "BPI-R4Pro-V1p0 assembly and schematic; USB hub port to SIM wiring"
|
||||
}
|
||||
],
|
||||
"evidence": {
|
||||
"version": 1,
|
||||
"chunk_bytes": 32768,
|
||||
"document_bytes": 2097152,
|
||||
"retention_seconds": 1200,
|
||||
"storage": "ram",
|
||||
"resources": [
|
||||
"diagnostics_latest",
|
||||
"diagnostic",
|
||||
"bundle",
|
||||
"events",
|
||||
"recovery_history",
|
||||
"recordings",
|
||||
"recording",
|
||||
"targets"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,7 +129,7 @@ func TestRedirectBodyLimitAndLocalPin(t *testing.T) {
|
||||
t.Fatal("oversize accepted")
|
||||
}
|
||||
a.check = func() bool { return false }
|
||||
if e := a.login(context.Background(), credential{"operator", "synthetic-secret"}); e != errLink || requests != 2 {
|
||||
if e := a.login(context.Background(), credential{Username: "operator", Password: "synthetic-secret"}); e != errLink || requests != 2 {
|
||||
t.Fatal("credential sent after link change")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os/exec"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type speedGrant struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
Address string `json:"address"`
|
||||
Fingerprint string `json:"fingerprint"`
|
||||
Token string `json:"token"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
ServerID string `json:"server_id"`
|
||||
}
|
||||
type Measurement struct {
|
||||
Phase string `json:"phase"`
|
||||
ServerID string `json:"server_id"`
|
||||
Interface string `json:"interface"`
|
||||
StartedAt int64 `json:"started_at"`
|
||||
FinishedAt int64 `json:"finished_at,omitempty"`
|
||||
SampledAt int64 `json:"sampled_at,omitempty"`
|
||||
CurrentBPS float64 `json:"current_bps"`
|
||||
DownloadBPS float64 `json:"download_bps"`
|
||||
UploadBPS float64 `json:"upload_bps"`
|
||||
LatencyMS float64 `json:"latency_ms"`
|
||||
JitterMS float64 `json:"jitter_ms"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func validSpeedtest(c Command) bool {
|
||||
if c.Query != nil || c.Settings != nil || c.Username != "" || c.Password != "" || c.Policy != nil || c.ClientAPI != nil || c.ModelID != "" || c.Mode != "" || c.SIM != "" || c.Recovery != "" || len(c.Slots) != 0 || c.ExpectedBootID != "" || c.ExpectedRevision != "" {
|
||||
return false
|
||||
}
|
||||
if c.Action == "speedtest_cancel" {
|
||||
return c.Speedtest == nil && operationID.MatchString(c.SpeedtestCancel)
|
||||
}
|
||||
g := c.Speedtest
|
||||
if c.Action != "speedtest" || c.SpeedtestCancel != "" || g == nil {
|
||||
return false
|
||||
}
|
||||
u, e := url.Parse(g.Endpoint)
|
||||
ip := net.ParseIP(g.Address)
|
||||
if e != nil || u.Scheme != "https" || u.User != nil || u.Hostname() == "" || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || ip == nil || ip.To4() == nil || !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
|
||||
return false
|
||||
}
|
||||
port, e := strconv.Atoi(u.Port())
|
||||
return e == nil && port >= 1024 && port <= 65535 && regexp.MustCompile(`^[a-f0-9]{64}$`).MatchString(g.Fingerprint) && regexp.MustCompile(`^[A-Za-z0-9_-]{43}$`).MatchString(g.Token) && regexp.MustCompile(`^ls_[a-f0-9]{32}$`).MatchString(g.ServerID) && g.ExpiresAt > time.Now().Unix() && g.ExpiresAt <= time.Now().Add(95*time.Second).Unix()
|
||||
}
|
||||
func speedRoute(ctx context.Context, d Device, address string) error {
|
||||
if runtime.GOOS != "linux" || d.Connection != "ethernet" || !d.Attached || !regexp.MustCompile(`^[a-zA-Z0-9_.-]{1,15}$`).MatchString(d.Interface) || net.ParseIP(d.LocalIP) == nil {
|
||||
return errors.New("ethernet_unavailable")
|
||||
}
|
||||
raw, e := exec.CommandContext(ctx, "ip", "-j", "route", "get", address, "from", d.LocalIP, "oif", d.Interface).Output()
|
||||
if e != nil || len(raw) > 8192 {
|
||||
return errors.New("ethernet_route_unavailable")
|
||||
}
|
||||
var routes []struct {
|
||||
Dev string `json:"dev"`
|
||||
Gateway string `json:"gateway"`
|
||||
Source string `json:"prefsrc"`
|
||||
}
|
||||
if json.Unmarshal(raw, &routes) != nil || len(routes) != 1 || routes[0].Dev != d.Interface || routes[0].Gateway != d.Address {
|
||||
return errors.New("ethernet_route_unavailable")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func speedClient(g speedGrant, d Device) *http.Client {
|
||||
u, _ := url.Parse(g.Endpoint)
|
||||
dial := net.Dialer{Timeout: 8 * time.Second, LocalAddr: &net.TCPAddr{IP: net.ParseIP(d.LocalIP)}, Control: func(_, _ string, c syscall.RawConn) error {
|
||||
var err error
|
||||
if runtime.GOOS != "linux" {
|
||||
return errors.New("unsupported_platform")
|
||||
}
|
||||
e := c.Control(func(fd uintptr) { err = syscall.SetsockoptString(int(fd), syscall.SOL_SOCKET, 25, d.Interface) }) // Linux SO_BINDTODEVICE; never changes host routes.
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
return err
|
||||
}}
|
||||
transport := &http.Transport{Proxy: nil, DisableCompression: true, MaxIdleConnsPerHost: 4, ResponseHeaderTimeout: 8 * time.Second, TLSHandshakeTimeout: 8 * time.Second,
|
||||
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return dial.DialContext(ctx, "tcp4", net.JoinHostPort(g.Address, u.Port()))
|
||||
},
|
||||
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS13, InsecureSkipVerify: true, VerifyConnection: func(cs tls.ConnectionState) error { // Explicit certificate pin replaces CA trust, before any HTTP secret.
|
||||
if len(cs.PeerCertificates) == 0 {
|
||||
return errors.New("certificate_rejected")
|
||||
}
|
||||
cert := cs.PeerCertificates[0]
|
||||
sum := sha256.Sum256(cert.Raw)
|
||||
if hex.EncodeToString(sum[:]) != g.Fingerprint || time.Now().Before(cert.NotBefore) || time.Now().After(cert.NotAfter) {
|
||||
return errors.New("certificate_rejected")
|
||||
}
|
||||
return nil
|
||||
}}}
|
||||
return &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect_rejected") }}
|
||||
}
|
||||
func speedRequest(ctx context.Context, client *http.Client, g speedGrant, path string, body []byte) (*http.Response, error) {
|
||||
method := "GET"
|
||||
if body != nil {
|
||||
method = "POST"
|
||||
}
|
||||
req, e := http.NewRequestWithContext(ctx, method, g.Endpoint+"/v1/test/"+path, bytes.NewReader(body))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+g.Token)
|
||||
req.Header.Set("Cache-Control", "no-store")
|
||||
response, e := client.Do(req)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if response.StatusCode != 200 {
|
||||
response.Body.Close()
|
||||
return nil, errors.New("server_rejected")
|
||||
}
|
||||
return response, nil
|
||||
}
|
||||
func measureTransfer(ctx context.Context, client *http.Client, g speedGrant, upload bool, duration time.Duration, progress func(float64)) (float64, error) {
|
||||
phase, cancel := context.WithTimeout(ctx, duration)
|
||||
defer cancel()
|
||||
var total atomic.Int64
|
||||
var failed atomic.Bool
|
||||
var workers sync.WaitGroup
|
||||
payload := make([]byte, 1024*1024)
|
||||
if _, e := rand.Read(payload); e != nil {
|
||||
return 0, e
|
||||
}
|
||||
started := time.Now()
|
||||
for range 3 {
|
||||
workers.Add(1)
|
||||
go func() {
|
||||
defer workers.Done()
|
||||
buffer := make([]byte, 65536)
|
||||
for phase.Err() == nil {
|
||||
path := "download"
|
||||
var body []byte
|
||||
if upload {
|
||||
path = "upload"
|
||||
body = payload
|
||||
}
|
||||
response, e := speedRequest(phase, client, g, path, body)
|
||||
if e != nil {
|
||||
if phase.Err() == nil {
|
||||
failed.Store(true)
|
||||
}
|
||||
return
|
||||
}
|
||||
for {
|
||||
n, readErr := response.Body.Read(buffer)
|
||||
if !upload {
|
||||
total.Add(int64(n))
|
||||
}
|
||||
if readErr != nil {
|
||||
if readErr != io.EOF && phase.Err() == nil {
|
||||
failed.Store(true)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
response.Body.Close()
|
||||
if upload && phase.Err() == nil {
|
||||
total.Add(int64(len(payload)))
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
done := make(chan struct{})
|
||||
go func() { workers.Wait(); close(done) }()
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
waiting := true
|
||||
for waiting {
|
||||
select {
|
||||
case <-done:
|
||||
waiting = false
|
||||
case <-ticker.C:
|
||||
if progress != nil && phase.Err() == nil {
|
||||
progress(float64(total.Load()) * 8 / time.Since(started).Seconds())
|
||||
}
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return 0, ctx.Err()
|
||||
}
|
||||
if total.Load() == 0 || failed.Load() {
|
||||
return 0, errors.New("transfer_failed")
|
||||
}
|
||||
return float64(total.Load()) * 8 / time.Since(started).Seconds(), nil
|
||||
}
|
||||
func (c *Collector) runSpeedtest(ctx context.Context, cmd Command) {
|
||||
if cmd.Action == "speedtest_cancel" {
|
||||
c.mu.Lock()
|
||||
if c.speedOperation == cmd.SpeedtestCancel && c.speedDevice == cmd.DeviceID && c.speedCancel != nil {
|
||||
c.speedCancel()
|
||||
}
|
||||
if _, exists := c.results[cmd.SpeedtestCancel]; !exists {
|
||||
c.results[cmd.SpeedtestCancel] = Result{ID: cmd.SpeedtestCancel, DeviceID: cmd.DeviceID, Action: "speedtest", State: "complete", At: time.Now().Unix()}
|
||||
c.resultTimes[cmd.SpeedtestCancel] = time.Now()
|
||||
}
|
||||
c.results[cmd.ID] = Result{ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: "complete", At: time.Now().Unix()}
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
record, ok := c.state.Records[cmd.DeviceID]
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
if c.speedCancel != nil {
|
||||
c.results[cmd.ID] = Result{ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: "error", Error: "router_busy"}
|
||||
c.mu.Unlock()
|
||||
return
|
||||
}
|
||||
deadline := min(cmd.Deadline, cmd.Speedtest.ExpiresAt)
|
||||
test, cancel := context.WithDeadline(ctx, time.Unix(deadline, 0))
|
||||
c.speedCancel = cancel
|
||||
c.speedOperation = cmd.ID
|
||||
c.speedDevice = cmd.DeviceID
|
||||
c.mu.Unlock()
|
||||
go func() {
|
||||
defer cancel()
|
||||
m := Measurement{Phase: "latency", ServerID: cmd.Speedtest.ServerID, Interface: record.Device.Interface, StartedAt: time.Now().Unix()}
|
||||
report := func(state string) {
|
||||
copy := m
|
||||
c.mu.Lock()
|
||||
c.results[cmd.ID] = Result{ID: cmd.ID, DeviceID: cmd.DeviceID, Action: cmd.Action, State: state, At: time.Now().Unix(), Measurement: ©}
|
||||
c.mu.Unlock()
|
||||
select {
|
||||
case c.speedUpdates <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
progress := func(bps float64) { m.CurrentBPS = bps; m.SampledAt = time.Now().UnixMilli(); report("applying") }
|
||||
report("applying")
|
||||
e := speedRoute(test, record.Device, cmd.Speedtest.Address)
|
||||
if e == nil {
|
||||
client := speedClient(*cmd.Speedtest, record.Device)
|
||||
defer func() {
|
||||
cleanup, cancelCleanup := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancelCleanup()
|
||||
r, err := speedRequest(cleanup, client, *cmd.Speedtest, "finish", []byte{})
|
||||
if err == nil {
|
||||
r.Body.Close()
|
||||
}
|
||||
}()
|
||||
defer client.CloseIdleConnections()
|
||||
var sum, jitter, previous float64
|
||||
for i := 0; i < 7; i++ {
|
||||
started := time.Now()
|
||||
var response *http.Response
|
||||
response, e = speedRequest(test, client, *cmd.Speedtest, "ping", nil)
|
||||
if e != nil {
|
||||
break
|
||||
}
|
||||
_, e = io.Copy(io.Discard, io.LimitReader(response.Body, 4096))
|
||||
response.Body.Close()
|
||||
if e != nil {
|
||||
break
|
||||
}
|
||||
ms := float64(time.Since(started).Microseconds()) / 1000
|
||||
sum += ms
|
||||
if i > 0 {
|
||||
jitter += math.Abs(ms - previous)
|
||||
}
|
||||
previous = ms
|
||||
}
|
||||
if e == nil {
|
||||
m.LatencyMS = sum / 7
|
||||
m.JitterMS = jitter / 6
|
||||
m.Phase = "download"
|
||||
report("applying")
|
||||
m.DownloadBPS, e = measureTransfer(test, client, *cmd.Speedtest, false, 10*time.Second, progress)
|
||||
}
|
||||
if e == nil {
|
||||
m.Phase = "upload"
|
||||
m.CurrentBPS = 0
|
||||
m.SampledAt = 0
|
||||
report("applying")
|
||||
m.UploadBPS, e = measureTransfer(test, client, *cmd.Speedtest, true, 10*time.Second, progress)
|
||||
}
|
||||
if e == nil {
|
||||
e = speedRoute(test, record.Device, cmd.Speedtest.Address)
|
||||
}
|
||||
}
|
||||
m.FinishedAt = time.Now().Unix()
|
||||
m.Phase = "complete"
|
||||
if e != nil {
|
||||
m.Phase = "error"
|
||||
m.Error = "measurement_failed"
|
||||
if test.Err() == context.Canceled {
|
||||
m.Phase = "cancelled"
|
||||
m.Error = ""
|
||||
} else if e.Error() == "ethernet_route_unavailable" || e.Error() == "ethernet_unavailable" {
|
||||
m.Error = e.Error()
|
||||
}
|
||||
}
|
||||
report("complete")
|
||||
c.mu.Lock()
|
||||
c.speedCancel = nil
|
||||
c.mu.Unlock()
|
||||
}()
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package routers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestSpeedGrantRejectsPrivateDestinationsAndMixedControls(t *testing.T) {
|
||||
c := Command{Action: "speedtest", Speedtest: &speedGrant{Endpoint: "https://example.com:19445", Address: "130.49.172.182", Fingerprint: strings.Repeat("a", 64), Token: strings.Repeat("b", 43), ServerID: "ls_" + strings.Repeat("c", 32), ExpiresAt: time.Now().Add(time.Minute).Unix()}}
|
||||
if !validCommand(c) {
|
||||
t.Fatal("valid grant rejected")
|
||||
}
|
||||
c.Speedtest.Address = "192.168.1.1"
|
||||
if validCommand(c) {
|
||||
t.Fatal("private destination accepted")
|
||||
}
|
||||
c.Speedtest.Address = "130.49.172.182"
|
||||
c.Speedtest.Endpoint = "https://user:password@example.com:19445"
|
||||
if validCommand(c) {
|
||||
t.Fatal("credentials in endpoint accepted")
|
||||
}
|
||||
c.Speedtest.Endpoint = "https://example.com:19445"
|
||||
c.Mode = "aggregation"
|
||||
if validCommand(c) {
|
||||
t.Fatal("mixed operation accepted")
|
||||
}
|
||||
}
|
||||
func TestTransferCountsBytesAndCancellationDoesNotProduceResult(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer test" {
|
||||
w.WriteHeader(403)
|
||||
return
|
||||
}
|
||||
if r.Method == "POST" {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
} else {
|
||||
w.Write(make([]byte, 65536))
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
g := speedGrant{Endpoint: server.URL, Token: "test"}
|
||||
for _, upload := range []bool{false, true} {
|
||||
bps, e := measureTransfer(context.Background(), server.Client(), g, upload, 80*time.Millisecond, nil)
|
||||
if e != nil || bps <= 0 {
|
||||
t.Fatalf("no measured bytes upload=%v: %v", upload, e)
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
bps, e := measureTransfer(ctx, server.Client(), g, false, time.Second, nil)
|
||||
if e == nil || bps != 0 {
|
||||
t.Fatal("cancelled transfer presented as measurement")
|
||||
}
|
||||
}
|
||||
func TestTransferRejectsUnauthorizedService(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(403) }))
|
||||
defer server.Close()
|
||||
bps, e := measureTransfer(context.Background(), server.Client(), speedGrant{Endpoint: server.URL}, false, time.Second, nil)
|
||||
if e == nil || bps != 0 {
|
||||
t.Fatal("unauthorized response counted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMeasuredProgressArrivesBeforeCompletion(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write(make([]byte, 65536)) }))
|
||||
defer server.Close()
|
||||
count := 0
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
_, e := measureTransfer(ctx, server.Client(), speedGrant{Endpoint: server.URL}, false, 3*time.Second, func(bps float64) {
|
||||
if bps <= 0 {
|
||||
t.Error("progress had no measured bytes")
|
||||
}
|
||||
count++
|
||||
cancel()
|
||||
})
|
||||
if count != 1 || e != context.Canceled {
|
||||
t.Fatalf("progress/cancel: %d %v", count, e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package routers
|
||||
|
||||
// Counter deltas belong on Node, using the router boot and uptime clock.
|
||||
// Samples remain bounded in RAM; restart, missing source, netdev or session
|
||||
// changes reset the baseline instead of fabricating a spike or a zero.
|
||||
type wanTraffic struct {
|
||||
RX *float64 `json:"rx_bytes"`
|
||||
TX *float64 `json:"tx_bytes"`
|
||||
RXPackets *float64 `json:"rx_packets"`
|
||||
TXPackets *float64 `json:"tx_packets"`
|
||||
RXErrors *float64 `json:"rx_errors"`
|
||||
TXErrors *float64 `json:"tx_errors"`
|
||||
RXDropped *float64 `json:"rx_dropped"`
|
||||
TXDropped *float64 `json:"tx_dropped"`
|
||||
}
|
||||
|
||||
func readTraffic(raw any) *wanTraffic {
|
||||
t := object(raw)
|
||||
if t == nil {
|
||||
return nil
|
||||
}
|
||||
n := func(k string) *float64 { return number(t[k], 0, 9007199254740991) }
|
||||
return &wanTraffic{n("rx_bytes"), n("tx_bytes"), n("rx_packets"), n("tx_packets"), n("rx_errors"), n("tx_errors"), n("rx_dropped"), n("tx_dropped")}
|
||||
}
|
||||
|
||||
type trafficSample struct {
|
||||
boot string
|
||||
wan []clientWAN
|
||||
}
|
||||
|
||||
func counterRate(current, old *float64, elapsed float64) *float64 {
|
||||
if current == nil || old == nil || *current < *old || elapsed <= 0 || elapsed > 60 {
|
||||
return nil
|
||||
}
|
||||
return number((*current-*old)*8/elapsed/1000, 0, 1e9)
|
||||
}
|
||||
func (c *Collector) rates(d *Device) {
|
||||
if d.ClientAPI == nil {
|
||||
return
|
||||
}
|
||||
previous, ok := c.traffic[d.ID]
|
||||
c.traffic[d.ID] = trafficSample{d.ClientAPI.BootID, d.ClientAPI.WAN}
|
||||
if !ok || previous.boot != d.ClientAPI.BootID {
|
||||
return
|
||||
}
|
||||
count := 0
|
||||
down, up := float64(0), float64(0)
|
||||
allDown, allUp := true, true
|
||||
for i := range d.Modems {
|
||||
m := &d.Modems[i]
|
||||
var current, old *clientWAN
|
||||
for j := range d.ClientAPI.WAN {
|
||||
if d.ClientAPI.WAN[j].Slot == m.Slot {
|
||||
current = &d.ClientAPI.WAN[j]
|
||||
}
|
||||
}
|
||||
for j := range previous.wan {
|
||||
if previous.wan[j].Slot == m.Slot {
|
||||
old = &previous.wan[j]
|
||||
}
|
||||
}
|
||||
if current == nil || current.Up == nil || !*current.Up {
|
||||
continue
|
||||
}
|
||||
count++
|
||||
valid := old != nil && old.Up != nil && *old.Up && current.Interface != "" && current.Interface == old.Interface && current.Traffic != nil && old.Traffic != nil && current.ObservedUptime != nil && old.ObservedUptime != nil
|
||||
if valid && current.SessionUptime != nil && old.SessionUptime != nil && *current.SessionUptime < *old.SessionUptime {
|
||||
valid = false
|
||||
}
|
||||
if valid {
|
||||
elapsed := *current.ObservedUptime - *old.ObservedUptime
|
||||
m.DownKbps = counterRate(current.Traffic.RX, old.Traffic.RX, elapsed)
|
||||
m.UpKbps = counterRate(current.Traffic.TX, old.Traffic.TX, elapsed)
|
||||
}
|
||||
if m.DownKbps == nil {
|
||||
allDown = false
|
||||
} else {
|
||||
down += *m.DownKbps
|
||||
}
|
||||
if m.UpKbps == nil {
|
||||
allUp = false
|
||||
} else {
|
||||
up += *m.UpKbps
|
||||
}
|
||||
}
|
||||
if count > 0 && allDown {
|
||||
d.DownKbps = number(down, 0, 1e9)
|
||||
}
|
||||
if count > 0 && allUp {
|
||||
d.UpKbps = number(up, 0, 1e9)
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,9 @@ const maxEvents = 256
|
||||
const retention = 7 * 24 * time.Hour
|
||||
|
||||
type Modem struct {
|
||||
RadioAge *float64 `json:"radio_age_seconds"`
|
||||
EARFCN *float64 `json:"earfcn"`
|
||||
TAC string `json:"tac"`
|
||||
Slot int `json:"slot"`
|
||||
Operator string `json:"operator"`
|
||||
Connectivity string `json:"connectivity"`
|
||||
@@ -28,31 +31,48 @@ type Modem struct {
|
||||
UpKbps *float64 `json:"up_kbps"`
|
||||
}
|
||||
|
||||
type SlotBinding struct {
|
||||
Slot int `json:"slot"`
|
||||
SIM int `json:"sim"`
|
||||
Position string `json:"position"`
|
||||
}
|
||||
type Device struct {
|
||||
ID string `json:"id"`
|
||||
Family string `json:"family"`
|
||||
Identity string `json:"identity"`
|
||||
Address string `json:"address"`
|
||||
Interface string `json:"interface"`
|
||||
LocalIP string `json:"local_ip"`
|
||||
State string `json:"state"`
|
||||
ObservedAt int64 `json:"observed_at"`
|
||||
Firmware string `json:"firmware"`
|
||||
Uptime *float64 `json:"uptime"`
|
||||
SelectedMode string `json:"selected_mode"`
|
||||
ActiveMode string `json:"active_mode"`
|
||||
PersistedMode string `json:"persisted_mode"`
|
||||
RebootResets *bool `json:"reboot_resets"`
|
||||
ManualMode string `json:"manual_mode"`
|
||||
ActiveSlots []int `json:"active_slots"`
|
||||
ActiveWAN string `json:"active_wan"`
|
||||
Internet string `json:"internet"`
|
||||
PublicIP string `json:"public_ip"`
|
||||
VPSUp *bool `json:"vps_up"`
|
||||
RTT *float64 `json:"rtt_ms"`
|
||||
DownKbps *float64 `json:"down_kbps"`
|
||||
UpKbps *float64 `json:"up_kbps"`
|
||||
Modems []Modem `json:"modems"`
|
||||
Name string `json:"name"`
|
||||
ModelName string `json:"model_name"`
|
||||
BoardID string `json:"board_id"`
|
||||
SlotMap []SlotBinding `json:"slot_map"`
|
||||
Attached bool `json:"attached"`
|
||||
Connection string `json:"connection"`
|
||||
WebAccess bool `json:"web_access"`
|
||||
WebUsername string `json:"web_username"`
|
||||
|
||||
ModelID string `json:"model_id,omitempty"`
|
||||
Adapter string `json:"adapter,omitempty"`
|
||||
ClientAPI *clientPublic `json:"client_api,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Family string `json:"family"`
|
||||
Identity string `json:"identity"`
|
||||
Address string `json:"address"`
|
||||
Interface string `json:"interface"`
|
||||
LocalIP string `json:"local_ip"`
|
||||
State string `json:"state"`
|
||||
ObservedAt int64 `json:"observed_at"`
|
||||
Firmware string `json:"firmware"`
|
||||
Uptime *float64 `json:"uptime"`
|
||||
SelectedMode string `json:"selected_mode"`
|
||||
ActiveMode string `json:"active_mode"`
|
||||
PersistedMode string `json:"persisted_mode"`
|
||||
RebootResets *bool `json:"reboot_resets"`
|
||||
ManualMode string `json:"manual_mode"`
|
||||
ActiveSlots []int `json:"active_slots"`
|
||||
ActiveWAN string `json:"active_wan"`
|
||||
Internet string `json:"internet"`
|
||||
PublicIP string `json:"public_ip"`
|
||||
VPSUp *bool `json:"vps_up"`
|
||||
RTT *float64 `json:"rtt_ms"`
|
||||
DownKbps *float64 `json:"down_kbps"`
|
||||
UpKbps *float64 `json:"up_kbps"`
|
||||
Modems []Modem `json:"modems"`
|
||||
}
|
||||
|
||||
type Event struct {
|
||||
@@ -75,40 +95,65 @@ type Journal struct {
|
||||
Error bool `json:"error"`
|
||||
}
|
||||
type Result struct {
|
||||
DeviceID string `json:"device_id,omitempty"`
|
||||
Action string `json:"action,omitempty"`
|
||||
ID string `json:"operation_id"`
|
||||
State string `json:"state"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Measurement *Measurement `json:"measurement,omitempty"`
|
||||
At int64 `json:"at,omitempty"`
|
||||
VendorID string `json:"vendor_id,omitempty"`
|
||||
DeviceID string `json:"device_id,omitempty"`
|
||||
Action string `json:"action,omitempty"`
|
||||
ID string `json:"operation_id"`
|
||||
State string `json:"state"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
type Snapshot struct {
|
||||
ControlVersion int `json:"control_version"`
|
||||
Schema string `json:"schema"`
|
||||
RuntimeID string `json:"runtime_id"`
|
||||
Available bool `json:"available"`
|
||||
ObservedAt int64 `json:"observed_at"`
|
||||
Items []Device `json:"items"`
|
||||
Events []Event `json:"events"`
|
||||
Journal Journal `json:"journal"`
|
||||
Results []Result `json:"results"`
|
||||
SpeedtestVersion int `json:"speedtest_version"`
|
||||
ReadVersion int `json:"read_version"`
|
||||
Evidence *EvidenceChunk `json:"evidence,omitempty"`
|
||||
ControlVersion int `json:"control_version"`
|
||||
Schema string `json:"schema"`
|
||||
RuntimeID string `json:"runtime_id"`
|
||||
Available bool `json:"available"`
|
||||
ObservedAt int64 `json:"observed_at"`
|
||||
Items []Device `json:"items"`
|
||||
Events []Event `json:"events"`
|
||||
Journal Journal `json:"journal"`
|
||||
Results []Result `json:"results"`
|
||||
}
|
||||
type Command struct {
|
||||
Action string `json:"action,omitempty"`
|
||||
Mode string `json:"mode,omitempty"`
|
||||
Slots []int `json:"slots,omitempty"`
|
||||
ID string `json:"operation_id"`
|
||||
RuntimeID string `json:"runtime_id"`
|
||||
DeviceID string `json:"device_id"`
|
||||
Deadline int64 `json:"deadline"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Speedtest *speedGrant `json:"speedtest,omitempty"`
|
||||
SpeedtestCancel string `json:"speedtest_cancel,omitempty"`
|
||||
Query *EvidenceQuery `json:"query,omitempty"`
|
||||
Settings *routerSettings `json:"settings,omitempty"`
|
||||
|
||||
ExpectedBootID string `json:"expected_boot_id,omitempty"`
|
||||
ExpectedRevision string `json:"expected_revision,omitempty"`
|
||||
ClientAPI *clientAPIAccess `json:"client_api,omitempty"`
|
||||
ModelID string `json:"model_id,omitempty"`
|
||||
Policy *clientPolicy `json:"policy,omitempty"`
|
||||
Recovery string `json:"recovery,omitempty"`
|
||||
SIM string `json:"sim,omitempty"`
|
||||
Action string `json:"action,omitempty"`
|
||||
Mode string `json:"mode,omitempty"`
|
||||
Slots []int `json:"slots,omitempty"`
|
||||
ID string `json:"operation_id"`
|
||||
RuntimeID string `json:"runtime_id"`
|
||||
DeviceID string `json:"device_id"`
|
||||
Deadline int64 `json:"deadline"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// Candidate is obtained solely from the physical, directly connected LAN.
|
||||
// MAC is a local pin, not a cryptographic assertion about the manufacturer.
|
||||
type Candidate struct{ Address, Interface, LocalIP, MAC string }
|
||||
type credential struct{ Username, Password string }
|
||||
type credential struct {
|
||||
Username, Password string
|
||||
ClientAPI *clientAPIAccess
|
||||
}
|
||||
type record struct {
|
||||
Name string
|
||||
WebAccess *credential
|
||||
WebRejected bool
|
||||
|
||||
Device Device
|
||||
MAC string
|
||||
Access *credential
|
||||
|
||||
Reference in New Issue
Block a user