diff --git a/README.md b/README.md index ce29241..cfb664f 100644 --- a/README.md +++ b/README.md @@ -2305,6 +2305,43 @@ pod's console `lan-tls` or the web app's pod Settings. Drop this computer's pin for the pod; the next TLS connection pins what it presents. +### `benchpod lan-clients` + +List the computers paired with the pod (firmware 4.0.1 and later). Over Ethernet and +Wi-Fi the pod answers only status to a computer that is not paired; `benchpod setup` +pairs this computer over the pod's USB-C cable on its own. The list marks this computer. +Over USB (the console or `--connection usb`), embeddedci.com (`--connection +embeddedci:`), or a paired computer on the network. + +### `benchpod lan-clients add` + +Pair this computer: its TLS client key (made on first use, `client.key` and `client.crt` +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. + +| Flag | Default | Purpose | +|-------------|-----------------|----------------------------------------------------------------------| +| `--name` | this host name | The name the pod lists it under (1 to 23 characters). | +| `--new-key` | off | Make a new key, pair it and print its certificate and key PEM once, for a CI runner's `BENCHPOD_CLIENT_KEY_PEM` secret. Needs `--name`. | + +A runner with `BENCHPOD_CLIENT_KEY_PEM` (or `BENCHPOD_CLIENT_CERT` and +`BENCHPOD_CLIENT_KEY`, files) uses that key instead of its own. + +### `benchpod lan-clients remove` + +`benchpod lan-clients remove `: unpair every computer with that name, or the +one key that starts with these hex digits (8 or more). Only over USB or embeddedci.com. + +### `benchpod lan-clients clear` + +Unpair every computer. Only over USB or embeddedci.com. + +### `benchpod lan-pairing [on|off]` + +Show or set LAN pairing (firmware 4.0.1 and later). `on`, the default: a computer on +Ethernet or Wi-Fi drives the pod only once it is paired. `off`: every computer on the +network may, as before 4.0.1. Only over USB or embeddedci.com. Stored on the pod. + ### `benchpod usb-network [show|on|off]` Show the pod's USB network setting, or turn its USB network adapter on or off diff --git a/cmd/benchpod-cli/commands_discover.go b/cmd/benchpod-cli/commands_discover.go index 10d5dcd..f329e07 100644 --- a/cmd/benchpod-cli/commands_discover.go +++ b/cmd/benchpod-cli/commands_discover.go @@ -50,7 +50,11 @@ type discoveredPod struct { reachable bool healthErr string // why the API check failed, when it did cloud cloudState - sameAs string // serial device of the pod this is (the same physical pod) + // LAN pairing (firmware 4.0.1+): pairingKnown when the pod reports it; unpaired when this + // computer must pair before it can do more than read status. + pairingKnown bool + unpaired bool + sameAs string // serial device of the pod this is (the same physical pod) } // cloudState is the pod's view of its registration, from `cloud_status`. @@ -200,6 +204,8 @@ func checkPod(p *discoveredPod) { p.cloud.known = true } } + known, required, paired := lanPairing(p.addr) + p.pairingKnown, p.unpaired = known, known && required && !paired } // correlate marks each network pod that is the same physical device as one of @@ -783,6 +789,11 @@ func describeHealth(p discoveredPod) string { parts = append(parts, fmt.Sprintf("registered, cloud %s", strings.ToLower(strings.TrimSpace(p.cloud.State)))) } } + if p.unpaired { + parts = append(parts, "this computer is not paired (status only: plug the pod into it over USB-C and run `benchpod setup`)") + } else if p.pairingKnown && p.reachable { + parts = append(parts, "paired") + } if v := apiVerdict(p.api); v != "" { parts = append(parts, v) } diff --git a/cmd/benchpod-cli/lanclients.go b/cmd/benchpod-cli/lanclients.go new file mode 100644 index 0000000..699c39e --- /dev/null +++ b/cmd/benchpod-cli/lanclients.go @@ -0,0 +1,427 @@ +package main + +import ( + "context" + "crypto/x509" + "encoding/json" + "encoding/pem" + "errors" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/spf13/cobra" + + "github.com/embeddedci-com/benchpod-cli/internal/serialconsole" + "github.com/embeddedci-com/benchpod-cli/internal/tcpclient" +) + +// LAN pairing (firmware 4.0.1+, feature lan_pairing; benchpod-firmware docs/design/lan-pairing.md): +// a computer on Ethernet or Wi-Fi drives the pod only once its TLS client key is on the pod's list. +// `benchpod setup` pairs this computer over the USB cable on its own; this command shows the list, +// pairs another key (a CI runner) and removes one. Changes go over USB (the console, or the USB +// network adapter) or embeddedci.com, never over the LAN. + +const lanClientsMissing = "this firmware has no LAN pairing (anyone on the network may use the pod); update the pod's firmware (4.0.1 or newer)" + +func newLanClientsCmd(g *globalFlags) *cobra.Command { + cmd := &cobra.Command{ + Use: "lan-clients", + Short: "The computers paired with the pod for use over Ethernet and Wi-Fi", + Long: "Show, pair or remove the computers paired with the pod (firmware 4.0.1+).\n\n" + + "Over Ethernet and Wi-Fi the pod only answers status to a computer that is not paired.\n" + + "`benchpod setup` pairs this computer over the pod's USB-C cable; a registered pod can also\n" + + "be paired through embeddedci.com (--connection embeddedci:, as an organization admin).\n" + + "Changes need USB or embeddedci.com: never the network itself.\n\n" + + " benchpod lan-clients list them\n" + + " benchpod lan-clients add pair this computer\n" + + " benchpod lan-clients add --new-key --name ci-runner-1\n" + + " pair a new key and print it for a CI secret\n" + + " (BENCHPOD_CLIENT_KEY_PEM on the runner)\n" + + " benchpod lan-clients remove unpair one (8+ hex digits of its key)\n" + + " benchpod lan-clients clear unpair them all", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + return runLanClients(g, lanClientsOp{}, os.Stdout) + }, + } + var name string + var newKey bool + add := &cobra.Command{ + Use: "add", + Short: "Pair this computer (or, with --new-key, a new key for a CI runner)", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + return runLanClients(g, lanClientsOp{op: "add", name: name, newKey: newKey}, os.Stdout) + }, + } + add.Flags().StringVar(&name, "name", "", "the name the pod lists it under (default: this computer's host name)") + add.Flags().BoolVar(&newKey, "new-key", false, "make a new key, pair it, and print its certificate and key PEM") + remove := &cobra.Command{ + Use: "remove ", + Short: "Unpair the computers with this name, or the one key that starts with these hex digits", + Args: cobra.ExactArgs(1), + RunE: func(_ *cobra.Command, args []string) error { + return runLanClients(g, lanClientsOp{op: "remove", what: args[0]}, os.Stdout) + }, + } + clear := &cobra.Command{ + Use: "clear", + Short: "Unpair every computer", + Args: cobra.NoArgs, + RunE: func(_ *cobra.Command, _ []string) error { + return runLanClients(g, lanClientsOp{op: "clear"}, os.Stdout) + }, + } + cmd.AddCommand(add, remove, clear) + return cmd +} + +type lanClientsOp struct { + op string // "", "add", "remove", "clear" + name string + newKey bool + what string +} + +// lanClientsView is the list as both transports report it. +type lanClientsView struct { + Pairing bool `json:"pairing"` + Count int `json:"count"` + Max int `json:"max"` + Clients []lanClientRecord `json:"clients"` +} + +type lanClientRecord struct { + Name string `json:"name"` + SHA256 string `json:"spki_sha256"` +} + +func runLanClients(g *globalFlags, o lanClientsOp, out io.Writer) error { + var key, pemOut string + if o.op == "add" { + if o.newKey { + cn := o.name + if cn == "" { + return usageErrorf("lan-clients add --new-key needs --name (what the runner is called)") + } + certPEM, keyPEM, err := tcpclient.NewClientIdentityPEM("benchpod client " + cn) + if err != nil { + return err + } + block, _ := pem.Decode(certPEM) + leaf, err := x509.ParseCertificate(block.Bytes) + if err != nil { + return err + } + key, pemOut = tcpclient.SPKIHash(leaf), string(certPEM)+string(keyPEM) + } else { + h, err := tcpclient.ClientKeyHash() + if err != nil { + return fmt.Errorf("lan-clients add: %w", err) + } + key = h + } + if o.name == "" { + o.name = tcpclient.PairingName() + } + o.name = tcpclient.SanitizePairingName(o.name) + } + + spec, err := g.resolveTarget() + if err != nil { + return err + } + var v lanClientsView + var label string + if spec.IsSerial() { + v, label, err = lanClientsConsole(g, spec.Device, o, key) + } else { + v, label, err = lanClientsNetwork(g, o, key) + } + if err != nil { + return err + } + switch o.op { + case "add": + fmt.Fprintf(out, "Paired %s with the pod at %s.\n", o.name, label) + case "remove": + fmt.Fprintf(out, "Removed %s from the pod at %s.\n", o.what, label) + case "clear": + fmt.Fprintf(out, "Removed every paired computer from the pod at %s.\n", label) + } + printLanClients(out, label, v, key) + if pemOut != "" { + fmt.Fprintln(out, "\nThe new key, for the runner's BENCHPOD_CLIENT_KEY_PEM secret (shown once, not stored here):") + fmt.Fprint(out, pemOut) + } + return nil +} + +func printLanClients(out io.Writer, label string, v lanClientsView, highlight string) { + mine, _ := tcpclient.ClientKeyHash() + state := "on: computers on Ethernet and Wi-Fi must be paired" + if !v.Pairing { + state = "off: every computer on the network may use the pod" + } + fmt.Fprintf(out, "Paired computers on %s: %d of %d (pairing %s)\n", label, v.Count, v.Max, state) + for _, c := range v.Clients { + note := "" + switch { + case mine != "" && strings.EqualFold(c.SHA256, mine): + note = " (this computer)" + case highlight != "" && strings.EqualFold(c.SHA256, highlight): + note = " (new)" + } + fmt.Fprintf(out, " %-23s %s%s\n", c.Name, c.SHA256[:16], note) + } +} + +func lanClientsConsole(g *globalFlags, device string, o lanClientsOp, key string) (lanClientsView, string, error) { + console, path, err := g.openBenchpodSerial(device, 2*time.Second) + if err != nil { + return lanClientsView{}, "", err + } + defer console.Close() + ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(20*time.Second)) + defer cancel() + var l serialconsole.LanClients + switch o.op { + case "add": + l, err = console.LanClientsAdd(ctx, o.name, key) + case "remove": + l, err = console.LanClientsRemove(ctx, o.what) + case "clear": + l, err = console.LanClientsClear(ctx) + default: + l, err = console.LanClientsList(ctx) + } + if errors.Is(err, serialconsole.ErrUnknownCommand) { + return lanClientsView{}, "", errors.New(lanClientsMissing) + } + if err != nil { + return lanClientsView{}, "", err + } + v := lanClientsView{Pairing: l.Pairing, Count: l.Count, Max: l.Max} + for _, c := range l.Clients { + v.Clients = append(v.Clients, lanClientRecord{Name: c.Name, SHA256: c.SHA256}) + } + return v, "USB " + path, nil +} + +func lanClientsNetwork(g *globalFlags, o lanClientsOp, key string) (lanClientsView, string, error) { + ctx, cancel, t, err := g.podClient("lan-clients", 30*time.Second) + if err != nil { + return lanClientsView{}, "", err + } + defer cancel() + req := map[string]any{"cmd": "lan_clients"} + switch o.op { + case "add": + req["add"], req["spki_sha256"] = o.name, key + case "remove": + req["remove"] = o.what + case "clear": + req["clear"] = true + } + v, err := lanClientsAll(ctx, t.client, req) + if err != nil { + if isUnknownCommand(err) { + return lanClientsView{}, "", errors.New(lanClientsMissing) + } + return lanClientsView{}, "", fmt.Errorf("lan-clients: %w", err) + } + return v, t.label, nil +} + +// lanClientsAll runs req and reads every page of the list (the pod sends 12 a reply). +func lanClientsAll(ctx context.Context, c podCommander, req map[string]any) (lanClientsView, error) { + var all lanClientsView + for page := 0; page < 4; page++ { + data, err := c.Command(ctx, req) + if err != nil { + return lanClientsView{}, err + } + var v lanClientsView + if err := json.Unmarshal(data, &v); err != nil { + return lanClientsView{}, fmt.Errorf("unexpected reply %s", strings.TrimSpace(string(data))) + } + all.Pairing, all.Count, all.Max = v.Pairing, v.Count, v.Max + all.Clients = append(all.Clients, v.Clients...) + if len(v.Clients) == 0 || len(all.Clients) >= v.Count { + break + } + req = map[string]any{"cmd": "lan_clients", "offset": len(all.Clients)} + } + return all, nil +} + +// ── setup's pairing ────────────────────────────────────────────────────────── + +// errNotPaired is what setup says when it finds a pod only on the network and cannot pair. +var errNotPaired = errors.New("this computer is not paired with the pod, so over the network it may only read the pod's status. " + + "Plug the pod's USB-C port (USB-C IN, on the back) into this computer once and run `benchpod setup` again: it pairs this computer over the cable. " + + "A pod registered to your embeddedci.com account is paired from there too: `benchpod login`, then setup again") + +// pairOverConsole pairs this computer with the pod on USB device and pins the pod's LAN +// certificate for lanAddr, so later LAN connections check they reach this very pod. "" when the +// firmware has no pairing (nothing to do). +func pairOverConsole(g *globalFlags, device, lanAddr string) (string, error) { + key, err := tcpclient.ClientKeyHash() + if err != nil { + return "", fmt.Errorf("pair: %w", err) + } + console, _, err := g.openBenchpodSerial(device, 2*time.Second) + if err != nil { + return "", fmt.Errorf("pair: %w", err) + } + defer console.Close() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + name := tcpclient.PairingName() + l, err := console.LanClientsAdd(ctx, name, key) + if errors.Is(err, serialconsole.ErrUnknownCommand) { + return "", nil + } + if err != nil { + return "", fmt.Errorf("pair this computer: %w", err) + } + if lanAddr != "" { + if fp, err := console.LanTLSFingerprint(ctx); err == nil && fp != "" { + if err := tcpclient.SetPinFingerprint(tcpclient.TLSAddr(lanAddr), fp, ""); err != nil { + return "", fmt.Errorf("pin the pod's certificate: %w", err) + } + } + } + if !l.Pairing { + return "", nil // pairing is off on this pod: nothing to say + } + if l.Outcome == "same" { + return fmt.Sprintf("This computer is paired with it (%s).", name), nil + } + return fmt.Sprintf("Paired this computer (%s) with it over USB, so it can drive the pod over the network too.", name), nil +} + +// lanPairing reads the pod's pairing state over the network: known is false on firmware without +// pairing or when status does not answer; paired is meaningless when the connection needs none. +func lanPairing(addr string) (known, required, paired bool) { + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + data, err := (&tcpclient.Client{Addr: addr}).Command(ctx, map[string]any{"cmd": "status", "caps": false}) + if err != nil { + return false, false, false + } + var st struct { + Pairing *bool `json:"lan_pairing"` + Paired *bool `json:"lan_paired"` + } + if json.Unmarshal(data, &st) != nil || st.Pairing == nil { + return false, false, false + } + if st.Paired == nil { // the USB link, or pairing off: nothing to say about this computer + return false, false, false + } + return true, *st.Pairing, *st.Paired +} + +// pairOverCloud pairs this computer through embeddedci.com (the pod's own cloud link). The server +// lets an organization owner or admin do it. +func pairOverCloud(g *globalFlags, podName string) (string, error) { + key, err := tcpclient.ClientKeyHash() + if err != nil { + return "", err + } + gc := *g + gc.connection = cloudConnPrefix + podName + ctx, cancel, t, err := gc.podClient("pair", 30*time.Second) + if err != nil { + return "", err + } + defer cancel() + name := tcpclient.PairingName() + if _, err := lanClientsAll(ctx, t.client, map[string]any{"cmd": "lan_clients", "add": name, "spki_sha256": key}); err != nil { + return "", err + } + return fmt.Sprintf("Paired this computer (%s) with it through embeddedci.com.", name), nil +} + +// ── lan-pairing ────────────────────────────────────────────────────────────── + +func newLanPairingCmd(g *globalFlags) *cobra.Command { + return &cobra.Command{ + Use: "lan-pairing [on|off]", + Short: "Show or set whether computers on Ethernet and Wi-Fi must be paired", + Long: "Show or set LAN pairing (firmware 4.0.1+). on (the default): a computer on Ethernet or\n" + + "Wi-Fi drives the pod only once it is paired (`benchpod setup`, `benchpod lan-clients`).\n" + + "off: every computer on the network may, as before 4.0.1; then keep the pod on a trusted\n" + + "lab network. Changed over USB (the console or --connection usb) or embeddedci.com.", + Args: cobra.MaximumNArgs(1), + ValidArgs: []string{"on", "off"}, + RunE: func(_ *cobra.Command, args []string) error { + set := "" + if len(args) == 1 { + set = strings.ToLower(strings.TrimSpace(args[0])) + if set != "on" && set != "off" { + return usageErrorf("lan-pairing: use on or off (got %q)", args[0]) + } + } + return runLanPairing(g, set, os.Stdout) + }, + } +} + +func runLanPairing(g *globalFlags, set string, out io.Writer) error { + spec, err := g.resolveTarget() + if err != nil { + return err + } + var on bool + var label string + if spec.IsSerial() { + console, path, err := g.openBenchpodSerial(spec.Device, 2*time.Second) + if err != nil { + return err + } + defer console.Close() + ctx, cancel := context.WithTimeout(context.Background(), g.effectiveTimeout(15*time.Second)) + defer cancel() + rep, err := console.Policy(ctx, "lan-pairing", set) + if errors.Is(err, serialconsole.ErrPolicyUnsupported) { + return errors.New(lanClientsMissing) + } + if err != nil { + return err + } + on, label = rep.Policy == "on", "USB "+path + } else { + ctx, cancel, t, err := g.podClient("lan-pairing", 20*time.Second) + if err != nil { + return err + } + defer cancel() + req := map[string]any{"cmd": "lan_policy"} + if set != "" { + req["pairing"] = set == "on" + } + data, err := t.client.Command(ctx, req) + if err != nil { + return fmt.Errorf("lan-pairing: %w", err) + } + var rep struct { + Pairing *bool `json:"pairing"` + } + if json.Unmarshal(data, &rep) != nil || rep.Pairing == nil { + return errors.New(lanClientsMissing) + } + on, label = *rep.Pairing, t.label + } + state := map[bool]string{true: "on: computers on Ethernet and Wi-Fi must be paired", false: "off: every computer on the network may use the pod"}[on] + if set != "" { + fmt.Fprintf(out, "LAN pairing on %s is now %s (stored on the pod).\n", label, state) + } else { + fmt.Fprintf(out, "LAN pairing on %s: %s.\n", label, state) + } + return nil +} diff --git a/cmd/benchpod-cli/root.go b/cmd/benchpod-cli/root.go index 6c9cf9d..1976a8a 100644 --- a/cmd/benchpod-cli/root.go +++ b/cmd/benchpod-cli/root.go @@ -146,7 +146,7 @@ func newRootCmd() *cobra.Command { {"pod", "The pod:", []*cobra.Command{ newStatusCmd(g), newPingCmd(g), newLACmd(g), newIdentityCmd(g), newFlashSelfCmd(g), newInstallBlobsCmd(g), newBootselCmd(g), newDfuCmd(g), - newLanPolicyCmd(g), newSigPolicyCmd(g), newUSBNetworkCmd(g), newLogLevelCmd(g), newLanTLSCmd(g), + newLanPolicyCmd(g), newSigPolicyCmd(g), newUSBNetworkCmd(g), newLogLevelCmd(g), newLanTLSCmd(g), newLanClientsCmd(g), newLanPairingCmd(g), newWiringCmd(g), newExplainCmd(), }}, {"target", "The target (DUT) and analog I/O:", []*cobra.Command{ diff --git a/cmd/benchpod-cli/setup.go b/cmd/benchpod-cli/setup.go index b67d7cd..81ed35d 100644 --- a/cmd/benchpod-cli/setup.go +++ b/cmd/benchpod-cli/setup.go @@ -120,6 +120,10 @@ type setupEnv interface { save(target string) error // latestFirmware is the latest firmware release tag, "" when it could not be read. latestFirmware() string + // pair makes sure this computer may drive the pod over the network (LAN pairing, firmware + // 4.0.1+): over the USB console when the pod is on USB, else through embeddedci.com. It returns + // a line to print ("" for nothing), or errNotPaired when it cannot pair. + pair(p setupPod) (string, error) } // errNeedsAnswer is returned under --yes when a step needs an answer that no flag gave. @@ -219,6 +223,13 @@ func runSetup(env setupEnv, ui *setupUI, o setupOpts) error { } p := pods[0] fmt.Fprintf(out, " Found %s.\n", describeSetupPod(p)) + // Pair first: on firmware 4.0.1+ the steps below talk to the pod over the network, which an + // unpaired computer may only ask for status. + if msg, err := env.pair(p); err != nil { + return err + } else if msg != "" { + fmt.Fprintf(out, " %s\n", msg) + } if latest := env.latestFirmware(); latest != "" && p.firmware != "" && versionLess(p.firmware, latest) { // A nudge, not a step: the update reboots the pod, so the user runs it when it suits them. fmt.Fprintf(out, " Firmware %s is out of date: %s is the latest. Update it with the pod on USB:\n"+ @@ -583,14 +594,19 @@ func (e *realSetupEnv) find() ([]setupPod, error) { return nil, err } var pods []setupPod - for _, sp := range serialPods { - if spec.Device == "" || sp.Device == spec.Device { - p := setupPodFromSerial(sp) - if spec.Pod != "" { - p.usbConn = raw - } - pods = append(pods, p) + for _, sp := range usbPodsFor(serialPods, spec) { + p := setupPodFromSerial(sp) + if spec.Pod != "" { + p.usbConn = raw } + pods = append(pods, p) + } + if len(pods) == 0 && spec.Pod != "" && len(serialPods) > 0 { + var ids []string + for _, sp := range serialPods { + ids = append(ids, "usb:benchpod-"+sp.ShortID) + } + return nil, fmt.Errorf("no pod %s on USB; found %s", raw, strings.Join(ids, ", ")) } return pods, nil } @@ -608,6 +624,23 @@ func (e *realSetupEnv) find() ([]setupPod, error) { return mergeSetupPods(serialPods, netPods), nil } +// usbPodsFor keeps the USB pods a connection names: a device path picks that port, usb: +// the pod with that identity short id (also as benchpod-), plain usb all of them. +func usbPodsFor(pods []serialconsole.SerialPod, spec ConnSpec) []serialconsole.SerialPod { + want := serialconsole.NormalizePodName(spec.Pod) + var out []serialconsole.SerialPod + for _, sp := range pods { + if spec.Device != "" && sp.Device != spec.Device { + continue + } + if want != "" && serialconsole.NormalizePodName(sp.ShortID) != want { + continue + } + out = append(out, sp) + } + return out +} + // mergeSetupPods turns discover's two lists into one entry per physical pod. A network pod that // does not answer its API is left out (a stale mDNS record is not a pod to set up). func mergeSetupPods(serialPods []serialconsole.SerialPod, netPods []discoveredPod) []setupPod { @@ -720,3 +753,26 @@ func (e *realSetupEnv) saveLaMV(deviceID string, mv int) (bool, error) { func (e *realSetupEnv) save(target string) error { return runSetConnection(e.g, target) } func (e *realSetupEnv) latestFirmware() string { return latestFirmwareRelease() } + +func (e *realSetupEnv) pair(p setupPod) (string, error) { + if p.device != "" { + return pairOverConsole(e.g, p.device, p.lanAddr) + } + if p.addr == "" || isUSBLinkAddr(p.addr) { + return "", nil + } + known, required, paired := lanPairing(p.addr) + if !known || !required || paired { + return "", nil + } + if p.cloud.Configured && e.signedIn() != "" { + if name, ok := e.accountDevices()[strings.TrimSpace(p.cloud.DeviceID)]; ok { + msg, err := pairOverCloud(e.g, name) + if err != nil { + return "", fmt.Errorf("pair this computer through embeddedci.com: %w. %v", err, errNotPaired) + } + return msg, nil + } + } + return "", errNotPaired +} diff --git a/cmd/benchpod-cli/setup_test.go b/cmd/benchpod-cli/setup_test.go index 9af765d..82ecb4c 100644 --- a/cmd/benchpod-cli/setup_test.go +++ b/cmd/benchpod-cli/setup_test.go @@ -27,6 +27,8 @@ type fakeSetupEnv struct { saveErr error // what saveLaMV fails with latest string // latest firmware release, "" = unknown regErr error // what register returns after registering + pairMsg string // what pair prints + pairErr error // what pair fails with calls []string wifiSSID string @@ -94,6 +96,11 @@ func (f *fakeSetupEnv) save(target string) error { func (f *fakeSetupEnv) latestFirmware() string { return f.latest } +func (f *fakeSetupEnv) pair(setupPod) (string, error) { + f.calls = append(f.calls, "pair") + return f.pairMsg, f.pairErr +} + func (f *fakeSetupEnv) did(call string) bool { for _, c := range f.calls { if c == call { @@ -526,3 +533,60 @@ func TestMergeSetupPodsKeepsTheLANAddress(t *testing.T) { t.Fatalf("got %+v", pods) } } + +func TestSetupPairsBeforeTheNetworkSteps(t *testing.T) { + env := &fakeSetupEnv{ + pods: []setupPod{{device: "/dev/cu.usbmodem1", addr: "192.168.1.221:8080", firmware: "v4.0.1", cloud: registeredMine}}, + laMV: 3300, + cloud: registeredMine, + who: "you@example.com", + account: map[string]string{"dev-1": "benchpod-baea06"}, + pairMsg: "Paired this computer (laptop) with it over USB, so it can drive the pod over the network too.", + } + out, err := runSetupWith(t, env, "", setupOpts{laVoltageMV: 3300, yes: true}) + if err != nil { + t.Fatalf("setup: %v\n%s", err, out) + } + if !strings.Contains(out, "Paired this computer (laptop)") || !strings.Contains(out, "1/5 Find the pod") { + t.Fatalf("no pairing line in step 1:\n%s", out) + } + if env.calls[0] != "find" || env.calls[1] != "pair" { + t.Fatalf("pair did not come right after find: %v", env.calls) + } +} + +func TestSetupStopsWhenItCannotPair(t *testing.T) { + env := &fakeSetupEnv{ + pods: []setupPod{{addr: "192.168.1.221:8443", lanAddr: "192.168.1.221:8443", firmware: "v4.0.1"}}, + pairErr: errNotPaired, + } + out, err := runSetupWith(t, env, "", setupOpts{yes: true}) + if !errors.Is(err, errNotPaired) || !strings.Contains(err.Error(), "USB-C") { + t.Fatalf("err %v\n%s", err, out) + } + if env.did("save") || env.did("register") { + t.Fatalf("setup went on unpaired: %v", env.calls) + } +} + +func TestUSBPodsForPicksThePodByName(t *testing.T) { + pods := []serialconsole.SerialPod{ + {Device: "/dev/cu.usbmodem1", ShortID: "c2f662"}, + {Device: "/dev/cu.usbmodem2", ShortID: "30a9f1"}, + } + for _, name := range []string{"30a9f1", "benchpod-30a9f1", "BenchPod-30A9F1"} { + got := usbPodsFor(pods, ConnSpec{Kind: connSerial, Pod: name}) + if len(got) != 1 || got[0].Device != "/dev/cu.usbmodem2" { + t.Errorf("usb:%s picked %v", name, got) + } + } + if got := usbPodsFor(pods, ConnSpec{Kind: connSerial}); len(got) != 2 { + t.Errorf("plain usb kept %d pods", len(got)) + } + if got := usbPodsFor(pods, ConnSpec{Kind: connSerial, Device: "/dev/cu.usbmodem1"}); len(got) != 1 || got[0].ShortID != "c2f662" { + t.Errorf("device path picked %v", got) + } + if got := usbPodsFor(pods, ConnSpec{Kind: connSerial, Pod: "ffffff"}); len(got) != 0 { + t.Errorf("an unknown name picked %v", got) + } +} diff --git a/internal/errcatalog/errors.json b/internal/errcatalog/errors.json index 5067f29..9144759 100644 --- a/internal/errcatalog/errors.json +++ b/internal/errcatalog/errors.json @@ -1,7 +1,7 @@ { "_generated": "GENERATED by tools/gen_errors.py from errors/catalog.toml. DO NOT EDIT: edit the catalog.", "version": 1, - "catalog_sha256": "8f18331e99506bc37019f0613a1361febb68316d985bbcb04e1ab7343071dc83", + "catalog_sha256": "2b61a8def1e0a7a3620fe675720cd1b93371f942e3618a4ab46cdb60e99c5544", "docs_url": "https://embeddedci.com/docs/errors#{code}", "codes": { "BP0001": { @@ -466,7 +466,7 @@ "BP0030": { "name": "client_too_old", "area": "protocol", - "since": "next", + "since": "4.0.0", "message": "Update the BenchPod SDK, MCP or CLI: this firmware needs client API {min_client_api} or newer (this client sent {client_api})", "cause": "The firmware on the pod changed a reply or a message in a way that clients built for client API {client_api} would misread, so it refuses their commands instead of giving them answers they get wrong. The firmware speaks client API {api} and takes {min_client_api} or newer. A client that sends no client_api counts as 0. These still run for any client: ping, status, diag, identity_public, lease_release, ota_status, ota_begin, ota_data, ota_end, ota_commit, ota_abort, ota_selftest and blob_status, so a client can see the levels, let go of the pod, and update the pod's firmware and blobs or roll them back.", "args": { @@ -484,7 +484,7 @@ "BP0031": { "name": "la_pin_in_use", "area": "io", - "since": "next", + "since": "4.0.0", "message": "LA{la} is in use by {owner}", "cause": "Each LA channel has one owner at a time: a GPIO, a UART, SWD, SPI or I2C session, a step train or an emulated sensor. {owner} holds LA{la}, so the pod refuses to give it to anything else until that owner lets it go. function is the owner's function (gpio, uart_tx, i2c_sda, ...), and instance the emulated sensor's name, empty for anything else.", "args": { @@ -503,7 +503,7 @@ "BP0032": { "name": "la_pull_down_engaged", "area": "io", - "since": "next", + "since": "4.0.0", "message": "LA{la} has its {ohms} pull-down on, which {function} cannot work with ({reason})", "cause": "A pull-down holds the line low. An open-drain bus (I2C), an idle-high UART line or SWDIO needs the line to rest high, so the pod refuses to start {function} on LA{la} while its pull-down is on.", "args": { @@ -522,7 +522,7 @@ "BP0033": { "name": "la_pull_down_conflict", "area": "io", - "since": "next", + "since": "4.0.0", "message": "LA{la} is used by {function}, which cannot work with the {ohms} pull-down ({reason})", "cause": "A pull-down holds the line low. {function} on LA{la} needs the line to rest high, so the pod refuses to switch the pull-down on under it.", "args": { @@ -541,7 +541,7 @@ "BP0034": { "name": "la_dut_output", "area": "io", - "since": "next", + "since": "4.0.0", "message": "LA{la} is wired to a DUT output, and {function} would drive against it", "cause": "The wiring marks LA{la} as a pin the DUT drives (la_dir dut_output). Two push-pull outputs on one wire fight each other, which can damage either side, so the pod refuses to drive it. There is no override.", "args": { @@ -558,7 +558,7 @@ "BP0035": { "name": "la_driven_pin", "area": "io", - "since": "next", + "since": "4.0.0", "message": "LA{la} is driven by {function}, so it cannot be marked as a DUT output", "cause": "{function} drives LA{la} from the pod. Marking the pin as one the DUT drives would put two outputs on one wire, so the pod refuses until the pod's side stops driving it.", "args": { @@ -575,7 +575,7 @@ "BP0036": { "name": "la_not_gpio_output", "area": "io", - "since": "next", + "since": "4.0.0", "message": "LA{la} is not a GPIO output (it is {function})", "cause": "Writing a level or sending a gpio step needs the channel set up as a GPIO output or open drain first.", "args": { @@ -592,7 +592,7 @@ "BP0037": { "name": "la_voltage_pins_in_use", "area": "io", - "since": "next", + "since": "4.0.0", "message": "The I/O voltage cannot change while pins are in use: {pins}", "cause": "Changing the I/O voltage under a running GPIO, UART, flash or sensor would put the wrong level on the DUT's pins, so the pod refuses until they are free.", "args": { @@ -608,7 +608,7 @@ "BP0038": { "name": "trigger_timeout", "area": "capture", - "since": "next", + "since": "4.0.0", "message": "No {edge} edge on LA{la} within {timeout_ms} ms", "cause": "A triggered capture waits for its trigger condition before it records. The DUT never made a {edge} edge on LA{la} in the time given, so the pod stopped waiting and recorded nothing.", "args": { @@ -626,7 +626,7 @@ "BP0039": { "name": "sensor_trigger_timeout", "area": "capture", - "since": "next", + "since": "4.0.0", "message": "No I2C start on LA{la} (SDA of {instance}) within {timeout_ms} ms: the DUT did not use the I2C bus", "cause": "A sensor bus capture with trigger \"start\" waits for the DUT's first I2C start condition on the emulated sensor's SDA. None came in time.", "args": { @@ -644,7 +644,7 @@ "BP0040": { "name": "lan_locked", "area": "policy", - "since": "next", + "since": "4.0.0", "message": "The pod's LAN is locked: {cmd} needs the cloud or USB", "cause": "The pod's LAN policy is locked, so commands that change settings, flash or update (tiers T2 and T3) only run from the cloud or over USB. Reads and tests still run on the LAN.", "args": { @@ -660,7 +660,7 @@ "BP0041": { "name": "policy_not_from_lan", "area": "policy", - "since": "next", + "since": "4.0.0", "message": "{setting} cannot be changed over the LAN: change it from the cloud or the USB console", "cause": "Policies that decide who may change the pod are only changed by someone with the pod's cloud account or its USB cable, never by anyone on the network.", "args": { @@ -676,7 +676,7 @@ "BP0042": { "name": "setting_cloud_or_usb", "area": "policy", - "since": "next", + "since": "4.0.0", "message": "{setting} cannot be changed over the LAN: change it from the cloud or over USB", "cause": "Settings that decide what the pod trusts (LAN TLS, the cloud CA, the cloud proxy) are not changed from the network. TLS on port 8443 has no client authentication, so it does not count either.", "args": { @@ -692,7 +692,7 @@ "BP0043": { "name": "setting_device_only", "area": "policy", - "since": "next", + "since": "4.0.0", "message": "{setting} can only be changed on the device: the USB console, or over the USB link", "cause": "This setting changes how the pod can be reached or updated, so it needs someone at the pod: its USB console or its USB network link. Neither the LAN nor the cloud may change it.", "args": { @@ -708,7 +708,7 @@ "BP0044": { "name": "policy_loosen_usb_only", "area": "policy", - "since": "next", + "since": "4.0.0", "message": "Only the USB console can loosen {setting} (now {now})", "cause": "The cloud may make the pod stricter but never looser: a stolen cloud account must not be able to lower the pod's firmware signature policy.", "args": { @@ -727,7 +727,7 @@ "BP0045": { "name": "role_required", "area": "policy", - "since": "next", + "since": "4.0.0", "message": "{cmd} needs an organization owner or admin", "cause": "A cloud session runs commands up to the tier the server allows its user. {cmd} changes or updates the pod, which needs an owner or admin of the pod's organization.", "args": { @@ -743,7 +743,7 @@ "BP0046": { "name": "no_analog_front_end", "area": "board", - "since": "next", + "since": "4.0.0", "message": "This BenchPod has no analog front end, so it cannot run {cmd}", "cause": "The digital board has no DAC, ADC or analog outputs. The pod checks at boot; after fitting an analog add-on, restart it.", "args": { @@ -759,7 +759,7 @@ "BP0047": { "name": "pod_busy", "area": "busy", - "since": "next", + "since": "4.0.0", "message": "The pod is running another long command (a capture, measurement, upload or update)", "cause": "Captures, measurements, waveform uploads and firmware updates share the pod's sample memory, so one runs at a time. Light commands (status, GPIO, ...) still run.", "args": {}, @@ -773,7 +773,7 @@ "BP0048": { "name": "storage_bus_busy", "area": "busy", - "since": "next", + "since": "4.0.0", "message": "The pod's storage bus is in use: {what}", "cause": "The flash that holds settings, gateware and update images shares a bus with the sample memory. While {what}, the pod cannot write it.", "args": { @@ -789,7 +789,7 @@ "BP0049": { "name": "uart_session_open", "area": "uart", - "since": "next", + "since": "4.0.0", "message": "A UART session is already open", "cause": "The pod runs one UART at a time: the web app's Terminal, a test, an MCP session or a flash over the UART holds it.", "args": {}, @@ -803,7 +803,7 @@ "BP0050": { "name": "swd_session_open", "area": "flash", - "since": "next", + "since": "4.0.0", "message": "An SWD session is already running", "cause": "The pod runs one SWD session (a flash or a debug run) at a time.", "args": {}, @@ -817,7 +817,7 @@ "BP0051": { "name": "update_in_progress", "area": "update", - "since": "next", + "since": "4.0.0", "message": "A {target} update from {holder} is in progress", "cause": "The pod takes one update at a time, from one place. Another one is running.", "args": { @@ -834,7 +834,7 @@ "BP0052": { "name": "cloud_command_busy", "area": "busy", - "since": "next", + "since": "4.0.0", "message": "The pod is still running the previous cloud command", "cause": "Over the cloud command channel the pod runs one command at a time. The server retries, so this is usually brief.", "args": {}, @@ -848,7 +848,7 @@ "BP0053": { "name": "reply_too_large", "area": "protocol", - "since": "next", + "since": "4.0.0", "message": "The reply did not fit the pod's reply buffer", "cause": "The command worked, but its answer is larger than the pod can send at once. Commands that can grow (la_pins) take a subset.", "args": {}, @@ -862,7 +862,7 @@ "BP0054": { "name": "cloud_reply_too_large", "area": "protocol", - "since": "next", + "since": "4.0.0", "message": "The reply is too large for the cloud channel ({bytes} bytes, limit {limit})", "cause": "Cloud command replies travel in one frame of at most {limit} bytes. This one is {bytes}. Large data (captures) go through the cloud byte tunnel instead.", "args": { @@ -879,7 +879,7 @@ "BP0055": { "name": "sensor_instance_unknown", "area": "sensors", - "since": "next", + "since": "4.0.0", "message": "The pod has no emulated sensor {instance}", "cause": "The instance was never defined or started on this pod, was stopped, or the pod restarted.", "args": { @@ -895,7 +895,7 @@ "BP0056": { "name": "no_module_link", "area": "board", - "since": "next", + "since": "4.0.0", "message": "This BenchPod has no module link, so it cannot run {cmd}", "cause": "Only boards with a module header (digital v3r3) talk to an add-on module.", "args": { @@ -911,7 +911,7 @@ "BP0057": { "name": "image_switch_sensors_running", "area": "sensors", - "since": "next", + "since": "4.0.0", "message": "The emulated sensors {sensors} need the emulation image; stop them before switching", "cause": "I2C, SPI and UART sensors run in the emulation gateware image. Switching to another image would stop them mid-run, so the pod refuses.", "args": { @@ -927,7 +927,7 @@ "BP0058": { "name": "fpga_image_required", "area": "firmware", - "since": "next", + "since": "4.0.0", "message": "{feature} is not in the running gateware image; it needs the {image} image", "cause": "The pod's FPGA runs one of three images (loop, deep replay, emulation), and each has some features. {feature} is in the {image} image.", "args": { @@ -944,7 +944,7 @@ "BP0059": { "name": "fpga_image_sensors_first", "area": "sensors", - "since": "next", + "since": "4.0.0", "message": "{feature} is not in the emulation image the emulated sensors use; stop them, then switch to the {image} image", "cause": "Emulated I2C, SPI and UART sensors run in the emulation gateware image, which has no room for {feature}. It needs the {image} image, and switching stops the sensors.", "args": { @@ -961,7 +961,7 @@ "BP0060": { "name": "ota_unknown_target", "area": "update", - "since": "next", + "since": "4.0.0", "message": "{target} is not an update target this firmware knows", "cause": "The firmware on the pod is older than the tool, or the target name is wrong.", "args": { @@ -977,7 +977,7 @@ "BP0061": { "name": "i2c_needs_pullups", "area": "i2c", - "since": "next", + "since": "4.0.0", "message": "I2C needs pull-ups: LA{la} has none switched on", "cause": "I2C lines are open drain: something must pull them high. The pod can do it with its own pull-ups, or the board has its own.", "args": { @@ -993,7 +993,7 @@ "BP0062": { "name": "i2c_session_not_open", "area": "i2c", - "since": "next", + "since": "4.0.0", "message": "No I2C session is open", "cause": "I2C transactions run inside a session that i2c_start opens.", "args": {}, @@ -1007,7 +1007,7 @@ "BP0063": { "name": "i2c_engine_reset", "area": "i2c", - "since": "next", + "since": "4.0.0", "message": "The I2C engine was reset, which ended the session", "cause": "A gateware reload (an image switch, a recovery) resets the I2C engine, so the open session is gone.", "args": {}, @@ -1021,7 +1021,7 @@ "BP0064": { "name": "loop_sweep_with_map", "area": "dac", - "since": "next", + "since": "4.0.0", "message": "The sweep input cannot be combined with an input map on this gateware", "cause": "The sweep spans the raw count range, not the mapped window, so most of each pass would sit at one end of the curve.", "args": {}, @@ -1035,7 +1035,7 @@ "BP0065": { "name": "output_used_by_sensor", "area": "sensors", - "since": "next", + "since": "4.0.0", "message": "The {output} output is played by the emulated sensor {instance}", "cause": "An analog emulated sensor drives the pod's {output} output, so a DAC or current command would fight it.", "args": { @@ -1052,7 +1052,7 @@ "BP0066": { "name": "step_busy", "area": "io", - "since": "next", + "since": "4.0.0", "message": "A step pulse train is running", "cause": "The pod runs one step train at a time.", "args": {}, @@ -1066,7 +1066,7 @@ "BP0067": { "name": "samples_out_of_range", "area": "capture", - "since": "next", + "since": "4.0.0", "message": "samples must be 1 to {max} for this capture", "cause": "Each capture holds a fixed number of samples: the shallow ADC capture what fits the RAM buffer, the deep ones what fits their PSRAM region at the rate asked for. A deep ADC capture is capture_dual with la_samples 0.", "args": { @@ -1082,7 +1082,7 @@ "BP0068": { "name": "la_rate_above_ceiling", "area": "capture", - "since": "next", + "since": "4.0.0", "message": "LA at {rate_mhz} MS/s does not fit: with ADC samples in the capture the raw LA runs at most {max_mhz} MS/s on this gateware, {fit_mhz} MS/s for {samples} samples", "cause": "On gateware before v53 the raw LA runs at most {max_mhz} MS/s when the same capture records ADC samples: faster, the PSRAM writer starved the ADC. The pod refuses an explicit rate it cannot run instead of slowing it down. {fit_mhz} MS/s is the fastest rate that fits {samples} samples. Above 12 MS/s the LA records its changes instead.", "args": { @@ -1101,7 +1101,7 @@ "BP0069": { "name": "la_rate_too_deep", "area": "capture", - "since": "next", + "since": "4.0.0", "message": "LA at {rate_mhz} MS/s does not fit {samples} samples: at most {max_samples} samples at {rate_mhz} MS/s, or at most {fit_mhz} MS/s for {samples} samples", "cause": "The raw LA samples into a burst buffer that drains to the PSRAM more slowly than the fastest rates. A capture deeper than the buffer holds at {rate_mhz} MS/s would drop samples, so the pod refuses it instead of slowing it down. Either way out works: fewer samples at this rate, or a lower rate for this depth.", "args": { @@ -1120,7 +1120,7 @@ "BP0070": { "name": "capture_dual_too_deep", "area": "capture", - "since": "next", + "since": "4.0.0", "message": "capture_dual takes at most {la_max} LA and {adc_max} ADC samples", "cause": "Each stream of a capture_dual has its own PSRAM region of a fixed size. A deeper LA-only capture fits la_capture, which takes up to {la_capture_max} LA samples.", "args": { @@ -1138,7 +1138,7 @@ "BP0071": { "name": "capture_overflowed", "area": "capture", - "since": "next", + "since": "4.0.0", "message": "The capture overflowed: the PSRAM could not keep up with LA {la_ksps} kS/s and ADC {adc_ksps} kS/s", "cause": "The capture started, but its streams wrote to the PSRAM faster than it could take them, so samples were lost and the pod returns none.", "args": { @@ -1155,7 +1155,7 @@ "BP0072": { "name": "psram_too_small", "area": "capture", - "since": "next", + "since": "4.0.0", "message": "The capture is too deep: LA, ADC and a loaded DAC waveform together exceed the 8 MB PSRAM", "cause": "A capture_dual packs its LA region, its ADC region and any deep-replay waveform still loaded into the pod's 8 MB PSRAM, and refuses up front when they do not fit.", "args": {}, @@ -1169,7 +1169,7 @@ "BP0073": { "name": "psram_bandwidth", "area": "capture", - "since": "next", + "since": "4.0.0", "message": "The combined sample rate is more than the PSRAM bus can take", "cause": "The LA, the ADC and a running deep replay share one PSRAM bus. The pod adds up their sustained rates and refuses a capture that would overrun it, instead of losing samples.", "args": {}, @@ -1183,7 +1183,7 @@ "BP0074": { "name": "signatures_always_required", "area": "policy", - "since": "next", + "since": "4.0.0", "message": "{setting} cannot be set to {want}: this firmware installs only signed images", "cause": "Firmware 4.0.0 and later take an update (firmware, gateware, the Wi-Fi chip's image) only with a good signature, on every path: the LAN, the USB network adapter and the cloud. No command loosens that. Dev builds also take images signed with the developer key. Firmware you built yourself goes in over USB DFU (`benchpod flash-self`), which needs the pod on a USB cable.", "args": { @@ -1200,7 +1200,7 @@ "BP0075": { "name": "lan_plaintext_off", "area": "policy", - "since": "next", + "since": "4.0.0", "message": "The pod serves its JSON API on the LAN over TLS only (port 8443): plaintext port 8080 is off", "cause": "Firmware 4.0.0 and later serve the JSON API over Ethernet and Wi-Fi on TLS port 8443 only. Plaintext port 8080 still answers on the USB network adapter, and from the LAN when SCPI is switched on, but only for SCPI there. Plaintext JSON on the LAN comes back only when it is switched on over USB or from the cloud.", "args": {}, @@ -1214,7 +1214,7 @@ "BP0076": { "name": "usb_host_over_usb", "area": "usb", - "since": "next", + "since": "4.0.0", "message": "USB host mode cannot start over the pod's own USB link", "cause": "While the pod hosts a board on its USB port it is off the computer's USB, so the connection that asked would drop before the answer arrives. USB host mode starts only over the network (LAN or Wi-Fi) or the cloud.", "args": {}, @@ -1228,7 +1228,7 @@ "BP0077": { "name": "usb_host_port_unavailable", "area": "usb", - "since": "next", + "since": "4.0.0", "message": "This pod has no USB host port {port}", "cause": "Only pods with a USB-A host port can host a board there. Every pod can host on its USB-C port, but only on a bench rig with an adapter cable that powers the pod and carries the data lines to the board under test.", "args": { @@ -1244,7 +1244,7 @@ "BP0078": { "name": "usb_host_no_crystal", "area": "usb", - "since": "next", + "since": "4.0.0", "message": "USB host mode needs the pod's crystal clock, which is not running", "cause": "A USB host keeps the bus timing itself and needs a precise clock. The pod runs on its internal oscillator because the crystal did not start at boot.", "args": {}, @@ -1258,7 +1258,7 @@ "BP0079": { "name": "usb_host_other_port", "area": "usb", - "since": "next", + "since": "4.0.0", "message": "USB host mode is already running on {port}", "cause": "The pod hosts one port at a time. A start for the same port renews the timeout; another port needs a stop first.", "args": { @@ -1274,7 +1274,7 @@ "BP0080": { "name": "dac_pinout_mismatch", "area": "analog", - "since": "next", + "since": "4.0.0", "message": "{cmd} refused, the DAC is off: the digital board ({digital}) and the analog module ({module}) use different flat-cable pinouts", "cause": "The flat cable between the two boards carries the DAC's clock and data. Digital board v3r4 and analog module 3.5 swapped those two lines, so a newer board paired with an older one would send the DAC scrambled data and its outputs could jump to any voltage. The pod refuses every command that drives the DAC and sends it nothing; everything else keeps working. The module's revision comes from its EEPROM, so a module that was never programmed counts as an older one.", "args": { @@ -1288,6 +1288,38 @@ "mcp": "tell the user the digital board and the analog module do not belong together (status shows both revisions): a digital v3r4+ board needs an analog module 3.5+, and an older digital board an older module", "web": "The digital board and the analog module do not belong together, so the analog outputs are off. A digital v3r4 or later board needs an analog module 3.5 or later." } + }, + "BP0081": { + "name": "lan_not_paired", + "area": "policy", + "since": "next", + "message": "This computer is not paired with the pod: {cmd} needs pairing over USB or from the cloud", + "cause": "The pod only takes commands from the LAN (Ethernet, Wi-Fi) from computers paired with it. An unpaired computer may only read the pod's status and whether it is registered. Pairing adds this computer's TLS client key to the pod: over the pod's USB-C cable once, or from embeddedci.com for a registered pod. USB itself never needs pairing.", + "args": { + "cmd": "str" + }, + "fix": { + "sdk": "pair this computer once: connect over USB and call bp.pair() (or run `benchpod setup`), or use the cloud (\"embeddedci:\")", + "cli": "plug the pod into this computer's USB-C port and run `benchpod setup` once, or use the cloud (--connection embeddedci:)", + "mcp": "tell the user this computer is not paired with the pod: they plug the pod into it over USB-C once and run `benchpod setup`, or connect through the cloud ('embeddedci:')", + "web": "This computer is not paired with the pod. Pair it from the pod's Settings tab, or plug the pod in over USB and run benchpod setup." + } + }, + "BP0082": { + "name": "lan_clients_full", + "area": "policy", + "since": "next", + "message": "The pod already has {max} paired computers", + "cause": "The pod keeps at most {max} paired computers (fewer when a large user certificate fills its flash record).", + "args": { + "max": "int" + }, + "fix": { + "sdk": "remove a computer you no longer use (bp.lan_clients(remove=...)) over USB or the cloud, then pair again", + "cli": "remove a computer you no longer use with `benchpod lan-clients remove `, then pair again", + "mcp": "tell the user the pod's list of paired computers is full; they remove one they no longer use", + "web": "This pod's list of paired computers is full. Remove one you no longer use." + } } } } diff --git a/internal/features/features.json b/internal/features/features.json index 1515380..0c7fa1d 100644 --- a/internal/features/features.json +++ b/internal/features/features.json @@ -1,10 +1,10 @@ { "_generated": "GENERATED by tools/gen_features.py from features/features.toml. DO NOT EDIT: edit the table.", "schema": 1, - "revision": 12, + "revision": 13, "api": 2, "min_client_api": 2, - "table_sha256": "875940ed02d7f8b7a9058803971565fc38e7f095d1795a80ee83627c563736dd", + "table_sha256": "4035ec709c8ba5a22bab6138d6cc18c22e1ff6f2d05569e833541f26a7808eaa", "floor": "3.9.2", "docs_base": "https://github.com/embeddedci-com/benchpod-firmware/blob/main/docs/", "facts": { @@ -775,6 +775,12 @@ "firmware": "next", "board": "any", "docs": "API.md#la_pins--report-every-la-pin" + }, + "lan_pairing": { + "rev": 13, + "firmware": "next", + "board": "any", + "docs": "API.md#lan_clients--paired-computers" } } } diff --git a/internal/serialconsole/lanclients.go b/internal/serialconsole/lanclients.go new file mode 100644 index 0000000..80cfde2 --- /dev/null +++ b/internal/serialconsole/lanclients.go @@ -0,0 +1,168 @@ +package serialconsole + +import ( + "context" + "errors" + "fmt" + "strconv" + "strings" +) + +// LAN pairing over the console (firmware 4.0.1+, docs/usb-serial-interface.md): +// +// lan-clients -> lan-clients of , pairing +// then " " per computer +// lan-clients add -> lan-clients added|renamed|same, then the list +// lan-clients remove -> the list | lan-clients error +// lan-tls -> lan-tls port 8443 https-only sha256 ... +// +// The console pairs a computer even while the pod's USB network adapter is off (built-in Wi-Fi +// turns it off). Older firmware answers "unknown command": ErrUnknownCommand. + +// LanClient is one paired computer. +type LanClient struct { + Name string + SHA256 string // of the computer's TLS client key (SubjectPublicKeyInfo) +} + +// LanClients is the pod's list of paired computers. +type LanClients struct { + Outcome string // after add: "added", "renamed" or "same" + Count int + Max int + Pairing bool // whether LAN computers must be paired + Clients []LanClient +} + +// Has reports whether key (64 hex digits) is paired. +func (l LanClients) Has(key string) bool { + for _, c := range l.Clients { + if strings.EqualFold(c.SHA256, key) { + return true + } + } + return false +} + +// LanClientsList runs `lan-clients`. +func (c *Console) LanClientsList(ctx context.Context) (LanClients, error) { + return c.lanClients(ctx, "lan-clients") +} + +// LanClientsAdd pairs the computer with key (64 hex digits) under name (no spaces). +func (c *Console) LanClientsAdd(ctx context.Context, name, key string) (LanClients, error) { + if name == "" || strings.ContainsAny(name, " \t\r\n\"") { + return LanClients{}, fmt.Errorf("lan-clients add: bad name %q", name) + } + if len(key) != 64 || strings.Trim(strings.ToLower(key), "0123456789abcdef") != "" { + return LanClients{}, fmt.Errorf("lan-clients add: the key must be 64 hex digits") + } + return c.lanClients(ctx, "lan-clients add "+name+" "+strings.ToLower(key)) +} + +// LanClientsRemove removes the computers named what, or the one key starting with what. +func (c *Console) LanClientsRemove(ctx context.Context, what string) (LanClients, error) { + if what == "" || strings.ContainsAny(what, " \t\r\n") { + return LanClients{}, fmt.Errorf("lan-clients remove: bad name or key %q", what) + } + return c.lanClients(ctx, "lan-clients remove "+what) +} + +// LanClientsClear forgets every paired computer. +func (c *Console) LanClientsClear(ctx context.Context) (LanClients, error) { + return c.lanClients(ctx, "lan-clients clear") +} + +func (c *Console) lanClients(ctx context.Context, line string) (LanClients, error) { + complete := func(acc string) bool { + l, err := parseLanClients(acc, line) + return err == nil && len(l.Clients) >= l.Count || (err != nil && !errors.Is(err, errNoLanClients)) + } + out, err := c.sendCommandUntil(ctx, line, line, "", complete) + l, perr := parseLanClients(out, line) + if perr == nil || !errors.Is(perr, errNoLanClients) { + return l, perr + } + if err != nil { + return LanClients{}, fmt.Errorf("lan-clients: %w", err) + } + return LanClients{}, fmt.Errorf("lan-clients: no reply from the pod (got: %q)", tail([]byte(out), 200)) +} + +var errNoLanClients = errors.New("no lan-clients reply yet") + +// parseLanClients reads the reply to line (the first copy of the echoed command is skipped). +func parseLanClients(raw, line string) (LanClients, error) { + var l LanClients + echoSeen, header := false, false + for _, ln := range consoleLines(raw) { + if strings.Contains(ln, "unknown command") { + return LanClients{}, ErrUnknownCommand + } + if !echoSeen && ln == line { + echoSeen = true + continue + } + rest, ok := strings.CutPrefix(ln, "lan-clients ") + if ok { + if why, isErr := replyError(rest); isErr { + return LanClients{}, &CommandError{Cmd: "lan-clients", Reason: why} + } + switch rest { + case "added", "renamed", "same": + l.Outcome = rest + continue + } + // " of , pairing " + f := strings.Fields(strings.ReplaceAll(rest, ",", " ")) + if len(f) >= 3 && f[1] == "of" { + n, err1 := strconv.Atoi(f[0]) + m, err2 := strconv.Atoi(f[2]) + if err1 == nil && err2 == nil { + l.Count, l.Max, header = n, m, true + l.Pairing = len(f) >= 5 && f[3] == "pairing" && f[4] == "on" + l.Clients = nil + } + } + continue + } + if header { + f := strings.Fields(ln) + if len(f) == 2 && len(f[1]) == 64 { + l.Clients = append(l.Clients, LanClient{Name: f[0], SHA256: f[1]}) + } + } + } + if !header { + return LanClients{}, errNoLanClients + } + return l, nil +} + +// LanTLSFingerprint is the SHA-256 of the pod's LAN TLS certificate, from `lan-tls`; "" when the +// pod has none. +func (c *Console) LanTLSFingerprint(ctx context.Context) (string, error) { + line := "lan-tls" + complete := func(acc string) bool { _, ok := lastReply(acc, "lan-tls", line); return ok } + out, err := c.sendCommandUntil(ctx, line, line, "", complete) + if strings.Contains(out, "unknown command") { + return "", ErrUnknownCommand + } + rest, ok := lastReply(out, "lan-tls", line) + if !ok { + if err != nil { + return "", fmt.Errorf("lan-tls: %w", err) + } + return "", fmt.Errorf("lan-tls: no reply from the pod (got: %q)", tail([]byte(out), 200)) + } + if why, isErr := replyError(rest); isErr { + return "", &CommandError{Cmd: "lan-tls", Reason: why} + } + f := strings.Fields(rest) + for i := 0; i+1 < len(f); i++ { + if f[i] == "sha256" && len(f[i+1]) == 64 { + return strings.ToLower(f[i+1]), nil + } + } + return "", nil +} diff --git a/internal/serialconsole/lanclients_test.go b/internal/serialconsole/lanclients_test.go new file mode 100644 index 0000000..cfda06f --- /dev/null +++ b/internal/serialconsole/lanclients_test.go @@ -0,0 +1,47 @@ +package serialconsole + +import ( + "errors" + "strings" + "testing" +) + +const keyA = "3f0c9a1e0000000000000000000000000000000000000000000000000000000a" +const keyB = "9b2e00000000000000000000000000000000000000000000000000000000000b" + +func TestParseLanClients(t *testing.T) { + line := "lan-clients add laptop " + keyA + raw := "> " + line + "\r\n[net] something\r\nlan-clients added\r\nlan-clients 2 of 32, pairing on\r\n" + + " laptop " + keyA + "\r\n ci-runner-1 " + keyB + "\r\n> " + l, err := parseLanClients(raw, line) + if err != nil { + t.Fatal(err) + } + if l.Outcome != "added" || l.Count != 2 || l.Max != 32 || !l.Pairing || len(l.Clients) != 2 { + t.Fatalf("got %+v", l) + } + if l.Clients[1].Name != "ci-runner-1" || !l.Has(strings.ToUpper(keyB)) || l.Has("00") { + t.Fatalf("clients %+v", l.Clients) + } +} + +func TestParseLanClientsEmptyAndOff(t *testing.T) { + l, err := parseLanClients("lan-clients\r\nlan-clients 0 of 8, pairing off\r\n> ", "lan-clients") + if err != nil || l.Count != 0 || l.Max != 8 || l.Pairing || len(l.Clients) != 0 { + t.Fatalf("got %+v, %v", l, err) + } +} + +func TestParseLanClientsErrors(t *testing.T) { + _, err := parseLanClients("lan-clients clear\r\nlan-clients error out of memory\r\n", "lan-clients clear") + var ce *CommandError + if !errors.As(err, &ce) || ce.Reason != "out of memory" { + t.Fatalf("error %v", err) + } + if _, err := parseLanClients("lan-clients\r\nunknown command: lan-clients\r\n", "lan-clients"); !errors.Is(err, ErrUnknownCommand) { + t.Fatalf("old firmware: %v", err) + } + if _, err := parseLanClients("lan-clients\r\n", "lan-clients"); !errors.Is(err, errNoLanClients) { + t.Fatalf("no reply: %v", err) + } +} diff --git a/internal/serialconsole/policy.go b/internal/serialconsole/policy.go index 74aa855..47885cc 100644 --- a/internal/serialconsole/policy.go +++ b/internal/serialconsole/policy.go @@ -33,7 +33,7 @@ type PolicyError = CommandError // Policy runs the console command cmd ("lan-policy" or "sig-policy"), setting the policy to set // when it is not empty, and returns what the pod reports afterwards. func (c *Console) Policy(ctx context.Context, cmd, set string) (PolicyReply, error) { - if cmd != "lan-policy" && cmd != "sig-policy" && cmd != "usb-network" { + if cmd != "lan-policy" && cmd != "sig-policy" && cmd != "usb-network" && cmd != "lan-pairing" { return PolicyReply{}, fmt.Errorf("unknown policy command %q", cmd) } line := cmd diff --git a/internal/serialconsole/probe.go b/internal/serialconsole/probe.go index 24bdb8e..1dc3578 100644 --- a/internal/serialconsole/probe.go +++ b/internal/serialconsole/probe.go @@ -42,6 +42,9 @@ type SerialPod struct { // different addresses (USB shows the wired IP, mDNS may answer on Wi-Fi) and the pod is not // registered yet, so there is no device id to match on. "" on firmware without `identity`. PublicKey string + // ShortID is the identity short id ("30a9f1"), what usb: names a pod by; "" on firmware + // without `identity`. + ShortID string } // Addressed reports whether the pod holds a usable IP address (it has a DHCP @@ -91,6 +94,7 @@ func ProbeSerial(preferred string, probeTimeout time.Duration) (pods []SerialPod ctx, cancel = context.WithTimeout(context.Background(), probeTimeout) if id, idErr := c.Identity(ctx); idErr == nil { pod.PublicKey = id.PublicKey + pod.ShortID = id.ShortID } cancel() _ = c.Close() diff --git a/internal/tcpclient/clientid.go b/internal/tcpclient/clientid.go new file mode 100644 index 0000000..52661a3 --- /dev/null +++ b/internal/tcpclient/clientid.go @@ -0,0 +1,269 @@ +package tcpclient + +// This computer's TLS client identity for LAN pairing (firmware 4.0.1+, docs/design/lan-pairing.md +// in benchpod-firmware). The pod asks every client on port 8443 for a certificate and trusts the +// ones whose public key is on its list of paired computers; pairing puts the key there, over the +// pod's USB cable or from embeddedci.com. +// +// One key per user, shared with the embeddedci SDK and the MCP server: client.key and client.crt +// next to known_pods.json ($XDG_CONFIG_HOME/benchpod-cli or ~/.config/benchpod-cli). They are made +// on first use. A CI runner without a home directory to keep them in passes its own: +// +// BENCHPOD_CLIENT_KEY_PEM the certificate and key PEM (a CI secret; `benchpod lan-clients add --new-key` prints one) +// BENCHPOD_CLIENT_CERT, BENCHPOD_CLIENT_KEY files + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/hex" + "encoding/pem" + "errors" + "fmt" + "math/big" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +const ( + clientKeyFile = "client.key" + clientCertFile = "client.crt" +) + +// ClientIdentityDir overrides the directory client.key and client.crt live in (tests). +var ClientIdentityDir string + +var ( + clientMu sync.Mutex + clientCert *tls.Certificate +) + +func clientDir() (string, error) { + if ClientIdentityDir != "" { + return ClientIdentityDir, nil + } + p, err := pinPath() + if err != nil { + return "", err + } + return filepath.Dir(p), nil +} + +// ClientIdentity is this computer's certificate and key, made on first use (see the file comment). +func ClientIdentity() (*tls.Certificate, error) { + clientMu.Lock() + defer clientMu.Unlock() + if clientCert != nil { + return clientCert, nil + } + c, err := loadClientIdentity() + if err != nil { + return nil, err + } + clientCert = c + return c, nil +} + +// ResetClientIdentity forgets the cached identity (tests, and after the files change). +func ResetClientIdentity() { + clientMu.Lock() + clientCert = nil + clientMu.Unlock() +} + +func loadClientIdentity() (*tls.Certificate, error) { + if pemData := strings.TrimSpace(os.Getenv("BENCHPOD_CLIENT_KEY_PEM")); pemData != "" { + c, err := tls.X509KeyPair([]byte(pemData), []byte(pemData)) + if err != nil { + return nil, fmt.Errorf("BENCHPOD_CLIENT_KEY_PEM: %w", err) + } + return withLeaf(&c) + } + certFile, keyFile := os.Getenv("BENCHPOD_CLIENT_CERT"), os.Getenv("BENCHPOD_CLIENT_KEY") + if certFile != "" || keyFile != "" { + if certFile == "" || keyFile == "" { + return nil, errors.New("set both BENCHPOD_CLIENT_CERT and BENCHPOD_CLIENT_KEY") + } + c, err := tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + return nil, fmt.Errorf("client certificate: %w", err) + } + return withLeaf(&c) + } + dir, err := clientDir() + if err != nil { + return nil, err + } + certPath, keyPath := filepath.Join(dir, clientCertFile), filepath.Join(dir, clientKeyFile) + if c, err := tls.LoadX509KeyPair(certPath, keyPath); err == nil { + return withLeaf(&c) + } else if !errors.Is(err, os.ErrNotExist) { + return nil, fmt.Errorf("client certificate %s: %w", certPath, err) + } + certPEM, keyPEM, err := NewClientIdentityPEM(defaultClientCN()) + if err != nil { + return nil, err + } + if err := os.MkdirAll(dir, 0o700); err != nil { + return nil, fmt.Errorf("client certificate: %w", err) + } + // The key first and exclusively: two processes starting at once must not end up with two + // different keys. The loser reads the winner's files. + if err := writeExclusive(keyPath, keyPEM, 0o600); err != nil { + if errors.Is(err, os.ErrExist) { + return waitForIdentity(certPath, keyPath) + } + return nil, fmt.Errorf("client key: %w", err) + } + if err := writeExclusive(certPath, certPEM, 0o644); err != nil { + return nil, fmt.Errorf("client certificate: %w", err) + } + c, err := tls.X509KeyPair(certPEM, keyPEM) + if err != nil { + return nil, err + } + return withLeaf(&c) +} + +func writeExclusive(path string, data []byte, mode os.FileMode) error { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, mode) + if err != nil { + return err + } + if _, err := f.Write(data); err != nil { + f.Close() + os.Remove(path) + return err + } + return f.Close() +} + +func waitForIdentity(certPath, keyPath string) (*tls.Certificate, error) { + var last error + for i := 0; i < 50; i++ { + c, err := tls.LoadX509KeyPair(certPath, keyPath) + if err == nil { + return withLeaf(&c) + } + last = err + time.Sleep(20 * time.Millisecond) + } + return nil, fmt.Errorf("client certificate: %w", last) +} + +func withLeaf(c *tls.Certificate) (*tls.Certificate, error) { + if c.Leaf == nil && len(c.Certificate) > 0 { + leaf, err := x509.ParseCertificate(c.Certificate[0]) + if err != nil { + return nil, fmt.Errorf("client certificate: %w", err) + } + c.Leaf = leaf + } + return c, nil +} + +func defaultClientCN() string { + h, _ := os.Hostname() + if h == "" { + h = "computer" + } + return "benchpod client " + h +} + +// NewClientIdentityPEM makes a new EC P-256 key and a self-signed client certificate for it: +// the certificate PEM and the key PEM (PKCS#8). +func NewClientIdentityPEM(cn string) (certPEM, keyPEM []byte, err error) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return nil, nil, err + } + serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 63)) + if err != nil { + return nil, nil, err + } + now := time.Now().UTC() + tmpl := &x509.Certificate{ + SerialNumber: serial, + Subject: pkix.Name{CommonName: cn}, + NotBefore: now.Add(-time.Hour), + NotAfter: now.AddDate(100, 0, 0), // the pod checks the key, not the dates + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) + if err != nil { + return nil, nil, err + } + pk, err := x509.MarshalPKCS8PrivateKey(key) + if err != nil { + return nil, nil, err + } + return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}), + pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: pk}), nil +} + +// SPKIHash is what the pod lists a paired computer by: the lowercase hex SHA-256 of the +// certificate's DER SubjectPublicKeyInfo. +func SPKIHash(cert *x509.Certificate) string { + sum := sha256.Sum256(cert.RawSubjectPublicKeyInfo) + return hex.EncodeToString(sum[:]) +} + +// ClientKeyHash is SPKIHash of this computer's identity. +func ClientKeyHash() (string, error) { + c, err := ClientIdentity() + if err != nil { + return "", err + } + return SPKIHash(c.Leaf), nil +} + +// PairingName is the name a computer pairs under: its host name, cut to what the pod takes +// (1-23 printable characters; no spaces, so the USB console takes it too). +func PairingName() string { + h, _ := os.Hostname() + return SanitizePairingName(strings.TrimSuffix(h, ".local")) +} + +// SanitizePairingName makes s a name the pod takes. +func SanitizePairingName(s string) string { + var b strings.Builder + for _, r := range s { + switch { + case r == ' ' || r == '\t': + b.WriteByte('-') + case r < 0x21 || r > 0x7e || r == '"' || r == '\\': + // dropped + default: + b.WriteRune(r) + } + if b.Len() >= 23 { + break + } + } + out := strings.Trim(b.String(), "-") + if len(out) > 23 { + out = out[:23] + } + if out == "" { + out = "computer" + } + return out +} + +// clientCertificate is the tls.Config hook: this computer's identity, or none when it cannot be +// read or made (the pod then treats the connection as unpaired and says so). +func clientCertificate(*tls.CertificateRequestInfo) (*tls.Certificate, error) { + c, err := ClientIdentity() + if err != nil { + return &tls.Certificate{}, nil + } + return c, nil +} diff --git a/internal/tcpclient/clientid_test.go b/internal/tcpclient/clientid_test.go new file mode 100644 index 0000000..8fafcf1 --- /dev/null +++ b/internal/tcpclient/clientid_test.go @@ -0,0 +1,93 @@ +package tcpclient + +import ( + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "encoding/hex" + "os" + "path/filepath" + "testing" +) + +func withClientDir(t *testing.T) string { + t.Helper() + dir := t.TempDir() + old := ClientIdentityDir + ClientIdentityDir = dir + ResetClientIdentity() + t.Setenv("BENCHPOD_CLIENT_KEY_PEM", "") + t.Setenv("BENCHPOD_CLIENT_CERT", "") + t.Setenv("BENCHPOD_CLIENT_KEY", "") + t.Cleanup(func() { ClientIdentityDir = old; ResetClientIdentity() }) + return dir +} + +func TestClientIdentityMadeOnceAndKept(t *testing.T) { + dir := withClientDir(t) + a, err := ClientKeyHash() + if err != nil { + t.Fatal(err) + } + st, err := os.Stat(filepath.Join(dir, clientKeyFile)) + if err != nil || st.Mode().Perm() != 0o600 { + t.Fatalf("key file: %v %v", err, st) + } + ResetClientIdentity() // a new process reads the same files + b, err := ClientKeyHash() + if err != nil || a != b || len(a) != 64 { + t.Fatalf("hash %q then %q (%v)", a, b, err) + } + c, _ := ClientIdentity() + if c.Leaf.ExtKeyUsage[0] != x509.ExtKeyUsageClientAuth { + t.Fatalf("usage %v", c.Leaf.ExtKeyUsage) + } + sum := sha256.Sum256(c.Leaf.RawSubjectPublicKeyInfo) + if hex.EncodeToString(sum[:]) != a { + t.Fatal("ClientKeyHash is not the SPKI hash") + } +} + +func TestClientIdentityFromEnvPEM(t *testing.T) { + withClientDir(t) + certPEM, keyPEM, err := NewClientIdentityPEM("ci-runner-1") + if err != nil { + t.Fatal(err) + } + t.Setenv("BENCHPOD_CLIENT_KEY_PEM", string(certPEM)+string(keyPEM)) + c, err := ClientIdentity() + if err != nil { + t.Fatal(err) + } + pair, _ := tls.X509KeyPair(certPEM, keyPEM) + leaf, _ := x509.ParseCertificate(pair.Certificate[0]) + if SPKIHash(c.Leaf) != SPKIHash(leaf) || c.Leaf.Subject.CommonName != "ci-runner-1" { + t.Fatal("not the environment's identity") + } + entries, _ := os.ReadDir(ClientIdentityDir) + if len(entries) != 0 { + t.Fatalf("wrote files with an environment identity: %v", entries) + } +} + +func TestClientIdentityHalfEnv(t *testing.T) { + withClientDir(t) + t.Setenv("BENCHPOD_CLIENT_CERT", "/nope.crt") + if _, err := ClientIdentity(); err == nil { + t.Fatal("one of the two file variables was accepted") + } +} + +func TestSanitizePairingName(t *testing.T) { + for in, want := range map[string]string{ + "Edward's MacBook Pro": "Edward's-MacBook-Pro", + "a\"b\\c": "abc", + "": "computer", + "build-runner-with-a-very-long-name-01": "build-runner-with-a-ver", + " x ": "x", + } { + if got := SanitizePairingName(in); got != want { + t.Errorf("%q: %q, want %q", in, got, want) + } + } +} diff --git a/internal/tcpclient/errors.go b/internal/tcpclient/errors.go index 91fa08a..8ff54fa 100644 --- a/internal/tcpclient/errors.go +++ b/internal/tcpclient/errors.go @@ -39,7 +39,8 @@ const ( // Refused is any other refusal: a bad argument, a missing feature, a failed operation, and // every refusal without a code (the client never reads a refusal's text). Refused RefusalKind = iota - // Locked is the LAN policy refusing a command on the LAN (BP0040). + // Locked is the LAN refusing a command: the LAN policy (BP0040), or a computer that is not + // paired with the pod (BP0081). Locked // Busy is the pod or one of its engines in use: a lease, the PSRAM bus, another session. Busy @@ -138,6 +139,8 @@ var codeKinds = map[string]RefusalKind{ "BP0078": Refused, // usb_host_no_crystal "BP0079": Refused, // usb_host_other_port "BP0080": Refused, // dac_pinout_mismatch + "BP0081": Locked, // lan_not_paired + "BP0082": Refused, // lan_clients_full } // CodeKind is the kind of a refusal code; ok is false for a code the table does not have. diff --git a/internal/tcpclient/tls.go b/internal/tcpclient/tls.go index 8e553f7..2a230fd 100644 --- a/internal/tcpclient/tls.go +++ b/internal/tcpclient/tls.go @@ -194,7 +194,10 @@ func tlsConfig(addr string, pin bool) (*tls.Config, error) { // ECDHE + ECDSA, a resumed one ~20 ms, and every command opens a connection. A resumed // session proves the same server as the full handshake whose certificate was pinned; // VerifyConnection still runs on it with that certificate. - cfg := &tls.Config{MinVersion: tls.VersionTLS12, ClientSessionCache: sessionCache} + cfg := &tls.Config{MinVersion: tls.VersionTLS12, ClientSessionCache: sessionCache, + // LAN pairing (clientid.go): firmware 4.0.1+ asks for a client certificate and lets in + // only paired keys beyond status; older firmware never asks. + GetClientCertificate: clientCertificate} if net.ParseIP(host) == nil { cfg.ServerName = host }