From f6eb3f9dc724ecc0f827abd56526f119c0baf870 Mon Sep 17 00:00:00 2001 From: kari-ts <135075563+kari-ts@users.noreply.github.com> Date: Tue, 10 Nov 2026 10:05:32 -0800 Subject: [PATCH] ipn, feature/guivisibility: send incremental gui visibility updates (#22067) This moves HiddenNetworkDvice policy out of ipnlocal and into an optional ipnext. This adds a per-session notification hook that uses each watcher's effective policy snapshot to populate NodeGUIVisibility. A full visibility snapshot is sent on initialization and policy changes, and on subsequent peer updates, only changed peers are evaluated. The extension populates Notify.NodeGUIVisibility with the hidden peers among the nodes the Notify covers: all peers when it carries Policy (initially and on policy change), or the PeersChanged peers otherwise. Absent means visible, so a Policy-bearing Notify replaces the client's visibility state and a peer-change Notify updates only the changed peers. No NodeGUIVisibilityChanges/Removed fields and no per-session node state are needed: removed peers simply leave the client's peer set, and full netmap updates already resend every peer alongside SelfChange. When the feature isn't linked, the hook slice is empty and the fast path in notifyForSessionLocked is unchanged. When the policy isn't configured, the hook costs a snapshot lookup per session per Notify and sends nothing. Updates tailscale/corp#44104 Signed-off-by: kari Signed-off-by: Nick Khyl --- cmd/tailscaled/depaware.txt | 1 + .../maybe_guivisibility_windows.go | 8 + feature/guivisibility/guivisibility.go | 135 +++++++++++ .../guivisibility/guivisibility_test.go | 2 +- ipn/backend.go | 16 +- ipn/ipnext/ipnext.go | 15 ++ ipn/ipnlocal/gui_visibility.go | 85 ------- ipn/ipnlocal/local.go | 46 ++-- ipn/ipnlocal/local_test.go | 226 ++++++++++++++++-- 9 files changed, 400 insertions(+), 134 deletions(-) create mode 100644 feature/condregister/maybe_guivisibility_windows.go create mode 100644 feature/guivisibility/guivisibility.go rename ipn/ipnlocal/gui_visibility_test.go => feature/guivisibility/guivisibility_test.go (99%) delete mode 100644 ipn/ipnlocal/gui_visibility.go diff --git a/cmd/tailscaled/depaware.txt b/cmd/tailscaled/depaware.txt index 47ecff265..f371b8753 100644 --- a/cmd/tailscaled/depaware.txt +++ b/cmd/tailscaled/depaware.txt @@ -319,6 +319,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de tailscale.com/feature/exitnodehealth from tailscale.com/feature/condregister tailscale.com/feature/favorites from tailscale.com/feature/condregister tailscale.com/feature/favorites/pintype from tailscale.com/client/local+ + W tailscale.com/feature/guivisibility from tailscale.com/feature/condregister L tailscale.com/feature/linkspeed from tailscale.com/feature/condregister L tailscale.com/feature/linuxdnsfight from tailscale.com/feature/condregister tailscale.com/feature/netlog from tailscale.com/feature/condregister/netlog diff --git a/feature/condregister/maybe_guivisibility_windows.go b/feature/condregister/maybe_guivisibility_windows.go new file mode 100644 index 000000000..17ad6c4dd --- /dev/null +++ b/feature/condregister/maybe_guivisibility_windows.go @@ -0,0 +1,8 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +//go:build windows + +package condregister + +import _ "tailscale.com/feature/guivisibility" diff --git a/feature/guivisibility/guivisibility.go b/feature/guivisibility/guivisibility.go new file mode 100644 index 000000000..fa4dfc015 --- /dev/null +++ b/feature/guivisibility/guivisibility.go @@ -0,0 +1,135 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +// Package guivisibility interprets the HiddenNetworkDevices policy for IPN +// bus watchers and populates [ipn.Notify.NodeGUIVisibility] accordingly. +package guivisibility + +import ( + "tailscale.com/feature" + "tailscale.com/ipn" + "tailscale.com/ipn/ipnext" + "tailscale.com/tailcfg" + "tailscale.com/types/logger" + "tailscale.com/util/mak" + "tailscale.com/util/syspolicy/pkey" + "tailscale.com/util/syspolicy/policyclient" +) + +func init() { + if feature.Register("guivisibility") { + ipnext.RegisterExtension("guivisibility", newExtension) + } +} + +func newExtension(logger.Logf, ipnext.SafeBackend) (ipnext.Extension, error) { + return &extension{}, nil +} + +type extension struct { + host ipnext.Host +} + +func (e *extension) Name() string { return "guivisibility" } + +func (e *extension) Init(h ipnext.Host) error { + e.host = h + h.Hooks().MutateNotifyForSessionLocked.Add(e.mutateNotifyForSession) + return nil +} + +func (e *extension) Shutdown() error { return nil } + +// mutateNotifyForSession populates n.NodeGUIVisibility with the peers that +// sess's HiddenNetworkDevices policy hides: all of them if n carries a policy +// snapshot, or those among n.PeersChanged otherwise. +func (e *extension) mutateNotifyForSession(sess ipnext.WatchSession, n *ipn.Notify) { + // Watchers requesting NotifySysPolicyChanges receive a Policy snapshot during + // initialization, so checking Policy covers the initial visibility calculation. + // Subsequent changes are handled via PeersChanged. + // + // TODO(kari-ts): consider handling InitialStatus directly if GUI visibility needs + // to support watchers that don't receive policy notifications. + if n.Policy == nil && len(n.PeersChanged) == 0 { + return + } + hidden := hiddenNetworkDevicesFromPolicy(sess.Policy()) + if !hidden.hasAny() { + return + } + nb := e.host.NodeBackend() + self := nb.Self() + if !self.Valid() { + return + } + var visibility map[tailcfg.StableNodeID]ipn.NodeGUIVisibility + updateVisibility := func(peer tailcfg.NodeView) { + if peerHiddenInGUI(peer, self, hidden) { + mak.Set(&visibility, peer.StableID(), ipn.NodeGUIVisibility{HideInGUI: true}) + } + } + if n.Policy != nil { + for _, peer := range nb.Peers() { + updateVisibility(peer) + } + } else { + for _, peer := range n.PeersChanged { + updateVisibility(peer.View()) + } + } + n.NodeGUIVisibility = visibility +} + +func (h hiddenNetworkDevices) hasAny() bool { + return h.currentUser || h.otherUsers || h.taggedDevices +} + +const ( + hiddenNetworkDevicesCurrentUser = "current-user" + hiddenNetworkDevicesOtherUsers = "other-users" + hiddenNetworkDevicesTaggedDevices = "tagged-devices" +) + +// hiddenNetworkDevices is the parsed HiddenNetworkDevices policy for a watch +// session. Its zero value means no devices are hidden. +type hiddenNetworkDevices struct { + currentUser bool + otherUsers bool + taggedDevices bool +} + +func hiddenNetworkDevicesFromPolicy(snapshot *policyclient.PolicySnapshot) hiddenNetworkDevices { + values := policyclient.GetStringArrayFromSnapshot( + snapshot, + pkey.HiddenNetworkDevices, + ) + + var hidden hiddenNetworkDevices + for _, value := range values { + switch value { + case hiddenNetworkDevicesCurrentUser: + hidden.currentUser = true + case hiddenNetworkDevicesOtherUsers: + hidden.otherUsers = true + case hiddenNetworkDevicesTaggedDevices: + hidden.taggedDevices = true + } + } + return hidden +} + +func peerHiddenInGUI(peer, self tailcfg.NodeView, hidden hiddenNetworkDevices) bool { + if peer.ID() == self.ID() { + return false + } + + if peer.IsTagged() { + return hidden.taggedDevices + } + + if peer.SharerOrUser() == self.User() { + return hidden.currentUser + } + + return hidden.otherUsers +} diff --git a/ipn/ipnlocal/gui_visibility_test.go b/feature/guivisibility/guivisibility_test.go similarity index 99% rename from ipn/ipnlocal/gui_visibility_test.go rename to feature/guivisibility/guivisibility_test.go index 376a1dadc..20707563d 100644 --- a/ipn/ipnlocal/gui_visibility_test.go +++ b/feature/guivisibility/guivisibility_test.go @@ -1,7 +1,7 @@ // Copyright (c) Tailscale Inc & contributors // SPDX-License-Identifier: BSD-3-Clause -package ipnlocal +package guivisibility import ( "testing" diff --git a/ipn/backend.go b/ipn/backend.go index 74fdd2add..5d941f917 100644 --- a/ipn/backend.go +++ b/ipn/backend.go @@ -384,13 +384,19 @@ type Notify struct { // a continuous view of node state without fetching the netmap. InitialStatus *ipnstate.Status `json:",omitzero"` - // NodeGUIVisibility, when non-nil, is a complete snapshot of GUI - // visibility state for the current node and peers, keyed by stable node ID. - // It is sent to watchers that requested [NotifySysPolicyChanges]. Clients - // should replace their previous visibility state with this map. + // NodeGUIVisibility, when non-empty, lists the nodes that GUI clients + // should hide, keyed by stable node ID, among the nodes this Notify + // covers: all nodes if it carries [Notify.Policy] (initially and on + // policy change), or the peers in [Notify.PeersChanged] otherwise. + // Covered nodes absent from the map are visible, so a Notify carrying + // Policy replaces any previously received visibility state, while one + // carrying PeersChanged updates it for the changed peers only. + // + // It is populated for watchers that requested [NotifySysPolicyChanges]; + // incremental updates additionally require [NotifyPeerChanges]. // // This is presentation metadata only. Nodes remain present in status, - // peer notifications, åand the underlying netmap. + // peer notifications, and the underlying netmap. NodeGUIVisibility map[tailcfg.StableNodeID]NodeGUIVisibility `json:",omitzero"` // PeerChangedPatch, if non-empty, lists narrow per-field peer patches diff --git a/ipn/ipnext/ipnext.go b/ipn/ipnext/ipnext.go index 0a9e91cae..9c00451b2 100644 --- a/ipn/ipnext/ipnext.go +++ b/ipn/ipnext/ipnext.go @@ -27,6 +27,7 @@ import ( "tailscale.com/types/mapx" "tailscale.com/types/netmap" "tailscale.com/types/views" + "tailscale.com/util/syspolicy/policyclient" "tailscale.com/wgengine/filter" ) @@ -378,6 +379,14 @@ type ProfileStateChangeCallback func(_ ipn.LoginProfileView, _ ipn.PrefsView, sa // back into LocalBackend, which may be locked during shutdown. type NewControlClientCallback func(controlclient.Client, ipn.LoginProfileView) (cleanup func()) +// WatchSession is an IPN bus watch session, as seen by +// [Hooks.MutateNotifyForSessionLocked]. +type WatchSession interface { + // Policy returns the effective policy snapshot most recently delivered to + // the session, or nil if it did not request [ipn.NotifySysPolicyChanges]. + Policy() *policyclient.PolicySnapshot +} + // Hooks is a collection of hooks that extensions can add to (non-concurrently) // during program initialization and can be called by LocalBackend and others at // runtime. @@ -439,6 +448,12 @@ type Hooks struct { // before sending it to the IPN bus. It is called with LocalBackend.mu held. MutateNotifyLocked feature.Hooks[func(*ipn.Notify)] + // MutateNotifyForSessionLocked is called to optionally mutate the provided + // Notify before sending it to a particular IPN bus watch session. It runs + // after per-session gating, so the Notify reflects what the session will + // receive. It is called with LocalBackend.mu held. + MutateNotifyForSessionLocked feature.Hooks[func(WatchSession, *ipn.Notify)] + // SetPeerStatus is called to mutate PeerStatus. // Callers must only use NodeBackend to read data. SetPeerStatus feature.Hooks[func(*ipnstate.PeerStatus, tailcfg.NodeView, NodeBackend)] diff --git a/ipn/ipnlocal/gui_visibility.go b/ipn/ipnlocal/gui_visibility.go deleted file mode 100644 index 7d76612a6..000000000 --- a/ipn/ipnlocal/gui_visibility.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright (c) Tailscale Inc & contributors -// SPDX-License-Identifier: BSD-3-Clause - -package ipnlocal - -import ( - "tailscale.com/ipn" - "tailscale.com/tailcfg" - "tailscale.com/util/syspolicy/pkey" - "tailscale.com/util/syspolicy/policyclient" -) - -const ( - hiddenNetworkDevicesCurrentUser = "current-user" - hiddenNetworkDevicesOtherUsers = "other-users" - hiddenNetworkDevicesTaggedDevices = "tagged-devices" -) - -// hiddenNetworkDevices is the parsed HiddenNetworkDevices policy for a watch -// session. Its zero value means no devices are hidden. -type hiddenNetworkDevices struct { - currentUser bool - otherUsers bool - taggedDevices bool -} - -func hiddenNetworkDevicesFromPolicy(snapshot *policyclient.PolicySnapshot) hiddenNetworkDevices { - values := policyclient.GetStringArrayFromSnapshot( - snapshot, - pkey.HiddenNetworkDevices, - ) - - var hidden hiddenNetworkDevices - for _, value := range values { - switch value { - case hiddenNetworkDevicesCurrentUser: - hidden.currentUser = true - case hiddenNetworkDevicesOtherUsers: - hidden.otherUsers = true - case hiddenNetworkDevicesTaggedDevices: - hidden.taggedDevices = true - } - } - return hidden -} - -// nodeGUIVisibilityLocked returns a complete snapshot of GUI visibility -// metadata for self and all current peers. -// -// b.mu must be held. -func (b *LocalBackend) nodeGUIVisibilityLocked(hidden hiddenNetworkDevices) map[tailcfg.StableNodeID]ipn.NodeGUIVisibility { - cn := b.currentNode() - nm := cn.NetMap() - if nm == nil || !nm.SelfNode.Valid() { - return nil - } - - visibility := make(map[tailcfg.StableNodeID]ipn.NodeGUIVisibility, len(nm.Peers)+1) - - visibility[nm.SelfNode.StableID()] = ipn.NodeGUIVisibility{} - - for _, peer := range nm.Peers { - visibility[peer.StableID()] = ipn.NodeGUIVisibility{ - HideInGUI: peerHiddenInGUI(peer, nm.SelfNode, hidden), - } - } - - return visibility -} - -func peerHiddenInGUI(peer, self tailcfg.NodeView, hidden hiddenNetworkDevices) bool { - if peer.ID() == self.ID() { - return false - } - - if peer.IsTagged() { - return hidden.taggedDevices - } - - if peer.SharerOrUser() == self.User() { - return hidden.currentUser - } - - return hidden.otherUsers -} diff --git a/ipn/ipnlocal/local.go b/ipn/ipnlocal/local.go index cd2a266ba..7230a519a 100644 --- a/ipn/ipnlocal/local.go +++ b/ipn/ipnlocal/local.go @@ -212,15 +212,17 @@ type watchSession struct { // Empty string means default/device scope. policyUID string - // hiddenNetworkDevices is the parsed GUI visibility policy from the - // most recent effective policy snapshot for this session. - hiddenNetworkDevices hiddenNetworkDevices + // policy is the effective policy snapshot most recently delivered to + // this session, or nil if it didn't request [ipn.NotifySysPolicyChanged] + policy *policyclient.PolicySnapshot // suspended is whether this session fell behind and is waiting for // [LocalBackend.ResumeWatchNotifications]. See [ipn.NotifySuspendWhenBehind]. suspended bool } +func (sess *watchSession) Policy() *policyclient.PolicySnapshot { return sess.policy } + var ( // errShutdown indicates that the [LocalBackend.Shutdown] was called. errShutdown = errors.New("shutting down") @@ -2527,11 +2529,10 @@ func (b *LocalBackend) sysPolicyChangedForSession(sess *watchSession) { return } - sess.hiddenNetworkDevices = hiddenNetworkDevicesFromPolicy(snapshot) + sess.policy = snapshot n := ipn.Notify{ - Policy: snapshot, - NodeGUIVisibility: b.nodeGUIVisibilityLocked(sess.hiddenNetworkDevices), - Version: version.Long(), + Policy: snapshot, + Version: version.Long(), } for _, f := range b.extHost.Hooks().MutateNotifyLocked { f(&n) @@ -4118,14 +4119,14 @@ func (b *LocalBackend) buildInitialNotifyLocked(sb *ipnstate.StatusBuilder, sess ini.Policy, err = b.polc.GetPolicySnapshot(sess.policyUID) if err != nil { b.logf("syspolicy: GetPolicySnapshot(%q): %v", sess.policyUID, err) - } else if ini.Policy != nil { - sess.hiddenNetworkDevices = hiddenNetworkDevicesFromPolicy(ini.Policy) - ini.NodeGUIVisibility = b.nodeGUIVisibilityLocked(sess.hiddenNetworkDevices) } + sess.policy = ini.Policy } if mask&ipn.NotifyPeerWireGuardState != 0 { ini.PeerState = maps.Clone(b.peerWGState) } + + b.mutateNotifyForSessionLocked(sess, ini) return ini } @@ -4449,7 +4450,8 @@ func (b *LocalBackend) suspendLaggingWatchSessionLocked(sess *watchSession) { // into full-Node [Notify.PeersChanged] entries for sessions that asked // for peer changes but not patches, and tracking on sess which // [tailcfg.UserProfileView]s have already been delivered so subsequent -// sends only carry new/changed profiles. +// sends only carry new/changed profiles. Finally, it runs the extensions' +// [ipnext.Hooks.MutateNotifyForSessionLocked] hooks, if any, on the result. // // The returned pointer is either n itself (no adjustments needed for // this session) or a fresh *ipn.Notify with the adjusted fields. The @@ -4473,11 +4475,7 @@ func (b *LocalBackend) notifyForSessionLocked(sess *watchSession, n *ipn.Notify) stripPatches := len(n.PeerChangedPatch) > 0 && !wantsPeerPatches stripPeerState := len(n.PeerState) > 0 && sess.mask&ipn.NotifyPeerWireGuardState == 0 promotePatches := len(n.PeerChangedPatch) > 0 && wantsPeerChanges && !wantsPeerPatches - refreshNodeGUIVisibility := - sess.mask&ipn.NotifySysPolicyChanges != 0 && - (n.SelfChange != nil || - len(n.PeersChanged) != 0 || - len(n.PeersRemoved) != 0) + mutateHooks := b.extHost.Hooks().MutateNotifyForSessionLocked if sess.selfChangeResetsImplicitState(n.SelfChange.View()) { sess.lastSentUserProfile = nil @@ -4507,13 +4505,10 @@ func (b *LocalBackend) notifyForSessionLocked(sess *watchSession, n *ipn.Notify) } replaceUserProfiles := !stripUserProfiles && len(sessUserProfiles) != len(n.UserProfiles) - if !stripPeersChanged && !stripPeersRemoved && !stripPatches && !stripPeerState && !stripUserProfiles && !replaceUserProfiles && !promotePatches && !refreshNodeGUIVisibility { + if !stripPeersChanged && !stripPeersRemoved && !stripPatches && !stripPeerState && !stripUserProfiles && !replaceUserProfiles && !promotePatches && len(mutateHooks) == 0 { return n } nCopy := *n - if refreshNodeGUIVisibility { - nCopy.NodeGUIVisibility = b.nodeGUIVisibilityLocked(sess.hiddenNetworkDevices) - } if stripPeersChanged { nCopy.PeersChanged = nil } @@ -4544,9 +4539,20 @@ func (b *LocalBackend) notifyForSessionLocked(sess *watchSession, n *ipn.Notify) } else if replaceUserProfiles { nCopy.UserProfiles = sessUserProfiles } + b.mutateNotifyForSessionLocked(sess, &nCopy) return &nCopy } +// mutateNotifyForSessionLocked lets extensions adjust n, which must not be +// shared with other sessions, before it is delivered to sess. +// +// b.mu must be held. +func (b *LocalBackend) mutateNotifyForSessionLocked(sess *watchSession, n *ipn.Notify) { + for _, f := range b.extHost.Hooks().MutateNotifyForSessionLocked { + f(sess, n) + } +} + // selfChangeResetsImplicitState reports whether self changes the identity of // the self node last delivered to sess. WatchIPNBus sessions survive profile // switches, but a self-node identity change is a boundary for implicit bus diff --git a/ipn/ipnlocal/local_test.go b/ipn/ipnlocal/local_test.go index bfe4a25a7..e140118af 100644 --- a/ipn/ipnlocal/local_test.go +++ b/ipn/ipnlocal/local_test.go @@ -38,6 +38,7 @@ import ( "tailscale.com/drive/driveimpl" "tailscale.com/feature" _ "tailscale.com/feature/condregister/portmapper" + _ "tailscale.com/feature/guivisibility" "tailscale.com/health" "tailscale.com/hostinfo" "tailscale.com/ipn" @@ -9568,7 +9569,7 @@ func TestHiddenNetworkDevicesNotifyPerUser(t *testing.T) { userStoreA.SetStringLists( source.TestSettingOf( pkey.HiddenNetworkDevices, - []string{hiddenNetworkDevicesOtherUsers}, + []string{"other-users"}, ), ) rsop.RegisterStoreForTest(t, "UserStoreA", setting.UserScopeOf(uidA), userStoreA) @@ -9579,6 +9580,7 @@ func TestHiddenNetworkDevicesNotifyPerUser(t *testing.T) { sys := tsd.NewSystem() sys.PolicyClient.Set(testPolicyClient{}) lb := newTestLocalBackendWithSys(t, sys) + lb.extHost.Init() lb.currentNode().SetNetMap(&netmap.NetworkMap{ SelfNode: (&tailcfg.Node{ @@ -9602,16 +9604,11 @@ func TestHiddenNetworkDevicesNotifyPerUser(t *testing.T) { return wantedNotification{ name: fmt.Sprintf("NodeGUIVisibility-hidden=%v", wantHidden), cond: func(t testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { - if n.NodeGUIVisibility == nil { + if n.Policy == nil { return false } - got, ok := n.NodeGUIVisibility["peer-10"] - if !ok { - t.Errorf("NodeGUIVisibility missing peer-10") - return true - } - + got := n.NodeGUIVisibility["peer-10"] if got.HideInGUI != wantHidden { t.Errorf( "NodeGUIVisibility[peer-10].HideInGUI = %v; want %v", @@ -9647,14 +9644,13 @@ func TestHiddenNetworkDevicesPolicyChangeUpdatesVisibility(t *testing.T) { ) uid := "S-1-5-21-1001" - userStore := source.NewTestStore(t) rsop.RegisterStoreForTest(t, "UserStore", setting.UserScopeOf(uid), userStore) sys := tsd.NewSystem() sys.PolicyClient.Set(testPolicyClient{}) lb := newTestLocalBackendWithSys(t, sys) - + lb.extHost.Init() lb.currentNode().SetNetMap(&netmap.NetworkMap{ SelfNode: (&tailcfg.Node{ ID: 1, @@ -9672,30 +9668,25 @@ func TestHiddenNetworkDevicesPolicyChangeUpdatesVisibility(t *testing.T) { actor := &ipnauth.TestActor{UID: ipn.WindowsUserID(uid)} nw := newNotificationWatcher(t, lb, actor) - nw.watch(ipn.NotifySysPolicyChanges, []wantedNotification{ { name: "initially visible", cond: func(t testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { - if n.NodeGUIVisibility == nil { + if n.Policy == nil { return false } - got, ok := n.NodeGUIVisibility["peer-10"] - return ok && !got.HideInGUI + if len(n.NodeGUIVisibility) != 0 { + t.Errorf("NodeGUIVisibility = %v; want empty", n.NodeGUIVisibility) + } + return true }, }, { name: "hidden after policy change", cond: func(t testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { - if n.NodeGUIVisibility == nil { + if n.Policy == nil || !n.NodeGUIVisibility["peer-10"].HideInGUI { return false } - - got, ok := n.NodeGUIVisibility["peer-10"] - if !ok || !got.HideInGUI { - return false - } - if len(n.PeersChanged) != 0 { t.Errorf("PeersChanged = %v; want none", n.PeersChanged) } @@ -9705,7 +9696,6 @@ func TestHiddenNetworkDevicesPolicyChangeUpdatesVisibility(t *testing.T) { if len(n.PeerChangedPatch) != 0 { t.Errorf("PeerChangedPatch = %v; want none", n.PeerChangedPatch) } - return true }, }, @@ -9714,13 +9704,203 @@ func TestHiddenNetworkDevicesPolicyChangeUpdatesVisibility(t *testing.T) { userStore.SetStringLists( source.TestSettingOf( pkey.HiddenNetworkDevices, - []string{hiddenNetworkDevicesOtherUsers}, + []string{"other-users"}, ), ) nw.check() } +func TestHiddenNetworkDevicesPolicyRemovalUpdatesVisibility(t *testing.T) { + setting.SetDefinitionsForTest(t, + setting.NewDefinition( + pkey.HiddenNetworkDevices, + setting.UserSetting, + setting.StringListValue, + ), + ) + + uid := "S-1-5-21-1001" + userStore := source.NewTestStore(t) + userStore.SetStringLists( + source.TestSettingOf( + pkey.HiddenNetworkDevices, + []string{"other-users"}, + ), + ) + rsop.RegisterStoreForTest(t, "UserStore", setting.UserScopeOf(uid), userStore) + + sys := tsd.NewSystem() + sys.PolicyClient.Set(testPolicyClient{}) + lb := newTestLocalBackendWithSys(t, sys) + lb.extHost.Init() + lb.currentNode().SetNetMap(&netmap.NetworkMap{ + SelfNode: (&tailcfg.Node{ + ID: 1, + StableID: "self", + User: 1, + }).View(), + Peers: []tailcfg.NodeView{ + (&tailcfg.Node{ + ID: 10, + StableID: "peer-10", + User: 2, + }).View(), + }, + }) + + actor := &ipnauth.TestActor{UID: ipn.WindowsUserID(uid)} + nw := newNotificationWatcher(t, lb, actor) + nw.watch(ipn.NotifySysPolicyChanges, []wantedNotification{ + { + name: "initially hidden", + cond: func(t testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { + if n.Policy == nil { + return false + } + if !n.NodeGUIVisibility["peer-10"].HideInGUI { + t.Errorf("NodeGUIVisibility = %v; want peer-10 hidden", n.NodeGUIVisibility) + } + return true + }, + }, + { + name: "visible after policy removal", + cond: func(t testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { + if n.Policy == nil { + return false + } + if len(n.NodeGUIVisibility) != 0 { + t.Errorf("NodeGUIVisibility = %v; want empty", n.NodeGUIVisibility) + } + if len(n.PeersChanged) != 0 { + t.Errorf("PeersChanged = %v; want none", n.PeersChanged) + } + if len(n.PeersRemoved) != 0 { + t.Errorf("PeersRemoved = %v; want none", n.PeersRemoved) + } + if len(n.PeerChangedPatch) != 0 { + t.Errorf("PeerChangedPatch = %v; want none", n.PeerChangedPatch) + } + return true + }, + }, + }) + + userStore.SetStringLists( + source.TestSettingOf( + pkey.HiddenNetworkDevices, + []string{}, + ), + ) + + nw.check() +} + +func TestHiddenNetworkDevicesIncrementalPeerUpdates(t *testing.T) { + setting.SetDefinitionsForTest(t, + setting.NewDefinition( + pkey.HiddenNetworkDevices, + setting.UserSetting, + setting.StringListValue, + ), + ) + + uid := "S-1-5-21-1001" + userStore := source.NewTestStore(t) + userStore.SetStringLists( + source.TestSettingOf( + pkey.HiddenNetworkDevices, + []string{"other-users"}, + ), + ) + rsop.RegisterStoreForTest(t, "UserStore", setting.UserScopeOf(uid), userStore) + + sys := tsd.NewSystem() + sys.PolicyClient.Set(testPolicyClient{}) + lb := newTestLocalBackendWithSys(t, sys) + lb.extHost.Init() + + lb.currentNode().SetNetMap(&netmap.NetworkMap{ + SelfNode: (&tailcfg.Node{ + ID: 1, + StableID: "self", + User: 1, + }).View(), + Peers: []tailcfg.NodeView{ + (&tailcfg.Node{ + ID: 10, + StableID: "peer-10", + User: 2, + }).View(), + }, + }) + + // wantVisibility matches a peer-change notification and checks that + // its NodeGUIVisibility hides exactly the given peers. + wantVisibility := func(name string, hidden ...tailcfg.StableNodeID) wantedNotification { + return wantedNotification{ + name: name, + cond: func(t testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { + if len(n.PeersChanged) == 0 && len(n.PeersRemoved) == 0 { + return false + } + want := make(map[tailcfg.StableNodeID]ipn.NodeGUIVisibility) + for _, id := range hidden { + want[id] = ipn.NodeGUIVisibility{HideInGUI: true} + } + if got := n.NodeGUIVisibility; !maps.Equal(got, want) { + t.Errorf("%s: NodeGUIVisibility = %v; want %v", name, got, want) + } + return true + }, + } + } + + actor := &ipnauth.TestActor{UID: ipn.WindowsUserID(uid)} + nw := newNotificationWatcher(t, lb, actor) + nw.watch(ipn.NotifySysPolicyChanges|ipn.NotifyPeerChanges, []wantedNotification{ + { + name: "initial visibility snapshot", + cond: func(t testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { + if n.Policy == nil { + return false + } + if len(n.NodeGUIVisibility) != 1 || !n.NodeGUIVisibility["peer-10"].HideInGUI { + t.Errorf("unexpected initial visibility: %v", n.NodeGUIVisibility) + } + return true + }, + }, + wantVisibility("hidden peer added", "peer-20"), + wantVisibility("hidden peer becomes visible"), + wantVisibility("hidden peer removed"), + }, func(t testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { + if n.NodeGUIVisibility != nil { + t.Errorf("unexpected visibility update: %v", n.NodeGUIVisibility) + } + return false + }) + + lb.SendNotify(ipn.Notify{ + PeersChanged: []*tailcfg.Node{ + {ID: 20, StableID: "peer-20", User: 2}, + }, + }) + + lb.SendNotify(ipn.Notify{ + PeersChanged: []*tailcfg.Node{ + {ID: 20, StableID: "peer-20", User: 1}, + }, + }) + + lb.SendNotify(ipn.Notify{ + PeersRemoved: []tailcfg.NodeID{10}, + }) + + nw.check() +} + func TestPolicySnapshotMergesDeviceAndUserScopes(t *testing.T) { setting.SetDefinitionsForTest(t, setting.NewDefinition(pkey.AdminConsoleVisibility, setting.UserSetting, setting.VisibilityValue),