From de6ce3272493868cad9f511baae08f7406d2b55c Mon Sep 17 00:00:00 2001 From: Steven Beverly Date: Mon, 23 Nov 2026 06:37:27 -0700 Subject: [PATCH 1/2] fix(mdns): stop advertising the computer's hostname over mDNS PAIR published A records and an SRV target naming the machine's own hostname, which made it a second responder asserting the operating system's host name. macOS responds to that contention by renaming the computer's Local hostname to -2. PAIR now advertises a synthetic host label derived from the node UUID, retracts every record it claimed on shutdown, and no longer hashes that label into discovery record IDs, so existing nodes neither re-key nor re-pair. Closes #229 Signed-off-by: Steven Beverly --- docs/architecture.mdx | 4 + services/nvpair-cluster-manager/spec.md | 2 +- services/nvpair-node-scanner/daemon.go | 62 ++- services/nvpair-node-scanner/daemon_test.go | 139 +++++ services/nvpair-node-scanner/directory.go | 19 +- .../nvpair-node-scanner/directory_test.go | 140 ++++- services/nvpair-node-scanner/scanner.go | 43 +- .../nvpair-node-scanner/shutdown_wait_test.go | 102 ++++ services/nvpair-node-scanner/spec.md | 17 +- services/shared/mdns/responder.go | 224 ++++++-- services/shared/mdns/responder_test.go | 524 +++++++++++++++++- services/shared/nodeid/nodeid.go | 14 +- services/shared/nodeid/nodeid_test.go | 113 ++++ services/shared/noderec/hostlabel.go | 91 +++ services/shared/noderec/hostlabel_test.go | 232 ++++++++ services/shared/noderec/noderec.go | 5 +- services/tests/broker_test.go | 14 +- services/tests/cluster_data_plane_test.go | 8 +- services/tests/discovery_test.go | 15 +- services/tests/ghost_node_test.go | 8 +- services/tests/mdns_advertisement_test.go | 484 ++++++++++++++++ services/tests/models_http_test.go | 8 +- 22 files changed, 2153 insertions(+), 115 deletions(-) create mode 100644 services/nvpair-node-scanner/shutdown_wait_test.go create mode 100644 services/shared/noderec/hostlabel.go create mode 100644 services/shared/noderec/hostlabel_test.go create mode 100644 services/tests/mdns_advertisement_test.go diff --git a/docs/architecture.mdx b/docs/architecture.mdx index d066d723b..c6d657db0 100644 --- a/docs/architecture.mdx +++ b/docs/architecture.mdx @@ -631,6 +631,10 @@ PAIR keys the owned local node and authenticated peers by stable host UUID. That UUID correlates cluster membership, workload attribution, error reports, scheduling telemetry, and verified proxy routes. Hostnames are display names, so renaming a host or sharing a hostname does not merge distinct hosts. +PAIR's own host record follows that line: the scanner advertises it under a +synthetic host label, never a name the operating system owns, with the rule +that derives it in the `nvpair-node-scanner` spec §7.1. The computer's +hostname remains only the record's display instance name. Unverified announcements have independent discovery record IDs. Their claimed UUIDs cannot select a local or authenticated peer's record. A manual engine diff --git a/services/nvpair-cluster-manager/spec.md b/services/nvpair-cluster-manager/spec.md index bd43eceaa..5a73c4d0d 100644 --- a/services/nvpair-cluster-manager/spec.md +++ b/services/nvpair-cluster-manager/spec.md @@ -443,7 +443,7 @@ The exact `` is the per-user data dir shared by every component: `%L The Cluster Manager runs no responder or browser of its own. `nvpair-node-scanner` is the single discovery daemon on the node: the Broker registers this service's `cl` service key and listening port with that daemon, the daemon carries the key on this node's one consolidated `_nvpair-node._tcp` record, and the Cluster Manager learns peers by subscribing upward — `discovery:subscribe` filtered to the `cl` service — and consuming the `discovery:nodes` snapshots the Broker relays back. - **Registered port**: the inter-node listener, **`14321`** (one above `nvpair-workload-manager`'s `14320`; the pairing channel and the mTLS endpoints share it, distinguished by path and by whether the TLS handshake presents a client cert). It reaches the record as the `cl` service key. -- **The record layout is the daemon's contract, not this service's.** Service type, instance name, SRV port, and TXT keys are owned by the discovery daemon and the shared `nvpair-shared/noderec` wire format; this service reads the directory entries it is handed and never parses a record itself. The record's SRV port is a fixed, non-authoritative constant, so a consumer takes each service's port from TXT and never from SRV. The instance name is the OS hostname (the logical `nodeId`), surfaced on a directory entry as its `name` — display only, never trusted. +- **The record layout is the daemon's contract, not this service's.** Service type, instance name, SRV target host label, SRV port, and TXT keys are owned by the discovery daemon and the shared `nvpair-shared/noderec` wire format; this service reads the directory entries it is handed and never parses a record itself. The record's SRV target and A records carry the daemon's own synthetic host label, never a name the operating system owns (`nvpair-node-scanner` spec §7.1). The record's SRV port is a fixed, non-authoritative constant, so a consumer takes each service's port from TXT and never from SRV. The instance name is the OS hostname (the logical `nodeId`), surfaced on a directory entry as its `name` — display only, never trusted. - **TXT keys this service depends on** (all carried on the one consolidated record, alongside the other services' port keys): | Key | Value | Why | diff --git a/services/nvpair-node-scanner/daemon.go b/services/nvpair-node-scanner/daemon.go index b6c37651a..e90d5d314 100644 --- a/services/nvpair-node-scanner/daemon.go +++ b/services/nvpair-node-scanner/daemon.go @@ -73,6 +73,12 @@ type daemon struct { // empty selects nodeid's shared default (production's default layout). baseDir string + // hostLabel is the single DNS label PAIR claims as its mDNS host record — + // the SRV target and A owner name the responder advertises — derived from + // the node UUID by noderec.HostLabel, never the machine's name. Empty when + // HostLabel refused and this node advertises nothing over mDNS. + hostLabel string + // clusterDir is the cluster trust subtree (--cluster-dir) holding this node's // keypair, pins, and admission record. It gates whether we advertise a // cluster-uuid=: we advertise only while actually a member @@ -298,6 +304,12 @@ func telemetryRetryDelay(consecutiveFailures int) time.Duration { } // newDaemon builds the registry publisher and pinned peer discovery daemon. +// hostLabelOf is the source of the advertised mDNS host label. It is a +// variable only so a test can force the no-entropy error the real +// noderec.HostLabel cannot produce in-process (os.Hostname() never fails or +// empties here); production always uses noderec.HostLabel. +var hostLabelOf = noderec.HostLabel + func newDaemon(codec *Codec, mesh *clustertrust.Mesh, clusterDir string) *daemon { // nodeid reads /cluster/identity.json; --cluster-dir is that cluster // subdir, so its parent is the base. Empty -> nodeid's shared default. @@ -320,11 +332,18 @@ func newDaemon(codec *Codec, mesh *clustertrust.Mesh, clusterDir string) *daemon reg := newRegistry(hostUUID, cluUUID, netpick.LocalCandidates(netpick.Evidence{})) instance, _ := os.Hostname() + // The host record advertised over mDNS is PAIR's own label from the node + // UUID, never `instance`: claiming the machine's name is the contention + // that makes macOS append a digit to the computer's Local hostname (issue + // #229). The instance name stays the hostname — it is a display name and is + // legal even when the hostname is not a single DNS label. + hostLabel, labelErr := hostLabelOf(hostUUID, instance) d := &daemon{ codec: codec, mesh: mesh, reg: reg, instance: instance, + hostLabel: hostLabel, baseDir: baseDir, clusterDir: clusterDir, dir: newDirectory(), @@ -342,10 +361,30 @@ func newDaemon(codec *Codec, mesh *clustertrust.Mesh, clusterDir string) *daemon d.browser = NewDiscovery(noderec.ServiceType, noderec.Domain, WithKeyFunc(nodeDiscoveryRecordID), ) - if resp, err := mdns.NewResponder(instance, noderec.ServiceType, noderec.Domain, noderec.SRVPort, reg.txt()); err != nil { - slog.Warn("mDNS advertising disabled for _nvpair-node", "err", err) + if labelErr != nil { + // No entropy to name this host with; advertising a fixed placeholder + // would give every host on this path the same record, recreating the + // contention the synthetic label exists to avoid. Advertise nothing. + slog.Error("mDNS advertising disabled for _nvpair-node: no host label to advertise", + "err", labelErr, "baseDir", baseDir) } else { - d.responder = resp + // HostLabel is pure by design — it cannot log which rule produced the + // label — so ask it the fallback question directly: the same call with + // no node UUID is hostname-derived by definition, and an equal answer + // means the UUID passed in was empty or unusable, so the advertised + // name moves if the hostname moves. + if derived, derivedErr := noderec.HostLabel("", instance); derivedErr == nil && derived == hostLabel { + slog.Warn("advertising a hostname-derived mDNS host label", + "hostLabel", hostLabel, "hostUUID", hostUUID, + "reason", "no usable node identity, so the label follows the hostname and will move with it") + } + if resp, err := mdns.NewResponder(instance, hostLabel, noderec.ServiceType, noderec.Domain, + noderec.SRVPort, reg.txt()); err != nil { + slog.Warn("mDNS advertising disabled for _nvpair-node", "err", err) + } else { + d.responder = resp + slog.Info("advertising _nvpair-node", "instance", instance, "advertisedHost", resp.AdvertisedHost()) + } } return d } @@ -353,8 +392,17 @@ func newDaemon(codec *Codec, mesh *clustertrust.Mesh, clusterDir string) *daemon // run starts the _nvpair-node responder and browser, folding browse events into // the directory and emitting discovery:node-* until ctx is cancelled. func (d *daemon) run(ctx context.Context) { + // responderDone closes when responder.Run returns — including the + // shutdown goodbye it sends after ctx is cancelled (RFC 6762 §10.1), + // which is why Scanner.Run joins this before allowing process exit. + // Nil when the responder is disabled, meaning there is nothing to wait + // for. + var responderDone <-chan struct{} if d.responder != nil { + done := make(chan struct{}) + responderDone = done go func() { + defer close(done) if err := d.responder.Run(ctx); err != nil { slog.Warn("_nvpair-node responder exited", "err", err) } @@ -388,6 +436,14 @@ func (d *daemon) run(ctx context.Context) { if d.nodeInfoClients != nil { d.nodeInfoClients.CloseIdle() } + // responder.Run returns only after its shutdown goodbye has + // left the machine, so returning here first would let + // Scanner.Run return — and the process exit — with the + // retraction still unsent. The other background loops are not + // joined: after cancellation they hold nothing the wire still + // needs, and joining them could outlast the responder send for + // no retraction benefit. + waitForShutdown(responderDone, shutdownJoinTimeout, "_nvpair-node mDNS responder") return case ev, ok := <-events: if !ok { diff --git a/services/nvpair-node-scanner/daemon_test.go b/services/nvpair-node-scanner/daemon_test.go index 93802ae76..6069f0316 100644 --- a/services/nvpair-node-scanner/daemon_test.go +++ b/services/nvpair-node-scanner/daemon_test.go @@ -8,6 +8,7 @@ import ( "context" "crypto/tls" "encoding/json" + "errors" "fmt" "io" "net" @@ -30,6 +31,7 @@ import ( "nvpair-shared/clustertrust" "nvpair-shared/clustertrusttest" + "nvpair-shared/nodeid" "nvpair-shared/noderec" ) @@ -131,6 +133,114 @@ func newSelfTestDaemon(hostUUID, ip string) *daemon { } } +// TestNewDaemon_AdvertisesASyntheticHostLabelNotTheMachineName covers the +// newDaemon wiring no test reached before: newSelfTestDaemon builds a daemon +// literal, so the responder construction that decides which host name this +// node advertises over mDNS was never exercised by anything. +func TestNewDaemon_AdvertisesASyntheticHostLabelNotTheMachineName(t *testing.T) { + dir := t.TempDir() + // Pin the node identity through nodeid's own file so the label is + // UUID-derived (same trick as newDiscoveryPeerFixture), with a real UUID so + // HostLabel takes the UUID rule and not the hostname hash. + require.NoError(t, os.WriteFile(filepath.Join(dir, "node-id.json"), + []byte(`{"node_uuid":"6ba7b810-9dad-11d1-80b4-00c04fd430c8"}`), 0o600)) + // A nil codec is safe (emit and friends check for nil), and clustertrust.Open + // on a fresh directory yields an unclustered mesh. + logs := captureLogs(t) + + // baseDir becomes dir, so the pinned node-id.json is what nodeid.Resolve + // reads here. + d := newDaemon(nil, clustertrust.Open(dir), filepath.Join(dir, "cluster")) + + instance, err := os.Hostname() + require.NoError(t, err) + // Assert against nodeid.Resolve(dir) rather than a literal UUID so the + // expectation cannot drift from what the resolver hands the daemon. + want, err := noderec.HostLabel(nodeid.Resolve(dir), instance) + require.NoError(t, err) + assert.Equal(t, want, d.hostLabel, "newDaemon must advertise the HostLabel of the node UUID") + // With a usable node UUID, the label must be UUID-derived: the label + // HostLabel would have produced from the hostname alone must NOT be what is + // advertised. (Skips only where os.Hostname() is unusable, which is where + // no hostname-derived label exists to begin with.) + if fallback, fallbackErr := noderec.HostLabel("", instance); fallbackErr == nil { + assert.NotEqual(t, fallback, d.hostLabel, + "with a usable node UUID the label must not follow the hostname") + } + assert.NotContains(t, logs.String(), "hostname-derived", + "only a hostname-derived label is worth warning about; this one came from the node UUID") + + if d.responder == nil { + // A disabled responder is only an environment when the log names the + // multicast precondition NewResponder documents; any other reason to + // have no responder is the failure this test exists to catch. + if !strings.Contains(logs.String(), "no multicast-capable IPv4 interface") { + t.Fatalf("newDaemon left d.responder nil without naming the multicast precondition:\n%s", logs) + } + t.Skipf("no multicast-capable IPv4 interface on this host, so only the hostLabel wiring was asserted") + } + assert.Equal(t, want+".local.", d.responder.AdvertisedHost(), + "the responder's SRV target and A owner name is the synthetic label under the domain") + require.NotEqual(t, instance+".local.", d.responder.AdvertisedHost(), + "the machine's hostname must never become the advertised host record") +} + +// TestNewDaemon_WarnsWhenTheHostLabelIsHostnameDerived pins the operational +// warning beside that name: when the node UUID is empty or unusable the +// advertised label follows the machine's hostname and will move with it, so +// the log must say so rather than let an operator assume the name is stable. +func TestNewDaemon_WarnsWhenTheHostLabelIsHostnameDerived(t *testing.T) { + dir := t.TempDir() + // "self-uuid" is neither empty nor a usable UUID — fewer than twelve hex + // digits once sanitized — so HostLabel falls back to hashing the hostname. + require.NoError(t, os.WriteFile(filepath.Join(dir, "node-id.json"), + []byte(`{"node_uuid":"self-uuid"}`), 0o600)) + logs := captureLogs(t) + + d := newDaemon(nil, clustertrust.Open(dir), filepath.Join(dir, "cluster")) + + require.NotEmpty(t, d.hostLabel, "a hostname-derived label is still advertised, not withheld") + assert.Contains(t, logs.String(), "advertising a hostname-derived mDNS host label", + "the hostname-derived provenance of the label must be visible in the operational log") + assert.Contains(t, logs.String(), "level=WARN", "the warning must be visible at default log level") +} + +// TestNewDaemon_AdvertisesNothingWhenNoHostLabelCanBeDerived pins the branch +// D6 forbids any fallback into: when HostLabel finds no entropy at all, +// newDaemon must start no responder, claim no label, and name why in the +// operational log — never fall back to the machine's hostname. hostLabelOf +// stands in for the real derivation only because os.Hostname() never fails +// in-process, so the real HostLabel can never error here; nothing else about +// newDaemon's path is faked. +// +// Tests that touch hostLabelOf must not use t.Parallel: it is package state. +func TestNewDaemon_AdvertisesNothingWhenNoHostLabelCanBeDerived(t *testing.T) { + realHostLabelOf := hostLabelOf + t.Cleanup(func() { hostLabelOf = realHostLabelOf }) + hostLabelOf = func(string, string) (string, error) { + return "", errors.New("host label: no node UUID and no usable hostname to derive one from") + } + + dir := t.TempDir() + logs := captureLogs(t) + + d := newDaemon(nil, clustertrust.Open(dir), filepath.Join(dir, "cluster")) + + assert.Nil(t, d.responder, "without a host label the daemon must advertise nothing, not fall back to one") + assert.Empty(t, d.hostLabel, "no label may be claimed when HostLabel found no entropy") + assert.Contains(t, logs.String(), "no host label to advertise", + "the operational log must name why mDNS advertising was disabled") + assert.Contains(t, logs.String(), "level=ERROR", "the reason must be visible at default log level") + assert.NotContains(t, logs.String(), "advertisedHost", + "nothing was advertised, so no responder success line may have been logged") + + hostname, err := os.Hostname() + require.NoError(t, err) + require.NotEmpty(t, hostname, "this assertion is vacuous on a host with no hostname to leak") + require.NotContains(t, logs.String(), hostname, + "the machine hostname must not appear in any log line, least of all as a fallback advertised name") +} + // The scanner may create a UUID before cluster-manager writes identity.json. // Reloading must use the UUID from that file and remove the old local record. func TestReloadIdentity_UsesClusterIdentityUUIDAndRemovesOldRecord(t *testing.T) { @@ -558,6 +668,35 @@ func TestDiscovery_ReplacesUnverifiedDiscoveryWithVerifiedPeer(t *testing.T) { assert.Len(t, f.daemon.dir.snapshot(""), 1) } +// A promoted peer's record ID comes from the local certificate pin +// (Mesh.PeerRecordID), never from the observation hash, so the SRV target stays +// out of a verified identity on both sides of promotion. This test is a guard and +// not the red: it passes whether or not raw.Host is a hash input, because nothing +// on the pinning path reads that field. The tests that do fail while the SRV +// target is hashed are TestToDirectoryNode_DoesNotHashTheSRVTarget and +// TestNodeDiscoveryRecordID_IgnoresTheSRVTarget in directory_test.go. +func TestDiscovery_PinnedPeerRecordIDIgnoresTheSRVTarget(t *testing.T) { + f := newDiscoveryPeerFixture(t, "peer-uuid") + f.discover(t) + pinned, ok := f.daemon.dir.get("peer-uuid") + require.True(t, ok, "the pinned peer is missing from the directory") + require.Equal(t, noderec.IdentityPinned, pinned.IdentityVerification) + require.Equal(t, f.daemon.mesh.PeerRecordID("peer-uuid"), pinned.DiscoveryRecordID) + assert.False(t, strings.HasPrefix(pinned.DiscoveryRecordID, "observation:"), + "a verified record must not carry the unverified observation prefix (%q)", pinned.DiscoveryRecordID) + + // Announce the same connection candidate again, under another SRV target. + f.raw.Host = "another-host.local." + f.discover(t) + + again, ok := f.daemon.dir.get("peer-uuid") + require.True(t, ok, "the peer disappeared after re-announcing a different host label") + assert.Equal(t, pinned.DiscoveryRecordID, again.DiscoveryRecordID, + "the host label moved a verified record's ID") + snapshot := f.daemon.dir.snapshot("") + assert.Len(t, snapshot, 1, "the host label left a second record behind (%v)", snapshot) +} + // Authenticate a real pinned test peer and inspect the scanner's outbound // notifications. Exactly one full hardware snapshot must carry that verified // record's identity and the hardware supplied by its authenticated response. diff --git a/services/nvpair-node-scanner/directory.go b/services/nvpair-node-scanner/directory.go index 74f4fd37e..d61b70efc 100644 --- a/services/nvpair-node-scanner/directory.go +++ b/services/nvpair-node-scanner/directory.go @@ -55,16 +55,31 @@ func toDirectoryNode(raw RawNode) (noderec.DirectoryNode, bool) { } // nodeDiscoveryRecordID identifies a connection candidate, not its claimed owner. -// Address ordering and UUID/principal claims do not change that identity. +// Its inputs are the mDNS service instance name, the advertised node-info port, +// and the address set; address ordering and UUID or principal claims do not change +// that identity. +// +// The SRV target (RawNode.Host) is not an input, and must not become one. It is a +// host label PAIR claims for itself (noderec.HostLabel), so its value carries a +// host-identity claim from the network, and it moves on its own: a host whose +// config directory cannot be written and has no saved identity to read mints a +// new node UUID each start (nodeid.Resolve), so its label — and every record ID +// that hashed it — would change every boot. Every element of +// discoveryRecordID's input list is part of the key, so adding a field back +// there re-keys every unverified discovery fleet-wide rather than only new ones. func nodeDiscoveryRecordID(raw RawNode) string { rec := noderec.ParseTXT(raw.TXT) return discoveryRecordID(raw, rec.Services[noderec.ServiceNodeInfo], netpick.Candidates(raw.TXT, raw.Addresses)) } +// discoveryRecordID is the only producer of the "observation:" record ID prefix, +// shared by the browser's key and the projected directory record so they cannot +// drift. Its inputs are the connection candidate alone; see nodeDiscoveryRecordID +// before changing them. func discoveryRecordID(raw RawNode, nodeInfoPort int, addresses []string) string { addresses = slices.Clone(addresses) sort.Strings(addresses) - fields := []string{raw.ID, raw.Host, strconv.Itoa(nodeInfoPort)} + fields := []string{raw.ID, strconv.Itoa(nodeInfoPort)} fields = append(fields, addresses...) return fmt.Sprintf("observation:%x", sha256.Sum256([]byte(fmt.Sprintf("%q", fields)))) } diff --git a/services/nvpair-node-scanner/directory_test.go b/services/nvpair-node-scanner/directory_test.go index 4e0902e73..64baf259c 100644 --- a/services/nvpair-node-scanner/directory_test.go +++ b/services/nvpair-node-scanner/directory_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "nvpair-shared/netpick" "nvpair-shared/noderec" ) @@ -279,7 +280,44 @@ func TestToDirectoryNode_AddressOrderAndClaimChangesPreserveDiscoveryRecordID(t test("identity and other service claims change", claims) } +// netpick.Candidates deliberately preserves the publisher's order, so a node +// re-publishing its own instance can hand the hash the same address set in a +// different order: one fixture publishes "192.0.2.30,192.0.2.20", which is not +// sort.Strings order, and the other the reverse. Only the hash's own +// normalization keeps them at one record ID. The "resolved address order +// changes" case above cannot stand in for this one: its TXT publishes no +// ip=/ips=, so netpick.RankRemote's ascending tie-break sorts the addresses +// before the hash sees a difference. +func TestToDirectoryNode_PublishedAddressOrderChangesPreserveDiscoveryRecordID(t *testing.T) { + published := RawNode{ + ID: "spark", + Host: "nvpair-0123456789ab.local.", + Addresses: []string{"192.0.2.20", "192.0.2.30"}, + TXT: []string{ + "v=1", "uuid=spark-1", "ni=14318", + "ip=192.0.2.30", "ips=192.0.2.30,192.0.2.20", + }, + } + republished := published + republished.TXT = []string{ + "v=1", "uuid=spark-1", "ni=14318", + "ip=192.0.2.20", "ips=192.0.2.20,192.0.2.30", + } + + first, ok := toDirectoryNode(published) + require.True(t, ok, "published observation was not projected") + second, ok := toDirectoryNode(republished) + require.True(t, ok, "re-published observation was not projected") + require.NotEmpty(t, first.DiscoveryRecordID) + assert.Equal(t, first.DiscoveryRecordID, second.DiscoveryRecordID, + "swapping the published ip=/ips= order changed the discovery record ID") +} + func TestToDirectoryNode_DifferencesInDiscoveryFieldsYieldDifferentDiscoveryRecordIDs(t *testing.T) { + // Every field listed here is a hash input by rule. The SRV target used to be + // one of these cases; it is no longer a discovery field, and + // TestToDirectoryNode_DoesNotHashTheSRVTarget and + // TestNodeDiscoveryRecordID_IgnoresTheSRVTarget now pin that invariant. test := func(name string, candidate RawNode) { t.Run(name, func(t *testing.T) { original, ok := toDirectoryNode(observationFixture()) @@ -295,9 +333,6 @@ func TestToDirectoryNode_DifferencesInDiscoveryFieldsYieldDifferentDiscoveryReco instance := observationFixture() instance.ID = "another-instance" test("different service instance", instance) - host := observationFixture() - host.Host = "another-host.local." - test("different resolved host", host) address := observationFixture() address.Addresses = []string{"192.0.2.30"} test("copied UUID at another resolved address", address) @@ -309,6 +344,105 @@ func TestToDirectoryNode_DifferencesInDiscoveryFieldsYieldDifferentDiscoveryReco test("different node-info port", port) } +// The SRV target is a PAIR-claimed host label (noderec.HostLabel), so it is not +// an input to an unverified record ID: a record whose service instance, advertised +// node-info port and address set are unchanged keeps its ID as the label the peer +// advertises moves — including the move from a hostname-derived label to a +// synthetic one when a node upgrades. +func TestToDirectoryNode_DoesNotHashTheSRVTarget(t *testing.T) { + original, ok := toDirectoryNode(observationFixture()) + require.True(t, ok, "original observation was not projected") + require.NotEmpty(t, original.DiscoveryRecordID) + + test := func(name, advertisedHost string) { + t.Run(name, func(t *testing.T) { + candidate := observationFixture() + candidate.Host = advertisedHost + next, ok := toDirectoryNode(candidate) + require.True(t, ok, "candidate observation was not projected") + require.NotEmpty(t, next.DiscoveryRecordID) + assert.Equal(t, original.DiscoveryRecordID, next.DiscoveryRecordID, + "host label %q changed the unverified record ID", advertisedHost) + }) + } + + test("hostname-derived label replaced by another hostname", "another-host.local.") + test("hostname-derived label replaced by the synthetic PAIR label", "nvpair-0123456789ab.local.") + test("SRV target missing or unresolvable in the browse result", "") +} + +// nodeDiscoveryRecordID is the key daemon.go hands the browser (WithKeyFunc) and +// the key the directory stores unverified records under, so the SRV-target rule +// has to hold there too and not only on the projected node. +// +// The fixture publishes an ip= the browse did not resolve, so the two address +// sources the call sites could use differ: the projection hashes +// netpick.Candidates(...) while the browser key hashes whatever +// nodeDiscoveryRecordID feeds it, and an agreement assertion between them is +// only worth having while those inputs are distinguishable. +func TestNodeDiscoveryRecordID_IgnoresTheSRVTarget(t *testing.T) { + base := observationFixture() + base.TXT = append(base.TXT, "ip=192.0.2.30") + require.NotEqual(t, netpick.Candidates(base.TXT, base.Addresses), base.Addresses, + "the published ip= must stay outside the resolved set, or the call-site agreement assertion below is toothless") + baseID := nodeDiscoveryRecordID(base) + require.NotEmpty(t, baseID) + + for _, advertisedHost := range []string{"another-host.local.", "nvpair-0123456789ab.local.", ""} { + // RawNode has no nested state this test mutates: only the scalar Host + // field differs, so the copy needs no deep copy of the slices. + candidate := base + candidate.Host = advertisedHost + assert.Equal(t, baseID, nodeDiscoveryRecordID(candidate), + "host label %q reached the record key the browser and directory use", advertisedHost) + // Both call sites must still agree: a change to one of them would re-key + // the directory under the key the browser no longer uses. + node, ok := toDirectoryNode(candidate) + require.True(t, ok, "observation with host %q was not projected", advertisedHost) + assert.Equal(t, nodeDiscoveryRecordID(candidate), node.DiscoveryRecordID, + "the projected record and the browser key diverged for host %q", advertisedHost) + } +} + +// The byte-identity proof for this record ID: one exact digest for one fixed +// input, pinned in the tree rather than in a scratch program. The two cases are +// one address set published in two orders, so removing the hash's +// order-insensitivity breaks the first; letting any field that is not a +// connection input into the hash breaks both — the SRV target and port are +// populated right here precisely to make that mistake tempting to commit. +func TestDiscoveryRecordID_MatchesThePinnedGoldenDigest(t *testing.T) { + test := func(name string, addresses []string) { + t.Run(name, func(t *testing.T) { + raw := RawNode{ + ID: "workstation", + Host: "nvpair-a1b2c3d4e5f6.local.", + Port: noderec.SRVPort, + } + // sha256 over fmt.Sprintf("%q", fields) for fields = + // ["workstation" "14318" "192.0.2.10" "192.0.2.20" "192.0.2.30"], + // the addresses in sort.Strings order. Updating this digest is a + // deliberate, rollout-impacting act: it re-keys every unverified + // discovery in the field at once. + assert.Equal(t, "observation:a719ee0865d3fe75d10ba7711aa94290d5d1a191ff898a8a0f9577d1cf562678", + discoveryRecordID(raw, 14318, addresses)) + }) + } + test("published order", []string{"192.0.2.30", "192.0.2.10", "192.0.2.20"}) + test("sorted order", []string{"192.0.2.10", "192.0.2.20", "192.0.2.30"}) +} + +// The caller's ranked address order is a candidate preference the hash must read +// without rewriting: it sorts a clone, so a slice handed to it stays in the +// publication order its owner is still using. +func TestDiscoveryRecordID_LeavesTheCallersAddressOrderAlone(t *testing.T) { + raw := RawNode{ID: "workstation", Host: "workstation.local."} + addresses := []string{"192.0.2.30", "192.0.2.10", "192.0.2.20"} + want := []string{"192.0.2.30", "192.0.2.10", "192.0.2.20"} + recordID := discoveryRecordID(raw, 14318, addresses) + require.NotEmpty(t, recordID) + assert.Equal(t, want, addresses, "discoveryRecordID sorted the caller's slice in place") +} + func TestToDirectoryNode_ClaimsNeverVerifyIdentity(t *testing.T) { node, ok := toDirectoryNode(observationFixture()) require.True(t, ok, "observation was not projected") diff --git a/services/nvpair-node-scanner/scanner.go b/services/nvpair-node-scanner/scanner.go index ed1491b23..0b6d0ced5 100644 --- a/services/nvpair-node-scanner/scanner.go +++ b/services/nvpair-node-scanner/scanner.go @@ -9,6 +9,7 @@ import ( "io" "log" "log/slog" + "time" "nvpair-shared/applog" "nvpair-shared/clustertrust" @@ -63,9 +64,47 @@ func (s *Scanner) Run(ctx context.Context) error { return fmt.Errorf("failed to send ready notification: %w", err) } - go s.daemon.run(ctx) + daemonDone := make(chan struct{}) + go func() { + defer close(daemonDone) + s.daemon.run(ctx) + }() + + err := s.readLoop(ctx) + // The daemon's mDNS responder sends its RFC 6762 §10.1 shutdown + // retraction only after ctx is cancelled, and readLoop's stdin-EOF + // return path is exactly such a moment with ctx still live (the broker + // vanished; nothing cancelled us). Cancel explicitly — the kept + // defer cancel() would only run after this wait, and the daemon's join + // would deadlock on a context nobody cancels — then wait for the daemon + // so the retraction has left the machine before Run returns and main + // may exit. + cancel() + waitForShutdown(daemonDone, shutdownJoinTimeout, "discovery daemon") + return err +} - return s.readLoop(ctx) +// shutdownJoinTimeout bounds the waits Scanner.Run and daemon.run take for +// the mDNS responder's shutdown retraction to finish. A send is one small +// multicast per interface, so the timeout only fires when a socket send +// itself stalls; dropping the retraction is then the price of a bounded +// shutdown, which beats hanging the broker's wait forever. +const shutdownJoinTimeout = 2 * time.Second + +// waitForShutdown waits for done to close, bounded by timeout. A nil done +// means the responder is disabled and there is nothing to wait for. The +// timeout logs at Warn because the cost of giving up is every peer holding +// our dead node's records until the record TTL expires. +func waitForShutdown(done <-chan struct{}, timeout time.Duration, what string) { + if done == nil { + return + } + select { + case <-done: + case <-time.After(timeout): + slog.Warn("shutdown wait gave up before component returned", + "component", what, "timeout", timeout) + } } func (s *Scanner) readLoop(ctx context.Context) error { diff --git a/services/nvpair-node-scanner/shutdown_wait_test.go b/services/nvpair-node-scanner/shutdown_wait_test.go new file mode 100644 index 000000000..077fef441 --- /dev/null +++ b/services/nvpair-node-scanner/shutdown_wait_test.go @@ -0,0 +1,102 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package main + +import ( + "context" + "io" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "nvpair-shared/clustertrust" +) + +// These pin the shutdown waits that let the mDNS responder's goodbye +// retraction (RFC 6762 §10.1) leave the machine before the process exits: +// Scanner.Run joins the daemon, and daemon.run joins responder.Run. The +// Scanner.Run half is exercised end-to-end by +// TestScannerRun_DoesNotReturnBeforeTheDaemonHasShutDownWhenStdinEOFs; the +// per-interface send it is waiting for is pinned in the shared mdns +// package's goodbye tests, and live SIGTERM wire capture is a Task 7 +// deliverable. + +func TestWaitForShutdown_ReturnsImmediatelyWhenNothingToJoin(t *testing.T) { + // A daemon built without an mDNS responder hands down a nil done + // channel: there is no retraction waiting to be sent, so shutdown must + // not pay the join timeout for it. + logs := captureLogs(t) + start := time.Now() + waitForShutdown(nil, 5*time.Second, "_nvpair-node mDNS responder") + assert.Less(t, time.Since(start), time.Second, + "a nil done channel means nothing to wait for, so the wait must not block") + assert.NotContains(t, logs.String(), "gave up", + "joining nothing is not a failed shutdown and must not log a give-up warning") +} + +func TestWaitForShutdown_ReturnsAsSoonAsDoneCloses(t *testing.T) { + logs := captureLogs(t) + done := make(chan struct{}) + go func() { + time.Sleep(10 * time.Millisecond) + close(done) + }() + start := time.Now() + waitForShutdown(done, 5*time.Second, "_nvpair-node mDNS responder") + assert.Less(t, time.Since(start), time.Second, + "the wait must end on done closing, not on the timeout expiring") + assert.NotContains(t, logs.String(), "gave up", + "a shutdown that finished inside its budget must not be reported as timed out") +} + +func TestWaitForShutdown_WarnsNamingTheComponentWhenTheWaitExpires(t *testing.T) { + // Giving up means peers keep our dead node's records until the record + // TTL expires, so the wait that expired has to be visible at the warn + // level the desktop configures by default, and name the component that + // never came back — without the name, a give-up line says only that + // some anonymous join lost, not which retraction was lost. + logs := captureLogs(t) + start := time.Now() + waitForShutdown(make(chan struct{}), 10*time.Millisecond, "_nvpair-node mDNS responder") + assert.GreaterOrEqual(t, time.Since(start), 10*time.Millisecond, + "the wait must honor the timeout it was given, not return early") + + gotLogs := logs.String() + assert.Contains(t, gotLogs, "level=WARN", + "a shutdown wait that timed out is retraction loss and must not hide below the desktop's default log level") + assert.Contains(t, gotLogs, `component="_nvpair-node mDNS responder"`, + "the give-up line must name which component never returned, i.e. whose retraction was lost") +} + +// TestScannerRun_DoesNotReturnBeforeTheDaemonHasShutDownWhenStdinEOFs pins +// the deadlock trap and the join together on the real code path: broker +// gone means stdin EOFs while ctx is still live, so Scanner.Run must cancel +// the daemon's context itself before joining it. Forget that cancel and the +// daemon sits in its ctx.Done select until the join times out — Run still +// returns, but two seconds late and with a give-up warning, which is what +// this test fails on. (A permanent hang cannot survive the test binary's +// own timeout, and the 5s wait here is far below go test's default 10m.) +func TestScannerRun_DoesNotReturnBeforeTheDaemonHasShutDownWhenStdinEOFs(t *testing.T) { + logs := captureLogs(t) + clusterDir := t.TempDir() + sc := NewScanner( + NewCodec(&stdioTransport{Reader: strings.NewReader(""), Writer: io.Discard}), + clustertrust.Open(clusterDir), clusterDir) + + returned := make(chan error, 1) + go func() { returned <- sc.Run(context.Background()) }() + + select { + case err := <-returned: + require.NoError(t, err, "stdin EOF is a clean broker departure, not an error to report to the broker") + case <-time.After(5 * time.Second): + t.Fatal("Scanner.Run never returned after stdin EOF: shutdown deadlocked") + } + + assert.NotContains(t, logs.String(), "gave up", + "Scanner.Run reached its daemon join only through its own cancel; if the daemon had to wait out the join timeout the explicit cancel before the wait is missing") +} diff --git a/services/nvpair-node-scanner/spec.md b/services/nvpair-node-scanner/spec.md index aec4c59fc..d87bb3294 100644 --- a/services/nvpair-node-scanner/spec.md +++ b/services/nvpair-node-scanner/spec.md @@ -173,8 +173,12 @@ the host that record describes. For an unverified discovery, `hostUuid` is only an advertised claim. Two announcements can claim the same `hostUuid` while receiving different `discoveryRecordId` values because their service instances or connection endpoints differ. Those distinct record IDs let Scanner track -the candidates separately while checking their claims. Neither identifier proves -ownership of a host; `identityVerification` records how identity was established. +the candidates separately while checking their claims. A record ID is +computed from the announcement's service instance name, its advertised +node-info port, and its address set; the SRV host label is not an input, so a +node re-advertising under a different host label with those unchanged keeps +its record ID. Neither identifier proves ownership of a host; +`identityVerification` records how identity was established. ## 7. API / Interface Contract @@ -293,6 +297,15 @@ connecting. Verified peer ports come from authenticated node-info metadata. Unknown service keys with valid ports are retained. The TXT record lists at most four addresses, in preferred order. +The SRV target, and the address (A) records published with the announcement, +share one host label that Scanner derives from the node UUID: `nvpair-` plus +the UUID's first twelve hex digits, lowercased, for example `nvpair-f0e1d2c34b5a` +(`noderec.HostLabel`). It is a name PAIR claims for itself, never the +machine's hostname. With no usable node UUID, the label instead hashes the +hostname under the same prefix and Scanner warns that the name follows host +renames; with no usable UUID and no hostname, Scanner starts no `_nvpair-node` +responder at all and advertises nothing over mDNS. + The service instance name comes from the hostname. It can help distinguish discovery records, but cannot establish a verified host's identity. Different hosts may use the same name. diff --git a/services/shared/mdns/responder.go b/services/shared/mdns/responder.go index 6ce42fd4c..42e51198a 100644 --- a/services/shared/mdns/responder.go +++ b/services/shared/mdns/responder.go @@ -36,7 +36,6 @@ import ( "fmt" "log/slog" "net" - "os" "strings" "sync" "time" @@ -78,7 +77,7 @@ type Responder struct { service string // e.g. "_nvpair-ollama._tcp" domain string // e.g. "local" port int - hostName string // e.g. "myhost.local." + hostName string // the host record PAIR owns, e.g. "nvpair-0123456789ab.local."; never derived from the environment serviceName string // "_nvpair-ollama._tcp.local." instanceName string // "myhost._nvpair-ollama._tcp.local." @@ -98,11 +97,22 @@ type Responder struct { ifaceAddrs map[int][]net.IP } +// enumerateSnapshot is the source of interface addresses. It is a variable +// only so a test can supply a snapshot on a host with no multicast-capable +// interface; production always uses netmon.Enumerate. +var enumerateSnapshot = netmon.Enumerate + // NewResponder builds a Responder for the given service instance. domain -// defaults to "local" if empty. The hostname is taken from os.Hostname(). -// Returns an error if no multicast-capable IPv4 interface with at least one -// non-loopback address can be found. -func NewResponder(instance, service, domain string, port int, txt []string) (*Responder, error) { +// defaults to "local" if empty. hostLabel is the single DNS label the responder +// claims as its own host record — the SRV target and the owner name of its A +// records, as returned by AdvertisedHost — never the machine's hostname; +// claiming that contends with the host's own mDNS responder over a name it +// already owns (RFC 6762 §9 renamed macOS Local hostnames, issue #229). +// hostLabel is one label, not an FQDN: a trailing dot is decoration (trimmed, +// like the instance and service), anything else that is not one DNS label is +// refused. Returns an error if no multicast-capable IPv4 interface with at +// least one non-loopback address can be found. +func NewResponder(instance, hostLabel, service, domain string, port int, txt []string) (*Responder, error) { domain = strings.Trim(domain, ".") if domain == "" { domain = "local" @@ -120,12 +130,16 @@ func NewResponder(instance, service, domain string, port int, txt []string) (*Re return nil, errors.New("missing port") } - hostBase, err := os.Hostname() - if err != nil { - return nil, fmt.Errorf("hostname: %w", err) + // A trailing dot is decoration, trimmed like the other name arguments, so a + // caller that passed an FQDN ("nvpair-x.local.") is refused below for + // carrying two labels instead of being assembled into one name by accident. + // Validation runs before enumerating interfaces so a bad label is rejected + // cheaply and identically on every host. + hostLabel = strings.TrimSuffix(hostLabel, ".") + if err := validateHostLabel(hostLabel); err != nil { + return nil, err } - hostBase = strings.Trim(hostBase, ".") - hostName := hostBase + "." + domain + "." + hostName := hostLabel + "." + domain + "." r := &Responder{ instance: instance, @@ -139,7 +153,7 @@ func NewResponder(instance, service, domain string, port int, txt []string) (*Re // netmon's IfaceV4 applies the same filter we used to build by hand // (up + multicast + non-loopback interface, non-loopback IPv4), and // is what watchAddrs feeds back on every change. - ifaceAddrs: netmon.Enumerate().IfaceV4, + ifaceAddrs: enumerateSnapshot().IfaceV4, } if len(r.ifaceAddrs) == 0 { return nil, errors.New("no multicast-capable IPv4 interfaces with non-loopback addresses") @@ -147,6 +161,34 @@ func NewResponder(instance, service, domain string, port int, txt []string) (*Re return r, nil } +// validateHostLabel reports whether label is a single DNS label the responder +// may advertise: 1-63 bytes of the letters, digits, and hyphens DNS allows. A +// label carrying a dot would silently become a two-label host name once the +// domain is appended, so it is refused here rather than on the wire — macOS +// does not author or resolve a name like "indigo.lab.local.". shared/mdns +// assembles DNS names for any PAIR service type, so it validates its inputs +// defensively instead of trusting every caller. +func validateHostLabel(label string) error { + if label == "" || len(label) > 63 { + return fmt.Errorf("invalid host label %q: must be a single DNS label of 1-63 bytes", label) + } + for i := range len(label) { + c := label[i] + if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' { + continue + } + return fmt.Errorf("invalid host label %q: must contain only letters, digits, or hyphens", label) + } + return nil +} + +// AdvertisedHost returns the FQDN this responder claims as its own host +// record — the SRV target and the name every A record answers under, trailing +// dot included. Peers resolve the service by following the SRV to this name. +func (r *Responder) AdvertisedHost() string { + return r.hostName +} + // ifaces returns the current interface→addresses map. The returned map is // immutable (refreshes swap in a new one), so callers may use it lock-free // after this returns. @@ -352,7 +394,7 @@ func (r *Responder) handleQuery(query *dns.Msg, ifIndex int, from net.Addr) { } case r.hostName: if q.Qtype == dns.TypeA || q.Qtype == dns.TypeANY { - resp.Answer = r.appendAddrRecords(resp.Answer, ifIndex, false) + resp.Answer = r.appendAddrRecords(resp.Answer, ifIndex, false, recordTTL) matched = true } } @@ -382,36 +424,38 @@ func (r *Responder) appendBrowseRRs(resp *dns.Msg, ifIndex int) { Hdr: dns.RR_Header{Name: r.serviceName, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: recordTTL}, Ptr: r.instanceName, }) - resp.Extra = append(resp.Extra, r.srvRR(false), r.txtRR(false)) - resp.Extra = r.appendAddrRecords(resp.Extra, ifIndex, false) + resp.Extra = append(resp.Extra, r.srvRR(false, recordTTL), r.txtRR(false, recordTTL)) + resp.Extra = r.appendAddrRecords(resp.Extra, ifIndex, false, recordTTL) } // appendLookupRRs fills resp for a direct instance lookup (an SRV/TXT question): // SRV+TXT as the Answer, A records as Extra. func (r *Responder) appendLookupRRs(resp *dns.Msg, ifIndex int, flushCache bool) { - resp.Answer = append(resp.Answer, r.srvRR(flushCache), r.txtRR(flushCache)) - resp.Extra = r.appendAddrRecords(resp.Extra, ifIndex, flushCache) + resp.Answer = append(resp.Answer, r.srvRR(flushCache, recordTTL), r.txtRR(flushCache, recordTTL)) + resp.Extra = r.appendAddrRecords(resp.Extra, ifIndex, flushCache, recordTTL) } // srvRR builds the instance's SRV record. flushCache sets the cache-flush bit // (RFC 6762 §10.2) — set on unsolicited announcements so peers replace a stale // cached value, clear on reactive replies. The same convention applies to -// txtRR and appendAddrRecords. -func (r *Responder) srvRR(flushCache bool) *dns.SRV { +// txtRR and appendAddrRecords. ttl is the record's RR TTL: announcements pass +// recordTTL, a goodbye passes 0 (§10.1 retracts the identical record at TTL +// 0), so the caller states the TTL instead of a value corrected after the fact. +func (r *Responder) srvRR(flushCache bool, ttl uint32) *dns.SRV { class := uint16(dns.ClassINET) if flushCache { class |= cacheFlush } return &dns.SRV{ - Hdr: dns.RR_Header{Name: r.instanceName, Rrtype: dns.TypeSRV, Class: class, Ttl: recordTTL}, + Hdr: dns.RR_Header{Name: r.instanceName, Rrtype: dns.TypeSRV, Class: class, Ttl: ttl}, Port: uint16(r.port), Target: r.hostName, } } // txtRR builds the instance's TXT record from the live set (which UpdateTXT may -// have swapped). See srvRR for flushCache. -func (r *Responder) txtRR(flushCache bool) *dns.TXT { +// have swapped). See srvRR for flushCache and ttl. +func (r *Responder) txtRR(flushCache bool, ttl uint32) *dns.TXT { class := uint16(dns.ClassINET) if flushCache { class |= cacheFlush @@ -423,21 +467,21 @@ func (r *Responder) txtRR(flushCache bool) *dns.TXT { txt = []string{""} } return &dns.TXT{ - Hdr: dns.RR_Header{Name: r.instanceName, Rrtype: dns.TypeTXT, Class: class, Ttl: recordTTL}, + Hdr: dns.RR_Header{Name: r.instanceName, Rrtype: dns.TypeTXT, Class: class, Ttl: ttl}, Txt: txt, } } // appendAddrRecords appends A records for the addresses we advertise on ifIndex -// (see addrsForResponse). See srvRR for flushCache. -func (r *Responder) appendAddrRecords(list []dns.RR, ifIndex int, flushCache bool) []dns.RR { +// (see addrsForResponse). See srvRR for flushCache and ttl. +func (r *Responder) appendAddrRecords(list []dns.RR, ifIndex int, flushCache bool, ttl uint32) []dns.RR { class := uint16(dns.ClassINET) if flushCache { class |= cacheFlush } for _, ip := range r.addrsForResponse(ifIndex) { list = append(list, &dns.A{ - Hdr: dns.RR_Header{Name: r.hostName, Rrtype: dns.TypeA, Class: class, Ttl: recordTTL}, + Hdr: dns.RR_Header{Name: r.hostName, Rrtype: dns.TypeA, Class: class, Ttl: ttl}, A: ip, }) } @@ -486,24 +530,30 @@ func (r *Responder) announceLoop(ctx context.Context) { } } -// sendAnnouncement multicasts an unsolicited PTR+SRV+TXT+A (with the cache-flush -// bit) on every interface, so peers learn or refresh our record without querying. +// announcementMsg builds the unsolicited PTR+SRV+TXT+A announcement sent on +// ifIdx (with the cache-flush bit), so peers learn or refresh our record +// without querying. The A records are scoped to ifIdx's addresses. +func (r *Responder) announcementMsg(ifIdx int) *dns.Msg { + resp := new(dns.Msg) + resp.MsgHdr.Response = true + resp.MsgHdr.Authoritative = true + resp.Compress = true + resp.Answer = append(resp.Answer, + &dns.PTR{ + Hdr: dns.RR_Header{Name: r.serviceName, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: recordTTL}, + Ptr: r.instanceName, + }, + r.srvRR(true, recordTTL), + r.txtRR(true, recordTTL), + ) + resp.Answer = r.appendAddrRecords(resp.Answer, ifIdx, true, recordTTL) + return resp +} + +// sendAnnouncement multicasts announcementMsg on every interface. func (r *Responder) sendAnnouncement() { for ifIdx := range r.ifaces() { - resp := new(dns.Msg) - resp.MsgHdr.Response = true - resp.MsgHdr.Authoritative = true - resp.Compress = true - resp.Answer = append(resp.Answer, - &dns.PTR{ - Hdr: dns.RR_Header{Name: r.serviceName, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: recordTTL}, - Ptr: r.instanceName, - }, - r.srvRR(true), - r.txtRR(true), - ) - resp.Answer = r.appendAddrRecords(resp.Answer, ifIdx, true) - buf, err := resp.Pack() + buf, err := r.announcementMsg(ifIdx).Pack() if err != nil { continue } @@ -511,22 +561,90 @@ func (r *Responder) sendAnnouncement() { } } -// sendGoodbye multicasts a TTL=0 PTR on every interface so peers evict us at -// once on shutdown instead of waiting out the record TTL. -func (r *Responder) sendGoodbye() { - for ifIdx := range r.ifaces() { - resp := new(dns.Msg) - resp.MsgHdr.Response = true - resp.MsgHdr.Authoritative = true - resp.Answer = append(resp.Answer, &dns.PTR{ +// goodbyeMsg builds the TTL=0 PTR+SRV+TXT+A that tells peers to evict our +// records at once instead of waiting out the record TTL. RFC 6762 §10.1 makes +// a retraction the announced record with only its RR TTL set to zero, so the +// records come from the same builders announcementMsg uses — at ttl 0, with +// its flushCache arguments — never a hand-rolled second copy whose rdata +// could drift from what the peer actually cached. ifIdx scopes the retraction +// A records to the addresses announced on the interface the goodbye goes out. +// +// Why every record type retracts: §10.1, "In the case where a host knows +// that certain resource record data is about to become invalid (for example, +// when the host is undergoing a clean shutdown), the host SHOULD send an +// unsolicited Multicast DNS response packet, giving the same resource record +// name, rrtype, rrclass, and rdata, but an RR TTL of zero." At shutdown our +// A records are record data about to become invalid too. §8.4's "In the case +// of unique records, a host SHOULD omit the 'goodbye' announcement, since +// the cache-flush bit on the newly announced records will cause old rdata to +// be flushed from peer caches anyway" is about *updates*: there a replacement +// arrives and its flush bit does the retracting. Shutdown has no replacement, +// so §10.1 governs and §10.2 requires the whole set — "it MUST send the +// entire RRSet" and "The host MUST set the cache-flush bit on all members of +// the unique RRSet." A goodbye that dropped the flush bit would carry a +// different rrclass on the wire than the peer cached and would retract +// nothing, so the unique members keep the bit exactly as announced. +// +// Why one goodbye per record instead of repeating §8.3's "at least two +// unsolicited responses, one second apart": that repetition is §8.3's +// robustness device for announcements, and §10.1 asks for no such repetition +// for retractions. The peer's one-second hold on a TTL=0 record — "Queriers +// receiving a Multicast DNS response with a TTL of zero SHOULD NOT +// immediately delete the record from the cache, but instead record a TTL of +// 1 and then delete the record one second later" — gives "other cooperating +// responders one second to send out their own response to 'rescue' the +// records", which by design rescues records that should live, not our +// retraction; and it cannot rescue a goodbye that was never sent. What +// protects the single retraction is that sendGoodbye fails loudly, and that +// Run's caller treats Run's return — not its own cancel — as permission to +// exit, so the packet has left before the process does. +func (r *Responder) goodbyeMsg(ifIdx int) *dns.Msg { + resp := new(dns.Msg) + resp.MsgHdr.Response = true + resp.MsgHdr.Authoritative = true + resp.Compress = true + resp.Answer = append(resp.Answer, + &dns.PTR{ Hdr: dns.RR_Header{Name: r.serviceName, Rrtype: dns.TypePTR, Class: dns.ClassINET, Ttl: 0}, Ptr: r.instanceName, - }) - buf, err := resp.Pack() + }, + r.srvRR(true, 0), + r.txtRR(true, 0), + ) + resp.Answer = r.appendAddrRecords(resp.Answer, ifIdx, true, 0) + return resp +} + +// goodbyeSend is the single place a retraction leaves the machine; it exists +// as a variable only so a test can watch what shutdown offers each interface +// and force one interface's failure without touching the others. Production +// always uses the real multicast send. +var goodbyeSend = func(r *Responder, buf []byte, ifIndex int) error { + return r.sendOnInterface(buf, ifIndex, mdnsTargetV4) +} + +// sendGoodbye multicasts goodbyeMsg on every interface so peers evict us at +// once on shutdown instead of waiting out the record TTL. A lost retraction +// is operational impact — every peer then resolves this dead node until the +// record TTL expires — so a goodbye that cannot be serialized or sent on one +// interface is logged at Warn, the level the desktop configures services at +// by default, and the other interfaces still retract. +func (r *Responder) sendGoodbye() { + for ifIdx := range r.ifaces() { + buf, err := r.goodbyeMsg(ifIdx).Pack() if err != nil { + slog.Warn("mdns: goodbye could not be serialized", + "ifIndex", ifIdx, "instance", r.instance, "err", err) continue } - r.sendOnInterface(buf, ifIdx, mdnsTargetV4) + if err := goodbyeSend(r, buf, ifIdx); err != nil { + name := "" + if ifi, ifErr := net.InterfaceByIndex(ifIdx); ifErr == nil { + name = ifi.Name + } + slog.Warn("mdns: goodbye send failed", + "iface", name, "ifIndex", ifIdx, "instance", r.instance, "err", err) + } } } diff --git a/services/shared/mdns/responder_test.go b/services/shared/mdns/responder_test.go index 1fe23b1b7..aebca2b27 100644 --- a/services/shared/mdns/responder_test.go +++ b/services/shared/mdns/responder_test.go @@ -4,24 +4,54 @@ package mdns import ( + "errors" + "fmt" "net" + "os" + "sort" + "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/miekg/dns" + + "nvpair-shared/netmon" ) +// noMulticastErrFragment is the substring of NewResponder's failure that names +// its one environmental precondition (see responder.go's +// "no multicast-capable IPv4 interfaces" error). +const noMulticastErrFragment = "no multicast-capable IPv4 interface" + +// requireMulticastOrFail lets a constructor-path test skip only on the +// one environmental precondition NewResponder documents — no multicast-capable +// IPv4 interface — and fail on any other error. An arbitrary error is not an +// environment, it's a bug; letting it skip would mean a responder broken for +// every host could pass with the host-record invariant unpinned. +func requireMulticastOrFail(t *testing.T, err error) { + t.Helper() + if err == nil { + return + } + if !strings.Contains(err.Error(), noMulticastErrFragment) { + t.Fatalf("NewResponder failed for a reason other than the environment precondition: %v", err) + } + t.Skipf("no multicast-capable IPv4 interface with a non-loopback address on this host: %v", err) +} + // testResponder builds a Responder with fixed fields so the record-building -// tests don't depend on the host's real interfaces or hostname. +// tests don't depend on the host's real interfaces or hostname. hostName is +// the synthetic host record PAIR claims, never a machine name; the instance +// name "myhost" stays a display name and owns no address record of its own. func testResponder(txt []string) *Responder { r := &Responder{ instance: "myhost", service: "_nvpair-test._tcp", domain: "local", port: 14318, - hostName: "myhost.local.", + hostName: "nvpair-0123456789ab.local.", serviceName: "_nvpair-test._tcp.local.", instanceName: "myhost._nvpair-test._tcp.local.", ifaceAddrs: map[int][]net.IP{ @@ -38,7 +68,7 @@ func TestNewResponder_RejectsInvalidRegistration(t *testing.T) { // environment-independent. test := func(name, instance, service, domain string, port int) { t.Run(name, func(t *testing.T) { - _, err := NewResponder(instance, service, domain, port, nil) + _, err := NewResponder(instance, "nvpair-0123456789ab", service, domain, port, nil) require.Error(t, err) }) } @@ -47,16 +77,145 @@ func TestNewResponder_RejectsInvalidRegistration(t *testing.T) { test("missing port", "myhost", "_nvpair-test._tcp", "local", 0) } -func TestNewResponder_NormalizesNames(t *testing.T) { - // The success path needs a real multicast-capable interface; skip where - // there isn't one (e.g. a locked-down CI sandbox) rather than fail. - r, err := NewResponder(".myhost.", "._nvpair-test._tcp.", "", 14318, []string{"v=1"}) - if err != nil { - t.Skipf("NewResponder unavailable in this environment: %v", err) +func TestNewResponder_RejectsHostLabelThatIsNotASingleDNSLabel(t *testing.T) { + // Like TestNewResponder_RejectsInvalidRegistration, these return before any + // interface enumeration, so they're environment-independent: on a machine + // without multicast the error must still be the label rejection, which is + // why the assertion checks the message names the host label rather than + // settling for any error. + // + // "two labels" is the shape develop produced BY ITSELF: NewResponder built + // the host name as hostname + "." + domain + "." with the hostname from + // os.Hostname(), so a machine whose BSD hostname carries a DNS search + // domain ("indigo.lab") advertised the two-label SRV target + // "indigo.lab.local." — a name macOS does not author and will not + // resolve. Refusing multi-label input fixes that second defect; it is not + // a style point. + test := func(name, hostLabel string) { + t.Run(name, func(t *testing.T) { + _, err := NewResponder("myhost", hostLabel, "._nvpair-test._tcp.", "local", 14318, nil) + require.Error(t, err, "host label %q must not be advertised", hostLabel) + assert.ErrorContains(t, err, "host label", + "the error must name the offending host label, proving the rejection is the label check and not the interface enumeration below it") + }) } + test("two labels", "indigo.local") + test("two labels with trailing dot", "nvpair-0123456789ab.local.") + test("contains a space", "nvpair test") + test("empty", "") + test("64 bytes", strings.Repeat("a", 64)) + test("contains a slash", "nvpair/test") +} + +func TestNewResponder_NormalizesNames(t *testing.T) { + // The success path needs a real multicast-capable interface; skip only on + // that named precondition (a locked-down CI sandbox), never on some other + // error NewResponder could return. + r, err := NewResponder(".myhost.", "nvpair-0123456789ab.", "._nvpair-test._tcp.", "", 14318, []string{"v=1"}) + requireMulticastOrFail(t, err) assert.Equal(t, "local", r.domain) assert.Equal(t, "_nvpair-test._tcp.local.", r.serviceName) assert.Equal(t, "myhost._nvpair-test._tcp.local.", r.instanceName) + // A trailing dot on the host label is decoration, trimmed like the one on + // the instance, so the advertised record stays a single label under the + // domain rather than a name ending in an empty label. + assert.Equal(t, "nvpair-0123456789ab.local.", r.AdvertisedHost(), "trailing dot on the host label") +} + +// TestNewResponder_DoesNotAdvertiseTheOperatingSystemHostname is the red for +// the real defect: NewResponder used to derive its host record — the SRV target +// and the name its A records answer under — from os.Hostname(), so PAIR +// claimed the machine's name and macOS answered the contention by renaming the +// computer's Local hostname (issue #229). It runs the constructor for real, +// which needs a multicast-capable interface, so it skips on that one named +// precondition — on such hosts the invariant stays pinned by +// TestNewResponder_DerivesTheHostRecordFromItsParameterWithoutMulticast, which +// fakes only the interface source and never skips. +func TestNewResponder_DoesNotAdvertiseTheOperatingSystemHostname(t *testing.T) { + r, err := NewResponder("myhost", "nvpair-0123456789ab", "._nvpair-test._tcp.", "local", 14318, nil) + requireMulticastOrFail(t, err) + assert.Equal(t, "nvpair-0123456789ab.local.", r.AdvertisedHost(), + "the advertised host record must be the caller's single label plus the domain") + + hostname, err := os.Hostname() + require.NoError(t, err) + if hostname == "" || hostname == "nvpair-0123456789ab" { + t.Skipf("this machine's os.Hostname() is %q, which cannot be told apart from the fixture label", hostname) + } + require.NotEqual(t, hostname+".local.", r.AdvertisedHost(), + "the responder must not derive its host record from os.Hostname() (%q)", hostname) + + buf, err := r.announcementMsg(1).Pack() + require.NoError(t, err, "pack announcement") + var msg dns.Msg + require.NoError(t, msg.Unpack(buf), "unpack announcement") + for _, rr := range append(msg.Answer, msg.Extra...) { + assert.NotEqual(t, hostname+".local.", rr.Header().Name, + "no record on the wire may be named for the machine hostname %q", hostname) + } +} + +// TestNewResponder_DerivesTheHostRecordFromItsParameterWithoutMulticast pins +// the central invariant of the fix — the advertised host record is built from +// the hostLabel parameter, never from the machine — on EVERY host: it swaps +// only the interface source (the enumerateSnapshot seam) for a fake snapshot +// and still calls the real NewResponder, so there is no skip path and no +// environment it can hide in. A machine whose own hostname collides with the +// usual fixture label gets a different label so the "a hostname-derived value +// would be wrong" half stays meaningful here too. +// +// Tests that touch enumerateSnapshot must not use t.Parallel: it is package +// state, and a parallel sibling would read the fake or lose its own. +func TestNewResponder_DerivesTheHostRecordFromItsParameterWithoutMulticast(t *testing.T) { + realEnumerate := enumerateSnapshot + t.Cleanup(func() { enumerateSnapshot = realEnumerate }) + enumerateSnapshot = func() netmon.Snapshot { + return netmon.Snapshot{ + LocalIPs: map[string]bool{"203.0.113.7": true}, + IfaceV4: map[int][]net.IP{2: {net.IPv4(203, 0, 113, 7)}}, + } + } + + hostname, err := os.Hostname() + require.NoError(t, err) + hostLabel := "nvpair-0123456789ab" + if hostname == hostLabel { + // Even on a machine named for this suite's fixture label, a + // hostname-derived host record must be visibly wrong: any other + // single label will do. + hostLabel = "nvpair-not-the-hostname" + } + + r, err := NewResponder("myhost", hostLabel, "._nvpair-test._tcp.", "local", 14318, nil) + require.NoError(t, err, "the fake snapshot must satisfy the interface requirement") + + assert.Equal(t, hostLabel+".local.", r.AdvertisedHost(), + "the host record must be the caller's label under the domain") + require.NotEqual(t, hostname+".local.", r.AdvertisedHost(), + "the host record must not be the machine hostname %q", hostname) + + buf, err := r.announcementMsg(2).Pack() + require.NoError(t, err, "pack announcement") + var msg dns.Msg + require.NoError(t, msg.Unpack(buf), "unpack announcement") + var srv *dns.SRV + var addrs []*dns.A + for _, rr := range append(msg.Answer, msg.Extra...) { + switch rec := rr.(type) { + case *dns.SRV: + srv = rec + case *dns.A: + addrs = append(addrs, rec) + } + require.NotEqual(t, hostname+".local.", rr.Header().Name, + "no record on the wire may be named for the machine hostname %q", hostname) + } + require.NotNil(t, srv, "announcement carries an SRV") + require.NotEmpty(t, addrs, "announcement carries A records from the fake interface") + assert.Equal(t, r.AdvertisedHost(), srv.Target, "SRV target is the advertised host record") + for _, a := range addrs { + assert.Equal(t, r.AdvertisedHost(), a.Header().Name, "A record owner name is the advertised host record") + } } func TestNewResponder_CopiesTXT(t *testing.T) { @@ -68,24 +227,24 @@ func TestNewResponder_CopiesTXT(t *testing.T) { func TestSrvRR_EncodesServiceTargetAndPort(t *testing.T) { r := testResponder(nil) - srv := r.srvRR(false) + srv := r.srvRR(false, recordTTL) assert.Equal(t, uint16(14318), srv.Port, "SRV port") - assert.Equal(t, "myhost.local.", srv.Target, "SRV target") + assert.Equal(t, "nvpair-0123456789ab.local.", srv.Target, "SRV target") assert.Equal(t, "myhost._nvpair-test._tcp.local.", srv.Hdr.Name, "SRV name") assert.Equal(t, uint16(0), srv.Hdr.Class&cacheFlush, "SRV class has cache-flush bit when flushCache=false") - assert.NotEqual(t, uint16(0), r.srvRR(true).Hdr.Class&cacheFlush, "SRV class missing cache-flush bit when flushCache=true") + assert.NotEqual(t, uint16(0), r.srvRR(true, recordTTL).Hdr.Class&cacheFlush, "SRV class missing cache-flush bit when flushCache=true") } func TestTxtRR_EncodesConfiguredTXTValues(t *testing.T) { r := testResponder([]string{"v=1", "ip=192.168.1.10"}) - txt := r.txtRR(false) + txt := r.txtRR(false, recordTTL) assert.Equal(t, []string{"v=1", "ip=192.168.1.10"}, txt.Txt, "TXT records") assert.Equal(t, "myhost._nvpair-test._tcp.local.", txt.Hdr.Name, "TXT name") } func TestTxtRR_UsesFallbackForEmptyTXT(t *testing.T) { r := testResponder(nil) - txt := r.txtRR(false) + txt := r.txtRR(false, recordTTL) assert.Equal(t, []string{""}, txt.Txt, "empty TXT set should emit one empty string") } @@ -144,6 +303,343 @@ func TestAppendBrowseRRs_IncludesServiceRecords(t *testing.T) { assert.Equal(t, 1, aCount, "browse Extra A count") } +func TestAnnouncementMsg_EveryAddressRecordIsOwnedByTheSRVTarget(t *testing.T) { + // GUARD, not the red: testResponder injects hostName directly, so this is + // green against develop too. It pins the wire consequence of the design + // rule that the instance name is only a display name: an A record answering + // under "myhost.local." would contend with the host's own mDNS responder + // over the machine name even if the SRV pointed somewhere else. It runs with + // no socket and no constructor, so the rule stays checked on machines that + // have no multicast interface and must skip the constructor-path tests. + r := testResponder(nil) + buf, err := r.announcementMsg(1).Pack() + require.NoError(t, err, "pack announcement") + var msg dns.Msg + require.NoError(t, msg.Unpack(buf), "unpack announcement") + + var srv *dns.SRV + var addrs []*dns.A + for _, rr := range append(msg.Answer, msg.Extra...) { + switch rec := rr.(type) { + case *dns.SRV: + srv = rec + case *dns.A: + addrs = append(addrs, rec) + } + require.NotEqual(t, "myhost.local.", rr.Header().Name, + "the instance name %q is a display name and must never own a record", r.instance) + } + require.NotNil(t, srv, "announcement carries an SRV") + require.NotEmpty(t, addrs, "announcement carries A records") + assert.Equal(t, "nvpair-0123456789ab.local.", srv.Target, "SRV target") + for _, a := range addrs { + assert.Equal(t, srv.Target, a.Header().Name, "A record owner name must match the SRV target") + } +} + +// packUnpack round-trips msg through the wire format so the goodbye tests +// assert what a peer parses, not an in-memory shortcut a later refactor could +// take before Pack is ever reached. +func packUnpack(t *testing.T, msg *dns.Msg, label string) *dns.Msg { + t.Helper() + buf, err := msg.Pack() + require.NoError(t, err, "pack %s", label) + var got dns.Msg + require.NoError(t, got.Unpack(buf), "unpack %s", label) + return &got +} + +// sortedRecordStrings renders rrs as wire-notation strings, sorted so two +// messages carrying the same records compare equal regardless of append order. +// Each record's TTL is zeroed before rendering because the caller asserts TTL +// separately and RFC 6762 §10.1 makes TTL the only field allowed to differ +// between an announcement and its retraction — so a zeroed render pins that +// name, rrtype, class and rdata are exactly the announced ones. The zeroing +// happens on a deep copy: callers routinely assert TTL on the very records +// they render, and zeroing in place would turn each later assertion into a +// check against this helper's own side effect. +func sortedRecordStrings(rrs []dns.RR) []string { + out := make([]string, 0, len(rrs)) + for _, rr := range rrs { + rendered := dns.Copy(rr) + rendered.Header().Ttl = 0 + out = append(out, rendered.String()) + } + sort.Strings(out) + return out +} + +// TestGoodbye_RetractsEveryRecordTheResponderClaimed is the D4 red: on +// shutdown PAIR must retract the SRV, TXT and A records it claimed at TTL 0, +// not just the PTR. Peers handed only a PTR retraction keep a live SRV target, +// TXT and A cached for up to the 120s record TTL, resolving and connecting to +// a node that is already gone for that whole window. It drives goodbyeMsg and +// announcementMsg through the real wire format with a fixture Responder, so +// unlike the constructor-path tests it cannot skip on a host without a +// multicast-capable interface. +func TestGoodbye_RetractsEveryRecordTheResponderClaimed(t *testing.T) { + r := testResponder([]string{"v=1"}) + + goodbye := packUnpack(t, r.goodbyeMsg(1), "goodbye on interface 1") + announced := packUnpack(t, r.announcementMsg(1), "announcement on interface 1") + require.NotEmpty(t, announced.Answer, "the fixture announcement carries records to retract") + + // A receiver that walks only Answer would ignore a retraction parked in + // Ns or Extra, so every retraction record has to sit in the Answer section. + require.Empty(t, goodbye.Ns, "goodbye parks records in Ns, where a receiver that walks only Answer would miss them") + require.Empty(t, goodbye.Extra, "goodbye parks records in Extra, where a receiver that walks only Answer would miss them") + + var ptrs []*dns.PTR + var srvs []*dns.SRV + var txts []*dns.TXT + var addrs []*dns.A + for _, rr := range goodbye.Answer { + switch rec := rr.(type) { + case *dns.PTR: + ptrs = append(ptrs, rec) + case *dns.SRV: + srvs = append(srvs, rec) + case *dns.TXT: + txts = append(txts, rec) + case *dns.A: + addrs = append(addrs, rec) + } + } + require.Len(t, ptrs, 1, "goodbye answers with exactly one PTR") + require.Len(t, srvs, 1, "goodbye answers with exactly one SRV: a PTR-only goodbye leaves the SRV target cached live") + require.Len(t, txts, 1, "goodbye answers with exactly one TXT: a PTR-only goodbye leaves the TXT record cached") + require.NotEmpty(t, addrs, "goodbye answers with at least one A: a PTR-only goodbye leaves the host address cached") + + // RFC 6762 §10.1: a retraction is the announced record with an RR TTL of + // zero, while the announcement itself must keep the real record TTL. + for _, rr := range goodbye.Answer { + assert.Zero(t, rr.Header().Ttl, "goodbye record %s must retract at TTL 0", rr.Header().Name) + } + for _, rr := range announced.Answer { + assert.Equal(t, uint32(recordTTL), rr.Header().Ttl, "announcement record %s must still carry the real record TTL", rr.Header().Name) + } + + // Cache-flush bits mirror the announcement: §10.2, "The cache-flush bit + // MUST NOT ever be set in any shared resource record" — so not on the + // shared PTR — and "The host MUST set the cache-flush bit on all members + // of the unique RRSet" — so on the unique SRV, TXT and A. (§8.3 is where + // those records earn the bit by being verified-unique announcements; + // §10.2 is where the rule itself lives, for every response.) Asserting + // them against fixed expectations (not just against the announcement) + // means a regression that drops the bit from both sides still fails here. + assert.Zero(t, ptrs[0].Hdr.Class&cacheFlush, "the goodbye PTR is a shared record and must not carry the cache-flush bit, as announced") + assert.NotZero(t, srvs[0].Hdr.Class&cacheFlush, "the goodbye SRV is a unique record and must carry the cache-flush bit, as announced") + assert.NotZero(t, txts[0].Hdr.Class&cacheFlush, "the goodbye TXT is a unique record and must carry the cache-flush bit, as announced") + for _, a := range addrs { + assert.NotZero(t, a.Hdr.Class&cacheFlush, "the goodbye A for %s is a unique record and must carry the cache-flush bit, as announced", a.A) + } + + // Same name, rrtype, class and rdata as the announcement — under §10.1 + // only the TTL may differ. A retraction record differing in any other + // field does not match what the peer cached, so it retracts nothing. + // Comparing the announced set against the goodbye set also pins A rdata: + // goodbyeMsg(1) must retract exactly the addresses announcementMsg(1) + // published on that same interface. + assert.Equal(t, sortedRecordStrings(announced.Answer), sortedRecordStrings(goodbye.Answer), + "the goodbye must retract the very records the announcement published") + + for _, a := range addrs { + assert.Equal(t, srvs[0].Target, a.Header().Name, "A record owner name must be the SRV target it retracts") + } +} + +// TestGoodbye_ScopesAddressRetractionsToTheInterfaceTheyAreSentOn makes +// goodbyeMsg's ifIdx parameter load-bearing. The fixture's interfaces 1 and 2 +// hold different addresses, so each goodbye must retract exactly its own +// interface's announced addresses and the two goodbye sets must differ: if a +// refactor hard-codes one interface, the goodbye on the other interface +// retracts the wrong address and this test fails — leaving peers to cache a +// reachable-looking address on an interface this node no longer serves. +func TestGoodbye_ScopesAddressRetractionsToTheInterfaceTheyAreSentOn(t *testing.T) { + r := testResponder([]string{"v=1"}) + + scopedAddrs := map[int][]string{} + for _, ifIdx := range []int{1, 2} { + goodbye := packUnpack(t, r.goodbyeMsg(ifIdx), fmt.Sprintf("goodbye on interface %d", ifIdx)) + announced := packUnpack(t, r.announcementMsg(ifIdx), fmt.Sprintf("announcement on interface %d", ifIdx)) + + var goodbyeAddrs, announcedAddrs []string + for _, rr := range goodbye.Answer { + if a, ok := rr.(*dns.A); ok { + goodbyeAddrs = append(goodbyeAddrs, a.A.String()) + } + } + for _, rr := range announced.Answer { + if a, ok := rr.(*dns.A); ok { + announcedAddrs = append(announcedAddrs, a.A.String()) + } + } + sort.Strings(goodbyeAddrs) + sort.Strings(announcedAddrs) + require.NotEmpty(t, goodbyeAddrs, "goodbye on interface %d carries A records", ifIdx) + require.Equal(t, announcedAddrs, goodbyeAddrs, + "the goodbye sent on interface %d must retract exactly the addresses that interface's announcement published", ifIdx) + scopedAddrs[ifIdx] = goodbyeAddrs + } + + // The fixture guarantees interfaces 1 and 2 hold different addresses, so + // equal goodbye sets would prove ifIdx never reached the A-record builder. + require.NotEqual(t, scopedAddrs[1], scopedAddrs[2], + "interfaces 1 and 2 hold different addresses, so goodbyeMsg must retract different addresses on each") +} + +// goodbyeAttempt is one send recorded by the goodbyeSend seam: the interface +// index it was sent on and the records parsed back out of the exact bytes +// handed to the send, so assertions run on what would hit the wire. +type goodbyeAttempt struct { + ifIndex int + records []string // sortedRecordStrings over the sent bytes' Answer +} + +// captureGoodbyeSends replaces the goodbyeSend seam for one test and records +// every send attempt. sendGoodbye runs synchronously on the test goroutine, +// so the recorder needs no locking, and require.* inside the seam stays legal. +func captureGoodbyeSends(t *testing.T, onSend func(ifIndex int) error) *[]goodbyeAttempt { + t.Helper() + attempts := &[]goodbyeAttempt{} + old := goodbyeSend + t.Cleanup(func() { goodbyeSend = old }) + goodbyeSend = func(_ *Responder, buf []byte, ifIndex int) error { + var msg dns.Msg + require.NoError(t, msg.Unpack(buf), "goodbye bytes offered for interface %d do not parse", ifIndex) + for _, rr := range msg.Answer { + require.Zero(t, rr.Header().Ttl, "goodbye record %s offered on interface %d carries TTL %d, not the 0 that retracts it", + rr.Header().Name, ifIndex, rr.Header().Ttl) + } + *attempts = append(*attempts, goodbyeAttempt{ifIndex: ifIndex, records: sortedRecordStrings(msg.Answer)}) + return onSend(ifIndex) + } + return attempts +} + +// TestSendGoodbye_SendsOneGoodbyePerInterfaceScopedToItsOwnAddresses is the +// send-layer half of D4: on shutdown sendGoodbye must hand the send exactly +// one packed goodbye per interface the responder knows, and each packet must +// be that interface's own full retraction. The per-interface address scoping +// is proven at the send layer — from the bytes offered — not only at message +// construction, because a shutdown that packs iface 1's addresses into every +// interface's packet retracts the wrong A records wherever it goes out. +func TestSendGoodbye_SendsOneGoodbyePerInterfaceScopedToItsOwnAddresses(t *testing.T) { + r := testResponder([]string{"v=1"}) + attempts := captureGoodbyeSends(t, func(int) error { return nil }) + + r.sendGoodbye() + + require.Len(t, *attempts, 2, "the fixture responder knows exactly two interfaces, so shutdown must offer exactly two goodbye sends") + byIface := map[int][]goodbyeAttempt{} + for _, a := range *attempts { + byIface[a.ifIndex] = append(byIface[a.ifIndex], a) + } + assert.Len(t, byIface[1], 1, "interface 1 must receive exactly one goodbye send") + assert.Len(t, byIface[2], 1, "interface 2 must receive exactly one goodbye send") + + for _, ifIdx := range []int{1, 2} { + require.Len(t, byIface[ifIdx], 1) + want := sortedRecordStrings(packUnpack(t, r.goodbyeMsg(ifIdx), fmt.Sprintf("locally built goodbye for interface %d", ifIdx)).Answer) + assert.Equal(t, want, byIface[ifIdx][0].records, + "the packet offered for interface %d must be that interface's own full retraction", ifIdx) + } + assert.NotEqual(t, byIface[1][0].records, byIface[2][0].records, + "the fixture interfaces hold different addresses, so the two offered packets must differ — identical packets would mean ifIdx was flattened away before the A records reached the wire") +} + +// TestSendGoodbye_LogsWarnAndKeepsOtherInterfacesWhenOneSendFails pins I1 +// and the loop rule together: the desktop runs services at warn by default, +// so a goodbye failure logged any quieter is invisible, and a retraction +// that never left the machine costs every peer the full record TTL of +// resolving a dead node — that is operational impact, not debug noise. One +// dead interface must still not suppress the other retractions. +func TestSendGoodbye_LogsWarnAndKeepsOtherInterfacesWhenOneSendFails(t *testing.T) { + r := testResponder([]string{"v=1"}) + logs := captureDebugLogs(t) + attempts := captureGoodbyeSends(t, func(ifIndex int) error { + if ifIndex == 1 { + return errors.New("synthetic send failure on interface 1") + } + return nil + }) + + r.sendGoodbye() + + var attempted []int + for _, a := range *attempts { + attempted = append(attempted, a.ifIndex) + } + sort.Ints(attempted) + assert.Equal(t, []int{1, 2}, attempted, + "a failed send on interface 1 must not suppress interface 2's retraction") + + gotLogs := logs.String() + assert.Contains(t, gotLogs, "level=WARN", + "a goodbye send failure must be visible at the warn level the desktop default configures, which is where a silent 120s stale record becomes discoverable") + assert.Contains(t, gotLogs, "ifIndex=1", + "the goodbye failure line must name which interface index failed") + // The interface name half is exactly as available to this test as it is + // to production: net.InterfaceByIndex is a fact about the host, and a + // fixture index that resolves nowhere gets logged by index only. The + // ifIndex and WARN assertions above hold either way. + if ifi, err := net.InterfaceByIndex(1); err == nil { + assert.Contains(t, gotLogs, "iface="+ifi.Name, + "the goodbye failure line must name the interface, not only its index") + } + assert.NotContains(t, gotLogs, "ifIndex=2", + "the interface whose send succeeded must not be reported as failed") +} + +// TestSendGoodbye_LogsWarnAndKeepsOtherInterfacesWhenOneGoodbyeCannotBePacked +// covers the other way one interface's retraction can be lost: a malformed +// address makes dns refuse to serialize that interface's packet. The failure +// must be logged at Warn like a send failure, and the loop must still reach +// the interfaces whose packets do build. +func TestSendGoodbye_LogsWarnAndKeepsOtherInterfacesWhenOneGoodbyeCannotBePacked(t *testing.T) { + r := testResponder([]string{"v=1"}) + // A five-byte net.IP is not valid A rdata: it builds into the message in + // memory, but dns.Msg.Pack refuses it — the hazard a silent `continue` + // would swallow. + r.ifaceAddrs = map[int][]net.IP{ + 1: {net.IP{192, 0, 2, 100, 200}}, + 2: {net.IPv4(10, 0, 0, 5)}, + } + logs := captureDebugLogs(t) + attempts := captureGoodbyeSends(t, func(int) error { return nil }) + + r.sendGoodbye() + + var attempted []int + for _, a := range *attempts { + attempted = append(attempted, a.ifIndex) + } + assert.Equal(t, []int{2}, attempted, + "interface 1's packet cannot be built, so only interface 2's retraction may be offered — and it may not be skipped") + gotLogs := logs.String() + assert.Contains(t, gotLogs, "level=WARN", + "a goodbye that could not even be serialized is just as invisible a retraction loss as a failed send") + assert.Contains(t, gotLogs, "ifIndex=1", + "the unbuildable-goodbye line must name which interface index it happened on") +} + +// TestSortedRecordStrings_DoesNotMutateTheRecordsItRenders pins the helper's +// contract: it exists to render records for comparison, and TTL is asserted +// by callers elsewhere in the very same tests that call it. A helper that +// zeroes TTL in place turns every TTL assertion that runs after it into a +// check against its own side effect. +func TestSortedRecordStrings_DoesNotMutateTheRecordsItRenders(t *testing.T) { + rrs := []dns.RR{&dns.A{ + Hdr: dns.RR_Header{Name: "x.local.", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: recordTTL}, + A: net.IPv4(192, 0, 2, 1), + }} + rendered := sortedRecordStrings(rrs) + assert.Equal(t, uint32(recordTTL), rrs[0].Header().Ttl, + "sortedRecordStrings rewrote the caller's record TTL to 0 while rendering") + require.Len(t, rendered, 1) + assert.Contains(t, rendered[0], "\t0\t", "rendered form must still zero the TTL for order-free comparison") +} + func TestIfaceAddrsEqual_IgnoresAddressOrdering(t *testing.T) { base := map[int][]net.IP{ 1: {net.IPv4(192, 168, 1, 10), net.IPv4(192, 168, 1, 11)}, diff --git a/services/shared/nodeid/nodeid.go b/services/shared/nodeid/nodeid.go index 7299da56d..ea1218bfa 100644 --- a/services/shared/nodeid/nodeid.go +++ b/services/shared/nodeid/nodeid.go @@ -5,6 +5,9 @@ // subprocess can advertise so peers can tell two hosts apart even when they // share a hostname (the mDNS instance name defaults to os.Hostname(), so a // hostname collision otherwise silently merges two machines into one node). +// The same UUID also fixes the host label PAIR advertises beside it +// (noderec.HostLabel), so an identity that cannot be saved and re-mints on +// every start renames the host as well. // // It reuses the nvpair-cluster-manager's persisted cryptographic identity // (/cluster/identity.json) when present, so a host presents one UUID @@ -18,6 +21,7 @@ import ( "crypto/rand" "encoding/json" "fmt" + "log/slog" "os" "path/filepath" "time" @@ -55,7 +59,15 @@ func Resolve(baseDir string) string { if err != nil { return "" } - _ = persist(idPath, u) // best effort; an unpersisted UUID is still usable for this run + if err := persist(idPath, u); err != nil { + // The UUID is still usable for this run, but nothing reached disk, so the + // next start mints a different one and both names derived from it move: + // the node UUID in TXT and the host label advertised with it. This is the + // only place that can tell "read from disk" from "minted but unsaved", so + // the failed write is reported here rather than as a provenance flag. + slog.Warn("node identity could not be persisted; the advertised node UUID and host label will change on every start", + "path", idPath, "err", err) + } return u } diff --git a/services/shared/nodeid/nodeid_test.go b/services/shared/nodeid/nodeid_test.go index 698e6c386..c53642d6b 100644 --- a/services/shared/nodeid/nodeid_test.go +++ b/services/shared/nodeid/nodeid_test.go @@ -4,6 +4,8 @@ package nodeid import ( + "context" + "log/slog" "os" "path/filepath" "testing" @@ -34,3 +36,114 @@ func TestResolve_PrefersClusterIdentity(t *testing.T) { _, err := os.Stat(filepath.Join(base, "node-id.json")) assert.ErrorIs(t, err, os.ErrNotExist, "node-id.json should not exist when cluster identity is present") } + +func TestResolve_UnwritableConfigDirStillAdvertisesAndWarns(t *testing.T) { + base := t.TempDir() + idPath := filepath.Join(base, "node-id.json") + + handler := &capturingHandler{} + previousLogger := slog.Default() + slog.SetDefault(slog.New(handler)) + t.Cleanup(func() { slog.SetDefault(previousLogger) }) + + t.Cleanup(func() { + // t.TempDir's own teardown cannot delete a directory that is not + // writable, so hand the mode back before that teardown runs. + if err := os.Chmod(base, 0o700); err != nil { + t.Errorf("restore mode on %s: %v", base, err) + } + }) + // A read-only config directory is the case the warning exists for. Inside + // persist, os.MkdirAll reports success for the directory that already exists, + // so the tight mode is not silently widened, and the write that then fails is + // node-id.json.tmp beside the file it was staging. + require.NoError(t, os.Chmod(base, 0o500)) + + uuid := Resolve(base) + + // Running as root bypasses the directory mode, so the save succeeds and there + // is no failed write to report; skip rather than fail such an environment. + if _, err := os.Stat(idPath); err == nil { + t.Skipf("%s was written although %s is read-only, so this process bypasses directory permissions", idPath, base) + } + + assert.NotEqual(t, "", uuid, "a UUID that could not be saved is still usable for this run") + + warning := handler.recordAt(slog.LevelWarn) + require.NotNil(t, warning, "Resolve must warn when the identity it minted could not be saved") + assert.Contains(t, warning.Message, "node identity could not be persisted", + "the warning must say what failed, not just that something did") + + var loggedPath, loggedErr string + warning.Attrs(func(attr slog.Attr) bool { + switch attr.Key { + case "path": + loggedPath = attr.Value.String() + case "err": + loggedErr = attr.Value.String() + } + return true + }) + assert.Equal(t, idPath, loggedPath, "the warning must name the file it could not write") + assert.NotEmpty(t, loggedErr, "the warning must carry the I/O error") +} + +func TestResolve_PersistedIdentityLogsNoWarning(t *testing.T) { + // The warning is about the write that failed, not about minting in general. A + // first start that saves cleanly has a stable identity, so there is nothing + // to report: warning anyway would point at a disk that is fine and train + // whoever reads the log to ignore the one warning that matters. Only the level + // is pinned. A benign notice on this path, such as "minted new node identity" + // at Info level, would be a reasonable addition, so this test must not forbid + // it — forbidding every record would be rejected for the wrong reason later. + base := t.TempDir() + + handler := &capturingHandler{} + previousLogger := slog.Default() + slog.SetDefault(slog.New(handler)) + t.Cleanup(func() { slog.SetDefault(previousLogger) }) + + uuid := Resolve(base) + + require.NotEqual(t, "", uuid, "Resolve returned empty UUID") + require.FileExists(t, filepath.Join(base, "node-id.json"), "node-id.json not persisted") + + var problems []string + for _, record := range handler.records { + if record.Level >= slog.LevelWarn { + problems = append(problems, record.Level.String()+": "+record.Message) + } + } + assert.Empty(t, problems, "a saved identity is not a problem, so nothing at warning level or above may be logged") +} + +// capturingHandler keeps every record it is handed so a test can assert what a +// call logged. The package has no shared slog test helper yet, so this file +// owns the one it needs. records has no mutex, so a handler instance belongs +// to one test: it is not safe for t.Parallel(), which would let a second test +// log through the process-wide default logger while the first reads them. The +// package has no parallel tests today. +type capturingHandler struct { + records []slog.Record +} + +func (*capturingHandler) Enabled(context.Context, slog.Level) bool { return true } + +func (h *capturingHandler) Handle(_ context.Context, record slog.Record) error { + h.records = append(h.records, record.Clone()) + return nil +} + +func (h *capturingHandler) WithAttrs([]slog.Attr) slog.Handler { return h } + +func (h *capturingHandler) WithGroup(string) slog.Handler { return h } + +// recordAt returns the first record logged at level, or nil when nothing was. +func (h *capturingHandler) recordAt(level slog.Level) *slog.Record { + for i := range h.records { + if h.records[i].Level == level { + return &h.records[i] + } + } + return nil +} diff --git a/services/shared/noderec/hostlabel.go b/services/shared/noderec/hostlabel.go new file mode 100644 index 000000000..11de58b69 --- /dev/null +++ b/services/shared/noderec/hostlabel.go @@ -0,0 +1,91 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package noderec + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "strings" +) + +// hostLabelPrefix marks the host label as PAIR's own, so it can never be +// mistaken for a name the operating system owns. +const hostLabelPrefix = "nvpair-" + +// hostLabelHexDigits is the width of the identity part of the label: twelve hex +// digits, the leading 48 bits of the node UUID. The width IS the collision +// guard — about 16.7 million hosts before a collision becomes likely, against +// about 65 thousand for eight digits — and the finished label is still only 19 +// bytes against the 63-byte DNS label limit, so the wider form costs nothing. +// Do not narrow it later for tidiness: every host already advertised would +// change name. +const hostLabelHexDigits = 12 + +// HostLabel returns the single DNS label PAIR claims as its own host record +// when it advertises a node over mDNS, e.g. "nvpair-f0e1d2c34b5a". +// +// It is never the machine's hostname. Claiming the operating system's name puts +// two answers, or a cache-flushed retraction, under a name the host's own +// mDNS responder already owns, and RFC 6762 §9 resolves that contention by +// appending a digit to the computer's Local hostname ("indigo-2") — the +// defect this naming rule exists to avoid. The label instead comes from the +// per-host node UUID, which is stable across restarts, unique per host, and +// already advertised in TXT as uuid=, so a peer can tie the name it resolves to +// the identity inside the record. +// +// The rule, in order: +// +// 1. nodeUUID carries at least hostLabelHexDigits hex digits — dashes and any +// other decoration removed, lowercase — so the label is hostLabelPrefix +// plus the first twelve. Exactly the FIRST twelve: two node UUIDs sharing +// those twelve digits share a label, which is the deliberate 48-bit +// collision budget described above. +// 2. nodeUUID is empty, or is not a usable identity (non-empty but fewer than +// hostLabelHexDigits hex digits once sanitized, so not a UUID at all), and +// hostname is non-empty: fall back to hostLabelPrefix plus the first twelve +// hex digits of sha256(hostname). Hashing rather than using the hostname is +// what keeps the label from ever being the machine's name, and the hostname +// is already broadcast to the whole link as the mDNS instance name, so the +// hash leaks nothing. Such a label moves whenever the hostname moves, so +// the caller warns next to the name it is advertising: HostLabel itself is +// pure — no logging, no environment reads — which also keeps this path +// reachable from a test, where os.Hostname() is never empty. +// 3. No usable node UUID — empty, or too short to be one — and an empty +// hostname: no label, and an error naming what is missing. There is no +// entropy to derive a name from, and a fixed label such as +// "nvpair-000000000000" would give every host that reached this path the +// same name, recreating the contention this rule removes. Advertising +// nothing is strictly better. +// +// Whatever the inputs, a returned label is one lowercase DNS label with no dots +// and no spaces, exactly len(hostLabelPrefix)+hostLabelHexDigits = 19 bytes, so +// a responder can advertise it without checking it again. +func HostLabel(nodeUUID, hostname string) (string, error) { + if digits := hexDigits(nodeUUID); len(digits) >= hostLabelHexDigits { + return hostLabelPrefix + digits[:hostLabelHexDigits], nil + } + if hostname == "" { + return "", fmt.Errorf("noderec: no usable node UUID and no hostname to derive a host label from") + } + sum := sha256.Sum256([]byte(hostname)) + return hostLabelPrefix + hex.EncodeToString(sum[:])[:hostLabelHexDigits], nil +} + +// hexDigits lowercases s and keeps only its hex digits, so a hyphenated UUID — +// and any other spelling or decoration of the same identity — reduces to the +// same digits, and nothing that is not hex can reach a label. +func hexDigits(s string) string { + var b strings.Builder + b.Grow(len(s)) + for _, r := range s { + switch { + case r >= '0' && r <= '9', r >= 'a' && r <= 'f': + b.WriteRune(r) + case r >= 'A' && r <= 'F': + b.WriteRune(r - 'A' + 'a') + } + } + return b.String() +} diff --git a/services/shared/noderec/hostlabel_test.go b/services/shared/noderec/hostlabel_test.go new file mode 100644 index 000000000..50a35eee1 --- /dev/null +++ b/services/shared/noderec/hostlabel_test.go @@ -0,0 +1,232 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package noderec + +import ( + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestHostLabel_DerivesStableNameFromNodeUUID(t *testing.T) { + label, err := HostLabel("f0e1d2c3-4b5a-4678-9abc-def012345678", "indigo") + require.NoError(t, err) + assert.Equal(t, "nvpair-f0e1d2c34b5a", label, "the first twelve hex digits, dashes removed, lowercase") + assert.Equal(t, 19, len(label), "the seven-byte prefix plus twelve hex digits") + + again, err := HostLabel("f0e1d2c3-4b5a-4678-9abc-def012345678", "indigo") + require.NoError(t, err) + assert.Equal(t, label, again, "the same node UUID must always give the same label") + + // The digits are what identify the host, not the spelling they arrive in: the + // node UUID reaches this call from a JSON file another process wrote, so + // upper-case hex and surrounding decoration must still yield the label of the + // identity they spell rather than quietly dropping the host onto the + // hostname-derived fallback path. + cases := []struct { + name string + nodeUUID string + }{ + {"upper-case hex", "F0E1D2C3-4B5A-4678-9ABC-DEF012345678"}, + {"wrapped in decoration", "{f0e1d2c3-4b5a-4678-9abc-def012345678}\n"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + spelledLabel, err := HostLabel(tc.nodeUUID, "indigo") + require.NoError(t, err) + assert.Equal(t, "nvpair-f0e1d2c34b5a", spelledLabel, "node UUID %q spells the same identity", tc.nodeUUID) + }) + } +} + +func TestHostLabel_TwoNodeUUIDsYieldDifferentLabels(t *testing.T) { + // Two hosts must never advertise the same name, so a difference anywhere + // inside the twelve hex digits the label is built from has to show up in it. + test := func(name, firstUUID, secondUUID string) { + t.Run(name, func(t *testing.T) { + firstLabel, err := HostLabel(firstUUID, "indigo") + require.NoError(t, err) + secondLabel, err := HostLabel(secondUUID, "indigo") + require.NoError(t, err) + assert.NotEqual(t, firstLabel, secondLabel, "node UUIDs that differ inside the label's window must not share a host label") + }) + } + test("first hex digit differs", + "f0e1d2c3-4b5a-4678-9abc-def012345678", + "a0e1d2c3-4b5a-4678-9abc-def012345678") + test("twelfth hex digit differs", + "f0e1d2c3-4b5a-4678-9abc-def012345678", + "f0e1d2c3-4b5b-4678-9abc-def012345678") +} + +func TestHostLabel_WindowIsTheFirstTwelveHexDigits(t *testing.T) { + // The label spends exactly the first twelve hex digits of the node UUID — a + // 48-bit window, about 16.7 million hosts before a collision becomes likely — + // and nothing more. Two UUIDs that agree there share a label on purpose: + // widening the window later would rename every host already advertising + // itself, and narrowing it would give up the collision guard for free. + // Recorded here so the trade-off is visible to whoever is tempted to resize it. + test := func(name, otherUUID string) { + t.Run(name, func(t *testing.T) { + label, err := HostLabel("f0e1d2c3-4b5a-4678-9abc-def012345678", "indigo") + require.NoError(t, err) + require.Equal(t, "nvpair-f0e1d2c34b5a", label, "the window starts at the first hex digit") + + otherLabel, err := HostLabel(otherUUID, "indigo") + require.NoError(t, err) + assert.Equal(t, label, otherLabel, "hex digits past the twelfth are not part of the label") + }) + } + test("thirteenth hex digit differs", "f0e1d2c3-4b5a-4679-9abc-def012345678") + test("last hex digit differs", "f0e1d2c3-4b5a-4678-9abc-def012345679") +} + +func TestHostLabel_UsableNodeUUIDAdvertisesWithoutAHostname(t *testing.T) { + // The ladder is tried in the order the doc states it: the node UUID first, + // the hostname only when there is no usable identity. That ordering is the + // whole subject here, because moving the "no hostname" error above the node + // UUID branch is an easy refactor that makes a node whose hostname is unknown + // advertise nothing — the exact opposite of what the identity branch is for. + label, err := HostLabel("f0e1d2c3-4b5a-4678-9abc-def012345678", "") + require.NoError(t, err, "a usable node UUID is enough on its own, with no hostname to fall back on") + assert.Equal(t, "nvpair-f0e1d2c34b5a", label) + assert.Equal(t, 19, len(label)) + + // Once the identity is usable the hostname plays no part, so a host that does + // know its name does not advertise a different label because of it. + withHostname, err := HostLabel("f0e1d2c3-4b5a-4678-9abc-def012345678", "indigo") + require.NoError(t, err) + assert.Equal(t, label, withHostname, "the node UUID alone decides the label") +} + +func TestHostLabel_UnusableNodeUUIDFallsBackToHashedHostname(t *testing.T) { + // Twelve hex digits is the rule, and it belongs to this function rather than + // to whoever produced the value: anything shorter is not a node UUID, so the + // caller's bad input cannot narrow the label below the collision guard. The + // expectation is the same call with no node UUID at all, which pins "treat it + // as absent" without recomputing the hash here. + test := func(name, nodeUUID string) { + t.Run(name, func(t *testing.T) { + label, err := HostLabel(nodeUUID, "indigo") + require.NoError(t, err) + fallbackLabel, err := HostLabel("", "indigo") + require.NoError(t, err) + assert.Equal(t, fallbackLabel, label, "node UUID %q holds no usable identity and must yield the hostname-derived label", nodeUUID) + }) + } + test("two hex digits", "ab") + test("no node UUID shape at all", "not-a-uuid-at-all") + test("eleven hex digits, one short of the width", "f0e1d2c34b5") + + // Control: twelve digits is usable, so the test above cannot be satisfied by + // falling back for everything. + t.Run("exactly twelve hex digits still uses the node UUID", func(t *testing.T) { + label, err := HostLabel("f0e1d2c3-4b5a", "indigo") + require.NoError(t, err) + assert.Equal(t, "nvpair-f0e1d2c34b5a", label) + }) +} + +func TestHostLabel_EmptyUUIDFallsBackToHashedHostname(t *testing.T) { + label, err := HostLabel("", "indigo") + require.NoError(t, err) + assert.True(t, strings.HasPrefix(label, hostLabelPrefix), "fallback label %q must carry the PAIR prefix", label) + assert.Equal(t, len(hostLabelPrefix)+12, len(label), "the fallback keeps the same twelve-hex-digit width as the node UUID path") + + // The derivation itself is part of the contract, so this is a known-answer + // vector rather than a recomputation of the rule: "indigo" is hashed whole, + // and its first twelve hex digits are aecdef998727 (printf 'indigo' | + // shasum -a 256). Prefix, width and stability are all satisfied by + // sha256(hostname[:1]) or sha256(salt+hostname), and either change renames + // every host that has no node identity — the same regression the twelve-digit + // width exists to prevent for hosts that do. Changing this literal is a + // renaming event on the network, so it has to fail loudly here. + assert.Equal(t, "nvpair-aecdef998727", label, + "the fallback is hostLabelPrefix plus the first twelve hex digits of sha256(hostname); changing the derivation renames every fallback host already advertised") + + again, err := HostLabel("", "indigo") + require.NoError(t, err) + assert.Equal(t, label, again, "one hostname must always give the same fallback label") +} + +func TestHostLabel_FallbackLabelsDifferAcrossHostnames(t *testing.T) { + // The fallback has to be derived from the hostname, not merely look like it: + // prefix, width and stability are all satisfied by one fixed label, and a + // fixed label gives every host without a node identity the same name — the + // contention this rule exists to remove. The hash itself is not recomputed + // here; that would just re-run the production rule. + indigoLabel, err := HostLabel("", "indigo") + require.NoError(t, err) + vegaLabel, err := HostLabel("", "vega") + require.NoError(t, err) + iglooLabel, err := HostLabel("", "igloo") + require.NoError(t, err) + + assert.NotEqual(t, indigoLabel, vegaLabel, "two hostnames must not share one fallback host label") + assert.NotEqual(t, vegaLabel, iglooLabel, "two hostnames must not share one fallback host label") + // indigo and igloo share their first character on purpose. Hashing part of + // the hostname, e.g. sha256(hostname[:1]), passes the two assertions above — + // those pairs differ early anyway — and gives these two hosts one name. + assert.NotEqual(t, indigoLabel, iglooLabel, + "hostnames that agree only on their first character must not share one fallback host label, so hashing part of the hostname cannot pass") +} + +func TestHostLabel_NeverProducesTheOperatingSystemHostname(t *testing.T) { + // The defect being fixed is PAIR claiming the machine's own name, which makes + // macOS append "-2" to the computer's Local hostname. Whatever the machine + // calls itself, the name PAIR advertises stays its own: one label, lowercase, + // within the 63-byte DNS label limit. + cases := []struct { + name string + hostname string + }{ + {"lowercase", "indigo"}, + {"capitalised", "Indigo"}, + {"carries the mDNS suffix", "indigo.local"}, + {"carries a DNS search domain", "indigo.lab"}, + // What os.Hostname() actually returns on a Mac: macOS re-derived the + // hostname from the Local hostname, itself its rendering of the computer + // name "Home Mac". Upper case, a hyphen and a search domain in one + // string — embedding rather than hashing this would advertise a name that + // is not a single DNS label, and not one the host has claimed. + {"real macOS name with uppercase, hyphen and search domain", "Home-Server.lab"}, + {"contains spaces", "a host with spaces"}, + {"longer than a DNS label", strings.Repeat("h", 70)}, // 70 bytes + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + label, err := HostLabel("", tc.hostname) + require.NoError(t, err) + + assert.NotEqual(t, tc.hostname, label, "the host label must never be the operating system's hostname") + assert.NotContains(t, label, ".", "a host label is one DNS label, so no suffix separator") + assert.NotContains(t, label, " ", "a host label is one DNS label, so no spaces") + assert.Equal(t, strings.ToLower(label), label, "a host label is lowercase") + assert.Less(t, len(label), 64, "a DNS label is at most 63 bytes") + }) + } +} + +func TestHostLabel_NoUsableInputReturnsError(t *testing.T) { + // With no usable node UUID and no hostname there is no entropy to derive a + // name from, and a fixed label would give every host that reached this path + // the same name. An error and no label lets the caller advertise nothing + // instead. + test := func(name, nodeUUID string) { + t.Run(name, func(t *testing.T) { + label, err := HostLabel(nodeUUID, "") + assert.Error(t, err, "no identity and no hostname must not yield a label") + assert.Equal(t, "", label) + assert.ErrorContains(t, err, "no usable node UUID") + assert.ErrorContains(t, err, "no hostname") + }) + } + test("no node UUID at all", "") + // The wording has to be true here too: the node UUID was not empty, it just + // held no usable identity, and telling the operator otherwise would send them + // looking at the wrong input. + test("node UUID too short to use", "ab") +} diff --git a/services/shared/noderec/noderec.go b/services/shared/noderec/noderec.go index 258aef709..54aa72fca 100644 --- a/services/shared/noderec/noderec.go +++ b/services/shared/noderec/noderec.go @@ -47,7 +47,10 @@ const ( Domain = "local" // SRVPort is the fixed, non-authoritative SRV port on the _nvpair-node // record. Consumers MUST ignore it and read each service's port from TXT; - // it exists only so the SRV record is well-formed and deterministic. + // it exists only so the SRV record is well-formed and deterministic. The + // SRV target is the single per-host label HostLabel derives from the node + // UUID, never the machine's hostname, and the announcement's A records + // carry that same name. SRVPort = 14318 // SchemaVersion is the current v= TXT schema version. It is for // diagnostics/logs/tests and to disambiguate the record format across future diff --git a/services/tests/broker_test.go b/services/tests/broker_test.go index b9d7a8fce..c35d21497 100644 --- a/services/tests/broker_test.go +++ b/services/tests/broker_test.go @@ -105,17 +105,15 @@ func sendReq(t *testing.T, w io.Writer, id int, method string) { require.NoError(t, err, "write %s request", method) } -func registerNodeInfo(t *testing.T, instance string, port int) *zeroconf.Server { +func registerNodeInfo(t *testing.T, instance, hostLabel string, port int) *zeroconf.Server { t.Helper() // One consolidated _nvpair-node record carrying ni= (the node-info // service). A distinct uuid keeps each stub from colliding with this node's // own record or the others. The daemon browses this, folds it into its // directory, and pushes it to the broker store. txt := []string{"v=1", "uuid=" + instance + "-uuid", fmt.Sprintf("ni=%d", port)} - srv, err := zeroconf.Register(instance, nodeRecordService, testDomain, port, txt, nil) - require.NoError(t, err, "register %s", instance) - t.Cleanup(srv.Shutdown) - t.Logf("advertising %s @ %s (ni=%d)", instance, nodeRecordService, port) + srv := registerTestAdvertisement(t, instance, nodeRecordService, hostLabel, port, txt) + t.Logf("advertising %s @ %s (ni=%d, host=%s)", instance, nodeRecordService, port, hostLabel) return srv } @@ -199,7 +197,7 @@ func TestBroker_RelaysDiscoverySubscriptionAcrossProcesses(t *testing.T) { // Advertise the first node before the broker starts so it is in the // store by the time we query it. - registerNodeInfo(t, inst1, port1) + registerNodeInfo(t, inst1, testHostFour, port1) stdin, msgs, cleanup := startBroker(t) t.Cleanup(cleanup) @@ -242,7 +240,7 @@ func TestBroker_RelaysDiscoverySubscriptionAcrossProcesses(t *testing.T) { t.Log("phase 2 OK: subscribe acked and baseline snapshot received") // Phase 3 — subscribed: a newly advertised node must be pushed. - registerNodeInfo(t, inst2, port2) + registerNodeInfo(t, inst2, testHostBrokerTwo, port2) waitForPushContaining(t, msgs, inst2, 25*time.Second) t.Log("phase 3 OK: live push received for new node while subscribed") @@ -275,7 +273,7 @@ func TestBroker_RelaysDiscoverySubscriptionAcrossProcesses(t *testing.T) { // discovered (visible via get-nodes) but must NOT be pushed. Keying // the negative assertion on inst3 (which only exists from now on) // makes it immune to any pre-unsubscribe push still draining. - registerNodeInfo(t, inst3, port3) + registerNodeInfo(t, inst3, testHostBrokerThree, port3) pollNodeListed(t, stdin, msgs, inst3, 300, 25*time.Second, func(nodes []availableNode) bool { return !containsNode(nodes, inst3) }) diff --git a/services/tests/cluster_data_plane_test.go b/services/tests/cluster_data_plane_test.go index b0ccc9cc2..2662fdb9f 100644 --- a/services/tests/cluster_data_plane_test.go +++ b/services/tests/cluster_data_plane_test.go @@ -36,8 +36,6 @@ import ( "nvpair-shared/jsonrpc" "nvpair-shared/netpick" "nvpair-shared/noderec" - - "github.com/grandcat/zeroconf" ) // The block's wl and er endpoints for this run, set by TestMain from the @@ -152,8 +150,7 @@ func (c *interNodeCluster) startStubClusterPeer(t *testing.T, instance string) ( txt := []string{"v=1", "uuid=" + c.peerUUID, "ip=" + addresses[0], "ips=" + strings.Join(addresses, ","), fmt.Sprintf("ni=%d", port), fmt.Sprintf("wl=%d", port), clustertrust.ClusterUUIDTXTKey + "=" + c.peerUUID} - adv, err := zeroconf.Register(instance, nodeRecordService, testDomain, port, txt, nil) - require.NoError(t, err, "register stub peer") + adv := registerTestAdvertisement(t, instance, nodeRecordService, testHostFive, port, txt) stop := sync.OnceFunc(func() { adv.Shutdown() if err := srv.Close(); err != nil { @@ -161,7 +158,8 @@ func (c *interNodeCluster) startStubClusterPeer(t *testing.T, instance string) ( } }) t.Cleanup(stop) - t.Logf("stub cluster peer advertising %s (ni=%d, wl=%d, cluster-uuid=%s)", nodeRecordService, port, port, c.peerUUID) + t.Logf("stub cluster peer advertising %s (ni=%d, wl=%d, cluster-uuid=%s, host=%s)", + nodeRecordService, port, port, c.peerUUID, testHostFive) return received, stop } diff --git a/services/tests/discovery_test.go b/services/tests/discovery_test.go index 3b4f441e0..341d36ed3 100644 --- a/services/tests/discovery_test.go +++ b/services/tests/discovery_test.go @@ -5,6 +5,7 @@ package tests import ( "context" + "fmt" "net" "testing" "time" @@ -24,9 +25,7 @@ func TestDiscovery_ResolvesRegisteredNode(t *testing.T) { port = 55555 ) - server, err := zeroconf.Register(instance, service, testDomain, port, []string{"env=test"}, nil) - require.NoError(t, err, "register") - defer server.Shutdown() + registerTestAdvertisement(t, instance, service, testHostOne, port, []string{"env=test"}) time.Sleep(500 * time.Millisecond) resolver, err := zeroconf.NewResolver(nil) @@ -65,12 +64,9 @@ func TestDiscovery_ResolvesMultipleRegisteredNodes(t *testing.T) { const service = "_test-multi._tcp" instances := []string{"node-alpha", "node-beta", "node-gamma"} - var servers []*zeroconf.Server for i, inst := range instances { - s, err := zeroconf.Register(inst, service, testDomain, 50000+i, nil, nil) - require.NoError(t, err, "register %s", inst) - servers = append(servers, s) - defer s.Shutdown() + // registerTestAdvertisement registers t.Cleanup(srv.Shutdown) itself. + registerTestAdvertisement(t, inst, service, fmt.Sprintf("%s-%d", testHostLoopPrefix, i+1), 50000+i, nil) } time.Sleep(500 * time.Millisecond) @@ -110,8 +106,7 @@ func TestDiscovery_RemovesDepartedNode(t *testing.T) { port = 55556 ) - server, err := zeroconf.Register(instance, service, testDomain, port, nil, nil) - require.NoError(t, err, "register") + server := registerTestAdvertisement(t, instance, service, testHostThree, port, nil) // Phase 1: verify discoverable entry := browseForInstance(t, service, instance, 5*time.Second) diff --git a/services/tests/ghost_node_test.go b/services/tests/ghost_node_test.go index 1355d2568..f1b5d6a56 100644 --- a/services/tests/ghost_node_test.go +++ b/services/tests/ghost_node_test.go @@ -20,8 +20,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/grandcat/zeroconf" - "nvpair-shared/jsonrpc" "nvpair-shared/noderec" ) @@ -81,9 +79,11 @@ func TestScanner_EvictsRecordSupersededAtItsAddress(t *testing.T) { "ip=127.0.0.1", fmt.Sprintf("%s=%d", noderec.ServiceNodeInfo, niPort), } - responder, err := zeroconf.Register(peerInstance, noderec.ServiceType, testDomain, noderec.SRVPort, txt, nil) - require.NoError(t, err, "register peer") + responder := registerTestAdvertisement(t, peerInstance, noderec.ServiceType, testHostSix, noderec.SRVPort, txt) responderDown := false + // Safety net for an early return; the normal path shuts the responder down + // deliberately below, and the helper's own cleanup is then a no-op because + // grandcat's Shutdown is idempotent. defer func() { if !responderDown { responder.Shutdown() diff --git a/services/tests/mdns_advertisement_test.go b/services/tests/mdns_advertisement_test.go new file mode 100644 index 000000000..adae4619c --- /dev/null +++ b/services/tests/mdns_advertisement_test.go @@ -0,0 +1,484 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +// Test-side mDNS advertisements. +// +// A stub node used to be advertised with zeroconf.Register, which defaults the +// advertised host to the machine's own hostname, so every test run announced +// "A .local -> 127.0.0.1" (and a conflicting SRV target) to +// every real node on the LAN. A real PAIR node then replaced its correct entry +// with a dead one pointing at the test machine (issue #229). +// +// registerTestAdvertisement below replaces every such call site. It refuses to +// run when the host label it was given is the machine's name, so a future edit +// cannot reintroduce the conflict by passing hostname again, and it pins the +// records it assembles itself — the SRV target and the A and AAAA records — to +// a synthetic label and the loopback address, so no machine-chosen address can +// appear in them. What it does not cover is the TXT payload, which every call +// site passes through untouched: the cluster-stub sites still publish their +// real routable address in their ip=/ips= keys (159 such records in the +// post-conversion capture against 167 at baseline — the same pre-existing +// channel, deliberately left alone by this conversion). Closing that TXT +// channel is a known, separate follow-up. +package tests + +import ( + "context" + "fmt" + "os" + "strings" + "testing" + "time" + + "github.com/grandcat/zeroconf" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The testHost* constants are the synthetic host labels test advertisements +// use instead of the machine hostname. They carry no dot, and the guard below +// treats one as a claim of the machine name only when the machine is literally +// named like it, so they are safe on this machine and on CI runners. +const ( + testHostOne = "nvpair-test-1" + testHostTwo = "nvpair-test-2" + testHostThree = "nvpair-test-3" + testHostFour = "nvpair-test-4" + testHostFive = "nvpair-test-5" + testHostSix = "nvpair-test-6" + testHostSeven = "nvpair-test-7" + + // testHostBrokerTwo / testHostBrokerThree cover the second and third + // concurrent stubs of the one cross-process broker test, which has three + // simultaneous advertisements and therefore needs two labels beyond the + // seven single-site labels. + testHostBrokerTwo = "nvpair-test-8" + testHostBrokerThree = "nvpair-test-9" + + // testHostLoopPrefix is the label prefix for a site that registers several + // advertisements in one loop; each iteration gets its own number so the + // labels remain distinct within the run. + testHostLoopPrefix = "nvpair-test-loop" + + // testHostLoopCount is the number of loop-variant labels the guard tests + // cover; keep it in step with the largest loop in the converted sites. + testHostLoopCount = 3 +) + +// testHostLabels lists every single-stub host label the converted call sites +// use, plus the loop variants, so the guard test can assert none of them ever +// collides with this machine's name. +func testHostLabels() []string { + labels := []string{ + testHostOne, testHostTwo, testHostThree, testHostFour, + testHostFive, testHostSix, testHostSeven, + testHostBrokerTwo, testHostBrokerThree, + } + for i := 1; i <= testHostLoopCount; i++ { + labels = append(labels, fmt.Sprintf("%s-%d", testHostLoopPrefix, i)) + } + return labels +} + +// claimsMachineHostname reports whether a host label claims the machine's own +// mDNS name: the test label and the machine hostname agree on their first DNS +// label, which is the part that resolves under .local. +// +// It compares first labels exactly, case-insensitively. Substring containment +// would be wrong — a machine named "test" must not reject the innocuous label +// "nvpair-test-1", and a label like "nothome-server" is not the machine name — +// so the comparison is equality of the first label only, never Contains. +func claimsMachineHostname(hostLabel, hostname string) bool { + return strings.EqualFold(firstLabel(hostLabel), firstLabel(hostname)) +} + +func firstLabel(s string) string { + return strings.SplitN(s, ".", 2)[0] +} + +// registerTestAdvertisement publishes one service advertisement for a test stub +// node, under a synthetic host label and a loopback A record instead of the +// machine hostname and a machine-chosen address. +// +// The host label is passed to RegisterProxy as a bare label. grandcat trims +// dots from the label and then re-appends the domain; the branch meant to +// spare a label that already ends with the domain compares a dot-trimmed +// label against a domain still spelled "local." (testDomain, trailing dot +// included), so that check can never succeed and the domain is always +// re-appended. Pass bare labels, as every converted site does: "nvpair-test-1" +// advertises as "nvpair-test-1.local.", while a pre-suffixed +// "nvpair-test-1.local" would advertise as "nvpair-test-1.local.local." — +// verified on the wire against the vendored grandcat v1.0.0. +// +// It fails the test when hostLabel claims the machine hostname, so a future +// call site cannot reintroduce the conflict by passing os.Hostname(); every +// converted site passes one of the synthetic labels above and can never reach +// that check. ifaces stays nil, so the announcement reaches every interface and +// same-process discovery keeps working exactly as before the conversion. +func registerTestAdvertisement(t *testing.T, instance, service, hostLabel string, port int, txt []string) *zeroconf.Server { + t.Helper() + + hostname, err := os.Hostname() + require.NoError(t, err, "read machine hostname") + require.Falsef(t, claimsMachineHostname(hostLabel, hostname), + "test advertisement must not claim the machine hostname: host label %q resolves as %q under .local, "+ + "the same name as this machine (%q); issue #229 — such announcements tell real nodes the services are "+ + "on this machine and kill the live entries when the test exits", + hostLabel, hostLabel+".local.", hostname) + + srv, err := zeroconf.RegisterProxy(instance, service, testDomain, port, hostLabel, []string{"127.0.0.1"}, txt, nil) + require.NoErrorf(t, err, "register test advertisement %s under %s", instance, hostLabel) + t.Cleanup(srv.Shutdown) + return srv +} + +// TestClaimsMachineHostname_FlagsOnlyTheMachineName pins the guard's boundary: +// it flags every spelling of the machine's own name and refuses to flag the +// synthetic labels the converted call sites use, including against a machine +// whose name is a substring or superstring of a test label. +func TestClaimsMachineHostname_FlagsOnlyTheMachineName(t *testing.T) { + tests := []struct { + name string + hostLabel string + hostname string + want bool + }{ + {"same name", "home-server", "home-server", true}, + {"machine FQDN against a label", "home-server", "home-server.lab", true}, + {"test label against a machine FQDN", testHostOne, "nvpair-test-1.lab", true}, + {"differ only by case", "Home-Server", "home-server", true}, + {"machine name with a domain suffix", "home-server", "home-server.example.com", true}, + {"label with a domain suffix", "home-server.local", "home-server", true}, + {"dotted claim of a machine FQDN", "home-server.local", "home-server.lab", true}, + {"a different name", "indigo", "home-server", false}, + {"every converted test label", testHostTwo, "nvpair-test-9", false}, + {"loop label against the seven", testHostLoopPrefix + "-1", testHostOne, false}, + {"machine named test against a containment trap", testHostOne, "test", false}, + {"machine is a superstring of the label", "nvpair-test-10", testHostOne, false}, + {"label is a superstring of the machine name", "notnvpair-test-1", "nvpair-test-1", false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := claimsMachineHostname(tc.hostLabel, tc.hostname); got != tc.want { + t.Fatalf("claimsMachineHostname(%q, %q) = %v, want %v", tc.hostLabel, tc.hostname, got, tc.want) + } + }) + } + + t.Run("the actual machine name is always a claim", func(t *testing.T) { + hostname, err := os.Hostname() + require.NoError(t, err) + require.Truef(t, claimsMachineHostname(hostname, hostname), + "a test label equal to this machine's hostname (%q) must count as a claim", hostname) + for _, label := range testHostLabels() { + // The loop labels can never collide with a real hostname here on + // purpose; this machine's first label differs from every one of + // them (checked, not assumed, below). + // A synthetic label must never collide with this machine's real + // name — checked here, not assumed from the label family. + if claimsMachineHostname(label, hostname) { + t.Fatalf("synthetic label %q collides with this machine's hostname %q", label, hostname) + } + } + }) +} + +// normalizeHostLabel reduces an mDNS name — a bare label, an FQDN with a +// trailing dot as it appears on the wire, or an FQDN without one — to the same +// bare first label claimsMachineHostname compares, so a wire assertion and the +// guard speak one language. +func normalizeHostLabel(s string) string { + return firstLabel(strings.TrimSuffix(s, ".")) +} + +// callOutcome records what happened to a helper call made on a throwaway +// *testing.T inside its own goroutine. A require failure on that throwaway T +// runs FailNow, which unwinds with runtime.Goexit and dies inside the goroutine +// only, so the deferred function here can report how far the helper got. +type callOutcome struct { + reachedEnd bool + crash any +} + +// runOnThrowawayT runs fn with an unwatched *testing.T in a private goroutine +// and reports whether the helper finished or aborted. A helper that calls +// t.FailNow cannot be observed any other way: failing the caller's own *testing.T +// would take the whole test binary with it. +func runOnThrowawayT(t *testing.T, fn func(ft *testing.T)) callOutcome { + t.Helper() + + out := callOutcome{} + done := make(chan struct{}) + go func() { + defer func() { + out.crash = recover() + close(done) + }() + fn(new(testing.T)) + out.reachedEnd = true + }() + select { + case <-done: + case <-time.After(60 * time.Second): + t.Fatalf("the helper never returned: it must either abort or register") + } + return out +} + +// TestRegisterTestAdvertisement_RejectsAClaimOfTheMachineName drives the guard +// through the helper a real call site uses: handing the helper the machine's own +// hostname must abort it before it publishes anything, so no converted site can +// silently go back to announcing this machine (issue #229). +func TestRegisterTestAdvertisement_RejectsAClaimOfTheMachineName(t *testing.T) { + hostname, err := os.Hostname() + require.NoError(t, err, "read machine hostname") + require.Falsef(t, claimsMachineHostname(testHostOne, hostname), + "this machine is named %q, which collides with synthetic label %q; a differently named machine is needed to run this", + hostname, testHostOne) + + claimed := runOnThrowawayT(t, func(ft *testing.T) { + registerTestAdvertisement(ft, "nvpair-guard-claim-probe", "_t5guard._tcp", hostname, 59911, nil) + }) + require.Nilf(t, claimed.crash, "the helper crashed instead of failing the test: %v", claimed.crash) + require.Falsef(t, claimed.reachedEnd, + "the helper published an advertisement whose host label is this machine's hostname %q instead of refusing it; "+ + "that is the exact announcement issue #229 is about", hostname) + + // The control keeps the assertion above from passing vacuously: with a + // synthetic label the same helper does reach the wire, so the abort above is + // the guard refusing the claim and not a broken helper. + control := runOnThrowawayT(t, func(ft *testing.T) { + srv := registerTestAdvertisement(ft, "nvpair-guard-control-probe", "_t5guard._tcp", testHostOne, 59911, nil) + if srv != nil { + // The throwaway *testing.T never runs its cleanups, so the + // helper's t.Cleanup(srv.Shutdown) can never fire: close the + // server on this goroutine instead, deferred right where it is + // created so it leaves the wire even if the closure unwinds + // before returning normally. + defer srv.Shutdown() + } + }) + require.Nilf(t, control.crash, "the helper crashed on a synthetic label: %v", control.crash) + require.Truef(t, control.reachedEnd, + "the helper refused the synthetic label %q too, so the refusal of %q proves nothing", testHostOne, hostname) +} + +// TestZeroconfAdvertisements_AllRoutedThroughTheHelper pins the conversion +// itself. A call site that went back to plain zeroconf.Register would open the +// machine-hostname conflict again (issue #229) and no behavioral test here would +// notice, because every consumer asserts on instance IDs and TXT keys rather than +// on the advertised host — so this is the gate that keeps it from coming back. +// +// Its threat model is the accidental regression, not sabotage: it catches a +// call site reverting to the plain constructor and cites the offender as +// file:line:code, but a line spelled differently sails past the needle — +// `var reg = zc.Register` called as reg(...), an aliased import, or a call +// from any non-test file all keep this gate green. Read it as a hair trigger +// against a careless edit, never as a barrier against a determined one; the +// wire read-back test is the witness that the helper itself behaves. +func TestZeroconfAdvertisements_AllRoutedThroughTheHelper(t *testing.T) { + files, err := os.ReadDir(".") + require.NoError(t, err, "read test package directory") + + var offenders []string + for _, de := range files { + if de.IsDir() || !strings.HasSuffix(de.Name(), "_test.go") { + continue + } + src, err := os.ReadFile(de.Name()) + require.NoErrorf(t, err, "read %s", de.Name()) + // Built by concatenation so this file's own source cannot match the + // needle it searches for. + const callNeedle = "zeroconf." + "Register" + "(" + for i, line := range strings.Split(string(src), "\n") { + // The plain constructor's name followed by an open parenthesis: + // no RegisterProxy call can match, so prose mentions of the old + // name never do either. + if strings.Contains(line, callNeedle) { + offenders = append(offenders, fmt.Sprintf("%s:%d: %s", de.Name(), i+1, strings.TrimSpace(line))) + } + } + } + require.Emptyf(t, offenders, + "test advertisements must go through registerTestAdvertisement, which refuses a host label that claims the "+ + "machine hostname; plain zeroconf.Register defaults that label to os.Hostname():\n%s", + strings.Join(offenders, "\n")) +} + +// browseOnce resolves one service through a resolver it owns alone, for up to +// window, and returns the first entry whose instance matches; nil, nil when +// the window passes without seeing it. Every browse gets its own resolver: one +// grandcat client shares a single multicast socket between the read loops of +// all the browses made through it, so two live browses on one resolver would +// each silently swallow part of the other's responses. +func browseOnce(service, instance string, window time.Duration) (*zeroconf.ServiceEntry, error) { + resolver, err := zeroconf.NewResolver(nil) + if err != nil { + return nil, err + } + ctx, cancel := context.WithTimeout(context.Background(), window) + defer cancel() + + entries := make(chan *zeroconf.ServiceEntry) + found := make(chan *zeroconf.ServiceEntry, 1) + go func() { + for e := range entries { + if e.Instance == instance { + select { + case found <- e: + default: + } + } + } + }() + + if err := resolver.Browse(ctx, service, testDomain, entries); err != nil { + return nil, err + } + select { + case e := <-found: + return e, nil + case <-ctx.Done(): + return nil, nil + } +} + +// discoverProbeWithMulticastControl decides what a browse that never saw the +// probe's advertisement actually means, because "never discovered" has two +// opposite causes and only one of them makes a skip honest. It publishes one +// control advertisement directly through zeroconf.RegisterProxy — deliberately +// NOT through registerTestAdvertisement, which is the very thing this suite +// pins — and browses the probe's service and the control's service at the same +// time: +// +// - control seen, probe not seen: multicast works here, so the helper's own +// registration is the broken one. t.Fatalf, never a skip: the host and +// address assertions that follow the caller's browse are the suite's only +// witnesses to what issue #229 is about, and skipping would retire them in +// silence. +// - probe seen after all: the first browse was merely slow; the entry is +// returned so the caller's assertions still run. +// - neither seen: multicast genuinely is unavailable here, and only now is a +// skip telling the truth. +// +// The control carries a host label outside the nvpair-test-* family — checked +// against the real hostname with the same first-label guard the helper applies +// — and an explicit 127.0.0.1, and it is shut down by a defer on every exit +// path, including the fatal and skip ones, so the diagnosis leaves nothing +// announced behind. +func discoverProbeWithMulticastControl(t *testing.T, probeService, probeInstance string) *zeroconf.ServiceEntry { + t.Helper() + + const ( + window = 8 * time.Second + controlService = "_t5ctl._tcp" + controlInstance = "nvpair-mcast-control" + controlHost = "nvpair-mcast-host" + controlPort = 59913 + ) + + hostname, err := os.Hostname() + require.NoError(t, err, "read machine hostname") + require.Falsef(t, claimsMachineHostname(controlHost, hostname), + "the multicast control label %q collides with this machine's hostname %q; a differently named machine is needed to run this", + controlHost, hostname) + + srv, err := zeroconf.RegisterProxy(controlInstance, controlService, testDomain, controlPort, controlHost, []string{"127.0.0.1"}, nil, nil) + if err != nil { + t.Skipf("the probe stayed unseen and even a control published straight through grandcat could not be registered (%v): this environment does not support the mDNS this test needs", err) + } + defer srv.Shutdown() + + type browseOutcome struct { + entry *zeroconf.ServiceEntry + err error + } + probeCh := make(chan browseOutcome, 1) + controlCh := make(chan browseOutcome, 1) + go func() { + e, err := browseOnce(probeService, probeInstance, window) + probeCh <- browseOutcome{e, err} + }() + go func() { + e, err := browseOnce(controlService, controlInstance, window) + controlCh <- browseOutcome{e, err} + }() + probe, control := <-probeCh, <-controlCh + + switch { + case probe.entry != nil: + return probe.entry + case control.entry != nil && probe.err == nil: + t.Fatalf("multicast works in this environment — the control advertisement was discovered while the helper's %q never once appeared under %s — registerTestAdvertisement's registration is what is broken here, and this test is the suite's only witness to the host and address claims issue #229 is about", probeInstance, probeService) + case control.entry != nil: + t.Skipf("the control was discovered but re-browsing the probe's service itself failed (%v): a broken helper cannot be told apart from a resolver fault here", probe.err) + case probe.err != nil || control.err != nil: + t.Skipf("neither advertisement was discovered and the diagnosis hit resolver faults (probe: %v, control: %v): multicast is unavailable in this environment", probe.err, control.err) + default: + t.Skipf("neither the probe nor the directly-published control appeared within %s of browsing: multicast is genuinely unavailable in this environment, so this machine's announcements cannot be observed — or pinned — here", window) + } + return nil // t.Fatalf and t.Skipf unwind with runtime.Goexit; reached by no honest path +} + +// TestRegisterTestAdvertisement_AdvertisesOnlyItsOwnHostAndLoopback reads back +// one advertisement through the same resolver production discovery uses, and +// asserts what issue #229 is about: the SRV target names a synthetic host, the +// A record says 127.0.0.1, there is no AAAA record at all — the helper passes +// only the loopback IPv4, so any IPv6 on the wire is a machine-chosen address — +// and neither address class carries this machine's hostname. If the helper ever +// went back to Register's defaults, or passed a machine-chosen address in +// either family, this is what fails. +func TestRegisterTestAdvertisement_AdvertisesOnlyItsOwnHostAndLoopback(t *testing.T) { + const ( + service = "_t5wire._tcp" + instance = "nvpair-guard-wire" + host = testHostTwo + port = 59912 + ) + hostname, err := os.Hostname() + require.NoError(t, err, "read machine hostname") + require.Falsef(t, claimsMachineHostname(host, hostname), + "this machine is named %q, which collides with synthetic label %q; a different machine is needed to run this", + hostname, host) + + registerTestAdvertisement(t, instance, service, host, port, []string{"probe=guard"}) + + resolver, err := zeroconf.NewResolver(nil) + require.NoError(t, err, "resolver") + entries := make(chan *zeroconf.ServiceEntry) + found := make(chan *zeroconf.ServiceEntry, 1) + go func() { + for e := range entries { + if e.Instance == instance { + select { + case found <- e: + default: + } + } + } + }() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + require.NoError(t, resolver.Browse(ctx, service, testDomain, entries), "browse") + + var entry *zeroconf.ServiceEntry + select { + case entry = <-found: + case <-ctx.Done(): + // Skipping straight away would state the environment's condition as + // fact without checking it: a helper publishing under a name nobody + // browses skips in exactly the same way, silently taking every + // assertion below with it. Diagnose against a directly-published + // control first — see discoverProbeWithMulticastControl. + entry = discoverProbeWithMulticastControl(t, service, instance) + } + + assert.Equal(t, host+".local.", entry.HostName, "SRV target / advertised host") + require.Len(t, entry.AddrIPv4, 1, "A records for the advertised host: %v", entry.AddrIPv4) + assert.Equal(t, "127.0.0.1", entry.AddrIPv4[0].String(), "A record address") + assert.Emptyf(t, entry.AddrIPv6, + "AAAA records for the advertised host: %v — registerTestAdvertisement hands grandcat only 127.0.0.1, so any IPv6 on the wire is a machine-chosen address leaking out of the announcement", entry.AddrIPv6) + assert.NotEqualf(t, normalizeHostLabel(hostname), normalizeHostLabel(entry.HostName), + "the advertisement carries this machine's hostname (%q): test nodes are telling the LAN they are this machine", + entry.HostName) +} diff --git a/services/tests/models_http_test.go b/services/tests/models_http_test.go index c728fc62b..b40b85a65 100644 --- a/services/tests/models_http_test.go +++ b/services/tests/models_http_test.go @@ -19,8 +19,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/grandcat/zeroconf" - "nvpair-shared/noderec" ) @@ -88,10 +86,8 @@ func (c *interNodeCluster) startModelsPeer(t *testing.T, instance string, models txt := []string{"v=1", "uuid=" + c.peerUUID, "cluster-uuid=" + c.peerUUID, "ip=127.0.0.1", fmt.Sprintf("ni=%d", port), fmt.Sprintf("em=%d", port)} - advertisement, err := zeroconf.Register(instance, nodeRecordService, testDomain, port, txt, nil) - require.NoError(t, err, "register model peer") - t.Cleanup(advertisement.Shutdown) - t.Logf("advertising %s with pinned node-info and models (port=%d)", instance, port) + registerTestAdvertisement(t, instance, nodeRecordService, testHostSeven, port, txt) + t.Logf("advertising %s with pinned node-info and models (port=%d, host=%s)", instance, port, testHostSeven) } func modelsMatch(models []string) bool { From 723e5bbe8107ba2db486952cd5fd0fa0a99bc241 Mon Sep 17 00:00:00 2001 From: Steven Beverly Date: Wed, 25 Nov 2026 14:25:55 -0700 Subject: [PATCH 2/2] test(mdns): bound grandcat teardowns so one interface cannot stall the suite MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit grandcat v1.0.0 sets no write deadline anywhere, and Server.Shutdown holds its shutdown lock while unregister sends the goodbye on every interface listMulticastInterfaces reports — loopback, VPN tunnels and peer-to-peer interfaces included — before it closes any socket. An interface that answers "network is unreachable" is harmless, because grandcat discards write errors, but one that accepts the packet into a queue that never drains leaves that write waiting to become writable indefinitely. Reported on an M5 mac, whose goroutine dump shows exactly that park. Route all three grandcat teardowns in the package through one bounded wait: the cleanup registerTestAdvertisement registers on behalf of every call site, the control of the hostname-claim guard, and the multicast control of the discovery diagnosis. The cleanup is the one that matters most — cleanups run one test at a time, so a parked one stalls every later test until go test's own timeout dumps the binary. A teardown that outlives the deadline is reported rather than failed: one interface that will not take a goodbye should not turn red every test that advertised anything. That report goes to the test's own *testing.T, because a throwaway one discards everything written to it. The bound frees the test, not the write: grandcat's sockets are unexported and closed only after the write returns, so a stalled advertisement is retracted when its records reach their TTL. Those records are always a synthetic label pointing at 127.0.0.1, so the residue is a dead entry a peer drops by itself, not a live node's entry being replaced. Test-only: no service binary's compiled output changes. Signed-off-by: Steven Beverly --- services/tests/discovery_test.go | 3 +- services/tests/mdns_advertisement_test.go | 89 +++++++++++++++++++++-- 2 files changed, 83 insertions(+), 9 deletions(-) diff --git a/services/tests/discovery_test.go b/services/tests/discovery_test.go index 341d36ed3..e8332c6d6 100644 --- a/services/tests/discovery_test.go +++ b/services/tests/discovery_test.go @@ -65,7 +65,8 @@ func TestDiscovery_ResolvesMultipleRegisteredNodes(t *testing.T) { instances := []string{"node-alpha", "node-beta", "node-gamma"} for i, inst := range instances { - // registerTestAdvertisement registers t.Cleanup(srv.Shutdown) itself. + // registerTestAdvertisement unregisters each advertisement itself when + // the test ends. registerTestAdvertisement(t, inst, service, fmt.Sprintf("%s-%d", testHostLoopPrefix, i+1), 50000+i, nil) } time.Sleep(500 * time.Millisecond) diff --git a/services/tests/mdns_advertisement_test.go b/services/tests/mdns_advertisement_test.go index adae4619c..05a7ef5f9 100644 --- a/services/tests/mdns_advertisement_test.go +++ b/services/tests/mdns_advertisement_test.go @@ -96,6 +96,59 @@ func firstLabel(s string) string { return strings.SplitN(s, ".", 2)[0] } +// shutdownDeadline bounds one grandcat teardown, with room to spare: a healthy +// host finishes unregistering in single-digit milliseconds, so anything still +// running this long after the request is parked rather than merely slow. +const shutdownDeadline = 5 * time.Second + +// boundedShutdown unregisters a test advertisement and reports whether grandcat +// finished within shutdownDeadline. +// +// The bound is needed because the teardown cannot be interrupted from here: +// Server.Shutdown takes its shutdown lock, then sends the goodbye on every +// multicast-capable interface the host reports — loopback, VPN tunnels and +// peer-to-peer interfaces included — before it closes any socket, and grandcat +// sets no write deadline on that socket at all. An interface that answers +// "network is unreachable" is harmless, because grandcat discards write errors; +// one that accepts the packet into a queue that never drains leaves the write +// waiting for the socket to become writable, and nothing ever wakes it. On such +// a host every advertisement in this package would be torn down by a parked +// goroutine, and because cleanups run one test at a time the whole package +// stalls until go test's own timeout dumps it. +// +// What this bounds is the wait, not the write: after a timeout the parked +// goroutine keeps the socket until this binary exits, and the advertisement is +// retracted only when its records reach their TTL. That residue is always a +// synthetic label pointing at 127.0.0.1 and never this machine's hostname, so +// what is left behind is a dead entry a peer drops by itself, not a live node's +// entry being replaced. +func boundedShutdown(srv *zeroconf.Server) bool { + done := make(chan struct{}) + go func() { + defer close(done) + srv.Shutdown() + }() + select { + case <-done: + return true + case <-time.After(shutdownDeadline): + return false + } +} + +// logStuckTeardown reports an advertisement that outlived shutdownDeadline. It +// is a report and not a failure: a host that cannot send a goodbye is an +// environment this suite cannot fully exercise, and that is worth stating once +// per advertisement rather than turning every test that advertised anything into +// a failure. Call it with the test's own *testing.T — a throwaway one discards +// everything written to it. +func logStuckTeardown(t *testing.T, what string) { + t.Helper() + t.Logf("%s did not finish unregistering within %s: a multicast interface on this host accepts the goodbye "+ + "write into a queue it never drains, so its records linger until their TTL and grandcat's unregister "+ + "goroutine stays parked until this binary exits", what, shutdownDeadline) +} + // registerTestAdvertisement publishes one service advertisement for a test stub // node, under a synthetic host label and a loopback A record instead of the // machine hostname and a machine-chosen address. @@ -114,7 +167,9 @@ func firstLabel(s string) string { // call site cannot reintroduce the conflict by passing os.Hostname(); every // converted site passes one of the synthetic labels above and can never reach // that check. ifaces stays nil, so the announcement reaches every interface and -// same-process discovery keeps working exactly as before the conversion. +// same-process discovery keeps working exactly as before the conversion. The +// cleanup it registers bounds grandcat's teardown, so an interface that will not +// take the goodbye cannot stall the rest of the package — see boundedShutdown. func registerTestAdvertisement(t *testing.T, instance, service, hostLabel string, port int, txt []string) *zeroconf.Server { t.Helper() @@ -128,7 +183,11 @@ func registerTestAdvertisement(t *testing.T, instance, service, hostLabel string srv, err := zeroconf.RegisterProxy(instance, service, testDomain, port, hostLabel, []string{"127.0.0.1"}, txt, nil) require.NoErrorf(t, err, "register test advertisement %s under %s", instance, hostLabel) - t.Cleanup(srv.Shutdown) + t.Cleanup(func() { + if !boundedShutdown(srv) { + logStuckTeardown(t, "the test advertisement "+instance+" under "+hostLabel) + } + }) return srv } @@ -247,20 +306,29 @@ func TestRegisterTestAdvertisement_RejectsAClaimOfTheMachineName(t *testing.T) { // The control keeps the assertion above from passing vacuously: with a // synthetic label the same helper does reach the wire, so the abort above is // the guard refusing the claim and not a broken helper. + // + // controlUnregistered reports whether that control left the wire. It is set + // from the goroutine runOnThrowawayT owns and read only once that goroutine + // has reported itself finished, and it is reported through t rather than ft + // because a throwaway *testing.T discards everything written to it. + controlUnregistered := true control := runOnThrowawayT(t, func(ft *testing.T) { srv := registerTestAdvertisement(ft, "nvpair-guard-control-probe", "_t5guard._tcp", testHostOne, 59911, nil) if srv != nil { // The throwaway *testing.T never runs its cleanups, so the - // helper's t.Cleanup(srv.Shutdown) can never fire: close the + // helper's bounded teardown can never fire: unregister the // server on this goroutine instead, deferred right where it is // created so it leaves the wire even if the closure unwinds // before returning normally. - defer srv.Shutdown() + defer func() { controlUnregistered = boundedShutdown(srv) }() } }) require.Nilf(t, control.crash, "the helper crashed on a synthetic label: %v", control.crash) require.Truef(t, control.reachedEnd, "the helper refused the synthetic label %q too, so the refusal of %q proves nothing", testHostOne, hostname) + if !controlUnregistered { + logStuckTeardown(t, "the control advertisement of "+testHostOne) + } } // TestZeroconfAdvertisements_AllRoutedThroughTheHelper pins the conversion @@ -363,9 +431,10 @@ func browseOnce(service, instance string, window time.Duration) (*zeroconf.Servi // // The control carries a host label outside the nvpair-test-* family — checked // against the real hostname with the same first-label guard the helper applies -// — and an explicit 127.0.0.1, and it is shut down by a defer on every exit -// path, including the fatal and skip ones, so the diagnosis leaves nothing -// announced behind. +// — and an explicit 127.0.0.1, and it is unregistered by a bounded defer on +// every exit path, including the fatal and skip ones, so the diagnosis leaves +// nothing announced behind and a host that will not take the goodbye cannot +// stall the package here either. func discoverProbeWithMulticastControl(t *testing.T, probeService, probeInstance string) *zeroconf.ServiceEntry { t.Helper() @@ -387,7 +456,11 @@ func discoverProbeWithMulticastControl(t *testing.T, probeService, probeInstance if err != nil { t.Skipf("the probe stayed unseen and even a control published straight through grandcat could not be registered (%v): this environment does not support the mDNS this test needs", err) } - defer srv.Shutdown() + defer func() { + if !boundedShutdown(srv) { + logStuckTeardown(t, "the multicast control "+controlInstance) + } + }() type browseOutcome struct { entry *zeroconf.ServiceEntry