diff --git a/ipn/ipnlocal/local.go b/ipn/ipnlocal/local.go index fbc207e19..48857e6ee 100644 --- a/ipn/ipnlocal/local.go +++ b/ipn/ipnlocal/local.go @@ -465,6 +465,10 @@ type LocalBackend struct { // avoid unnecessary churn between multiple equally-good options. lastSuggestedExitNode tailcfg.StableNodeID + // suggestedExitNodePending is set when lastSuggestedExitNode changed and + // no broadcast [ipn.Notify] has carried the new value yet. + suggestedExitNodePending bool + // allowedSuggestedExitNodes is a set of exit nodes permitted by the most recent // [pkey.AllowedSuggestedExitNodes] value. The allowedSuggestedExitNodesMu // mutex guards access to this set. @@ -1989,6 +1993,11 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c } } + // notify collects the login, prefs, netmap, and exit node changes from + // this status. It is sent once, below, before the state machine runs. + var notify ipn.Notify + notifyPending := false // true once notify must be sent + wasBlocked := b.blocked authWasInProgress := b.authURL != "" keyExpiryExtended := false @@ -2013,7 +2022,8 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c b.blockEngineUpdatesLocked(false) } b.authReconfigLocked() - b.sendLocked(ipn.Notify{LoginFinished: &empty.Message{}}) + notify.LoginFinished = &empty.Message{} + notifyPending = true } prefsChanged := false @@ -2087,8 +2097,6 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c }); err != nil { b.logf("Failed to save new controlclient state: %v", err) } - - b.sendToLocked(ipn.Notify{Prefs: new(prefs.View())}, allClients) } // initTKALocked is dependent on CurrentProfile.ID, which is initialized @@ -2098,7 +2106,6 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c } // Perform all reconfiguration based on the netmap here. - var oldPeers []tailcfg.NodeView // set below only if hasPeerChangeWatcherLocked if st.NetMap != nil { b.capTailnetLock = st.NetMap.HasCap(nodecap.TailnetLock) b.setWebClientAtomicBoolLocked(st.NetMap.AllCaps) @@ -2110,6 +2117,8 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c b.mu.Lock() if b.cc != c { // The client was replaced (e.g. by Logout) while b.mu was released. + // The Notify built so far is dropped. The replacing path has + // already sent its own prefs. b.logf("Ignoring SetControlClientStatus from old client") return } @@ -2132,30 +2141,30 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c } // Snapshot the live peer set (last full netmap plus deltas) so the // peer-change Notify below can report the peers this netmap drops. + var oldPeers []tailcfg.NodeView if b.hasPeerChangeWatcherLocked() { oldPeers = cn.Peers() } b.setNetMapLocked(st.NetMap) b.updateFilterLocked(prefs.View()) - } - // Now complete the lock-free parts of what we started while locked. - if st.NetMap != nil { if envknob.NoLogsNoSupport() && st.NetMap.HasCap(nodecap.DataPlaneAuditLogs) { msg := "tailnet requires logging to be enabled. Remove --no-logs-no-support from tailscaled command line." b.health.SetLocalLogConfigHealth(errors.New(msg)) // Get the current prefs again, since we unlocked above. prefs := b.pm.CurrentPrefs().AsStruct() prefs.WantRunning = false - p := prefs.View() - if err := b.pm.SetPrefs(p, ipn.NetworkProfile{ + if err := b.pm.SetPrefs(prefs.View(), ipn.NetworkProfile{ MagicDNSName: st.NetMap.MagicDNSSuffix(), DomainName: st.NetMap.DomainName(), DisplayName: st.NetMap.TailnetDisplayName(), }); err != nil { b.logf("Failed to save new controlclient state: %v", err) } - b.sendLocked(ipn.Notify{ErrMessage: &msg, Prefs: &p}) + notify.ErrMessage = &msg + notify.Prefs = new(b.pm.CurrentPrefs()) + b.addSuggestedExitNodeLocked(¬ify) + b.sendLocked(notify) return } if oldNetMap != nil { @@ -2198,11 +2207,10 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c // consumers (containerboot, kube agents, sniproxy, etc.) listen on // this signal and re-fetch peers/DNS via other LocalAPI methods if // they need more than self info. - var selfChange *tailcfg.Node if st.NetMap.SelfNode.Valid() { - selfChange = st.NetMap.SelfNode.AsStruct() + notify.SelfChange = st.NetMap.SelfNode.AsStruct() } - notify := ipn.Notify{SelfChange: selfChange} + notifyPending = true if b.hasPeerChangeWatcherLocked() { notify.UserProfiles = st.NetMap.UserProfiles notify.PeersChanged = make([]*tailcfg.Node, 0, len(st.NetMap.Peers)) @@ -2219,24 +2227,32 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c } } } - b.sendLocked(notify) - // The error here is unimportant as is the result. This will recalculate the suggested exit node - // cache the value and push any changes to the IPN bus. + // Recalculate the suggested exit node against the new netmap. A + // changed suggestion is added to notify below. b.suggestExitNodeLocked() - // Check and update the exit node if needed, now that we have a new netmap. - // - // This must happen after the netmap change is sent via [ipn.Notify], - // so the GUI can correctly display the exit node if it has changed - // since the last netmap was sent. - // - // Otherwise, it might briefly show the exit node as offline and display a warning, - // if the node wasn't online or wasn't advertising default routes in the previous netmap. + // Re-resolve the exit node against the new netmap. The resolved + // prefs ride in the same Notify as the peers they select. if b.refreshExitNodeLocked() { - b.sendLocked(ipn.Notify{Prefs: new(b.pm.CurrentPrefs())}) + prefsChanged = true } } + + // The prefs in effect are in b.pm, not in the local copy. They may have + // changed since the copy was made, by the exit node resolution above or + // by an edit made while b.mu was released for tkaSyncIfNeeded. + if prefsChanged { + notify.Prefs = new(b.pm.CurrentPrefs()) + notifyPending = true + } + if b.addSuggestedExitNodeLocked(¬ify) { + notifyPending = true + } + if notifyPending { + b.sendLocked(notify) + } + if st.URL != "" { b.logf("Received auth URL: %.20v...", st.URL) b.setAuthURLLocked(st.URL) @@ -2572,7 +2588,11 @@ func (b *LocalBackend) UpdateNetmapDelta(muts []netmap.NodeMutation) (handled bo defer func() { // Sent while b.mu is still held, so it reflects the state this // delta produced and nothing newer. + if b.suggestedExitNodePending && notify == nil { + notify = &ipn.Notify{} + } if notify != nil { + b.addSuggestedExitNodeLocked(notify) b.sendLocked(*notify) } }() @@ -3500,7 +3520,9 @@ func (b *LocalBackend) startLocked(opts ipn.Options) error { blid := b.backendLogID.String() b.logf("Backend: logs: be:%v fe:%v", blid, opts.FrontendLogID) - b.sendToLocked(ipn.Notify{Prefs: &prefs}, allClients) + notify := ipn.Notify{Prefs: &prefs} + b.addSuggestedExitNodeLocked(¬ify) + b.sendToLocked(notify, allClients) // initialize Taildrive shares from saved state if fs, ok := b.sys.DriveForRemote.GetOK(); ok { @@ -4130,6 +4152,9 @@ func (b *LocalBackend) buildInitialNotifyLocked(sb *ipnstate.StatusBuilder, sess if en, err := b.suggestExitNodeLocked(); err == nil { ini.SuggestedExitNode = &en.ID } + // Existing sessions do not receive the initial Notify. Broadcast + // a changed suggestion to them. + b.sendSuggestedExitNodeLocked() } if mask&ipn.NotifyInitialClientVersion != 0 { if prefs := b.pm.CurrentPrefs(); prefs.Valid() && prefs.AutoUpdate().Check { @@ -5959,7 +5984,9 @@ func (b *LocalBackend) setPrefsLocked(newp *ipn.Prefs) ipn.PrefsView { } } - b.sendLocked(ipn.Notify{Prefs: &prefs}) + notify := ipn.Notify{Prefs: &prefs} + b.addSuggestedExitNodeLocked(¬ify) + b.sendLocked(notify) return prefs } @@ -7605,8 +7632,17 @@ func (b *LocalBackend) RefreshExitNode() { } b.mu.Lock() defer b.mu.Unlock() + var notify ipn.Notify + send := false if b.refreshExitNodeLocked() { - b.sendLocked(ipn.Notify{Prefs: new(b.pm.CurrentPrefs())}) + notify.Prefs = new(b.pm.CurrentPrefs()) + send = true + } + if b.addSuggestedExitNodeLocked(¬ify) { + send = true + } + if send { + b.sendLocked(notify) } } @@ -8882,6 +8918,7 @@ func (b *LocalBackend) resetForProfileChangeLocked() error { b.lastServeConfJSON = mem.B(nil) b.serveConfig = ipn.ServeConfigView{} b.lastSuggestedExitNode = "" + b.suggestedExitNodePending = false b.keyExpired = false b.setNodeRemovedLocked(false) b.resetAlwaysOnOverrideLocked() @@ -9201,6 +9238,11 @@ var ErrNoPreferredDERP = errors.New("no preferred DERP, try again later") // When the client has [tailcfg.NodeAttrClientSideReachabilityRouteCheck] in its CapMap, // it will use [HookRouteCheckReport] to get the latest cached routecheck report. // +// It does not notify clients of a changed suggestion. A caller that goes on +// to broadcast an [ipn.Notify] must call [LocalBackend.addSuggestedExitNodeLocked] +// on it first. A caller that broadcasts nothing else must call +// [LocalBackend.sendSuggestedExitNodeLocked] instead. +// // b.mu must be held. func (b *LocalBackend) suggestExitNodeLocked() (response apitype.ExitNodeSuggestionResponse, err error) { if !buildfeatures.HasUseExitNode { @@ -9229,14 +9271,39 @@ func (b *LocalBackend) suggestExitNodeLocked() (response apitype.ExitNodeSuggest return res, err } if prevSuggestion != res.ID { - // Notify the clients via the IPN bus if the exit node suggestion has changed. - b.sendToLocked(ipn.Notify{SuggestedExitNode: &res.ID}, allClients) + b.suggestedExitNodePending = true } b.lastSuggestedExitNode = res.ID return res, err } +// addSuggestedExitNodeLocked sets n.SuggestedExitNode to the current +// suggestion if it changed since the last broadcast, marks it as sent, and +// reports whether it set the field. The caller must then send n to all +// clients. +// +// b.mu must be held. +func (b *LocalBackend) addSuggestedExitNodeLocked(n *ipn.Notify) (added bool) { + if !b.suggestedExitNodePending { + return false + } + n.SuggestedExitNode = new(b.lastSuggestedExitNode) + b.suggestedExitNodePending = false + return true +} + +// sendSuggestedExitNodeLocked broadcasts the current exit node suggestion +// if it changed since the last broadcast. +// +// b.mu must be held. +func (b *LocalBackend) sendSuggestedExitNodeLocked() { + var n ipn.Notify + if b.addSuggestedExitNodeLocked(&n) { + b.sendLocked(n) + } +} + // SuggestExitNode computes an exit-node suggestion based on the current netmap and // other optional factors. If there are multiple equally good options, one may // be selected at random, so the result is not stable. To be eligible for @@ -9247,7 +9314,9 @@ func (b *LocalBackend) SuggestExitNode() (response apitype.ExitNodeSuggestionRes } b.mu.Lock() defer b.mu.Unlock() - return b.suggestExitNodeLocked() + response, err = b.suggestExitNodeLocked() + b.sendSuggestedExitNodeLocked() + return response, err } // getAllowedSuggestions returns a set of exit nodes permitted by the most recent diff --git a/ipn/ipnlocal/local_test.go b/ipn/ipnlocal/local_test.go index 09428dc6e..2879f0854 100644 --- a/ipn/ipnlocal/local_test.go +++ b/ipn/ipnlocal/local_test.go @@ -1638,7 +1638,11 @@ func TestPrefsChangeDisablesExitNode(t *testing.T) { } } -func TestExitNodeNotifyOrder(t *testing.T) { +// TestFullNetmapNotifyCombined checks that a full netmap produces one +// notification carrying the self node, the peers, the prefs that select the +// auto exit node, and the exit node suggestion. No other notification may +// carry any of those fields. +func TestFullNetmapNotifyCombined(t *testing.T) { const controlURL = "https://localhost:1/" report := &netcheck.Report{ @@ -1662,34 +1666,67 @@ func TestExitNodeNotifyOrder(t *testing.T) { }) nw := newNotificationWatcher(t, lb, ipnauth.Self) - - // Updating the netmap should trigger both a netmap notification - // and an exit node ID notification (since an exit node is selected). - // The netmap notification should be sent first. - nw.watch(0, []wantedNotification{ - wantSelfChangeNotify(selfNode), - wantExitNodeIDNotify(exitNode1.StableID()), + nw.watch(ipn.NotifyPeerChanges|ipn.NotifyNoNetMap, []wantedNotification{{ + name: "self, peers, prefs and suggestion in one notification", + cond: func(_ testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { + hasSelf := n.SelfChange != nil && n.SelfChange.StableID == selfNode.StableID() + hasPeer := slices.ContainsFunc(n.PeersChanged, func(p *tailcfg.Node) bool { return p.ID == exitNode1.ID() }) + hasPrefs := n.Prefs != nil && n.Prefs.Valid() && n.Prefs.ExitNodeID() == exitNode1.StableID() + hasSuggestion := n.SuggestedExitNode != nil && *n.SuggestedExitNode == exitNode1.StableID() + return hasSelf && hasPeer && hasPrefs && hasSuggestion + }, + }}, func(t testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { + if n.LoginFinished != nil || n.Prefs != nil || n.SelfChange != nil || len(n.PeersChanged) > 0 || n.SuggestedExitNode != nil { + t.Errorf("netmap fields sent outside the combined notification: %v", n) + } + return false }) lb.SetControlClientStatus(lb.cc, controlclient.Status{NetMap: clientNetmap}) nw.check() } -func wantSelfChangeNotify(want tailcfg.NodeView) wantedNotification { - return wantedNotification{ - name: "SelfChange", - cond: func(t testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { - return n.SelfChange != nil && want.Valid() && n.SelfChange.StableID == want.StableID() +// TestSuggestExitNodeNotifies checks that SuggestExitNode broadcasts a changed +// suggestion and stays silent when the suggestion is unchanged. +func TestSuggestExitNodeNotifies(t *testing.T) { + report := &netcheck.Report{ + RegionLatency: map[tailcfg.DERPRegionID]time.Duration{ + 1: 5 * time.Millisecond, + 2: 10 * time.Millisecond, }, + PreferredDERP: 1, } -} + exitNode1 := makeExitNode(1, withName("node-1"), withDERP(1), withAddresses(netip.MustParsePrefix("100.64.1.1/32"))) + exitNode2 := makeExitNode(2, withName("node-2"), withDERP(2), withAddresses(netip.MustParsePrefix("100.64.1.2/32"))) + selfNode := makeExitNode(3, withName("node-3"), withDERP(1), withAddresses(netip.MustParsePrefix("100.64.1.3/32"))) + nm := buildNetmapWithPeers(selfNode, exitNode1, exitNode2) -func wantExitNodeIDNotify(want tailcfg.StableNodeID) wantedNotification { - return wantedNotification{ - name: fmt.Sprintf("ExitNodeID-%s", want), + lb := newTestLocalBackend(t) + lb.sys.MagicSock.Get().AddNetcheckReportForTest(nm.DERPMap, report, time.Now()) + lb.currentNode().SetNetMap(nm) + + nw := newNotificationWatcher(t, lb, ipnauth.Self) + nw.watch(0, []wantedNotification{{ + name: "suggested exit node", cond: func(_ testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { - return n.Prefs != nil && n.Prefs.Valid() && n.Prefs.ExitNodeID() == want + return n.SuggestedExitNode != nil && *n.SuggestedExitNode == exitNode1.StableID() }, + }}) + if res, err := lb.SuggestExitNode(); err != nil || res.ID != exitNode1.StableID() { + t.Fatalf("SuggestExitNode = %q, %v; want %q", res.ID, err, exitNode1.StableID()) } + nw.check() + + // The same suggestion again is not announced. + nw.watch(0, nil, func(t testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { + if n.SuggestedExitNode != nil { + t.Errorf("unchanged suggestion was announced: %v", n) + } + return false + }) + if _, err := lb.SuggestExitNode(); err != nil { + t.Fatal(err) + } + nw.check() } func TestInternalAndExternalInterfaces(t *testing.T) { @@ -2792,9 +2829,22 @@ func TestAutoExitNodeResolvedOnDeltaUpsert(t *testing.T) { t.Fatalf("after unrelated upsert: ExitNodeID=%q; want %q", p.ExitNodeID(), ipn.UnresolvedExitNodeID) } + // The exit node arrives by delta. The peer, the prefs that select it, + // and the new suggestion all ride in the same notification. + nw := newNotificationWatcher(t, b, ipnauth.Self) + nw.watch(ipn.NotifyPeerChanges|ipn.NotifyNoNetMap, []wantedNotification{{ + name: "exit node peer change with prefs and suggestion", + cond: func(_ testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { + hasPeer := slices.ContainsFunc(n.PeersChanged, func(p *tailcfg.Node) bool { return p.ID == exitNode.ID() }) + hasPrefs := n.Prefs != nil && n.Prefs.Valid() && n.Prefs.ExitNodeID() == exitNode.StableID() + hasSuggestion := n.SuggestedExitNode != nil && *n.SuggestedExitNode == exitNode.StableID() + return hasPeer && hasPrefs && hasSuggestion + }, + }}) if !b.UpdateNetmapDelta([]netmap.NodeMutation{netmap.NodeMutationUpsert{Node: exitNode}}) { t.Fatal("UpdateNetmapDelta returned false") } + nw.check() if p := b.Prefs(); p.ExitNodeID() != exitNode.StableID() { t.Errorf("after delta upsert: ExitNodeID = %q, want %q", p.ExitNodeID(), exitNode.StableID()) } diff --git a/ipn/ipnlocal/state_test.go b/ipn/ipnlocal/state_test.go index 87bfcb873..49a991bcd 100644 --- a/ipn/ipnlocal/state_test.go +++ b/ipn/ipnlocal/state_test.go @@ -609,15 +609,16 @@ func TestStateMachine(t *testing.T) { // Pretend that the interactive login actually happened. // Controlclient always sends the netmap and LoginFinished at the // same time. - // The backend should propagate this upward for the UI. + // The backend reports LoginFinished and the updated prefs to the UI + // in one notification. t.Logf("\n\nLoginFinished") - notifies.expect(3) + notifies.expect(2) cc.persist.UserProfile.LoginName = "user1" cc.persist.NodeID = "node1" cc.send(sendOpt{loginFinished: true, nm: &netmap.NetworkMap{}}) { - nn := notifies.drain(3) + nn := notifies.drain(2) // Arguably it makes sense to unpause now, since the machine // authorization status is part of the netmap. // @@ -628,9 +629,9 @@ func TestStateMachine(t *testing.T) { // it's visible in the logs) cc.assertCalls() c.Assert(nn[0].LoginFinished, qt.IsNotNil) - c.Assert(nn[1].Prefs, qt.IsNotNil) - c.Assert(nn[1].Prefs.Persist().UserProfile().LoginName(), qt.Equals, "user1") - // nn[2] is a state notification after login + c.Assert(nn[0].Prefs, qt.IsNotNil) + c.Assert(nn[0].Prefs.Persist().UserProfile().LoginName(), qt.Equals, "user1") + // nn[1] is a state notification after login // Verify login finished but need machine auth using backend state c.Assert(isFullyAuthenticated(b), qt.IsTrue) c.Assert(needsMachineAuth(b), qt.IsTrue) @@ -829,7 +830,7 @@ func TestStateMachine(t *testing.T) { c.Assert(*nn[1].BrowseToURL, qt.Equals, url3) } t.Logf("%q visited", url3) - notifies.expect(3) + notifies.expect(2) cc.persist.UserProfile.LoginName = "user2" cc.persist.NodeID = "node2" cc.send(sendOpt{loginFinished: true, nm: &netmap.NetworkMap{ @@ -837,16 +838,17 @@ func TestStateMachine(t *testing.T) { }}) t.Logf("\n\nLoginFinished3") { - nn := notifies.drain(3) + nn := notifies.drain(2) c.Assert(nn[0].LoginFinished, qt.IsNotNil) - c.Assert(nn[1].Prefs, qt.IsNotNil) - c.Assert(nn[1].Prefs.Persist(), qt.IsNotNil) + c.Assert(nn[0].Prefs, qt.IsNotNil) + c.Assert(nn[0].Prefs.Persist(), qt.IsNotNil) // Prefs after finishing the login, so LoginName updated. - c.Assert(nn[1].Prefs.Persist().UserProfile().LoginName(), qt.Equals, "user2") - c.Assert(nn[1].Prefs.LoggedOut(), qt.IsFalse) + c.Assert(nn[0].Prefs.Persist().UserProfile().LoginName(), qt.Equals, "user2") + c.Assert(nn[0].Prefs.LoggedOut(), qt.IsFalse) // If a user initiates an interactive login, they also expect WantRunning to become true. - c.Assert(nn[1].Prefs.WantRunning(), qt.IsTrue) - // nn[2] is state notification (Starting) - verify using backend state + c.Assert(nn[0].Prefs.WantRunning(), qt.IsTrue) + // nn[1] is the Starting state notification. The asserts below + // check the backend state instead. c.Assert(isWantRunning(b), qt.IsTrue) c.Assert(isLoggedIn(b), qt.IsTrue) } @@ -972,14 +974,14 @@ func TestStateMachine(t *testing.T) { // user account than before. WantRunning changes to true after an // interactive login, so we end up unpaused. t.Logf("\n\nLoginDifferent URL visited") - notifies.expect(3) + notifies.expect(2) cc.persist.UserProfile.LoginName = "user3" cc.persist.NodeID = "node3" cc.send(sendOpt{loginFinished: true, nm: &netmap.NetworkMap{ SelfNode: (&tailcfg.Node{MachineAuthorized: true}).View(), }}) { - nn := notifies.drain(3) + nn := notifies.drain(2) // BUG: pause() being called here is a bad sign. // It means that either the state machine ran at least once // with the old netmap, or it ran with the new login+netmap @@ -988,12 +990,13 @@ func TestStateMachine(t *testing.T) { // reason to pause(). cc.assertCalls("unpause") c.Assert(nn[0].LoginFinished, qt.IsNotNil) - c.Assert(nn[1].Prefs, qt.IsNotNil) + c.Assert(nn[0].Prefs, qt.IsNotNil) // Prefs after finishing the login, so LoginName updated. - c.Assert(nn[1].Prefs.Persist().UserProfile().LoginName(), qt.Equals, "user3") - c.Assert(nn[1].Prefs.LoggedOut(), qt.IsFalse) - c.Assert(nn[1].Prefs.WantRunning(), qt.IsTrue) - // nn[2] is state notification (Starting) - verify using backend state + c.Assert(nn[0].Prefs.Persist().UserProfile().LoginName(), qt.Equals, "user3") + c.Assert(nn[0].Prefs.LoggedOut(), qt.IsFalse) + c.Assert(nn[0].Prefs.WantRunning(), qt.IsTrue) + // nn[1] is the Starting state notification. The asserts below + // check the backend state instead. c.Assert(isWantRunning(b), qt.IsTrue) c.Assert(isLoggedIn(b), qt.IsTrue) }