Files
usb-server/internal/diag/diag_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

199 lines
5.1 KiB
Go

package diag
import (
"encoding/json"
"strings"
"testing"
"github.com/duffy/usb-server/internal/usb"
)
func TestCollectProducesUsableReport(t *testing.T) {
report := Collect("test")
if report.Generated == "" {
t.Error("no timestamp")
}
if report.Tool.OS == "" || report.Tool.Arch == "" {
t.Error("platform not recorded")
}
if report.System.Hostname == "" {
t.Error("hostname not recorded")
}
// A report that says nothing about either capability is useless: the
// whole point is answering whether this machine can share or use.
if report.Sharing.Mechanism == "" && report.Sharing.Reason == "" {
t.Error("sharing capability has neither a mechanism nor a reason")
}
if report.Using.Mechanism == "" && report.Using.Reason == "" {
t.Error("using capability has neither a mechanism nor a reason")
}
}
func TestReportRoundTripsThroughJSON(t *testing.T) {
report := Collect("test")
data, err := report.JSON()
if err != nil {
t.Fatalf("JSON: %v", err)
}
var decoded Report
if err := json.Unmarshal(data, &decoded); err != nil {
t.Fatalf("decoding the report we just produced: %v", err)
}
if decoded.Tool.OS != report.Tool.OS {
t.Errorf("OS survived as %q, want %q", decoded.Tool.OS, report.Tool.OS)
}
if len(decoded.Devices) != len(report.Devices) {
t.Errorf("device count changed: %d -> %d", len(report.Devices), len(decoded.Devices))
}
}
// A failed check without a fix leaves the reader stuck, which defeats the
// purpose of the report.
func TestFailedChecksSuggestAFix(t *testing.T) {
report := Collect("test")
for _, check := range report.Checks {
if !check.Passed && check.Fix == "" && check.Detail == "" {
t.Errorf("check %q failed but says nothing about why or what to do", check.Name)
}
}
}
func TestStringOutputMentionsEverything(t *testing.T) {
report := &Report{
Generated: "2026-01-01T00:00:00Z",
Tool: ToolInfo{OS: "linux", Arch: "amd64"},
System: SystemInfo{Hostname: "testhost"},
Sharing: Capability{Available: true, Mechanism: "usbdevfs"},
Using: Capability{Available: false, Reason: "vhci-hcd is not loaded"},
Devices: []DeviceInfo{{
BusID: "1-2",
VendorID: "046d",
ProductID: "c52b",
Name: "Logitech Receiver",
Shareable: true,
Endpoints: []EndpointInfo{{
Address: "0x81",
Direction: "IN",
TransferType: "interrupt",
MaxPacket: 8,
Interval: 10,
}},
}},
Checks: []Check{
{Name: "vhci-hcd module", Passed: false,
Detail: "not loaded", Fix: "sudo modprobe vhci-hcd"},
},
}
out := report.String()
for _, want := range []string{
"testhost", "usbdevfs", "vhci-hcd is not loaded",
"1-2", "046d", "c52b", "Logitech Receiver",
"0x81", "interrupt",
"sudo modprobe vhci-hcd",
} {
if !strings.Contains(out, want) {
t.Errorf("output does not mention %q", want)
}
}
}
func TestTransferTypeNames(t *testing.T) {
tests := []struct {
input uint8
want string
}{
{usb.TransferTypeControl, "control"},
{usb.TransferTypeIsochronous, "isochronous"},
{usb.TransferTypeBulk, "bulk"},
{usb.TransferTypeInterrupt, "interrupt"},
{99, "unknown(99)"},
}
for _, tt := range tests {
if got := transferTypeName(tt.input); got != tt.want {
t.Errorf("transferTypeName(%d) = %q, want %q", tt.input, got, tt.want)
}
}
}
func TestEndpointInfoReportsDirection(t *testing.T) {
in := endpointInfo(usb.Endpoint{
Address: 0x81,
TransferType: usb.TransferTypeInterrupt,
MaxPacketSize: 8,
Interval: 10,
})
if in.Direction != "IN" {
t.Errorf("0x81 reported as %s, want IN", in.Direction)
}
if in.Address != "0x81" {
t.Errorf("address rendered as %q", in.Address)
}
out := endpointInfo(usb.Endpoint{Address: 0x02, TransferType: usb.TransferTypeBulk})
if out.Direction != "OUT" {
t.Errorf("0x02 reported as %s, want OUT", out.Direction)
}
}
func TestDiagURLAcceptsEveryRelayForm(t *testing.T) {
tests := []struct {
relay string
want string
}{
{"ws://relay:8443", "http://relay:8443/diag/abc"},
{"wss://relay.example.com", "https://relay.example.com/diag/abc"},
{"http://relay:8443", "http://relay:8443/diag/abc"},
{"https://relay:8443", "https://relay:8443/diag/abc"},
{"relay:8443", "http://relay:8443/diag/abc"},
{"ws://relay:8443/ws", "http://relay:8443/diag/abc"},
{"ws://relay:8443/", "http://relay:8443/diag/abc"},
}
for _, tt := range tests {
got, err := DiagURL(tt.relay, "abc")
if err != nil {
t.Errorf("DiagURL(%q): %v", tt.relay, err)
continue
}
if got != tt.want {
t.Errorf("DiagURL(%q) = %q, want %q", tt.relay, got, tt.want)
}
}
}
func TestDiagURLRejectsBadIDs(t *testing.T) {
for _, id := range []string{"", "a/b", "a?b", "a#b"} {
if _, err := DiagURL("ws://relay:8443", id); err == nil {
t.Errorf("DiagURL accepted the ID %q", id)
}
}
}
func TestTruncate(t *testing.T) {
tests := []struct {
in string
max int
want string
}{
{"short", 10, "short"},
{"exactly-10", 10, "exactly-10"},
{"this is far too long", 10, "this is..."},
{"abc", 2, "ab"},
}
for _, tt := range tests {
if got := truncate(tt.in, tt.max); got != tt.want {
t.Errorf("truncate(%q, %d) = %q, want %q", tt.in, tt.max, got, tt.want)
}
}
}