diff --git a/ipn/backend.go b/ipn/backend.go index 5d941f917..ff6bd30d7 100644 --- a/ipn/backend.go +++ b/ipn/backend.go @@ -6,6 +6,7 @@ package ipn import ( "errors" "fmt" + "reflect" "slices" "strconv" "strings" @@ -593,6 +594,11 @@ type PeerState struct { PeerWireGuardStateAt time.Time } +// IsZero reports whether no field of n is set. +func (n Notify) IsZero() bool { + return reflect.ValueOf(n).IsZero() +} + func (n Notify) String() string { var sb strings.Builder sb.WriteString("Notify{") diff --git a/ipn/backend_test.go b/ipn/backend_test.go index df0bae5e7..111fe993d 100644 --- a/ipn/backend_test.go +++ b/ipn/backend_test.go @@ -8,6 +8,7 @@ import ( "go/types" "maps" "math/bits" + "reflect" "slices" "strconv" "strings" @@ -15,11 +16,54 @@ import ( "golang.org/x/tools/go/packages" + "tailscale.com/drive" "tailscale.com/health" "tailscale.com/types/empty" + "tailscale.com/types/views" "tailscale.com/util/mak" ) +// TestNotifyIsZero checks that IsZero is true for an empty Notify and false +// once any single field is set, so a new field cannot be missed. +func TestNotifyIsZero(t *testing.T) { + if !(Notify{}).IsZero() { + t.Error("empty Notify is not zero") + } + rt := reflect.TypeFor[Notify]() + for i := range rt.NumField() { + f := rt.Field(i) + if f.Name == "_" { + continue + } + var n Notify + fv := reflect.ValueOf(&n).Elem().Field(i) + switch f.Type.Kind() { + case reflect.Pointer: + fv.Set(reflect.New(f.Type.Elem())) + case reflect.Slice: + fv.Set(reflect.MakeSlice(f.Type, 1, 1)) + case reflect.Map: + fv.Set(reflect.MakeMap(f.Type)) + case reflect.String: + fv.SetString("x") + case reflect.Bool: + fv.SetBool(true) + case reflect.Struct: + switch f.Name { + case "DriveShares": + n.DriveShares = views.SliceOfViews[*drive.Share, drive.ShareView]([]*drive.Share{{}}) + default: + t.Fatalf("field %s: add a case for struct type %v", f.Name, f.Type) + } + default: + t.Fatalf("field %s: add a case for kind %v", f.Name, f.Type.Kind()) + } + if n.IsZero() { + t.Errorf("Notify with %s set reports zero", f.Name) + } + } +} + func TestNotifyString(t *testing.T) { for _, tt := range []struct { name string diff --git a/ipn/ipnlocal/local.go b/ipn/ipnlocal/local.go index 72e2d6465..7da78e7c1 100644 --- a/ipn/ipnlocal/local.go +++ b/ipn/ipnlocal/local.go @@ -1969,6 +1969,26 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c return } + if !b.applyControlClientStatusLocked(c, st) { + return + } + if st.URL != "" { + b.logf("Received auth URL: %.20v...", st.URL) + b.setAuthURLLocked(st.URL) + } + b.stateMachineLocked() + // This is currently (2020-07-28) necessary; conditionally disabling it is fragile! + // This is where netmap information gets propagated to router and magicsock. + b.authReconfigLocked() +} + +// applyControlClientStatusLocked applies a status that carries no error. It +// updates the login state, the prefs, the netmap, and the exit node, sends +// one [ipn.Notify] for everything it changed, and reports whether the caller +// should go on to run the state machine. +// +// b.mu must be held. +func (b *LocalBackend) applyControlClientStatusLocked(c controlclient.Client, st controlclient.Status) (runStateMachine bool) { // Track the number of calls currCall := b.numClientStatusCalls.Add(1) @@ -2003,6 +2023,16 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c } } + // notify collects the login, prefs, netmap, and exit node changes from + // this status. The deferred call sends it on every return, if any + // field was set. + var notify ipn.Notify + defer func() { + if !notify.IsZero() { + b.sendLocked(notify) + } + }() + wasBlocked := b.blocked authWasInProgress := b.authURL != "" keyExpiryExtended := false @@ -2027,7 +2057,7 @@ 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{} } prefsChanged := false @@ -2076,7 +2106,7 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c // switch is about to happen. // TODO(nickkhyl): remove this once we improve handling of implicit profile switching // in tailscale/corp#28014 and we apply syspolicy when the switch actually happens. - if b.reconcilePrefsLocked(prefs) { + if b.reconcilePrefsLocked(prefs, ¬ify) { prefsChanged = true } @@ -2101,8 +2131,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 @@ -2112,7 +2140,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) @@ -2124,8 +2151,11 @@ 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 + notify = ipn.Notify{} + return false } // b.cc is nil for a cached netmap applied by startLocked. if b.cc != nil { @@ -2146,31 +2176,29 @@ 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}) - return + notify.ErrMessage = &msg + notify.Prefs = new(b.pm.CurrentPrefs()) + return false } if oldNetMap != nil { diff := st.NetMap.ConciseDiffFrom(oldNetMap) @@ -2212,11 +2240,9 @@ 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} if b.hasPeerChangeWatcherLocked() { notify.UserProfiles = st.NetMap.UserProfiles notify.PeersChanged = make([]*tailcfg.Node, 0, len(st.NetMap.Peers)) @@ -2233,32 +2259,25 @@ 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. - b.suggestExitNodeLocked() + // Recalculate the suggested exit node against the new netmap. A + // changed suggestion is recorded in notify. + b.suggestExitNodeLocked(¬ify) - // 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. - if b.refreshExitNodeLocked() { - b.sendLocked(ipn.Notify{Prefs: new(b.pm.CurrentPrefs())}) + // 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(¬ify) { + prefsChanged = true } } - if st.URL != "" { - b.logf("Received auth URL: %.20v...", st.URL) - b.setAuthURLLocked(st.URL) + + // 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()) } - b.stateMachineLocked() - // This is currently (2020-07-28) necessary; conditionally disabling it is fragile! - // This is where netmap information gets propagated to router and magicsock. - b.authReconfigLocked() + return true } // handleNetmapExpiry reruns netmap status handling when a node may have @@ -2499,8 +2518,16 @@ func (b *LocalBackend) reconcilePrefs() (_ ipn.PrefsView, anyChange bool) { b.mu.Lock() defer b.mu.Unlock() + // A changed exit node suggestion is sent on return. When the prefs + // changed, setPrefsLocked sends them first. + var notify ipn.Notify + defer func() { + if !notify.IsZero() { + b.sendLocked(notify) + } + }() prefs := b.pm.CurrentPrefs().AsStruct() - if !b.reconcilePrefsLocked(prefs) { + if !b.reconcilePrefsLocked(prefs, ¬ify) { return prefs.View(), false } return b.setPrefsLocked(prefs), true @@ -2582,12 +2609,14 @@ func (b *LocalBackend) UpdateNetmapDelta(muts []netmap.NodeMutation) (handled bo b.mu.Lock() defer b.mu.Unlock() - var notify *ipn.Notify // non-nil if we need to send a Notify + // notify collects the peer changes, the resolved exit node prefs, and a + // changed suggestion from this delta. + var notify ipn.Notify defer func() { // Sent while b.mu is still held, so it reflects the state this // delta produced and nothing newer. - if notify != nil { - b.sendLocked(*notify) + if !notify.IsZero() { + b.sendLocked(notify) } }() @@ -2684,13 +2713,10 @@ func (b *LocalBackend) UpdateNetmapDelta(muts []netmap.NodeMutation) (handled bo // path resolves the exit node in // [LocalBackend.setControlClientStatusLocked]. Resolve it here too, // before the reconfig below, so the routes are installed once. - if b.exitNodeDeltaNeedsResolveLocked(muts, deltaRes.RemovedPeers) && b.resolveExitNodeLocked() { + if b.exitNodeDeltaNeedsResolveLocked(muts, deltaRes.RemovedPeers) && b.resolveExitNodeLocked(¬ify) { // Deliver the new prefs in the same Notify as the peer changes // below, so a GUI never sees prefs select a peer it has not been // told about. - if notify == nil { - notify = &ipn.Notify{} - } notify.Prefs = new(b.pm.CurrentPrefs()) needsAuthReconfig = true } @@ -2720,7 +2746,7 @@ func (b *LocalBackend) UpdateNetmapDelta(muts []netmap.NodeMutation) (handled bo // which should influence which exit nodes are considered valid to suggest. if cn.NetMap() != nil && mutationsAreWorthyOfRecalculatingSuggestedExitNode(muts, cn, b.lastSuggestedExitNode) { // Recompute the suggested exit node - b.suggestExitNodeLocked() + b.suggestExitNodeLocked(¬ify) } if cn.NetMap() == nil { @@ -2753,9 +2779,6 @@ func (b *LocalBackend) UpdateNetmapDelta(muts []netmap.NodeMutation) (handled bo // into full Nodes for watchers that asked for PeerChanges but not // PeerPatches). if peersUpsertedOrRemoved || mutationsAreWorthyOfTellingIPNBus(muts) { - if notify == nil { - notify = &ipn.Notify{} - } for _, m := range muts { switch m := m.(type) { case netmap.NodeMutationUpsert: @@ -2769,11 +2792,11 @@ func (b *LocalBackend) UpdateNetmapDelta(muts []netmap.NodeMutation) (handled bo } else if !ok { b.logf("[unexpected] got mutations worthy of telling IPN bus but failed to convert to peer changes") } - } else if testenv.InTest() && notify == nil { - // In tests, send an empty Notify as a wake-up so end-to-end - // integration tests in another repo can check on the status of - // LocalBackend after processing deltas. - notify = new(ipn.Notify) + } else if testenv.InTest() && notify.IsZero() { + // In tests, send a Notify for every delta as a wake-up for + // end-to-end tests in another repo. Version makes it non-zero; + // sendToLocked sets it on every Notify anyway. + notify.Version = version.Long() } return true } @@ -3032,9 +3055,10 @@ func mutationsAreWorthyOfTellingIPNBus(muts []netmap.NodeMutation) bool { // resolveAutoExitNodeLocked computes a suggested exit node and updates prefs // to use it if AutoExitNode is enabled, and reports whether prefs was mutated. +// notify is passed to [LocalBackend.suggestExitNodeLocked]. // // b.mu must be held. -func (b *LocalBackend) resolveAutoExitNodeLocked(prefs *ipn.Prefs) (prefsChanged bool) { +func (b *LocalBackend) resolveAutoExitNodeLocked(prefs *ipn.Prefs, notify *ipn.Notify) (prefsChanged bool) { if !buildfeatures.HasUseExitNode { return false } @@ -3051,7 +3075,7 @@ func (b *LocalBackend) resolveAutoExitNodeLocked(prefs *ipn.Prefs) (prefsChanged if !prefs.AutoExitNode.IsSet() { return false } - if _, err := b.suggestExitNodeLocked(); err != nil && !errors.Is(err, ErrNoPreferredDERP) { + if _, err := b.suggestExitNodeLocked(notify); err != nil && !errors.Is(err, ErrNoPreferredDERP) { b.logf("failed to select auto exit node: %v", err) // non-fatal, see below } var newExitNodeID tailcfg.StableNodeID @@ -3347,11 +3371,21 @@ func (b *LocalBackend) startLocked(opts ipn.Options) error { // Reset the always-on override whenever Start is called. b.resetAlwaysOnOverrideLocked() + // notify is sent with the prefs below. Reconciling records a changed + // exit node suggestion in it. The deferred send covers the error + // returns before the prefs are sent. + var notify ipn.Notify + defer func() { + if !notify.IsZero() { + b.sendToLocked(notify, allClients) + } + }() + // Apply any syspolicy overrides, resolve exit node ID, etc. // As of 2025-07-03, this is primarily needed in two cases: // - when opts.UpdatePrefs is not nil // - when Always Mode is enabled and we need to set WantRunning to true - if b.reconcilePrefsLocked(newPrefs) { + if b.reconcilePrefsLocked(newPrefs, ¬ify) { prefsChanged = true prefsChangedWhy = append(prefsChangedWhy, "reconcilePrefsLocked") } @@ -3514,7 +3548,11 @@ 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) + // Sent now rather than at return. Clear notify so the deferred send + // does not repeat it. + notify.Prefs = &prefs + b.sendToLocked(notify, allClients) + notify = ipn.Notify{} // initialize Taildrive shares from saved state if fs, ok := b.sys.DriveForRemote.GetOK(); ok { @@ -4141,9 +4179,15 @@ func (b *LocalBackend) buildInitialNotifyLocked(sb *ipnstate.StatusBuilder, sess ini.Health = b.HealthTracker().CurrentState() } if mask&ipn.NotifyInitialSuggestedExitNode != 0 { - if en, err := b.suggestExitNodeLocked(); err == nil { + // ini carries the current suggestion for the new session. A + // changed suggestion is also broadcast to the existing sessions. + var changed ipn.Notify + if en, err := b.suggestExitNodeLocked(&changed); err == nil { ini.SuggestedExitNode = &en.ID } + if !changed.IsZero() { + b.sendLocked(changed) + } } if mask&ipn.NotifyInitialClientVersion != 0 { if prefs := b.pm.CurrentPrefs(); prefs.Valid() && prefs.AutoUpdate().Check { @@ -5651,7 +5695,13 @@ func (b *LocalBackend) changeDisablesExitNodeLocked(prefs ipn.PrefsView, change // and resolve the exit node in the prefs. tmpPrefs := prefs.AsStruct() tmpPrefs.ApplyEdits(tmpChange) - b.resolveExitNodeInPrefsLocked(tmpPrefs) + // Resolving can change the exit node suggestion. That is broadcast + // even though tmpPrefs is discarded. + var notify ipn.Notify + b.resolveExitNodeInPrefsLocked(tmpPrefs, ¬ify) + if !notify.IsZero() { + b.sendLocked(notify) + } // If ExitNodeID is empty after applying the changes, // but wasn't empty before, then the change disables @@ -5888,8 +5938,10 @@ func (b *LocalBackend) setPrefsLocked(newp *ipn.Prefs) ipn.PrefsView { // Apply reconciliation to the prefs, such as policy overrides, // exit node resolution, and so on. The call returns whether it updated // newp, but everything in this function treats newp as completely new - // anyway, so its return value can be ignored here. - b.reconcilePrefsLocked(newp) + // anyway, so its return value can be ignored here. A changed exit node + // suggestion is recorded in notify, which is sent with the prefs below. + var notify ipn.Notify + b.reconcilePrefsLocked(newp, ¬ify) // We do this to avoid holding the lock while doing everything else. @@ -5976,7 +6028,8 @@ func (b *LocalBackend) setPrefsLocked(newp *ipn.Prefs) ipn.PrefsView { } } - b.sendLocked(ipn.Notify{Prefs: &prefs}) + notify.Prefs = &prefs + b.sendLocked(notify) return prefs } @@ -7628,18 +7681,22 @@ func (b *LocalBackend) RefreshExitNode() { } b.mu.Lock() defer b.mu.Unlock() - if b.refreshExitNodeLocked() { - b.sendLocked(ipn.Notify{Prefs: new(b.pm.CurrentPrefs())}) + var notify ipn.Notify + if b.refreshExitNodeLocked(¬ify) { + notify.Prefs = new(b.pm.CurrentPrefs()) + } + if !notify.IsZero() { + b.sendLocked(notify) } } // refreshExitNodeLocked is like RefreshExitNode but requires b.mu be held. // If it reports true, the caller must send an [ipn.Notify] carrying -// b.pm.CurrentPrefs(). -func (b *LocalBackend) refreshExitNodeLocked() (changed bool) { +// b.pm.CurrentPrefs(). notify is passed to [LocalBackend.suggestExitNodeLocked]. +func (b *LocalBackend) refreshExitNodeLocked(notify *ipn.Notify) (changed bool) { syncs.RequiresMutex(&b.mu) - if !b.resolveExitNodeLocked() { + if !b.resolveExitNodeLocked(notify) { return false } b.authReconfigLocked() @@ -7656,8 +7713,10 @@ func (b *LocalBackend) refreshExitNodeLocked() (changed bool) { // selected exit node, if needed. It reports false if the prefs could not // be saved, so the caller acts only on prefs that are in effect. // +// notify is passed to [LocalBackend.suggestExitNodeLocked]. +// // b.mu must be held. -func (b *LocalBackend) resolveExitNodeLocked() (changed bool) { +func (b *LocalBackend) resolveExitNodeLocked(notify *ipn.Notify) (changed bool) { syncs.RequiresMutex(&b.mu) if !buildfeatures.HasUseExitNode { @@ -7667,7 +7726,7 @@ func (b *LocalBackend) resolveExitNodeLocked() (changed bool) { nm := b.currentNode().NetMap() oldPrefs := b.pm.CurrentPrefs() prefs := oldPrefs.AsStruct() - if !b.resolveExitNodeInPrefsLocked(prefs) { + if !b.resolveExitNodeInPrefsLocked(prefs, notify) { return false } @@ -7704,12 +7763,14 @@ func (b *LocalBackend) resolveExitNodeLocked() (changed bool) { // // It must not perform any reconfiguration, as the prefs are not yet effective. // +// notify is passed to [LocalBackend.suggestExitNodeLocked]. +// // b.mu must be held. -func (b *LocalBackend) reconcilePrefsLocked(prefs *ipn.Prefs) (changed bool) { +func (b *LocalBackend) reconcilePrefsLocked(prefs *ipn.Prefs, notify *ipn.Notify) (changed bool) { if buildfeatures.HasSystemPolicy && b.applySysPolicyLocked(prefs) { changed = true } - if buildfeatures.HasUseExitNode && b.resolveExitNodeInPrefsLocked(prefs) { + if buildfeatures.HasUseExitNode && b.resolveExitNodeInPrefsLocked(prefs, notify) { changed = true } if changed { @@ -7721,14 +7782,15 @@ func (b *LocalBackend) reconcilePrefsLocked(prefs *ipn.Prefs) (changed bool) { // resolveExitNodeInPrefsLocked determines which exit node to use // based on the specified prefs and netmap. It updates the exit node ID // in the prefs if needed, and returns true if the exit node has changed. +// notify is passed to [LocalBackend.suggestExitNodeLocked]. // // b.mu must be held. -func (b *LocalBackend) resolveExitNodeInPrefsLocked(prefs *ipn.Prefs) (changed bool) { +func (b *LocalBackend) resolveExitNodeInPrefsLocked(prefs *ipn.Prefs, notify *ipn.Notify) (changed bool) { syncs.RequiresMutex(&b.mu) if !buildfeatures.HasUseExitNode { return false } - if b.resolveAutoExitNodeLocked(prefs) { + if b.resolveAutoExitNodeLocked(prefs, notify) { changed = true } if b.resolveExitNodeIPLocked(prefs) { @@ -9224,8 +9286,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. // +// A changed suggestion is recorded in notify, which the caller sends. +// notify must not be nil. +// // b.mu must be held. -func (b *LocalBackend) suggestExitNodeLocked() (response apitype.ExitNodeSuggestionResponse, err error) { +func (b *LocalBackend) suggestExitNodeLocked(notify *ipn.Notify) (response apitype.ExitNodeSuggestionResponse, err error) { if !buildfeatures.HasUseExitNode { return response, feature.ErrUnavailable } @@ -9252,8 +9317,7 @@ 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) + notify.SuggestedExitNode = new(res.ID) } b.lastSuggestedExitNode = res.ID @@ -9270,7 +9334,13 @@ func (b *LocalBackend) SuggestExitNode() (response apitype.ExitNodeSuggestionRes } b.mu.Lock() defer b.mu.Unlock() - return b.suggestExitNodeLocked() + var notify ipn.Notify + defer func() { + if !notify.IsZero() { + b.sendLocked(notify) + } + }() + return b.suggestExitNodeLocked(¬ify) } // 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 2e4d6aad8..3879f40fa 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,33 +1666,118 @@ 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) + + 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.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 wantExitNodeIDNotify(want tailcfg.StableNodeID) wantedNotification { - return wantedNotification{ - name: fmt.Sprintf("ExitNodeID-%s", want), - cond: func(_ testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { - return n.Prefs != nil && n.Prefs.Valid() && n.Prefs.ExitNodeID() == want +// TestSuggestExitNodeLockedNotify checks that a changed suggestion is +// recorded in the caller's Notify and that suggestExitNodeLocked sends +// nothing itself. +func TestSuggestExitNodeLockedNotify(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) + + 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, nil, func(t testing.TB, _ ipnauth.Actor, n *ipn.Notify) bool { + if n.SuggestedExitNode != nil { + t.Errorf("suggestExitNodeLocked sent a notification itself: %v", n) + } + return false + }) + var n ipn.Notify + lb.mu.Lock() + _, err := lb.suggestExitNodeLocked(&n) + lb.mu.Unlock() + if err != nil { + t.Fatal(err) + } + if n.SuggestedExitNode == nil || *n.SuggestedExitNode != exitNode1.StableID() { + t.Fatalf("Notify.SuggestedExitNode = %v, want %q", n.SuggestedExitNode, exitNode1.StableID()) + } + nw.check() + + // The same suggestion again records nothing. + n = ipn.Notify{} + lb.mu.Lock() + _, err = lb.suggestExitNodeLocked(&n) + lb.mu.Unlock() + if err != nil { + t.Fatal(err) + } + if !n.IsZero() { + t.Errorf("unchanged suggestion was recorded: %v", n) } } @@ -2792,9 +2881,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()) } @@ -4600,7 +4702,7 @@ func TestSetExitNodeIDPolicy(t *testing.T) { b.pm = pm b.lastSuggestedExitNode = test.lastSuggestedExitNode prefs := b.pm.prefs.AsStruct() - if changed := b.reconcilePrefsLocked(prefs); changed != test.prefsChanged { + if changed := b.reconcilePrefsLocked(prefs, new(ipn.Notify)); changed != test.prefsChanged { t.Errorf("wanted prefs changed %v, got prefs changed %v", test.prefsChanged, changed) } diff --git a/ipn/ipnlocal/state_test.go b/ipn/ipnlocal/state_test.go index a572043d9..e04ce0879 100644 --- a/ipn/ipnlocal/state_test.go +++ b/ipn/ipnlocal/state_test.go @@ -611,15 +611,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. // @@ -630,9 +631,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) @@ -831,7 +832,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{ @@ -839,16 +840,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) } @@ -974,14 +976,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 @@ -990,12 +992,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) }