diff --git a/cmd/k8s-operator/depaware.txt b/cmd/k8s-operator/depaware.txt index 6385b0064..07adb6472 100644 --- a/cmd/k8s-operator/depaware.txt +++ b/cmd/k8s-operator/depaware.txt @@ -857,7 +857,7 @@ tailscale.com/cmd/k8s-operator dependencies: (generated by github.com/tailscale/ tailscale.com/types/bools from tailscale.com/tsnet+ tailscale.com/types/dnstype from tailscale.com/ipn/ipnlocal+ tailscale.com/types/empty from tailscale.com/ipn+ - tailscale.com/types/events from tailscale.com/control/controlclient+ + tailscale.com/types/events from tailscale.com/net/tstun+ tailscale.com/types/ipproto from tailscale.com/net/flowtrack+ tailscale.com/types/key from tailscale.com/client/local+ tailscale.com/types/lazy from tailscale.com/ipn/ipnlocal+ diff --git a/cmd/tailscaled/depaware-min.txt b/cmd/tailscaled/depaware-min.txt index bfe8dd464..4a24be079 100644 --- a/cmd/tailscaled/depaware-min.txt +++ b/cmd/tailscaled/depaware-min.txt @@ -136,7 +136,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de tailscale.com/types/bools from tailscale.com/net/netcheck+ tailscale.com/types/dnstype from tailscale.com/client/tailscale/apitype+ tailscale.com/types/empty from tailscale.com/ipn+ - tailscale.com/types/events from tailscale.com/control/controlclient+ + tailscale.com/types/events from tailscale.com/net/tstun+ tailscale.com/types/flagtype from tailscale.com/cmd/tailscaled tailscale.com/types/ipproto from tailscale.com/ipn+ tailscale.com/types/key from tailscale.com/control/controlbase+ diff --git a/cmd/tailscaled/depaware-minbox.txt b/cmd/tailscaled/depaware-minbox.txt index 7eeea8d25..331a04eff 100644 --- a/cmd/tailscaled/depaware-minbox.txt +++ b/cmd/tailscaled/depaware-minbox.txt @@ -155,7 +155,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de tailscale.com/types/bools from tailscale.com/net/netcheck+ tailscale.com/types/dnstype from tailscale.com/client/tailscale/apitype+ tailscale.com/types/empty from tailscale.com/ipn+ - tailscale.com/types/events from tailscale.com/control/controlclient+ + tailscale.com/types/events from tailscale.com/net/tstun+ tailscale.com/types/flagtype from tailscale.com/cmd/tailscaled tailscale.com/types/ipproto from tailscale.com/ipn+ tailscale.com/types/key from tailscale.com/client/local+ diff --git a/cmd/tailscaled/depaware.txt b/cmd/tailscaled/depaware.txt index 6fbe5f9bc..48f4dd126 100644 --- a/cmd/tailscaled/depaware.txt +++ b/cmd/tailscaled/depaware.txt @@ -436,7 +436,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de tailscale.com/types/bools from tailscale.com/wgengine/netlog+ tailscale.com/types/dnstype from tailscale.com/ipn/ipnlocal+ tailscale.com/types/empty from tailscale.com/ipn+ - tailscale.com/types/events from tailscale.com/control/controlclient+ + tailscale.com/types/events from tailscale.com/net/tstun+ tailscale.com/types/flagtype from tailscale.com/cmd/tailscaled tailscale.com/types/ipproto from tailscale.com/net/flowtrack+ tailscale.com/types/key from tailscale.com/client/local+ diff --git a/cmd/tsidp/depaware.txt b/cmd/tsidp/depaware.txt index 517f96a54..0f744cac7 100644 --- a/cmd/tsidp/depaware.txt +++ b/cmd/tsidp/depaware.txt @@ -245,7 +245,7 @@ tailscale.com/cmd/tsidp dependencies: (generated by github.com/tailscale/depawar tailscale.com/types/bools from tailscale.com/tsnet+ tailscale.com/types/dnstype from tailscale.com/client/local+ tailscale.com/types/empty from tailscale.com/ipn+ - tailscale.com/types/events from tailscale.com/control/controlclient+ + tailscale.com/types/events from tailscale.com/net/tstun+ tailscale.com/types/ipproto from tailscale.com/ipn+ tailscale.com/types/key from tailscale.com/client/local+ tailscale.com/types/lazy from tailscale.com/cmd/tsidp+ diff --git a/control/controlclient/auto.go b/control/controlclient/auto.go index 137b8a39b..00201d3b5 100644 --- a/control/controlclient/auto.go +++ b/control/controlclient/auto.go @@ -575,28 +575,6 @@ func (mrs mapRoutineState) UpdateUserProfiles(profiles map[tailcfg.UserID]tailcf } } -var _ DiscoKeyUpdater = mapRoutineState{} - -func (mrs mapRoutineState) PatchDiscoKey(pub key.NodePublic, disco key.DiscoPublic) { - c := mrs.c - c.mu.Lock() - goodState := c.loggedIn && c.inMapPoll - dun, ok := c.observer.(DiscoKeyUpdater) - mapCtx := c.mapCtx - c.mu.Unlock() - - if !goodState || !ok { - return - } - - ctx, cancel := context.WithTimeout(mapCtx, 2*time.Second) - defer cancel() - - c.observerQueue.RunSync(ctx, func() { - dun.PatchDiscoKey(pub, disco) - }) -} - // mapRoutine is responsible for keeping a read-only streaming connection to the // control server, and keeping the netmap up to date. func (c *Auto) mapRoutine() { diff --git a/control/controlclient/direct.go b/control/controlclient/direct.go index 4d4567764..8414c7c40 100644 --- a/control/controlclient/direct.go +++ b/control/controlclient/direct.go @@ -52,7 +52,6 @@ import ( "tailscale.com/tailcfg/nodecap" "tailscale.com/tka" "tailscale.com/tstime" - "tailscale.com/types/events" "tailscale.com/types/key" "tailscale.com/types/logger" "tailscale.com/types/netmap" @@ -287,15 +286,6 @@ type UserProfileUpdater interface { UpdateUserProfiles(profiles map[tailcfg.UserID]tailcfg.UserProfileView) bool } -// DiscoKeyUpdater is an optional interface that can be implemented by an [Observer] to be -// notified about node disco keys received out-of-band from control, via -// existing connection state. -type DiscoKeyUpdater interface { - // PatchDiscoKey reports to the receiver that the specified disco key - // for node was obtained out-of-band from control. - PatchDiscoKey(key.NodePublic, key.DiscoPublic) -} - var nextControlClientID atomic.Int64 // NewDirect returns a new Direct client. @@ -425,38 +415,6 @@ func NewDirect(opts Options) (*Direct, error) { c.clientVersionPub = eventbus.Publish[tailcfg.ClientVersion](c.busClient) c.autoUpdatePub = eventbus.Publish[AutoUpdate](c.busClient) c.controlTimePub = eventbus.Publish[ControlTime](c.busClient) - discoKeyPub := eventbus.Publish[events.PeerDiscoKeyUpdate](c.busClient) - eventbus.SubscribeFunc(c.busClient, func(update events.DiscoKeyAdvertisement) { - c.logf("[v1] controlclient direct: got TSMP disco key advertisement from %v via eventbus", update.Src) - var peerID tailcfg.NodeID - var peerKey key.NodePublic - var ok bool - c.mu.Lock() - sess := c.streamingMapSession - c.mu.Unlock() - if sess != nil { - peerID, peerKey, ok = sess.PeerIDAndKeyByTailscaleIP(update.Src) - } - - if sess != nil && ok { - c.logf("[v1] controlclient direct: updating discoKey for %v via mapSession", update.Src) - - // If we update without error, return. If the err indicates that the - // mapSession has gone away, we want to fall back to pushing the key - // further down the chain. - if err := sess.updateDiscoForNode( - peerID, peerKey, update.Key, time.Now(), false); err == nil || - !errors.Is(err, ErrChangeQueueClosed) { - return - } - } - - // We need to push the update further down the chain. Either because we do - // not have a mapSession (we are not connected to control) or because the - // mapSession queue has closed. - c.logf("[v1] controlclient direct: updating discoKey for %v via magicsock", update.Src) - discoKeyPub.Publish(events.PeerDiscoKeyUpdate(update)) - }) return c, nil } @@ -972,8 +930,6 @@ func (c *Direct) PollNetMap(ctx context.Context, nu NetmapUpdater) error { // It will report only the first netmap seen. type rememberLastNetmapUpdater struct { last *netmap.NetworkMap - lastTSMPKey key.NodePublic - lastTSMPDisco key.DiscoPublic done chan any } @@ -985,11 +941,6 @@ func (nu *rememberLastNetmapUpdater) UpdateFullNetmap(nm *netmap.NetworkMap) { } } -func (nu *rememberLastNetmapUpdater) PatchDiscoKey(key key.NodePublic, disco key.DiscoPublic) { - nu.lastTSMPKey = key - nu.lastTSMPDisco = disco -} - // FetchNetMapForTest fetches the netmap once. func (c *Direct) FetchNetMapForTest(ctx context.Context) (*netmap.NetworkMap, error) { var nu rememberLastNetmapUpdater diff --git a/control/controlclient/map.go b/control/controlclient/map.go index 45a4143e4..f60a1a93f 100644 --- a/control/controlclient/map.go +++ b/control/controlclient/map.go @@ -39,11 +39,6 @@ import ( "tailscale.com/wgengine/filter" ) -type responseWithSource struct { - response *tailcfg.MapResponse - viaTSMP bool -} - // mapSession holds the state over a long-polled "map" request to the // control plane. // @@ -104,7 +99,7 @@ type mapSession struct { lastTKAInfo *tailcfg.TKAInfo lastNetmapSummary string // from NetworkMap.VeryConcise cqmu sync.Mutex - changeQueue chan responseWithSource + changeQueue chan *tailcfg.MapResponse changeQueueClosed bool processQueue sync.WaitGroup @@ -133,7 +128,7 @@ func newMapSession(privateNodeKey key.NodePrivate, nu NetmapUpdater, controlKnob cancel: func() {}, onDebug: func(context.Context, *tailcfg.Debug) error { return nil }, onSelfNodeChanged: func(*netmap.NetworkMap) {}, - changeQueue: make(chan responseWithSource), + changeQueue: make(chan *tailcfg.MapResponse), changeQueueClosed: false, } ms.sessionAliveCtx, ms.sessionAliveCtxClose = context.WithCancel(context.Background()) @@ -152,7 +147,7 @@ func (ms *mapSession) run() { for { select { case change := <-ms.changeQueue: - ms.handleNonKeepAliveMapResponse(ms.sessionAliveCtx, change.response, change.viaTSMP) + ms.handleNonKeepAliveMapResponse(ms.sessionAliveCtx, change) case <-ms.sessionAliveCtx.Done(): // Drain any remaining items in the queue before exiting. // Lock the queue during this time to avoid updates through other channels @@ -164,7 +159,7 @@ func (ms *mapSession) run() { for { select { case change := <-ms.changeQueue: - ms.handleNonKeepAliveMapResponse(ms.sessionAliveCtx, change.response, change.viaTSMP) + ms.handleNonKeepAliveMapResponse(ms.sessionAliveCtx, change) default: // Queue is empty, close it and exit close(ms.changeQueue) @@ -200,36 +195,6 @@ func (ms *mapSession) Close() { var ErrChangeQueueClosed = errors.New("change queue closed") -func (ms *mapSession) updateDiscoForNode(id tailcfg.NodeID, key key.NodePublic, discoKey key.DiscoPublic, lastSeen time.Time, online bool) error { - if discoKey.IsZero() { - ms.logf("[v1] controlclient: received zero disco key update from nodeID %v", id) - return nil - } - - ms.cqmu.Lock() - - if ms.changeQueueClosed { - ms.cqmu.Unlock() - ms.processQueue.Wait() - return ErrChangeQueueClosed - } - defer ms.cqmu.Unlock() - - resp := responseWithSource{ - response: &tailcfg.MapResponse{ - PeersChangedPatch: []*tailcfg.PeerChange{{ - NodeID: id, - Key: &key, - LastSeen: &lastSeen, - Online: &online, - DiscoKey: &discoKey, - }}, - }, - viaTSMP: true, - } - return ms.addRespToQueue(resp) -} - // HandleNonKeepAliveMapResponse handles a non-KeepAlive MapResponse (full or // incremental). // @@ -255,15 +220,10 @@ func (ms *mapSession) HandleNonKeepAliveMapResponse(ctx context.Context, resp *t defer ms.cqmu.Unlock() - change := responseWithSource{ - response: resp, - viaTSMP: false, - } - - return ms.addRespToQueue(change) + return ms.addRespToQueue(resp) } -func (ms *mapSession) addRespToQueue(resp responseWithSource) error { +func (ms *mapSession) addRespToQueue(resp *tailcfg.MapResponse) error { select { case ms.changeQueue <- resp: return nil @@ -280,7 +240,7 @@ func (ms *mapSession) addRespToQueue(resp responseWithSource) error { // // TODO(bradfitz): make this handle all fields later. For now (2023-08-20) this // is [re]factoring progress enough. -func (ms *mapSession) handleNonKeepAliveMapResponse(ctx context.Context, resp *tailcfg.MapResponse, viaTSMP bool) error { +func (ms *mapSession) handleNonKeepAliveMapResponse(ctx context.Context, resp *tailcfg.MapResponse) error { if DevKnob.StripEndpoints() { for _, p := range resp.Peers { p.Endpoints = nil @@ -320,23 +280,8 @@ func (ms *mapSession) handleNonKeepAliveMapResponse(ctx context.Context, resp *t ms.patchifyPeersChanged(resp) - ms.removeUnwantedDiscoUpdates(resp, viaTSMP) - - // TSMP learned key was rejected, no need to do any more work in the engine. - if viaTSMP && len(resp.PeersChangedPatch) == 0 { - return nil - } - ms.removeUnwantedDiscoUpdatesFromFullNetmapUpdate(resp) - ms.updateStateFromResponse(resp) - // If source was learned via TSMP, the updated disco key need to be marked in - // userspaceEngine as an update that should not reconfigure the wireguard - // connection. - if viaTSMP { - ms.tryMarkDiscoAsLearnedFromTSMP(resp) - } - if ms.tryHandleIncrementally(resp) { metricMapResponseHandledIncrementally.Add(1) ms.occasionallyPrintSummary(ms.lastNetmapSummary) @@ -367,21 +312,6 @@ func (ms *mapSession) handleNonKeepAliveMapResponse(ctx context.Context, resp *t return nil } -func (ms *mapSession) tryMarkDiscoAsLearnedFromTSMP(res *tailcfg.MapResponse) { - dun, ok := ms.netmapUpdater.(DiscoKeyUpdater) - if !ok { - return - } - - // In reality we should never really have more than one change here over TSMP. - for _, change := range res.PeersChangedPatch { - if change == nil || change.DiscoKey == nil || change.Key == nil { - continue - } - dun.PatchDiscoKey(*change.Key, *change.DiscoKey) - } -} - // upgradeNode upgrades Node fields from the server into the modern forms // not using deprecated fields. func upgradeNode(n *tailcfg.Node) { @@ -478,125 +408,6 @@ type updateStats struct { changed int } -// removeUnwantedDiscoUpdates goes over the patchified updates and reject items -// where the node is offline and has last been seen before the recorded last seen. -func (ms *mapSession) removeUnwantedDiscoUpdates(resp *tailcfg.MapResponse, viaTSMP bool) { - ms.peersMu.RLock() - defer ms.peersMu.RUnlock() - - acceptedDiscoUpdates := resp.PeersChangedPatch[:0] - - for _, change := range resp.PeersChangedPatch { - // Accept if: - // - DiscoKey is nil and did not change. - // - Fields we rely on for rejection is missing. - if change.DiscoKey == nil || change.Online == nil || change.LastSeen == nil { - acceptedDiscoUpdates = append(acceptedDiscoUpdates, change) - continue - } - - existingNode, ok := ms.peers[change.NodeID] - // Accept if: - // - Cannot find the peer, don't have enough data. - if !ok { - acceptedDiscoUpdates = append(acceptedDiscoUpdates, change) - continue - } - - // Reject if: - // - key was learned via tsmp AND, - // - existing node is online AND, - // - key did not change. - // Here to avoid a deeper reconfig in the case where we get a TSMP key - // exchange while that node is already in a connected state (from the view - // of the control plane). This is meant to keep the node stable, avoiding a - // reconfiguration of the node deeper down in the engine. - // With this, we are avoiding updating the LastSeen and Online fields from - // TSMP updates when that is not relevant, overall making the connection - // state change less, and updating the engine less. - if viaTSMP && existingNode.Online().Get() && - *change.DiscoKey == existingNode.DiscoKey() { - continue - } - - // Accept if: - // - Node is online. - if *change.Online { - acceptedDiscoUpdates = append(acceptedDiscoUpdates, change) - continue - } - - // Accept if: - // - if we don't have a last seen to compare against on the existing node. - // - OR lastSeen moved forward in time. - if existingLastSeen, ok := existingNode.LastSeen().GetOk(); !ok || - change.LastSeen.After(existingLastSeen) { - acceptedDiscoUpdates = append(acceptedDiscoUpdates, change) - } - } - - resp.PeersChangedPatch = acceptedDiscoUpdates -} - -// removeUnwantedDiscoUpdatesFromFullNetmapUpdate makes a pass over the full -// set of peers in an update, usually only received when getting a full netmap -// from control at startup. If the pass finds a peer with a disco key where the -// local netmap has a newer key learned via TSMP, overwrite the update with the -// key from TSMP. -func (ms *mapSession) removeUnwantedDiscoUpdatesFromFullNetmapUpdate(resp *tailcfg.MapResponse) { - ms.peersMu.RLock() - defer ms.peersMu.RUnlock() - - if len(resp.Peers) == 0 { - return - } - for _, peer := range resp.Peers { - if peer.DiscoKey.IsZero() { - continue - } - - // Accept if: - // - peer is new - existingNode, ok := ms.peers[peer.ID] - if !ok { - continue - } - - // Accept if: - // - disco key has not changed - if existingNode.DiscoKey() == peer.DiscoKey { - continue - } - - // Accept if: - // - key has changed but peer is online - if peer.Online != nil && *peer.Online { - continue - } - - // Accept if: - // - there's no last seen on the existing node - existingLastSeen, ok := existingNode.LastSeen().GetOk() - if !ok { - continue - } - - // Accept if: - // - last seen on on control is higher - if peer.LastSeen != nil && peer.LastSeen.After(existingLastSeen) { - continue - } - - // Overwrite the key and last seen in the full netmap update. - peer.DiscoKey = existingNode.DiscoKey() - if t, ok := existingNode.LastSeen().GetOk(); ok { - peer.LastSeen = new(t) - } else { - peer.LastSeen = nil - } - } -} - // updateStateFromResponse updates ms from res. It takes ownership of res. func (ms *mapSession) updateStateFromResponse(resp *tailcfg.MapResponse) { ms.updatePeersStateFromResponse(resp) diff --git a/control/controlclient/map_test.go b/control/controlclient/map_test.go index 262e97f5f..4d5d18a8b 100644 --- a/control/controlclient/map_test.go +++ b/control/controlclient/map_test.go @@ -14,7 +14,6 @@ import ( "strings" "sync/atomic" "testing" - "testing/synctest" "time" "github.com/google/go-cmp/cmp" @@ -625,426 +624,6 @@ func TestNetmapForResponse(t *testing.T) { }) } -func TestUpdateDiscoForNode(t *testing.T) { - tests := []struct { - name string - initialOnline bool - initialLastSeen time.Time - updateDiscoKey func() key.DiscoPublic - updateOnline bool - updateLastSeen time.Time - wantUpdate bool - wantKeyChanged bool - }{ - { - name: "newer_key_not_online", - initialOnline: true, - initialLastSeen: time.Unix(1, 0), - updateDiscoKey: key.NewDisco().Public, - updateOnline: false, - updateLastSeen: time.Now(), - wantUpdate: true, - wantKeyChanged: true, - }, - { - name: "newer_key_online", - initialOnline: true, - initialLastSeen: time.Unix(1, 0), - updateDiscoKey: key.NewDisco().Public, - updateOnline: true, - updateLastSeen: time.Now(), - wantUpdate: true, - wantKeyChanged: true, - }, - { - name: "older_key_not_online", - initialOnline: false, - initialLastSeen: time.Now(), - updateDiscoKey: key.NewDisco().Public, - updateOnline: false, - updateLastSeen: time.Unix(1, 0), - wantUpdate: false, - wantKeyChanged: false, - }, - { - name: "older_key_online", - initialOnline: false, - initialLastSeen: time.Now(), - updateDiscoKey: key.NewDisco().Public, - updateOnline: true, - updateLastSeen: time.Unix(1, 0), - wantUpdate: true, - wantKeyChanged: true, - }, - { - name: "same_newer_key_not_online", - initialOnline: true, - initialLastSeen: time.Unix(1, 0), - updateDiscoKey: nil, - updateOnline: false, - updateLastSeen: time.Now(), - wantUpdate: false, - wantKeyChanged: false, - }, - { - name: "same_newer_key_online", - initialOnline: true, - initialLastSeen: time.Unix(1, 0), - updateDiscoKey: nil, - updateOnline: true, - updateLastSeen: time.Now(), - wantUpdate: false, - wantKeyChanged: false, - }, - { - name: "same_older_key_not_online", - initialOnline: false, - initialLastSeen: time.Now(), - updateDiscoKey: nil, - updateOnline: false, - updateLastSeen: time.Unix(1, 0), - wantUpdate: false, - wantKeyChanged: false, - }, - { - name: "same_older_key_online", - initialOnline: false, - initialLastSeen: time.Now(), - updateDiscoKey: nil, - updateOnline: true, - updateLastSeen: time.Unix(1, 0), - wantUpdate: true, - wantKeyChanged: false, - }, - { - name: "no_initial_last_seen", - initialOnline: false, - updateDiscoKey: key.NewDisco().Public, - updateOnline: false, - updateLastSeen: time.Now(), - wantUpdate: true, - wantKeyChanged: true, - }, - { - name: "zero_key", - initialOnline: false, - updateDiscoKey: func() key.DiscoPublic { - return key.DiscoPublic{} - }, - updateOnline: false, - updateLastSeen: time.Now(), - wantUpdate: false, - wantKeyChanged: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - synctest.Test(t, func(*testing.T) { - nu := &rememberLastNetmapUpdater{ - done: make(chan any, 1), - } - ms := newTestMapSession(t, nu) - defer ms.Close() - - oldKey := key.NewDisco() - - // Insert existing node - node := tailcfg.Node{ - ID: 1, - Key: key.NewNode().Public(), - DiscoKey: oldKey.Public(), - Online: &tt.initialOnline, - } - if !tt.initialLastSeen.IsZero() { - node.LastSeen = &tt.initialLastSeen - } - - if nm := ms.netmapForResponse(&tailcfg.MapResponse{ - Peers: []*tailcfg.Node{&node}, - }); len(nm.Peers) != 1 { - t.Fatalf("node not inserted") - } - - newKey := oldKey.Public() - if tt.updateDiscoKey != nil { - newKey = tt.updateDiscoKey() - } - ms.updateDiscoForNode(node.ID, node.Key, newKey, tt.updateLastSeen, tt.updateOnline) - - // We have an early escape that would not trigger the netmap updater. - synctest.Wait() - select { - case <-nu.done: - if !tt.wantUpdate { - t.Errorf("did not expect update, got: %v", nu.last) - } - default: - if tt.wantUpdate { - t.Errorf("expected update, did not get any") - } - } - - peer, ok := ms.peers[node.ID] - if !ok { - t.Fatal("node not found") - } - - keyChanged := peer.DiscoKey().Compare(oldKey.Public()) != 0 - if keyChanged != tt.wantKeyChanged { - t.Errorf("Disco key update: %t, wanted update: %t", keyChanged, tt.wantKeyChanged) - } - }) - }) - } -} - -func TestUpdateDiscoForNodeCallback(t *testing.T) { - t.Run("key_wired_through_to_updater", func(t *testing.T) { - nu := &rememberLastNetmapUpdater{ - done: make(chan any, 1), - } - ms := newTestMapSession(t, nu) - - oldKey := key.NewDisco() - - // Insert existing node - node := tailcfg.Node{ - ID: 1, - Key: key.NewNode().Public(), - DiscoKey: oldKey.Public(), - Online: new(false), - LastSeen: new(time.Unix(1, 0)), - } - - if nm := ms.netmapForResponse(&tailcfg.MapResponse{ - Peers: []*tailcfg.Node{&node}, - }); len(nm.Peers) != 1 { - t.Fatalf("node not inserted") - } - - newKey := key.NewDisco() - ms.updateDiscoForNode(node.ID, node.Key, newKey.Public(), time.Now(), false) - <-nu.done - - if nu.lastTSMPKey != node.Key || nu.lastTSMPDisco != newKey.Public() { - t.Fatalf("expected [%s]=%s, got [%s]=%s", node.Key, newKey.Public(), - nu.lastTSMPKey, nu.lastTSMPDisco) - } - }) - // Even though key stays in list of update, the updater only triggers on TSMP. - t.Run("key_not_wired_through_to_updater", func(t *testing.T) { - nu := &rememberLastNetmapUpdater{ - done: make(chan any, 1), - } - ms := newTestMapSession(t, nu) - - oldKey := key.NewDisco() - - // Insert existing node - node := tailcfg.Node{ - ID: 1, - Key: key.NewNode().Public(), - DiscoKey: oldKey.Public(), - Online: new(false), - LastSeen: new(time.Unix(1, 0)), - } - - if nm := ms.netmapForResponse(&tailcfg.MapResponse{ - Peers: []*tailcfg.Node{&node}, - }); len(nm.Peers) != 1 { - t.Fatalf("node not inserted") - } - - newKey := key.NewDisco().Public() - resp := &tailcfg.MapResponse{ - PeersChangedPatch: []*tailcfg.PeerChange{{ - NodeID: node.ID, - Key: &node.Key, - LastSeen: new(time.Now()), - Online: new(true), - DiscoKey: &newKey, - }}, - } - // Not TSMP Path, just regular injection path. - ms.HandleNonKeepAliveMapResponse(t.Context(), resp) - <-nu.done - - if !nu.lastTSMPKey.IsZero() || !nu.lastTSMPDisco.IsZero() { - t.Fatalf("expected zero keys, got [%s]=%s", - nu.lastTSMPKey, nu.lastTSMPDisco) - } - }) - - t.Run("test_deadlock", func(t *testing.T) { - nu := &rememberLastNetmapUpdater{ - done: make(chan any, 1), - } - ms := newTestMapSession(t, nu) - // Very barebones onDebug func that will let us exercise sleep command - // from control and potentially induce deadlocks. - ms.onDebug = func(ctx context.Context, d *tailcfg.Debug) error { - time.Sleep(time.Duration(d.SleepSeconds * float64(time.Second))) - return nil - } - - oldKey := key.NewDisco() - - // Insert existing node - node := tailcfg.Node{ - ID: 1, - Key: key.NewNode().Public(), - DiscoKey: oldKey.Public(), - Online: new(false), - LastSeen: new(time.Unix(1, 0)), - } - - if nm := ms.netmapForResponse(&tailcfg.MapResponse{ - Peers: []*tailcfg.Node{&node}, - }); len(nm.Peers) != 1 { - t.Fatalf("node not inserted") - } - - sleep1 := &tailcfg.MapResponse{ - Debug: &tailcfg.Debug{ - SleepSeconds: 1.0, - }, - } - ms.HandleNonKeepAliveMapResponse(t.Context(), sleep1) - - // Resembles the disco key advert subscriber running in a separate context. - go func() { - newKey := key.NewDisco() - ms.updateDiscoForNode(node.ID, node.Key, newKey.Public(), time.Now(), false) - }() - - ms.Close() - - <-nu.done - }) -} - -func TestUpdateDiscoForNodeCallbackWithFullNetmap(t *testing.T) { - now := time.Now() - oldTime := time.Unix(1, 0) - - tests := []struct { - name string - initialOnline bool - initialLastSeen time.Time - updateOnline bool - updateLastSeen time.Time - expectNewDisco bool - }{ - { - name: "disco-key-newer-lastSeen", - initialOnline: false, - initialLastSeen: oldTime, - updateOnline: false, - updateLastSeen: now, - expectNewDisco: true, - }, - { - name: "disco-key-older-lastSeen", - initialOnline: false, - initialLastSeen: now, - updateOnline: false, - updateLastSeen: oldTime, - expectNewDisco: false, - }, - { - name: "disco-key-newer-lastSeen-going-offline", - initialOnline: true, - initialLastSeen: oldTime, - updateOnline: false, - updateLastSeen: now, - expectNewDisco: true, - }, - { - name: "online-flip-newer-lastSeen", - initialOnline: false, - initialLastSeen: oldTime, - updateOnline: true, - updateLastSeen: now, - expectNewDisco: true, - }, - { - name: "local-lastseen-preserved-after-first-reconnect", - initialOnline: false, - initialLastSeen: now, - updateOnline: false, - updateLastSeen: now, - expectNewDisco: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - nu := &rememberLastNetmapUpdater{ - done: make(chan any, 1), - } - ms := newTestMapSession(t, nu) - - oldKey := key.NewDisco() - - // Initial node - node := tailcfg.Node{ - ID: 1, - Key: key.NewNode().Public(), - DiscoKey: oldKey.Public(), - Online: new(tt.initialOnline), - LastSeen: new(tt.initialLastSeen), - Name: "host.network.ts.net", - } - - if nm := ms.netmapForResponse(&tailcfg.MapResponse{ - Peers: []*tailcfg.Node{&node}, - }); len(nm.Peers) != 1 { - t.Fatalf("node not inserted") - } - - newKey := key.NewDisco() - - // Updated node - newNode := tailcfg.Node{ - ID: 1, - Key: node.Key, - DiscoKey: newKey.Public(), - Online: new(tt.updateOnline), - LastSeen: new(tt.updateLastSeen), - Name: "host.network.ts.net", - } - - ms.HandleNonKeepAliveMapResponse(t.Context(), &tailcfg.MapResponse{ - Node: &newNode, - Peers: []*tailcfg.Node{ - &newNode, - }, - }) - <-nu.done - - newMap := nu.last - if n := len(newMap.Peers); n != 1 { - t.Fatalf("netmap not right length, got %d, expected %d", n, 1) - } - - peer := newMap.Peers[0] - - expectedDisco := oldKey.Public() - if tt.expectNewDisco { - expectedDisco = newKey.Public() - } - - if peer.Key() != node.Key || peer.DiscoKey() != expectedDisco { - t.Fatalf("expected [%s]=%s, got [%s]=%s", - node.Key, expectedDisco, - peer.Key(), peer.DiscoKey(), - ) - } - }) - } -} - func first[T any](s []T) T { if len(s) == 0 { var zero T @@ -1355,7 +934,7 @@ func TestExistingPeerReplacementHandledIncrementally(t *testing.T) { if err := ms.handleNonKeepAliveMapResponse(ctx, &tailcfg.MapResponse{ Node: &tailcfg.Node{Name: "self.example.ts.net."}, Peers: []*tailcfg.Node{peer}, - }, false); err != nil { + }); err != nil { t.Fatal(err) } if got := nu.full.Load(); got != 1 { @@ -1366,7 +945,7 @@ func TestExistingPeerReplacementHandledIncrementally(t *testing.T) { replacement.AllowedIPs = append(replacement.AllowedIPs, netip.MustParsePrefix("100.64.0.2/32")) if err := ms.handleNonKeepAliveMapResponse(ctx, &tailcfg.MapResponse{ PeersChanged: []*tailcfg.Node{replacement}, - }, false); err != nil { + }); err != nil { t.Fatal(err) } if got := nu.full.Load(); got != 1 { @@ -2034,101 +1613,3 @@ func TestPeerIDAndKeyByTailscaleIP(t *testing.T) { } }) } - -func TestRemoveUnwantedDiscoUpdates(t *testing.T) { - tests := []struct { - name string - viaTSMP bool - existingOnline bool - sameKey bool - newerLastSeen bool - wantAccepted bool - }{ - { - name: "tsmp_online_peer_same_key", - viaTSMP: true, - existingOnline: true, - sameKey: true, - newerLastSeen: true, - wantAccepted: false, - }, - { - name: "not_tsmp_online_peer_same_key", - viaTSMP: false, - existingOnline: true, - sameKey: true, - newerLastSeen: true, - wantAccepted: true, - }, - { - name: "tsmp_offline_peer_same_key", - viaTSMP: true, - existingOnline: false, - sameKey: true, - newerLastSeen: true, - wantAccepted: true, - }, - { - name: "tsmp_online_peer_diff_key", - viaTSMP: true, - existingOnline: true, - sameKey: false, - newerLastSeen: true, - wantAccepted: true, - }, - { - name: "tsmp_online_peer_same_key_old_lastseen", - viaTSMP: true, - existingOnline: true, - sameKey: true, - newerLastSeen: false, - wantAccepted: false, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ms := newTestMapSession(t, &rememberLastNetmapUpdater{done: make(chan any, 1)}) - - existingKey := key.NewDisco().Public() - existingOnline := tt.existingOnline - initialLastSeen := time.Unix(1, 0) - - ms.updateStateFromResponse(&tailcfg.MapResponse{ - Peers: []*tailcfg.Node{{ - ID: 1, - Key: key.NewNode().Public(), - DiscoKey: existingKey, - Online: &existingOnline, - LastSeen: &initialLastSeen, - }}, - }) - - changeKey := existingKey - if !tt.sameKey { - changeKey = key.NewDisco().Public() - } - changeOnline := false // must be false to reach the new guard - updateLastSeen := time.Unix(2, 0) - if !tt.newerLastSeen { - updateLastSeen = time.Unix(0, 0) - } - - resp := &tailcfg.MapResponse{ - PeersChangedPatch: []*tailcfg.PeerChange{{ - NodeID: 1, - DiscoKey: &changeKey, - Online: &changeOnline, - LastSeen: &updateLastSeen, - }}, - } - - ms.removeUnwantedDiscoUpdates(resp, tt.viaTSMP) - - got := len(resp.PeersChangedPatch) > 0 - if got != tt.wantAccepted { - t.Errorf("accepted=%v, want %v", got, tt.wantAccepted) - } - }) - } -} diff --git a/ipn/ipnlocal/local.go b/ipn/ipnlocal/local.go index 2a3cd987a..5ad9ab027 100644 --- a/ipn/ipnlocal/local.go +++ b/ipn/ipnlocal/local.go @@ -2126,13 +2126,6 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c b.authReconfigLocked() } -// PatchDiscoKey records that a peer's new disco key was learned via TSMP, -// so the netmap update carrying the same change need not reset the peer's -// WireGuard session. It implements [controlclient.DiscoKeyUpdater]. -func (b *LocalBackend) PatchDiscoKey(pub key.NodePublic, disco key.DiscoPublic) { - b.currentNode().recordTSMPLearnedDisco(pub, disco) -} - type preferencePolicyInfo struct { key pkey.Key get func(ipn.PrefsView) bool @@ -2413,7 +2406,6 @@ var ( _ controlclient.NetmapDeltaUpdater = (*LocalBackend)(nil) _ controlclient.PacketFilterUpdater = (*LocalBackend)(nil) _ controlclient.UserProfileUpdater = (*LocalBackend)(nil) - _ controlclient.DiscoKeyUpdater = (*LocalBackend)(nil) ) // UpdateNetmapDelta implements controlclient.NetmapDeltaUpdater. @@ -2494,11 +2486,11 @@ func (b *LocalBackend) UpdateNetmapDelta(muts []netmap.NodeMutation) (handled bo } b.setDataPlanePeerRoutes() - // Reset the WireGuard session for peers whose disco key changed in - // a way that indicates a restart, flushing their dead session keys; - // each such peer is lazily re-created on demand with current state. + // Mark the WireGuard session for an opportunistic handshake for peers whose + // disco key changed in a way that indicates a restart, flushing their dead + // session keys; or control catching up to a TSMP learned key. for k := range deltaRes.DiscoChanged { - b.e.ResetDevicePeer(k) + b.e.MarkDevicePeerForHandshake(k) } // Force a full authReconfig + SetSelfNode on any peer add or @@ -7326,7 +7318,7 @@ func (b *LocalBackend) setNetMapLocked(nm *netmap.NetworkMap) { // a way that indicates a restart, flushing their dead session keys; // each such peer is lazily re-created on demand with current state. for _, k := range discoChanged { - b.e.ResetDevicePeer(k) + b.e.MarkDevicePeerForHandshake(k) } // Converge the wireguard-go device for peers whose routes changed // (or that were removed) in the full-netmap resync above; peers not @@ -9186,11 +9178,6 @@ var ( metricNetmapDeltaPeerPatched = clientmetric.NewCounter("localbackend_netmap_delta_peer_patched") metricUpdatePacketFilter = clientmetric.NewCounter("localbackend_update_packet_filter") metricUpdateUserProfiles = clientmetric.NewCounter("localbackend_update_user_profiles") - - // metricTSMPLearnedKeyMismatch counts netmap updates carrying a peer - // disco key that doesn't match the one previously learned via TSMP - // for the same peer. See [nodeBackend.discoChangedLocked]. - metricTSMPLearnedKeyMismatch = clientmetric.NewCounter("magicsock_tsmp_learned_key_mismatch") ) func (b *LocalBackend) stateEncrypted() opt.Bool { diff --git a/ipn/ipnlocal/node_backend.go b/ipn/ipnlocal/node_backend.go index 3c91a391b..27b676a06 100644 --- a/ipn/ipnlocal/node_backend.go +++ b/ipn/ipnlocal/node_backend.go @@ -170,14 +170,6 @@ type nodeBackend struct { // nil in production, where no test installs a waiter. keyWaitersForTest map[key.NodePublic]chan struct{} - // tsmpLearnedDisco records, per node key, a peer disco key that was - // learned via TSMP (that is, over an existing WireGuard session with - // that peer). When a netmap update later reports the same disco key - // change, the peer's WireGuard session does not need to be reset, - // because the change demonstrably arrived over a working session. - // See [nodeBackend.discoChangedLocked]. - tsmpLearnedDisco map[key.NodePublic]key.DiscoPublic - // routeMgr tracks this node's view of which IPs route to which // peers and publishes lock-free snapshots for the data plane and // the OS router. It is initialized once and immutable, but its @@ -881,16 +873,10 @@ func (nb *nodeBackend) updatePeersLocked() (discoChanged []key.NodePublic, route } for _, p := range nb.peers { - if prev, ok := prevDisco[p.Key()]; ok && nb.discoChangedLocked(p.Key(), prev, p.DiscoKey()) { + if prev, ok := prevDisco[p.Key()]; ok && nb.discoChanged(p.Key(), prev, p.DiscoKey()) { discoChanged = append(discoChanged, p.Key()) } } - // Drop TSMP-learned disco keys for peers no longer in the netmap. - for k := range nb.tsmpLearnedDisco { - if _, ok := nb.nodeByKey[k]; !ok { - delete(nb.tsmpLearnedDisco, k) - } - } // Resync the route manager to the new peer set. Upserts of // unchanged peers are cheap no-ops; this is a full-netmap event, @@ -908,47 +894,17 @@ func (nb *nodeBackend) updatePeersLocked() (discoChanged []key.NodePublic, route return discoChanged, res.AllowedIPs } -// recordTSMPLearnedDisco notes that a peer's new disco key was learned via -// TSMP, so the netmap update carrying the same change need not reset the -// peer's WireGuard session. See the [nodeBackend.tsmpLearnedDisco] field doc. -func (nb *nodeBackend) recordTSMPLearnedDisco(pub key.NodePublic, disco key.DiscoPublic) { - nb.mu.Lock() - defer nb.mu.Unlock() - mak.Set(&nb.tsmpLearnedDisco, pub, disco) -} - -// discoChangedLocked reports whether a peer's disco key change from prev to -// cur should reset the peer's WireGuard session. A changed disco key means -// the peer restarted, so any existing session key material is dead weight; -// resetting lets the handshake start over immediately. The exception is a -// key change already learned via TSMP: that arrived over a working WireGuard -// session with the peer, so the session is demonstrably fine and is kept. -// -// It consumes any [nodeBackend.tsmpLearnedDisco] entry for pub. -// nb.mu must be held. -func (nb *nodeBackend) discoChangedLocked(pub key.NodePublic, prev, cur key.DiscoPublic) bool { - if prev.IsZero() || cur.IsZero() || prev == cur { +// discoChanged reports whether a peer's disco key change from prev to +// cur should trigger an opportunistic handshake the peer's WireGuard session. +// A changed disco key means the peer restarted, or that control caught up with +// the TSMP learned key material, so any existing session key material is +// possibly dead weight. Sending an opportunistic handshake lets the connection +// recover faster in the case where the peer restarted. +func (nb *nodeBackend) discoChanged(pub key.NodePublic, prev, cur key.DiscoPublic) bool { + if cur.IsZero() || prev == cur { return false } - if discoTSMP, ok := nb.tsmpLearnedDisco[pub]; ok { - delete(nb.tsmpLearnedDisco, pub) - if discoTSMP == cur { - nb.logf("nodeBackend: skipping WireGuard session reset (TSMP key): %s changed from %q to %q", - pub.ShortString(), prev, cur) - return false - } - // The new disco key does not match what we received via - // TSMP for this peer. This is unexpected, though possible - // if processing a change in a large netmap ends up taking - // longer than the 2 second timeout in - // [controlclient.mapRoutineState.UpdateNetmapDelta], or if - // the context is cancelled mid update. Log the event, and reset - // the session as it is possibly a stale entry in the map - // instead of a TSMP disco key update that led us here. - nb.logf("nodeBackend: [unexpected] using TSMP key for %s (control stale): tsmp=%q control=%q old=%q", - pub.ShortString(), discoTSMP, cur, prev) - metricTSMPLearnedKeyMismatch.Add(1) - } + nb.logf("nodeBackend: peer %s disco key changed from %q to %q", pub.ShortString(), prev, cur) return true } @@ -1076,7 +1032,7 @@ type netmapDeltaResult struct { // DiscoChanged is the set of peers whose disco key changed in a // way that requires a WireGuard session reset (see - // [nodeBackend.discoChangedLocked]). + // [nodeBackend.discoChanged]). DiscoChanged set.Set[key.NodePublic] // RemovedPeers is a slice of peer stable node IDs (if any) that were @@ -1115,12 +1071,10 @@ func (nb *nodeBackend) UpdateNetmapDelta(muts []netmap.NodeMutation) (res netmap nid := m.Node.ID() if old, ok := nb.peers[nid]; ok { if old.Key() == m.Node.Key() { - if nb.discoChangedLocked(m.Node.Key(), old.DiscoKey(), m.Node.DiscoKey()) { + if nb.discoChanged(m.Node.Key(), old.DiscoKey(), m.Node.DiscoKey()) { res.DiscoChanged.Make() res.DiscoChanged.Add(m.Node.Key()) } - } else { - delete(nb.tsmpLearnedDisco, old.Key()) } // Evict index entries derived from the old node value // before re-adding them from the new one below, so a @@ -1162,7 +1116,6 @@ func (nb *nodeBackend) UpdateNetmapDelta(muts []netmap.NodeMutation) (res netmap delete(nb.nodeByKey, old.Key()) delete(nb.nodeByWGString, old.Key().WireGuardGoString()) delete(nb.nodeByStableID, old.StableID()) - delete(nb.tsmpLearnedDisco, old.Key()) nb.removeNodeNameLocked(old.Name()) delete(nb.peers, nid) rt.RemovePeer(nid) diff --git a/ipn/ipnlocal/node_backend_test.go b/ipn/ipnlocal/node_backend_test.go index bed8ab8c2..9453b4c4c 100644 --- a/ipn/ipnlocal/node_backend_test.go +++ b/ipn/ipnlocal/node_backend_test.go @@ -372,8 +372,7 @@ func TestNodeBackendRouteManager(t *testing.T) { // TestNodeBackendDiscoChanged exercises the full-netmap disco change // detection: a peer whose disco key changes has restarted and needs its -// WireGuard session reset, unless the new key was already learned over -// TSMP (that is, over a working WireGuard session with the peer). +// WireGuard session to send an opportunistic handshake. func TestNodeBackendDiscoChanged(t *testing.T) { nb := newNodeBackend(t.Context(), tstest.WhileTestRunningLogger(t), eventbus.New()) @@ -406,41 +405,6 @@ func TestNodeBackendDiscoChanged(t *testing.T) { t.Errorf("SetNetMap(same disco) discoChanged = %v; want none", got) } - // A change already learned via TSMP is suppressed... - d3 := newDisco() - nb.recordTSMPLearnedDisco(nk, d3) - if got, _ := nb.SetNetMap(mkNetMap(d3)); len(got) != 0 { - t.Errorf("SetNetMap(TSMP-learned disco) discoChanged = %v; want none", got) - } - - // ...but the TSMP entry is consumed, so the next change resets again. - d4 := newDisco() - if got, _ := nb.SetNetMap(mkNetMap(d4)); !slices.Contains(got, nk) { - t.Errorf("SetNetMap(after TSMP entry consumed) discoChanged = %v; want %v", got, nk) - } - - // A TSMP-learned key that doesn't match the netmap's new key still - // resets the session and bumps the mismatch metric. - before := metricTSMPLearnedKeyMismatch.Value() - nb.recordTSMPLearnedDisco(nk, newDisco()) - d5 := newDisco() - if got, _ := nb.SetNetMap(mkNetMap(d5)); !slices.Contains(got, nk) { - t.Errorf("SetNetMap(TSMP mismatch) discoChanged = %v; want %v", got, nk) - } - if delta := metricTSMPLearnedKeyMismatch.Value() - before; delta != 1 { - t.Errorf("metricTSMPLearnedKeyMismatch delta = %d; want 1", delta) - } - - // Removing the peer garbage-collects its TSMP entry: after the peer - // comes back, a change to the once-recorded key is a normal reset. - d6 := newDisco() - nb.recordTSMPLearnedDisco(nk, d6) - nb.SetNetMap(&netmap.NetworkMap{}) - nb.SetNetMap(mkNetMap(d5)) - if got, _ := nb.SetNetMap(mkNetMap(d6)); !slices.Contains(got, nk) { - t.Errorf("SetNetMap(after TSMP entry GC) discoChanged = %v; want %v", got, nk) - } - // Transitions to or from a zero disco key never reset. if got, _ := nb.SetNetMap(mkNetMap(key.DiscoPublic{})); len(got) != 0 { t.Errorf("SetNetMap(to zero disco) discoChanged = %v; want none", got) @@ -484,29 +448,12 @@ func TestNodeBackendDiscoChangedDelta(t *testing.T) { t.Errorf("upsert(same disco) discoChanged = %v; want none", got) } - // A change already learned via TSMP is suppressed. - d3 := newDisco() - nb.recordTSMPLearnedDisco(nk, d3) - if got := apply(netmap.NodeMutationUpsert{Node: mkNode(nk, d3)}); len(got) != 0 { - t.Errorf("upsert(TSMP-learned disco) discoChanged = %v; want none", got) - } - // A node key rotation replaces the WireGuard peer outright, so no // disco-based reset is reported. nk2 := key.NewNode().Public() if got := apply(netmap.NodeMutationUpsert{Node: mkNode(nk2, newDisco())}); len(got) != 0 { t.Errorf("upsert(rotated node key) discoChanged = %v; want none", got) } - - // Removing the peer garbage-collects its TSMP entry: after the peer - // comes back, a change to the once-recorded key is a normal reset. - d4 := newDisco() - nb.recordTSMPLearnedDisco(nk2, d4) - apply(netmap.MakeNodeMutationRemove(1)) - apply(netmap.NodeMutationUpsert{Node: mkNode(nk2, newDisco())}) - if got := apply(netmap.NodeMutationUpsert{Node: mkNode(nk2, d4)}); !got.Contains(nk2) { - t.Errorf("upsert(after TSMP entry GC) discoChanged = %v; want %v", got, nk2) - } } func TestNodeBackendRouteManagerExtras(t *testing.T) { diff --git a/ipn/ipnlocal/state_test.go b/ipn/ipnlocal/state_test.go index 00442872d..dfd5b1c80 100644 --- a/ipn/ipnlocal/state_test.go +++ b/ipn/ipnlocal/state_test.go @@ -2010,7 +2010,7 @@ func (e *mockEngine) PeerAllowedIPs(k key.NodePublic) (_ []netip.Prefix, ok bool } func (e *mockEngine) SyncDevicePeer(key.NodePublic) {} -func (e *mockEngine) ResetDevicePeer(key.NodePublic) {} +func (e *mockEngine) MarkDevicePeerForHandshake(key.NodePublic) {} func (e *mockEngine) SetPeerSessionStateFunc(func(key.NodePublic, wgengine.PeerWireGuardState)) { } func (e *mockEngine) SetNetLogSource(wgengine.NetLogSource) {} diff --git a/tsnet/depaware.txt b/tsnet/depaware.txt index 2cb951175..bebbb4282 100644 --- a/tsnet/depaware.txt +++ b/tsnet/depaware.txt @@ -240,7 +240,7 @@ tailscale.com/tsnet dependencies: (generated by github.com/tailscale/depaware) tailscale.com/types/bools from tailscale.com/tsnet+ tailscale.com/types/dnstype from tailscale.com/client/local+ tailscale.com/types/empty from tailscale.com/ipn+ - tailscale.com/types/events from tailscale.com/control/controlclient+ + tailscale.com/types/events from tailscale.com/net/tstun+ tailscale.com/types/ipproto from tailscale.com/ipn+ tailscale.com/types/key from tailscale.com/client/local+ tailscale.com/types/lazy from tailscale.com/hostinfo+ diff --git a/types/events/disco_update.go b/types/events/disco_update.go index 206c554a1..fa2a4b88d 100644 --- a/types/events/disco_update.go +++ b/types/events/disco_update.go @@ -20,11 +20,3 @@ type DiscoKeyAdvertisement struct { Src netip.Addr // Src field is populated by the IP header of the packet, not from the payload itself. Key key.DiscoPublic } - -// PeerDiscoKeyUpdate is an event sent on the [eventbus.Bus] when -// [controlclient.Direct] deems that it cannot handle the key update. -// -// Its publisher is [controlclient.Direct]; its main subscriber is -// [wgengine.userspaceengine], that injects the received key into its -// [magicsock.Conn] in order to set up the key directly. -type PeerDiscoKeyUpdate DiscoKeyAdvertisement diff --git a/wgengine/magicsock/endpoint.go b/wgengine/magicsock/endpoint.go index 14d5c2503..bca0dc136 100644 --- a/wgengine/magicsock/endpoint.go +++ b/wgengine/magicsock/endpoint.go @@ -1553,12 +1553,11 @@ func (de *endpoint) updateDiscoKey(key key.DiscoPublic) bool { if old != nil { epDisco.tsmpKey = old.tsmpKey epDisco.tsmpShort = old.tsmpShort - epDisco.tsmpActive = key.IsZero() + epDisco.tsmpActive = old.tsmpActive || key.IsZero() } if !key.IsZero() { epDisco.controlKey = key epDisco.controlShort = key.ShortString() - epDisco.tsmpActive = false // TODO(cmol): Set conditional when routing TSMP through magicsock. } // We have no key material, nil out key. if epDisco.controlKey.IsZero() && epDisco.tsmpKey.IsZero() { diff --git a/wgengine/magicsock/endpoint_test.go b/wgengine/magicsock/endpoint_test.go index 2d2b44a59..10c3c10d4 100644 --- a/wgengine/magicsock/endpoint_test.go +++ b/wgengine/magicsock/endpoint_test.go @@ -801,7 +801,6 @@ func Test_endpoint_handlePongConnLocked(t *testing.T) { // TestUpdateFromNodeUsesControlKeyForComparison verifies that updateFromNode // compares the netmap-provided disco key against the endpoint's control-learned // key (keyFromControl), not the currently active key (key()). -// Some of this is scaffold for later changes. func TestUpdateFromNodeUsesControlKeyForComparison(t *testing.T) { dk1 := key.NewDisco().Public() // initial control key dk2 := key.NewDisco().Public() // TSMP key @@ -818,7 +817,7 @@ func TestUpdateFromNodeUsesControlKeyForComparison(t *testing.T) { netmapDiscoKey: dk2, wantControlKey: dk2, wantActiveKey: dk2, - wantTsmpActive: false, + wantTsmpActive: true, }, { name: "unchanged_netmap_key_preserves_active", @@ -1041,7 +1040,7 @@ func TestUpdateDiscoKey(t *testing.T) { }, newKey: dk3, wantChanged: true, - wantActiveKey: dk3, + wantActiveKey: dk2, }, { name: "control-key-cleared-tsmp-present", diff --git a/wgengine/userspace.go b/wgengine/userspace.go index c7cb29539..47467e7b4 100644 --- a/wgengine/userspace.go +++ b/wgengine/userspace.go @@ -595,7 +595,7 @@ func NewUserspaceEngine(logf logger.Logf, conf Config) (_ Engine, reterr error) } e.linkChangeQueue.Add(func() { e.linkChange(&cd) }) }) - eventbus.SubscribeFunc(ec, func(update events.PeerDiscoKeyUpdate) { + eventbus.SubscribeFunc(ec, func(update events.DiscoKeyAdvertisement) { e.logf("[v1] wgengine: got TSMP disco key advertisement from %v via eventbus", update.Src) if e.magicConn == nil { e.logf("wgengine: no magicConn") @@ -705,12 +705,12 @@ func (e *userspaceEngine) SyncDevicePeer(k key.NodePublic) { } } -// ResetDevicePeer implements [Engine.ResetDevicePeer]. -func (e *userspaceEngine) ResetDevicePeer(k key.NodePublic) { +// MarkDevicePeerForHandshake implements [Engine.MarkDevicePeerForHandshake]. +func (e *userspaceEngine) MarkDevicePeerForHandshake(k key.NodePublic) { e.wgLock.Lock() defer e.wgLock.Unlock() e.wgLogger.Invalidate() - e.wgdev.RemovePeer(k.Raw32()) + e.wgdev.ScheduleHandshakeOnUserSend(k.Raw32()) } // SetPeerByIPPacketFunc installs a callback used by wireguard-go to look up diff --git a/wgengine/wgengine.go b/wgengine/wgengine.go index ff5b9dabe..48e016068 100644 --- a/wgengine/wgengine.go +++ b/wgengine/wgengine.go @@ -211,15 +211,13 @@ type Engine interface { // It is a no-op if no config source is installed. SyncDevicePeer(key.NodePublic) - // ResetDevicePeer removes the peer from the WireGuard device, - // discarding any session key material and in-flight handshake - // state. If the peer is still known to the config source installed - // via [Engine.SetPeerConfigFunc], it is lazily re-created on demand - // with fresh state. + // MarkDevicePeerForHandshake marks the peer for an opportunistic handshake in the + // WireGuard device. // // LocalBackend calls it when a peer's disco key changes, which - // means the peer restarted and its old sessions are dead. - ResetDevicePeer(key.NodePublic) + // means the peer restarted and its old sessions are dead, or that control + // caught up to a key learned via TSMP previously. + MarkDevicePeerForHandshake(key.NodePublic) // SetNetLogSource installs the [NetLogSource] consulted by the // engine's network flow logger for node lookups and the current