diff --git a/README.md b/README.md index cfb664f..5b831e0 100644 --- a/README.md +++ b/README.md @@ -2319,6 +2319,13 @@ Pair this computer: its TLS client key (made on first use, `client.key` and `cli next to `known_pods.json`) goes on the pod's list. Only over USB or embeddedci.com (as an organization owner or admin), never over the network. +Given the pod's network address or name (`--connection 192.168.1.164`, +`benchpod-a1b2c3` or `benchpod-a1b2c3.local`), it reads the pod's status there and, when the +pod's USB-C cable is in this computer, pairs over that pod's own USB link: no need to pick +it among several pods on USB. Otherwise it says to plug the pod in over USB-C, or to use +`--connection embeddedci:`. A computer that is paired already is told so. `remove`, +`clear` and `benchpod setup` take the USB link the same way. + | Flag | Default | Purpose | |-------------|-----------------|----------------------------------------------------------------------| | `--name` | this host name | The name the pod lists it under (1 to 23 characters). | diff --git a/cmd/benchpod-cli/lanclients.go b/cmd/benchpod-cli/lanclients.go index 699c39e..75b086e 100644 --- a/cmd/benchpod-cli/lanclients.go +++ b/cmd/benchpod-cli/lanclients.go @@ -141,6 +141,11 @@ func runLanClients(g *globalFlags, o lanClientsOp, out io.Writer) error { } else { v, label, err = lanClientsNetwork(g, o, key) } + if errors.Is(err, errAlreadyPaired) { + fmt.Fprintf(out, "This computer (%s) is already paired with the pod at %s.\n", o.name, label) + printLanClients(out, label, v, "") + return nil + } if err != nil { return err } @@ -217,6 +222,26 @@ func lanClientsNetwork(g *globalFlags, o lanClientsOp, key string) (lanClientsVi return lanClientsView{}, "", err } defer cancel() + // A LAN address: changes, and a list this computer may not read, go over the pod's USB link. + lanAddr := "" + if t.spec.IsNetwork() && !isUSBLinkAddr(t.spec.Addr) { + usb, err := lanClientsRoute(ctx, t.spec.Addr, o) + if errors.Is(err, errAlreadyPaired) { + v, err := lanClientsAll(ctx, t.client, map[string]any{"cmd": "lan_clients"}) + if err != nil { + return lanClientsView{}, "", fmt.Errorf("lan-clients: %w", err) + } + return v, t.label, errAlreadyPaired + } + if err != nil { + return lanClientsView{}, "", err + } + if usb != "" { + lanAddr = t.spec.Addr + t = &podTarget{spec: ConnSpec{Kind: connNetwork, Addr: usb}, client: &tcpclient.Client{Addr: usb}, + label: t.spec.Addr + " (over its USB link " + hostOf(usb) + ")"} + } + } req := map[string]any{"cmd": "lan_clients"} switch o.op { case "add": @@ -233,6 +258,9 @@ func lanClientsNetwork(g *globalFlags, o lanClientsOp, key string) (lanClientsVi } return lanClientsView{}, "", fmt.Errorf("lan-clients: %w", err) } + if lanAddr != "" && o.op == "add" { + pinLanCertOverUSBLink(ctx, t.spec.Addr, lanAddr) + } return v, t.label, nil } diff --git a/cmd/benchpod-cli/pair_usblink.go b/cmd/benchpod-cli/pair_usblink.go new file mode 100644 index 0000000..7af2388 --- /dev/null +++ b/cmd/benchpod-cli/pair_usblink.go @@ -0,0 +1,176 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "strings" + "time" + + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" +) + +// Pairing through the pod's USB link when the connection is a LAN address. +// +// A computer that is not paired still gets `status` over the LAN, and its reply carries the pod's +// own USB network address (`usb.ip`, 10.237.x.y) when the pod's USB-C cable is in a computer. That +// address is unique per pod and only answers from the computer the cable is in, and the pod +// trusts the USB link, so `lan_clients` changes work there. So `lan-clients add --connection +// 192.168.1.164` (or a pod name, or a .local name) pairs the right pod even with several pods on +// USB, without asking which. + +// lanPodState is what a pod's status says about pairing and its USB link. +type lanPodState struct { + known bool // the pod has LAN pairing (firmware 4.0.1+) and status answered + pairing bool // pairing is on + paired *bool // this computer is paired; nil when the connection needs no pairing + usbIP string // the pod's address on its USB link, "" when the link is down +} + +// readLanPodState reads status at addr. known is false when status does not answer or the +// firmware has no pairing. +func readLanPodState(ctx context.Context, addr string) lanPodState { + data, err := (&tcpclient.Client{Addr: addr}).Command(ctx, map[string]any{"cmd": "status", "caps": false}) + if err != nil { + return lanPodState{} + } + var st struct { + Pairing *bool `json:"lan_pairing"` + Paired *bool `json:"lan_paired"` + USB *struct { + Link bool `json:"link"` + IP string `json:"ip"` + } `json:"usb"` + } + if json.Unmarshal(data, &st) != nil || st.Pairing == nil { + return lanPodState{} + } + s := lanPodState{known: true, pairing: *st.Pairing, paired: st.Paired} + if st.USB != nil && st.USB.Link && tcpclient.IsUSBLinkAddr(strings.TrimSpace(st.USB.IP)) { + s.usbIP = strings.TrimSpace(st.USB.IP) + } + return s +} + +// usbLinkAddr is where the pod's USB link address is dialed (plaintext 8080). A variable so tests +// can point it at a fake pod. +var usbLinkAddr = func(ip string) string { return net.JoinHostPort(ip, tcpclient.PlainPort) } + +// reachUSBLink returns the dial address of the pod's USB link when it answers from this computer +// and is the same pod as the one at lanAddr (its LAN certificate matches this computer's pin for +// lanAddr, when there is one), else "". A different pod is an error. +func reachUSBLink(ctx context.Context, lanAddr, ip string) (string, error) { + if ip == "" { + return "", nil + } + addr := usbLinkAddr(ip) + c := &tcpclient.Client{Addr: addr} + pctx, cancel := context.WithTimeout(ctx, 3*time.Second) + _, err := c.Command(pctx, map[string]any{"cmd": "ping"}) + cancel() + if err != nil { + return "", nil // the cable is in another computer, or the link is not up here + } + if pin, ok := tcpclient.GetPin(lanAddr); ok { + tctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + if data, err := c.Command(tctx, map[string]any{"cmd": "lan_tls"}); err == nil { + var r lanTLSReply + if json.Unmarshal(data, &r) == nil && r.SHA256 != "" && !strings.EqualFold(r.SHA256, pin.SHA256) { + return "", fmt.Errorf("the pod on this computer's USB link (%s) is not the pod at %s (their LAN certificates differ), "+ + "so this computer was not paired. Plug the pod at %s into this computer over USB-C, or pass --connection usb:", + ip, lanAddr, lanAddr) + } + } + } + return addr, nil +} + +// pinLanCertOverUSBLink pins the pod's LAN certificate (read on its USB link at usbAddr) for +// lanAddr, when this computer has no pin for it yet: later LAN connections then check they reach +// this pod. Best effort. +func pinLanCertOverUSBLink(ctx context.Context, usbAddr, lanAddr string) { + if _, ok := tcpclient.GetPin(lanAddr); ok { + return + } + data, err := (&tcpclient.Client{Addr: usbAddr}).Command(ctx, map[string]any{"cmd": "lan_tls"}) + if err != nil { + return + } + var r lanTLSReply + if json.Unmarshal(data, &r) == nil && r.SHA256 != "" { + _ = tcpclient.SetPinFingerprint(lanAddr, r.SHA256, r.Subject) + } +} + +// errNeedsUSBLink is what lan-clients says when a LAN connection cannot reach the pod's USB link. +func errNeedsUSBLink(what, lanAddr string, notPaired bool) error { + if notPaired { + return fmt.Errorf("%s: this computer is not paired with the pod at %s, and the pod is not plugged into this computer over USB, "+ + "so it cannot pair it from here. Plug the pod's USB-C port (USB-C IN, on the back) into this computer and run this again, "+ + "or pair it through the cloud: --connection embeddedci: (BP0081)", what, lanAddr) + } + return fmt.Errorf("%s: the paired computers are changed over USB or the cloud, never over the network, and the pod at %s "+ + "is not plugged into this computer over USB. Plug the pod's USB-C port (USB-C IN, on the back) into this computer and run this again, "+ + "or use the cloud: --connection embeddedci:", what, lanAddr) +} + +// errAlreadyPaired tells lan-clients add that this computer is paired already (nothing to change). +var errAlreadyPaired = errors.New("already paired") + +// lanClientsRoute decides where lan-clients sends op for the LAN address lanAddr: the pod's USB +// link address (a change, or a list this computer may not read over the LAN), "" for lanAddr +// itself, errAlreadyPaired for `add` of this computer when it is paired and the USB link is not +// here, or an error saying what to do. +func lanClientsRoute(ctx context.Context, lanAddr string, o lanClientsOp) (string, error) { + st := readLanPodState(ctx, lanAddr) + if !st.known { + return "", nil // no pairing on this firmware, or no answer: the command says so itself + } + notPaired := st.pairing && st.paired != nil && !*st.paired + if o.op == "" && !notPaired { + return "", nil // a paired computer lists over the LAN + } + usb, err := reachUSBLink(ctx, lanAddr, st.usbIP) + if err != nil { + return "", err + } + if usb != "" { + return usb, nil + } + if o.op == "add" && !o.newKey && st.pairing && st.paired != nil && *st.paired { + return "", errAlreadyPaired + } + what := "lan-clients" + if o.op != "" { + what += " " + o.op + } + return "", errNeedsUSBLink(what, lanAddr, notPaired) +} + +// pairOverUSBLink is setup's pairing for a pod found only at the LAN address lanAddr: through the +// pod's USB link when it answers from here. ok is false when the link is not here. +func pairOverUSBLink(lanAddr string) (msg string, ok bool, err error) { + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + st := readLanPodState(ctx, lanAddr) + if !st.known { + return "", false, nil + } + usb, err := reachUSBLink(ctx, lanAddr, st.usbIP) + if err != nil || usb == "" { + return "", err != nil, err + } + key, err := tcpclient.ClientKeyHash() + if err != nil { + return "", true, fmt.Errorf("pair: %w", err) + } + name := tcpclient.PairingName() + if _, err := lanClientsAll(ctx, &tcpclient.Client{Addr: usb}, map[string]any{"cmd": "lan_clients", "add": name, "spki_sha256": key}); err != nil { + return "", true, fmt.Errorf("pair this computer over the pod's USB link: %w", err) + } + pinLanCertOverUSBLink(ctx, usb, lanAddr) + return fmt.Sprintf("Paired this computer (%s) with it over its USB link (%s), so it can drive the pod over the network too.", name, st.usbIP), true, nil +} diff --git a/cmd/benchpod-cli/pair_usblink_test.go b/cmd/benchpod-cli/pair_usblink_test.go new file mode 100644 index 0000000..3b8d40e --- /dev/null +++ b/cmd/benchpod-cli/pair_usblink_test.go @@ -0,0 +1,217 @@ +package main + +import ( + "bufio" + "bytes" + "encoding/json" + "io" + "net" + "strings" + "sync" + "testing" + + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" +) + +// recordingPod is a fake pod that answers each command by name and keeps every request. +type recordingPod struct { + addr string + mu sync.Mutex + reqs []map[string]any +} + +func (p *recordingPod) cmds() []string { + p.mu.Lock() + defer p.mu.Unlock() + var out []string + for _, r := range p.reqs { + c, _ := r["cmd"].(string) + if _, ok := r["add"]; ok { + c += " add=" + r["add"].(string) + } + out = append(out, c) + } + return out +} + +func newRecordingPod(t *testing.T, replies map[string]string) *recordingPod { + t.Helper() + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ln.Close() }) + p := &recordingPod{addr: ln.Addr().String()} + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + line, _ := bufio.NewReader(conn).ReadString('\n') + var req map[string]any + _ = json.Unmarshal([]byte(line), &req) + p.mu.Lock() + p.reqs = append(p.reqs, req) + p.mu.Unlock() + cmd, _ := req["cmd"].(string) + reply, ok := replies[cmd] + if !ok { + reply = replies[""] + } + _, _ = io.WriteString(conn, reply+"\n") + conn.Close() + } + }() + return p +} + +// lanStatus is a 4.0.1 pod's status over the LAN, with its USB link up at 10.237.210.109. +func lanStatus(paired bool, usbLink bool) string { + return `{"status":"ok","data":{"device":"benchpod","version":"4.0.1","api":2,"min_client_api":2,"lan_pairing":true,"lan_paired":` + + map[bool]string{true: "true", false: "false"}[paired] + + `,"usb":{"net":true,"enabled":true,"link":` + map[bool]string{true: "true", false: "false"}[usbLink] + + `,"ip":"10.237.210.109","host_ip":"10.237.210.110"}}}` +} + +const lanClientsReply = `{"status":"ok","data":{"pairing":true,"count":1,"max":24,"clients":[{"name":"mac","spki_sha256":"00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff"}]}}` + +// withUSBLink points the pod's USB link address at addr ("" for a link that does not answer). +func withUSBLink(t *testing.T, addr string) { + t.Helper() + old := usbLinkAddr + usbLinkAddr = func(ip string) string { + if ip != "10.237.210.109" { + t.Errorf("USB link ip = %q", ip) + } + if addr == "" { + return "127.0.0.1:1" + } + return addr + } + t.Cleanup(func() { usbLinkAddr = old }) +} + +// The bug: two pods on USB, the app connected over the LAN. lan-clients add with the LAN address +// pairs over that pod's own USB link, not over "usb" (which asks which pod). +func TestLanClientsAddOverLANPairsThroughTheUSBLink(t *testing.T) { + lan := newRecordingPod(t, map[string]string{"status": lanStatus(false, true), "": `{"status":"error","code":"BP0081","args":{"cmd":"lan_clients"}}`}) + usb := newRecordingPod(t, map[string]string{ + "ping": `{"status":"ok","data":"pong"}`, + "lan_tls": `{"status":"ok","data":{"sha256":"abcd","subject":"CN=benchpod-c2f662"}}`, + "lan_clients": lanClientsReply, + }) + withUSBLink(t, usb.addr) + + var out bytes.Buffer + g := &globalFlags{connection: lan.addr} + if err := runLanClients(g, lanClientsOp{op: "add", name: "mac"}, &out); err != nil { + t.Fatalf("add: %v", err) + } + if !strings.Contains(out.String(), "Paired mac with the pod at "+lan.addr+" (over its USB link 127.0.0.1)") { + t.Errorf("output:\n%s", out.String()) + } + for _, c := range lan.cmds() { + if strings.HasPrefix(c, "lan_clients") { + t.Errorf("lan_clients went to the LAN address: %v", lan.cmds()) + } + } + if got := strings.Join(usb.cmds(), ","); !strings.Contains(got, "lan_clients add=mac") { + t.Errorf("USB link got %s", got) + } + // The LAN certificate is pinned from the USB link, for the LAN address. + if pin, ok := tcpclient.GetPin(lan.addr); !ok || pin.SHA256 != "abcd" { + t.Errorf("pin = %+v, %v", pin, ok) + } +} + +func TestLanClientsAddOverLANWithoutTheUSBLinkSaysPlugItIn(t *testing.T) { + for _, link := range []bool{true, false} { // link up but the cable is in another computer; link down + lan := newRecordingPod(t, map[string]string{"status": lanStatus(false, link)}) + withUSBLink(t, "") + g := &globalFlags{connection: lan.addr} + err := runLanClients(g, lanClientsOp{op: "add", name: "mac"}, io.Discard) + if err == nil { + t.Fatal("add: no error") + } + for _, want := range []string{"not paired with the pod at " + lan.addr, "USB-C", "--connection embeddedci:", "BP0081"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("link=%v: error %q lacks %q", link, err, want) + } + } + if strings.Contains(err.Error(), "[benchpod]") || strings.Contains(err.Error(), "pods on USB") { + t.Errorf("error: %v", err) + } + } +} + +func TestLanClientsAddOverLANWhenPairedAlready(t *testing.T) { + lan := newRecordingPod(t, map[string]string{"status": lanStatus(true, false), "lan_clients": lanClientsReply}) + withUSBLink(t, "") + var out bytes.Buffer + if err := runLanClients(&globalFlags{connection: lan.addr}, lanClientsOp{op: "add", name: "mac"}, &out); err != nil { + t.Fatalf("add: %v", err) + } + if !strings.Contains(out.String(), "This computer (mac) is already paired with the pod at "+lan.addr) { + t.Errorf("output:\n%s", out.String()) + } + for _, c := range lan.cmds() { + if strings.Contains(c, "add=") { + t.Errorf("sent an add over the LAN: %v", lan.cmds()) + } + } +} + +func TestLanClientsListOverLANWhenPaired(t *testing.T) { + lan := newRecordingPod(t, map[string]string{"status": lanStatus(true, true), "lan_clients": lanClientsReply}) + usb := newRecordingPod(t, map[string]string{"": `{"status":"ok","data":"pong"}`}) + withUSBLink(t, usb.addr) + if err := runLanClients(&globalFlags{connection: lan.addr}, lanClientsOp{}, io.Discard); err != nil { + t.Fatalf("list: %v", err) + } + if len(usb.cmds()) != 0 { + t.Errorf("a paired computer's list went to the USB link: %v", usb.cmds()) + } +} + +// Another pod's USB link (its LAN certificate differs from this computer's pin for the address) +// is never paired. +func TestLanClientsAddRefusesAnotherPodsUSBLink(t *testing.T) { + lan := newRecordingPod(t, map[string]string{"status": lanStatus(false, true)}) + usb := newRecordingPod(t, map[string]string{ + "ping": `{"status":"ok","data":"pong"}`, + "lan_tls": `{"status":"ok","data":{"sha256":"ffff"}}`, + "lan_clients": lanClientsReply, + }) + withUSBLink(t, usb.addr) + if err := tcpclient.SetPinFingerprint(lan.addr, "abcd", ""); err != nil { + t.Fatal(err) + } + err := runLanClients(&globalFlags{connection: lan.addr}, lanClientsOp{op: "add", name: "mac"}, io.Discard) + if err == nil || !strings.Contains(err.Error(), "is not the pod at "+lan.addr) { + t.Fatalf("err = %v", err) + } + for _, c := range usb.cmds() { + if strings.HasPrefix(c, "lan_clients") { + t.Errorf("paired another pod: %v", usb.cmds()) + } + } +} + +// setup, for a pod it found only on the network, pairs through its USB link too. +func TestSetupPairsOverTheUSBLink(t *testing.T) { + lan := newRecordingPod(t, map[string]string{"status": lanStatus(false, true)}) + usb := newRecordingPod(t, map[string]string{ + "ping": `{"status":"ok","data":"pong"}`, + "lan_tls": `{"status":"ok","data":{"sha256":"abcd"}}`, + "lan_clients": lanClientsReply, + }) + withUSBLink(t, usb.addr) + msg, err := (&realSetupEnv{g: &globalFlags{}}).pair(setupPod{addr: lan.addr}) + if err != nil || !strings.Contains(msg, "over its USB link (10.237.210.109)") { + t.Fatalf("pair = %q, %v", msg, err) + } + if got := strings.Join(usb.cmds(), ","); !strings.Contains(got, "lan_clients add=") { + t.Errorf("USB link got %s", got) + } +} diff --git a/cmd/benchpod-cli/setup.go b/cmd/benchpod-cli/setup.go index 81ed35d..4d40153 100644 --- a/cmd/benchpod-cli/setup.go +++ b/cmd/benchpod-cli/setup.go @@ -765,6 +765,9 @@ func (e *realSetupEnv) pair(p setupPod) (string, error) { if !known || !required || paired { return "", nil } + if msg, ok, err := pairOverUSBLink(p.addr); ok { + return msg, err + } if p.cloud.Configured && e.signedIn() != "" { if name, ok := e.accountDevices()[strings.TrimSpace(p.cloud.DeviceID)]; ok { msg, err := pairOverCloud(e.g, name)