Files
cantabile-ha-addons/src/edge/link/main_test.go
T

290 lines
10 KiB
Go

// Copyright © 2026 Setti Solutions S.R.L, www.setti.md. All rights reserved.
package main
import (
"bufio"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/nats-io/nkeys"
)
func TestWithPort(t *testing.T) {
for in, want := range map[string]string{
"wss://devices.cantabile.cloud/nats": "wss://devices.cantabile.cloud:443/nats",
"wss://devices.cantabile.cloud:443/nats": "wss://devices.cantabile.cloud:443/nats",
"ws://192.0.2.1/nats": "ws://192.0.2.1:80/nats",
"nats://nats:4222": "nats://nats:4222",
} {
if got := withPort(in); got != want {
t.Errorf("%s: %s, want %s", in, got, want)
}
}
}
func TestSiteIDFromHA(t *testing.T) {
d := t.TempDir()
p := filepath.Join(d, "core.uuid")
os.WriteFile(p, []byte(`{"version":1,"key":"core.uuid","data":{"uuid":"8B7C0F9E5A1D4C2B9E3F0A1B2C3D4E5F"}}`), 0o600)
id, err := siteID(config{HAUUID: p})
if err != nil || !siteIDRE.MatchString(id) {
t.Fatalf("%q %v", id, err)
}
// case does not matter; the raw uuid never shows
os.WriteFile(p, []byte(`{"data":{"uuid":"8b7c0f9e5a1d4c2b9e3f0a1b2c3d4e5f"}}`), 0o600)
if id2, _ := siteID(config{HAUUID: p}); id2 != id || strings.Contains(id, "8b7c0f9e") {
t.Errorf("%s %s", id, id2)
}
if _, err := siteID(config{SiteID: "nothex"}); err == nil {
t.Error("bad CANTABILE_SITE_ID taken")
}
}
func TestSolve(t *testing.T) {
var ch challenge
ch.Challenge, ch.Bits = "abc", 4
ch.Scrypt.N, ch.Scrypt.R, ch.Scrypt.P, ch.Scrypt.Len, ch.Scrypt.Salt = 1024, 8, 1, 32, "s"
n := solve(ch)
if n < 0 {
t.Fatal(n)
}
}
func signed(t *testing.T, k *ecdsa.PrivateKey, c command) []byte {
p, _ := json.Marshal(c)
sum := sha256.Sum256(p)
sig, err := ecdsa.SignASN1(rand.Reader, k, sum[:])
if err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(map[string]string{"p": base64.StdEncoding.EncodeToString(p), "sig": base64.StdEncoding.EncodeToString(sig)})
return b
}
func TestCheckCommand(t *testing.T) {
k, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
other, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
site := strings.Repeat("ab", 16)
now := time.Now()
good := command{V: 1, ID: "c1", Box: site, Cmd: "refresh", Expires: now.Add(time.Hour).Unix()}
if _, err := checkCommand(&k.PublicKey, site, signed(t, k, good), now); err != nil {
t.Errorf("good: %v", err)
}
if _, err := checkCommand(&k.PublicKey, site, signed(t, other, good), now); err == nil || err.Error() != "bad signature" {
t.Errorf("other key: %v", err)
}
wrong := good
wrong.Box = strings.Repeat("cd", 16)
if _, err := checkCommand(&k.PublicKey, site, signed(t, k, wrong), now); err == nil || err.Error() != "not for this site" {
t.Errorf("other site: %v", err)
}
old := good
old.Expires = now.Add(-time.Minute).Unix()
if _, err := checkCommand(&k.PublicKey, site, signed(t, k, old), now); err == nil || err.Error() != "expired" {
t.Errorf("expired: %v", err)
}
// a changed payload under the old signature
var w map[string]string
json.Unmarshal(signed(t, k, good), &w)
p, _ := json.Marshal(command{V: 1, ID: "c1", Box: site, Cmd: "mode", Expires: good.Expires})
w["p"] = base64.StdEncoding.EncodeToString(p)
b, _ := json.Marshal(w)
if _, err := checkCommand(&k.PublicKey, site, b, now); err == nil {
t.Error("tampered payload taken")
}
}
func TestDoneOnce(t *testing.T) {
l := &link{cfg: config{State: t.TempDir()}}
l.remember("c1", map[string]any{"ok": true})
if r, ok := l.done("c1"); !ok || r["ok"] != true {
t.Errorf("%v %v", r, ok)
}
for i := 0; i < 205; i++ {
l.remember(strings.Repeat("x", i+1), map[string]any{"ok": true})
}
var d map[string]any
b, _ := os.ReadFile(filepath.Join(l.cfg.State, "done.json"))
json.Unmarshal(b, &d)
if len(d) != 200 {
t.Errorf("kept %d", len(d))
}
}
// The local socket: hello, telemetry without a connection (not stored, so
// no acknowledgement), and a command answered by the agent.
func TestLocalSocket(t *testing.T) {
l := &link{id: strings.Repeat("ab", 16)}
p := filepath.Join(t.TempDir(), "link.sock")
lc, err := listen(l, p)
if err != nil {
t.Fatal(err)
}
defer lc.close()
l.loc = lc
c, err := net.Dial("unix", p)
if err != nil {
t.Fatal(err)
}
defer c.Close()
r := bufio.NewScanner(c)
read := func() msg {
c.SetReadDeadline(time.Now().Add(5 * time.Second))
if !r.Scan() {
t.Fatal("no answer")
}
var m msg
json.Unmarshal(r.Bytes(), &m)
return m
}
c.Write([]byte(`{"op":"hello"}` + "\n"))
if m := read(); m.Site != l.id {
t.Errorf("hello: %+v", m)
}
c.Write([]byte(`{"op":"tel","id":7,"msg_id":"x:1","data":{"a":1}}` + "\n"))
if m := read(); m.Op != "ack" || m.OK == nil || *m.OK || string(m.ID) != "7" {
t.Errorf("tel without connection: %+v", m)
}
for i := 0; i < 50 && !lc.connected(); i++ {
time.Sleep(10 * time.Millisecond)
}
done := make(chan [2]any, 1)
go func() {
ok, m := lc.command(command{ID: "c9", Cmd: "mode", Args: map[string]string{"mode": "shadow"}}, 5*time.Second)
done <- [2]any{ok, m}
}()
m := read()
if m.Op != "command" || m.Cmd != "mode" || m.Args["mode"] != "shadow" {
t.Fatalf("command: %+v", m)
}
c.Write([]byte(`{"op":"result","id":"c9","ok":true,"message":"already shadow"}` + "\n"))
if got := <-done; got[0] != true || got[1] != "already shadow" {
t.Errorf("result: %v", got)
}
}
// TestEnrolClaim: the claim code goes with the enrolment; a refusal for the
// code is errClaim and noted for the panel, cleared once enrolled.
func TestEnrolClaim(t *testing.T) {
var sent string
refuse := true
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/devices/challenge" {
w.Write([]byte(`{"challenge":"c","bits":0,"scrypt":{"n":2,"r":1,"p":1,"len":8,"salt":"s"}}`))
return
}
var in struct{ Claim string }
json.NewDecoder(r.Body).Decode(&in)
sent = in.Claim
if refuse {
w.WriteHeader(403)
w.Write([]byte(`{"error":"claim code required"}`))
return
}
w.Write([]byte(`{"box":"x","jwt":"j","nats":"wss://n","renew_after":60}`))
}))
defer srv.Close()
dir := t.TempDir()
kp, _ := nkeys.CreateUser()
l := &link{cfg: config{URL: srv.URL, State: dir, Claim: filepath.Join(dir, "claim-code")}, kp: kp, id: "x"}
if err := l.enrol(); !errors.Is(err, errClaim) || sent != "" {
t.Fatalf("no code: %v, sent %q", err, sent)
}
if b, _ := os.ReadFile(filepath.Join(dir, "enrol-refused")); string(b) != "claim code required\n" {
t.Fatalf("state %q", b)
}
os.WriteFile(l.cfg.Claim, []byte("ABCD-EFGH-JKLM\n"), 0o600)
refuse = false
if err := l.enrol(); err != nil || sent != "ABCD-EFGH-JKLM" {
t.Fatalf("with code: %v, sent %q", err, sent)
}
if _, err := os.Stat(filepath.Join(dir, "enrol-refused")); !os.IsNotExist(err) {
t.Fatal("refusal still noted")
}
}
// Before cantabile-update's first check after a boot there is no
// update.json: the reports say "not-checked", not null; after it, its state.
func TestUpdateState(t *testing.T) {
p := filepath.Join(t.TempDir(), "update.json")
if st, av := updateState(p); st != "not-checked" || av != nil {
t.Errorf("no file: %v, %v", st, av)
}
os.WriteFile(p, []byte(`{"state": "up-to-date", "available": "0.1.0-dev.20"}`), 0o644)
if st, av := updateState(p); st != "up-to-date" || av != "0.1.0-dev.20" {
t.Errorf("after a check: %v, %v", st, av)
}
}
// The owner's consents as the heartbeat carries them: what, and how and
// when it was given (the HA add-on's configuration at installation).
func TestConsentsCarrySourceAndVersion(t *testing.T) {
p := filepath.Join(t.TempDir(), "consent.json")
os.WriteFile(p, []byte(`{"share": true, "control": false, "at": 1767000000, "by": "ha-addon-config",
"source": "given at installation in the add-on's configuration", "text_version": "working-2026-10-29",
"recipients": {"building": {"granted": true}, "grid": {"granted": false}},
"addons": {"modbus-bridge": {"granted": true, "control": true, "text_version": "working-2026-10-29"}}}`), 0o600)
c := consents(p)
if c["share"] != true || c["control"] != false || c["at"] != int64(1767000000) || c["by"] != "ha-addon-config" ||
c["text_version"] != "working-2026-10-29" || !strings.Contains(c["source"].(string), "installation") {
t.Fatalf("consents: %v", c)
}
if a := c["addons"].(map[string]map[string]any)["modbus-bridge"]; a["granted"] != true || a["control"] != true {
t.Fatalf("addons: %v", c["addons"])
}
if r := c["recipients"].([]string); len(r) != 1 || r[0] != "building" {
t.Fatalf("recipients: %v", r)
}
if c := consents(filepath.Join(t.TempDir(), "none.json")); c["share"] != false || c["at"] != nil || c["by"] != nil {
t.Fatalf("no file: %v", c)
}
}
// The site's weather cell (the agent's site_cell.json) goes into the
// heartbeat only with the share consent, rounded to 0.1°, on a Hub too;
// a missing or bad file: no cell.
func TestHeartbeatCell(t *testing.T) {
for _, hub := range []string{"0", "1"} {
t.Setenv("CANTABILE_HUB", hub)
dir := t.TempDir()
cons := filepath.Join(dir, "consent.json")
t.Setenv("CANTABILE_CONSENT_FILE", cons)
l := &link{cfg: config{AgentState: dir}, loc: &local{}}
cell := filepath.Join(dir, "site_cell.json")
os.WriteFile(cell, []byte(`{"lat": 47.0234, "lon": 28.86}`), 0o644)
os.WriteFile(cons, []byte(`{"share": true}`), 0o600)
if c, ok := l.heartbeat()["cell"].([]float64); !ok || len(c) != 2 || c[0] != 47.0 || c[1] != 28.9 {
t.Fatalf("hub %s, shared: %v", hub, l.heartbeat()["cell"])
}
os.WriteFile(cons, []byte(`{"share": false, "control": true}`), 0o600)
if c, ok := l.heartbeat()["cell"]; ok {
t.Fatalf("hub %s, not shared: %v", hub, c)
}
os.WriteFile(cons, []byte(`{"share": true}`), 0o600)
for _, bad := range []string{`not json`, `{"lat": 47.0}`, `{"lat": 95, "lon": 28}`, `{"lat": 47, "lon": -181}`, `{"lat": "47", "lon": 28}`} {
os.WriteFile(cell, []byte(bad), 0o644)
if c, ok := l.heartbeat()["cell"]; ok {
t.Fatalf("hub %s, %s: %v", hub, bad, c)
}
}
os.Remove(cell)
if c, ok := l.heartbeat()["cell"]; ok {
t.Fatalf("hub %s, no file: %v", hub, c)
}
}
}