From 34c7539a082541a9c8ea75247edc833dfdde4be7 Mon Sep 17 00:00:00 2001 From: Brad Fitzpatrick Date: Thu, 3 Dec 2026 13:09:24 +0000 Subject: [PATCH] ipn/ipnlocal: clean up b.mu handling around TKA RPCs setControlClientStatusLocked dropped b.mu mid-function for TKA sync RPCs and then kept using state computed before the unlock, including for its startLocked and handleNetmapExpiry callers that assume b.mu is held throughout. Split it into two locked halves that share one ipn.Notify. Only SetControlClientStatus unlocks between them, and only when TKA actually needs a sync. Also make the TKA sync abandon its work if b.tka or the profile changes while b.mu is released for an RPC. Likewise, TailnetLockModify and TailnetLockSubmitRecoveryAUM now do their RPCs outside the locked section, and TailnetLockAffectedSigs no longer verifies control's response against a different profile's authority. Add a test for TailnetLockModify, which had none. This is prep for moving more of Tailnet Lock into its ./feature/tailnetlock directory. Updates #12614 Change-Id: I59f7cffc26877afe15cb0f0a6103ff943d9af74a Signed-off-by: Brad Fitzpatrick --- ipn/ipnlocal/local.go | 186 ++++++++++++++++--------- ipn/ipnlocal/tailnet-lock.go | 198 ++++++++++++++++----------- ipn/ipnlocal/tailnet-lock_test.go | 56 ++++++++ ipn/ipnlocal/tailnetlock_disabled.go | 2 + 4 files changed, 297 insertions(+), 145 deletions(-) diff --git a/ipn/ipnlocal/local.go b/ipn/ipnlocal/local.go index 7da78e7c1..34d361134 100644 --- a/ipn/ipnlocal/local.go +++ b/ipn/ipnlocal/local.go @@ -1916,8 +1916,35 @@ func (b *LocalBackend) SetControlClientStatus(c controlclient.Client, st control return } b.mu.Lock() - defer b.mu.Unlock() - b.setControlClientStatusLocked(c, st) + var notify ipn.Notify + prefs, ok := b.setControlClientStatusPrefsLocked(c, st, ¬ify) + if !ok { + b.mu.Unlock() + return + } + if st.NetMap != nil && b.tkaNeedsSyncLocked(st.NetMap) { + // TKA sync does network RPCs, which must not be done while + // holding b.mu. Nothing computed above carries across this + // unlock except notify; [LocalBackend.setControlClientStatusNetmapLocked] + // starts fresh from the current state. + // + // TODO(bradfitz): when TKA moves to feature/tailnetlock, replace + // this with an ipnext hook called without b.mu, taking narrow + // inputs (TKA enabled, TKA head, node key) rather than the netmap. + b.mu.Unlock() + if err := b.tkaSyncIfNeeded(st.NetMap, prefs); err != nil { + // The netmap is still applied below. If the sync failed or was + // abandoned (such as with [errTKAStateChanged] after a + // concurrent TailnetLockForceLocalDisable), the netmap is + // still the latest one from control for this profile, and it + // is filtered against whatever b.tka is now. A profile switch + // or logout replaces b.cc, which the netmap half checks. + b.logf("[v1] TKA sync error: %v", err) + } + b.mu.Lock() + } + b.setControlClientStatusNetmapLocked(c, st, ¬ify) + b.mu.Unlock() } // nodeRemovedWarnable is set while control says this node has been deleted. @@ -1944,18 +1971,39 @@ func (b *LocalBackend) setNodeRemovedLocked(removed bool) { } } -// setControlClientStatusLocked is the locked version of SetControlClientStatus. +// setControlClientStatusLocked is like [LocalBackend.SetControlClientStatus] +// but never releases b.mu, so it does not sync TKA state with control. +// It is used for statuses that don't come from a live map poll: a cached +// netmap loaded at startup and netmap expiry re-runs. // // b.mu must be held. func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st controlclient.Status) { + var notify ipn.Notify + if _, ok := b.setControlClientStatusPrefsLocked(c, st, ¬ify); ok { + b.setControlClientStatusNetmapLocked(c, st, ¬ify) + } +} + +// setControlClientStatusPrefsLocked is the first half of handling a status +// update from the control client. It handles errors, key expiry, auth state +// and prefs updates, and it initializes TKA state for the (possibly new) +// current profile. Changes for the IPN bus are recorded in notify, which +// [LocalBackend.setControlClientStatusNetmapLocked] sends. +// +// It reports whether the caller should proceed with +// [LocalBackend.setControlClientStatusNetmapLocked], along with the prefs to +// use for TKA sync. If not, notify is left zero. +// +// b.mu must be held. +func (b *LocalBackend) setControlClientStatusPrefsLocked(c controlclient.Client, st controlclient.Status, notify *ipn.Notify) (_ ipn.PrefsView, ok bool) { if b.cc != c { b.logf("Ignoring SetControlClientStatus from old client") - return + return ipn.PrefsView{}, false } if st.Err != nil { if errors.Is(st.Err, io.EOF) { b.logf("[v1] Received error: EOF") - return + return ipn.PrefsView{}, false } b.logf("Received error: %v", st.Err) if vizerr, ok := vizerror.As(st.Err); ok { @@ -1966,29 +2014,9 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c b.setNodeRemovedLocked(true) b.stateMachineLocked() } - return + return ipn.PrefsView{}, false } - 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) @@ -2023,16 +2051,6 @@ func (b *LocalBackend) applyControlClientStatusLocked(c controlclient.Client, st } } - // 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 @@ -2106,7 +2124,7 @@ func (b *LocalBackend) applyControlClientStatusLocked(c controlclient.Client, st // 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, ¬ify) { + if b.reconcilePrefsLocked(prefs, notify) { prefsChanged = true } @@ -2131,33 +2149,59 @@ func (b *LocalBackend) applyControlClientStatusLocked(c controlclient.Client, st }); err != nil { b.logf("Failed to save new controlclient state: %v", err) } + // The second half sends the prefs in effect at that point, + // which may differ from these by then. + notify.Prefs = new(prefs.View()) } // initTKALocked is dependent on CurrentProfile.ID, which is initialized // (for new profiles) on the first call to b.pm.SetPrefs. + // + // TODO(bradfitz): in feature/tailnetlock, do this from the extension's + // ProfileStateChange hook instead. if err := b.initTKALocked(); err != nil { b.logf("initTKALocked: %v", err) } - - // Perform all reconfiguration based on the netmap here. if st.NetMap != nil { b.capTailnetLock = st.NetMap.HasCap(nodecap.TailnetLock) b.setWebClientAtomicBoolLocked(st.NetMap.AllCaps) + } + return prefs.View(), true +} - b.mu.Unlock() // respect locking rules for tkaSyncIfNeeded - if err := b.tkaSyncIfNeeded(st.NetMap, prefs.View()); err != nil { - b.logf("[v1] TKA sync error: %v", err) - } - 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") - notify = ipn.Notify{} - return false - } +// setControlClientStatusNetmapLocked is the second half of handling a status +// update from the control client, run after +// [LocalBackend.setControlClientStatusPrefsLocked] and any TKA sync. It +// applies st.NetMap (if any), sends notify with everything this status +// changed, and runs the state machine. +// +// b.mu may have been released since the first half ran, so this reads the +// state it needs from b rather than having it passed in. +// +// b.mu must be held. +func (b *LocalBackend) setControlClientStatusNetmapLocked(c controlclient.Client, st controlclient.Status, notify *ipn.Notify) { + if b.cc != c { + // The client was replaced while b.mu was released. Every profile + // switch, logout, and profile reset goes through + // [LocalBackend.resetControlClientLocked], so this also catches an + // account change during TKA sync; don't apply the old account's + // netmap to the new profile. The Notify built so far is dropped. + // The replacing path has already sent its own prefs. + b.logf("Ignoring SetControlClientStatus from old client") + return + } + cn := b.currentNode() + prefs := b.pm.CurrentPrefs() + oldNetMap := cn.NetMap() + exitNodeChanged := false + + // Perform all reconfiguration based on the netmap here. + if st.NetMap != nil { // b.cc is nil for a cached netmap applied by startLocked. + // + // TODO(bradfitz): move this TKA head reporting and the netmap + // filtering below to feature/tailnetlock behind locked ipnext hooks + // that take peer views, not the netmap. if b.cc != nil { if b.tka != nil { head, err := b.tka.authority.Head().MarshalText() @@ -2181,13 +2225,12 @@ func (b *LocalBackend) applyControlClientStatusLocked(c controlclient.Client, st oldPeers = cn.Peers() } b.setNetMapLocked(st.NetMap) - b.updateFilterLocked(prefs.View()) + b.updateFilterLocked(prefs) 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 := prefs.AsStruct() prefs.WantRunning = false if err := b.pm.SetPrefs(prefs.View(), ipn.NetworkProfile{ MagicDNSName: st.NetMap.MagicDNSSuffix(), @@ -2198,7 +2241,8 @@ func (b *LocalBackend) applyControlClientStatusLocked(c controlclient.Client, st } notify.ErrMessage = &msg notify.Prefs = new(b.pm.CurrentPrefs()) - return false + b.sendLocked(*notify) + return } if oldNetMap != nil { diff := st.NetMap.ConciseDiffFrom(oldNetMap) @@ -2262,22 +2306,31 @@ func (b *LocalBackend) applyControlClientStatusLocked(c controlclient.Client, st // Recalculate the suggested exit node against the new netmap. A // changed suggestion is recorded in notify. - b.suggestExitNodeLocked(¬ify) + b.suggestExitNodeLocked(notify) // 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 - } + exitNodeChanged = b.refreshExitNodeLocked(notify) } - // 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 { + // If the first half or the exit node resolution above changed the + // prefs, send the ones in effect now. They may also have changed by an + // edit made while b.mu was released for TKA sync. + if notify.Prefs != nil || exitNodeChanged { notify.Prefs = new(b.pm.CurrentPrefs()) } - return true + if !notify.IsZero() { + b.sendLocked(*notify) + } + + 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() } // handleNetmapExpiry reruns netmap status handling when a node may have @@ -2629,6 +2682,9 @@ func (b *LocalBackend) UpdateNetmapDelta(muts []netmap.NodeMutation) (handled bo // such upsert into a NodeMutationRemove for the same node ID, so // any previously-signed peer at that ID is also evicted, matching // the full-netmap behavior of [tkaFilterNetmapLocked]. + // + // TODO(bradfitz): make this a feature/tailnetlock hook too, alongside + // the full-netmap filter. muts = b.tkaFilterDeltaMutsLocked(muts) needsAuthReconfig := netmapDeltaNeedsAuthReconfig(cn, muts) diff --git a/ipn/ipnlocal/tailnet-lock.go b/ipn/ipnlocal/tailnet-lock.go index f3f35a690..ecfd96ca4 100644 --- a/ipn/ipnlocal/tailnet-lock.go +++ b/ipn/ipnlocal/tailnet-lock.go @@ -337,6 +337,40 @@ func (r *rotationTracker) obsoleteKeys() set.Set[key.NodePublic] { return r.obsolete } +// tkaNeedsSyncLocked reports whether [LocalBackend.tkaSyncIfNeeded] has any +// work to do for nm, so callers can avoid releasing b.mu when it doesn't. +// +// b.mu must be held. +func (b *LocalBackend) tkaNeedsSyncLocked(nm *netmap.NetworkMap) bool { + if b.tka == nil { + return b.capTailnetLock && nm.TKAEnabled + } + return !nm.TKAEnabled || b.tka.authority.Head() != nm.TKAHead +} + +// errTKAStateChanged is returned by TKA sync when b.tka or the current +// profile changed while b.mu was released for an RPC to control. +var errTKAStateChanged = errors.New("TKA state or profile changed during sync") + +// tkaUnlockedRPC releases b.mu, calls rpc, and re-acquires b.mu. +// +// If b.tka or the current profile changed while b.mu was released, the +// result of rpc no longer applies to the local state, and tkaUnlockedRPC +// returns [errTKAStateChanged]. +// +// b.mu must be held. +func tkaUnlockedRPC[T any](b *LocalBackend, rpc func() (T, error)) (T, error) { + wantTKA, wantProfile := b.tka, b.pm.CurrentProfile().ID() + b.mu.Unlock() + res, err := rpc() + b.mu.Lock() + if b.tka != wantTKA || b.pm.CurrentProfile().ID() != wantProfile { + var zero T + return zero, errTKAStateChanged + } + return res, err +} + // tkaSyncIfNeeded examines TKA info reported from the control plane, // performing the steps necessary to synchronize local tka state. // @@ -352,8 +386,8 @@ func (r *rotationTracker) obsoleteKeys() set.Set[key.NodePublic] { // - Everything up to date: All other cases. // ∴ no action necessary. // -// tkaSyncIfNeeded immediately takes b.takeSyncLock which is held throughout, -// and may take b.mu as required. +// b.mu must not be held. tkaSyncIfNeeded takes b.tkaSyncLock, which is held +// throughout, and then b.mu, which is released only around RPCs to control. func (b *LocalBackend) tkaSyncIfNeeded(nm *netmap.NetworkMap, prefs ipn.PrefsView) error { b.tkaSyncLock.Lock() // take tkaSyncLock to make this function an exclusive section. defer b.tkaSyncLock.Unlock() @@ -389,9 +423,9 @@ func (b *LocalBackend) tkaSyncIfNeeded(nm *netmap.NetworkMap, prefs ipn.PrefsVie // Regardless of whether we are moving to disabled or enabled, we // need information from the tka bootstrap endpoint. - b.mu.Unlock() - bs, err := b.tkaFetchBootstrap(ourNodeKey, ourHead) - b.mu.Lock() + bs, err := tkaUnlockedRPC(b, func() (*tailcfg.TKABootstrapResponse, error) { + return b.tkaFetchBootstrap(ourNodeKey, ourHead) + }) if err != nil { return fmt.Errorf("fetching bootstrap: %w", err) } @@ -436,20 +470,20 @@ func (b *LocalBackend) tkaSyncIfNeeded(nm *netmap.NetworkMap, prefs ipn.PrefsVie return nil } -// tkaSyncLocked synchronizes TKA state with control. b.mu must be held -// and tka must be initialized. b.mu will be stepped out of (and back into) -// during network RPCs. +// tkaSyncLocked synchronizes TKA state with control. // -// b.mu must be held. +// b.mu must be held and b.tka must be non-nil. b.mu is released around RPCs +// to control. If b.tka or the current profile changes meanwhile, +// tkaSyncLocked returns [errTKAStateChanged] without touching the new state. func (b *LocalBackend) tkaSyncLocked(ourNodeKey key.NodePublic) error { offer, err := b.tka.authority.SyncOffer(b.tka.storage) if err != nil { return fmt.Errorf("offer: %w", err) } - b.mu.Unlock() - offerResp, err := b.tkaDoSyncOffer(ourNodeKey, offer) - b.mu.Lock() + offerResp, err := tkaUnlockedRPC(b, func() (*tailcfg.TKASyncOfferResponse, error) { + return b.tkaDoSyncOffer(ourNodeKey, offer) + }) if err != nil { return fmt.Errorf("offer RPC: %w", err) } @@ -492,9 +526,9 @@ func (b *LocalBackend) tkaSyncLocked(ourNodeKey key.NodePublic) error { // NOTE(tom): We always send this RPC so control knows what TKA // head we landed at. head := b.tka.authority.Head() - b.mu.Unlock() - sendResp, err := b.tkaDoSyncSend(ourNodeKey, head, toSendAUMs, false) - b.mu.Lock() + sendResp, err := tkaUnlockedRPC(b, func() (*tailcfg.TKASyncSendResponse, error) { + return b.tkaDoSyncSend(ourNodeKey, head, toSendAUMs, false) + }) if err != nil { return fmt.Errorf("send RPC: %v", err) } @@ -902,61 +936,15 @@ func (b *LocalBackend) TailnetLockModify(addKeys, removeKeys []tka.Key) (err err } }() - b.mu.Lock() - defer b.mu.Unlock() - - var ourNodeKey key.NodePublic - if p := b.pm.CurrentPrefs(); p.Valid() && p.Persist().Valid() && !p.Persist().PrivateNodeKey().IsZero() { - ourNodeKey = p.Persist().PublicNodeKey() - } - if ourNodeKey.IsZero() { - return errors.New("no node-key: is tailscale logged in?") - } - - var nlPriv key.TLPrivate - if p := b.pm.CurrentPrefs(); p.Valid() && p.Persist().Valid() { - nlPriv = p.Persist().NetworkLockKey() - } - if nlPriv.IsZero() { - return errMissingNetmap - } - if b.tka == nil { - return errTailnetLockNotActive - } - if !b.tka.authority.KeyTrusted(nlPriv.KeyID()) { - return errors.New("this node does not have a trusted tailnet lock key") - } - - updater := b.tka.authority.NewUpdater(nlPriv) - - for _, addKey := range addKeys { - if err := updater.AddKey(addKey); err != nil { - return err - } - } - for _, removeKey := range removeKeys { - keyID, err := removeKey.ID() - if err != nil { - return err - } - if err := updater.RemoveKey(keyID); err != nil { - return err - } - } - - aums, err := updater.Finalize(b.tka.storage) + ourNodeKey, head, aums, err := b.tkaModifyAUMs(addKeys, removeKeys) if err != nil { return err } - if len(aums) == 0 { return nil } - head := b.tka.authority.Head() - b.mu.Unlock() resp, err := b.tkaDoSyncSend(ourNodeKey, head, aums, true) - b.mu.Lock() if err != nil { return err } @@ -974,6 +962,60 @@ func (b *LocalBackend) TailnetLockModify(addKeys, removeKeys []tka.Key) (err err return nil } +// tkaModifyAUMs returns the AUMs that add addKeys and remove removeKeys, +// built on top of the local TKA head, along with that head and our node key. +// It doesn't change local TKA state; control applies the AUMs and the next +// sync brings them back to us. +func (b *LocalBackend) tkaModifyAUMs(addKeys, removeKeys []tka.Key) (key.NodePublic, tka.AUMHash, []tka.AUM, error) { + b.mu.Lock() + defer b.mu.Unlock() + + var ourNodeKey key.NodePublic + if p := b.pm.CurrentPrefs(); p.Valid() && p.Persist().Valid() && !p.Persist().PrivateNodeKey().IsZero() { + ourNodeKey = p.Persist().PublicNodeKey() + } + if ourNodeKey.IsZero() { + return key.NodePublic{}, tka.AUMHash{}, nil, errors.New("no node-key: is tailscale logged in?") + } + + var nlPriv key.TLPrivate + if p := b.pm.CurrentPrefs(); p.Valid() && p.Persist().Valid() { + nlPriv = p.Persist().NetworkLockKey() + } + if nlPriv.IsZero() { + return key.NodePublic{}, tka.AUMHash{}, nil, errMissingNetmap + } + if b.tka == nil { + return key.NodePublic{}, tka.AUMHash{}, nil, errTailnetLockNotActive + } + if !b.tka.authority.KeyTrusted(nlPriv.KeyID()) { + return key.NodePublic{}, tka.AUMHash{}, nil, errors.New("this node does not have a trusted tailnet lock key") + } + + updater := b.tka.authority.NewUpdater(nlPriv) + + for _, addKey := range addKeys { + if err := updater.AddKey(addKey); err != nil { + return key.NodePublic{}, tka.AUMHash{}, nil, err + } + } + for _, removeKey := range removeKeys { + keyID, err := removeKey.ID() + if err != nil { + return key.NodePublic{}, tka.AUMHash{}, nil, err + } + if err := updater.RemoveKey(keyID); err != nil { + return key.NodePublic{}, tka.AUMHash{}, nil, err + } + } + + aums, err := updater.Finalize(b.tka.storage) + if err != nil { + return key.NodePublic{}, tka.AUMHash{}, nil, err + } + return ourNodeKey, b.tka.authority.Head(), aums, nil +} + // Deprecated: use [LocalBackend.TailnetLockModify] instead. func (b *LocalBackend) NetworkLockModify(addKeys, removeKeys []tka.Key) (err error) { return b.TailnetLockModify(addKeys, removeKeys) @@ -1061,20 +1103,15 @@ func (b *LocalBackend) NetworkLockLog(maxEntries int) ([]ipnstate.TailnetLockUpd // TailnetLockAffectedSigs returns the signatures which would be invalidated // by removing trust in the specified KeyID. func (b *LocalBackend) TailnetLockAffectedSigs(keyID tkatype.KeyID) ([]tkatype.MarshaledSignature, error) { - var ( - ourNodeKey key.NodePublic - err error - ) + var ourNodeKey key.NodePublic b.mu.Lock() if p := b.pm.CurrentPrefs(); p.Valid() && p.Persist().Valid() && !p.Persist().PrivateNodeKey().IsZero() { ourNodeKey = p.Persist().PublicNodeKey() } - if b.tka == nil { - err = errTailnetLockNotActive - } + wantTKA := b.tka b.mu.Unlock() - if err != nil { - return nil, err + if wantTKA == nil { + return nil, errTailnetLockNotActive } resp, err := b.tkaReadAffectedSigs(ourNodeKey, keyID) @@ -1084,8 +1121,10 @@ func (b *LocalBackend) TailnetLockAffectedSigs(keyID tkatype.KeyID) ([]tkatype.M b.mu.Lock() defer b.mu.Unlock() - if b.tka == nil { - return nil, errTailnetLockNotActive + // A profile switch or local disable replaces b.tka, so a different + // pointer means resp was for some other authority. + if b.tka != wantTKA { + return nil, errTKAStateChanged } // Confirm for ourselves tha the signatures would actually be invalidated @@ -1200,21 +1239,20 @@ func (b *LocalBackend) NetworkLockCosignRecoveryAUM(aum *tka.AUM) (*tka.AUM, err func (b *LocalBackend) TailnetLockSubmitRecoveryAUM(aum *tka.AUM) error { b.mu.Lock() - defer b.mu.Unlock() - if b.tka == nil { - return errTailnetLockNotActive - } + active := b.tka != nil var ourNodeKey key.NodePublic if p := b.pm.CurrentPrefs(); p.Valid() && p.Persist().Valid() && !p.Persist().PrivateNodeKey().IsZero() { ourNodeKey = p.Persist().PublicNodeKey() } + b.mu.Unlock() + + if !active { + return errTailnetLockNotActive + } if ourNodeKey.IsZero() { return errors.New("no node-key: is tailscale logged in?") } - - b.mu.Unlock() _, err := b.tkaDoSyncSend(ourNodeKey, aum.Hash(), []tka.AUM{*aum}, false) - b.mu.Lock() return err } diff --git a/ipn/ipnlocal/tailnet-lock_test.go b/ipn/ipnlocal/tailnet-lock_test.go index 6d70bd6c1..1f1601ef8 100644 --- a/ipn/ipnlocal/tailnet-lock_test.go +++ b/ipn/ipnlocal/tailnet-lock_test.go @@ -1087,6 +1087,62 @@ func TestTKARecoverCompromisedKeyFlow(t *testing.T) { } } +func TestTailnetLockModify(t *testing.T) { + nodePriv := key.NewNode() + nlPriv := key.NewTLPrivate() + pm := setupProfileManager(t, nodePriv, nlPriv) + + ourKey := tka.Key{Kind: tka.Key25519, Public: nlPriv.Public().Verifier(), Votes: 2} + state := tka.CreateStateForTest(ourKey) + varRoot, chonk := setupChonkStorage(t, pm) + authority, genesis, err := tka.Create(chonk, state, nlPriv) + if err != nil { + t.Fatalf("tka.Create() failed: %v", err) + } + + // Control has its own copy of the authority, so the node's local state + // only changes if it syncs. + controlChonk := tka.ChonkMem() + controlAuthority, err := tka.Bootstrap(controlChonk, genesis) + if err != nil { + t.Fatalf("tka.Bootstrap() failed: %v", err) + } + + ts, client := fakeNoiseServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer r.Body.Close() + switch r.URL.Path { + case "/machine/tka/sync/send": + if err := tkatest.HandleTKASyncSend(w, r, controlAuthority, controlChonk); err != nil { + t.Errorf("HandleTKASyncSend: %v", err) + } + default: + t.Errorf("unhandled endpoint path: %v", r.URL.Path) + w.WriteHeader(404) + } + })) + defer ts.Close() + b := newLocalBackendForTKA(t, varRoot, client, pm, authority, chonk) + + newPriv := key.NewTLPrivate() + newKey := tka.Key{Kind: tka.Key25519, Public: newPriv.Public().Verifier(), Votes: 1} + if err := b.TailnetLockModify([]tka.Key{newKey}, nil); err != nil { + t.Fatalf("TailnetLockModify() failed: %v", err) + } + if !controlAuthority.KeyTrusted(newPriv.KeyID()) { + t.Error("control does not trust the added key") + } + if authority.KeyTrusted(newPriv.KeyID()) { + t.Error("local authority trusts the added key before any sync") + } + + // A node whose tailnet lock key isn't trusted fails before any RPC. + untrustedPM := setupProfileManager(t, nodePriv, key.NewTLPrivate()) + untrusted := newLocalBackendForTKA(t, varRoot, client, untrustedPM, authority, chonk) + if err := untrusted.TailnetLockModify([]tka.Key{newKey}, nil); err == nil { + t.Error("TailnetLockModify() with an untrusted key succeeded") + } +} + func TestRotationTracker(t *testing.T) { newNK := func(idx byte) key.NodePublic { // single-byte public key to make it human-readable in tests. diff --git a/ipn/ipnlocal/tailnetlock_disabled.go b/ipn/ipnlocal/tailnetlock_disabled.go index c8d418531..e0a9720cc 100644 --- a/ipn/ipnlocal/tailnetlock_disabled.go +++ b/ipn/ipnlocal/tailnetlock_disabled.go @@ -24,6 +24,8 @@ func (b *LocalBackend) tkaSyncIfNeeded(nm *netmap.NetworkMap, prefs ipn.PrefsVie return nil } +func (b *LocalBackend) tkaNeedsSyncLocked(nm *netmap.NetworkMap) bool { return false } + func (b *LocalBackend) tkaFilterNetmapLocked(nm *netmap.NetworkMap) {} func (b *LocalBackend) tkaFilterDeltaMutsLocked(muts []netmap.NodeMutation) []netmap.NodeMutation {