Files
usb-server/internal/bridge/bridge_test.go
T
duffyduckandClaude Opus 5 9ed473a965 Fix HID transfers, harden the tunnel, add E2E crypto and direct peers
The HID failure came down to the endpoint type map being indexed by
endpoint number without the direction bit. A composite device can have
endpoint 1 as both interrupt IN (0x81) and bulk OUT (0x01); the last one
read won, so interrupt URBs were submitted as bulk and the kernel rejected
them. The device attached and stayed silent.

Endpoint data now comes from the raw descriptors read from /dev/bus/usb
rather than sysfs, which only ever exposes the active alternate setting —
a webcam's isochronous endpoints are invisible there because they only
exist after SET_INTERFACE. Two sysfs parsing bugs fell out of that too:
the numeric endpoint attributes are hex without a prefix (wMaxPacketSize
"0040" was read as 40, not 64), and bInterval was never read at all.

Reliability: three places could freeze the whole process. The share path
fed io.Pipe from the WebSocket read loop, so one slow USB transfer stalled
every tunnel and the keepalives with them. The relay wrote to client
sockets while holding the hub lock, so one peer that stopped reading
blocked routing and registration for everyone. Control transfers ran
inline in the protocol loop behind a 5s timeout. Also fixed: a use-after-
free where a discarded URB's memory could be collected while the kernel
still owned it, a reap loop that spun at 100% CPU on ioctl errors, a
missing attach timeout, a double close(done) panic, and Hash[:8] in the
relay's log line, which let a client with a short hash take the server
down.

Adds mode "both", so one client can offer and consume devices at once.
The tunnel and client-left callbacks became multicast for it: as plain
fields the second manager to register silently unhooked the first.

Tunnel traffic is now AES-256-GCM end to end, on the relay path as well
as directly. The key is derived from the three tokens, not from the group
hash — the relay is told the hash, so a key derived from it would protect
nothing from the one party in the middle. Group IDs are unchanged, so
existing setups keep working; only clients configured without the tokens
drop to unencrypted, relay-only operation.

Peers now try to connect directly, with the relay supplying the public
address neither side can determine for itself. Candidates are raced
because an unreachable address hangs until timeout rather than refusing.
Falling back to the relay is not an error.

Platform reach: cross-compiled targets for ARM, MIPS and RISC-V (the
Linux client needed no code changes — usbdevfs is not architecture
specific), multi-arch Docker images, an Android bridge that accepts
devices over SCM_RIGHTS because apps cannot open /dev/bus/usb, and macOS
builds via system_profiler enumeration.

Adds a Windows KMDF filter driver under driver/windows with its Go side.
UNTESTED: it has never been compiled or run, needs the WDK to build and
an EV certificate to distribute. Treat it as a starting point.

Adds "usb-client diag": says per machine whether sharing and using are
possible, what stands in the way, and what fixes it. Reports can be
uploaded to a relay to get them off machines that are awkward to copy
from.

96 tests, all green under -race. Builds for linux, windows and darwin on
amd64 and arm64.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-11 22:02:04 +02:00

278 lines
6.7 KiB
Go

