Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/architecture.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion services/nvpair-cluster-manager/spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ The exact `<config-dir>` 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 |
Expand Down
62 changes: 59 additions & 3 deletions services/nvpair-node-scanner/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 <base>/cluster/identity.json; --cluster-dir is that cluster
// subdir, so its parent is the base. Empty -> nodeid's shared default.
Expand All @@ -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(),
Expand All @@ -342,19 +361,48 @@ 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
}

// 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)
}
Expand Down Expand Up @@ -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 {
Expand Down
139 changes: 139 additions & 0 deletions services/nvpair-node-scanner/daemon_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net"
Expand All @@ -30,6 +31,7 @@ import (

"nvpair-shared/clustertrust"
"nvpair-shared/clustertrusttest"
"nvpair-shared/nodeid"
"nvpair-shared/noderec"
)

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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.
Expand Down
19 changes: 17 additions & 2 deletions services/nvpair-node-scanner/directory.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))))
}
Expand Down
Loading