//go:build linux
package bridge
import (
"encoding/json"
"net"
"os"
"path/filepath"
"testing"
"time"
"github.com/duffy/usb-server/internal/usb"
"golang.org/x/sys/unix"
)
// A minimal but valid descriptor blob: device descriptor, one configuration,
// one HID interface, one interrupt IN endpoint.
func testDescriptors() []byte {
dev := []byte{
18, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 64,
0x6d, 0x04, // idVendor 046d
0x1c, 0xc0, // idProduct c01c
0x00, 0x01, // bcdDevice
1, 2, 3, 1,
}
iface := []byte{9, 0x04, 0, 0, 1, 0x03, 0x01, 0x02, 0}
ep := []byte{7, 0x05, 0x81, 0x03, 8, 0, 10}
body := append(iface, ep...)
cfg := append([]byte{9, 0x02, byte(9 + len(body)), 0, 1, 1, 0, 0x80, 250}, body...)
return append(dev, cfg...)
}
// send delivers one request, attaching fd if it is non-negative.
func send(t *testing.T, conn *net.UnixConn, req Request, fd int) Response {
t.Helper()
data, err := json.Marshal(req)
if err != nil {
t.Fatalf("marshalling request: %v", err)
}
var oob []byte
if fd >= 0 {
oob = unix.UnixRights(fd)
}
if _, _, err := conn.WriteMsgUnix(data, oob, nil); err != nil {
t.Fatalf("sending request: %v", err)
}
conn.SetReadDeadline(time.Now().Add(3 * time.Second))
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
t.Fatalf("reading response: %v", err)
}
var resp Response
if err := json.Unmarshal(buf[:n], &resp); err != nil {
t.Fatalf("parsing response %q: %v", buf[:n], err)
}
return resp
}
func startServer(t *testing.T) (*Server, *net.UnixConn) {
t.Helper()
path := filepath.Join(t.TempDir(), "bridge.sock")
srv, err := Listen(path)
if err != nil {
t.Fatalf("Listen: %v", err)
}
t.Cleanup(func() { srv.Close() })
conn, err := net.DialUnix("unix", nil, &net.UnixAddr{Name: path, Net: "unix"})
if err != nil {
t.Fatalf("dialling bridge: %v", err)
}
t.Cleanup(func() { conn.Close() })
return srv, conn
}
// openTestFD returns a real descriptor to hand over. Its contents do not
// matter — nothing in the bridge reads from it — only that it is open.
func openTestFD(t *testing.T) int {
t.Helper()
f, err := os.CreateTemp(t.TempDir(), "fd")
if err != nil {
t.Fatalf("creating temp file: %v", err)
}
defer f.Close()
fd, err := unix.Dup(int(f.Fd()))
if err != nil {
t.Fatalf("dup: %v", err)
}
return fd
}
func TestAddRegistersDeviceAndDescriptor(t *testing.T) {
usb.UnregisterExternalDevice("9-9")
srv, conn := startServer(t)
changed := make(chan struct{}, 1)
srv.OnChange = func() {
select {
case changed <- struct{}{}:
default:
}
}
resp := send(t, conn, Request{
Action: "add",
BusID: "9-9",
Descriptors: testDescriptors(),
BusNum: 9,
DevNum: 9,
Speed: 3,
ConfigValue: 1,
Manufacturer: "Test",
Product: "Keyboard",
}, openTestFD(t))
if !resp.OK {
t.Fatalf("add failed: %s", resp.Error)
}
t.Cleanup(func() { usb.UnregisterExternalDevice("9-9") })
select {
case <-changed:
case <-time.After(2 * time.Second):
t.Error("OnChange did not fire after a device was added")
}
// The device must show up in enumeration, parsed from the blob.
var found *usb.Device
for _, d := range usb.ExternalDevices() {
if d.BusID == "9-9" {
cp := d
found = &cp
}
}
if found == nil {
t.Fatal("device was not registered")
}
if found.VendorID != 0x046d || found.ProductID != 0xc01c {
t.Errorf("got %04x:%04x, want 046d:c01c", found.VendorID, found.ProductID)
}
if found.Product != "Keyboard" {
t.Errorf("product = %q, want %q", found.Product, "Keyboard")
}
// The endpoint has to survive with its real transfer type, which is the
// whole reason the descriptors are sent along.
ep, ok := found.Endpoints[0x81]
if !ok {
t.Fatal("endpoint 0x81 missing from the parsed descriptors")
}
if ep.TransferType != usb.TransferTypeInterrupt {
t.Errorf("endpoint type = %d, want interrupt", ep.TransferType)
}
if !usb.HasAdoptedFD("9-9") {
t.Error("the file descriptor was not adopted")
}
}
func TestAddRejectsMissingPieces(t *testing.T) {
_, conn := startServer(t)
tests := []struct {
name string
req Request
fd bool
}{
{"no bus id", Request{Action: "add", Descriptors: testDescriptors()}, true},
{"no descriptors", Request{Action: "add", BusID: "8-8"}, true},
{"no file descriptor", Request{Action: "add", BusID: "8-8", Descriptors: testDescriptors()}, false},
{"garbage descriptors", Request{Action: "add", BusID: "8-8", Descriptors: []byte{1, 2, 3}}, true},
{"unknown action", Request{Action: "frobnicate", BusID: "8-8"}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fd := -1
if tt.fd {
fd = openTestFD(t)
}
resp := send(t, conn, tt.req, fd)
if resp.OK {
t.Error("request was accepted but should have been rejected")
}
if resp.Error == "" {
t.Error("rejection carried no explanation")
}
})
}
if usb.HasAdoptedFD("8-8") {
t.Error("a rejected request left a descriptor behind")
usb.ReleaseAdoptedFDs()
}
}
func TestRemoveWithdrawsDevice(t *testing.T) {
_, conn := startServer(t)
resp := send(t, conn, Request{
Action: "add", BusID: "7-7", Descriptors: testDescriptors(), ConfigValue: 1,
}, openTestFD(t))
if !resp.OK {
t.Fatalf("add failed: %s", resp.Error)
}
resp = send(t, conn, Request{Action: "remove", BusID: "7-7"}, -1)
if !resp.OK {
t.Fatalf("remove failed: %s", resp.Error)
}
for _, d := range usb.ExternalDevices() {
if d.BusID == "7-7" {
t.Fatal("device is still registered after removal")
}
}
}
// The socket lets its holder make this client share arbitrary devices, so it
// must not be world-writable.
func TestSocketIsPrivate(t *testing.T) {
path := filepath.Join(t.TempDir(), "bridge.sock")
srv, err := Listen(path)
if err != nil {
t.Fatalf("Listen: %v", err)
}
defer srv.Close()
info, err := os.Stat(path)
if err != nil {
t.Fatalf("stat: %v", err)
}
if perm := info.Mode().Perm(); perm != 0600 {
t.Errorf("socket permissions are %04o, want 0600", perm)
}
}
// Restarting must not fail because the previous socket file is still there.
func TestListenReplacesStaleSocket(t *testing.T) {
path := filepath.Join(t.TempDir(), "bridge.sock")
first, err := Listen(path)
if err != nil {
t.Fatalf("first Listen: %v", err)
}
first.listener.Close() // simulate a crash: socket file survives
second, err := Listen(path)
if err != nil {
t.Fatalf("second Listen failed on a leftover socket: %v", err)
}
second.Close()
}
func TestCloseRemovesSocket(t *testing.T) {
path := filepath.Join(t.TempDir(), "bridge.sock")
srv, err := Listen(path)
if err != nil {
t.Fatalf("Listen: %v", err)
}
srv.Close()
if _, err := os.Stat(path); !os.IsNotExist(err) {
t.Error("the socket file outlived the server")
}
}