diff --git a/ipn/ipnlocal/local.go b/ipn/ipnlocal/local.go index fbc207e19..73df39c8c 100644 --- a/ipn/ipnlocal/local.go +++ b/ipn/ipnlocal/local.go @@ -379,6 +379,7 @@ type LocalBackend struct { // hostinfo is mutated in-place while mu is held. hostinfo *tailcfg.Hostinfo // TODO(nickkhyl): move to nodeBackend nmExpiryTimer tstime.TimerController // for updating netMap on node expiry; can be nil; TODO(nickkhyl): move to nodeBackend + nmExpiryAt time.Time // wall time at which nmExpiryTimer should fire activeLogin string // last logged LoginName from netMap; TODO(nickkhyl): move to nodeBackend (or remove? it's in [ipn.LoginProfile]). engineStatus ipn.EngineStatus endpoints []tailcfg.Endpoint @@ -1249,6 +1250,14 @@ func (b *LocalBackend) linkChange(delta *netmon.ChangeDelta) { b.interfaceState = delta.CurrentState() + if delta.TimeJumped() && b.nmExpiryTimer != nil { + // The timer runs on monotonic time, which on most platforms + // does not advance while the device is asleep. Reschedule it + // against the wall clock so that a key that expired during + // sleep is handled now rather than a sleep's duration late. + b.nmExpiryTimer.Reset(max(0, b.nmExpiryAt.Sub(b.clock.Now()))) + } + b.pauseOrResumeControlClientLocked() prefs := b.pm.CurrentPrefs() if delta.RebindLikelyRequired && prefs.AutoExitNode().IsSet() { @@ -1983,6 +1992,9 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c nextExpiry := b.em.nextPeerExpiry(st.NetMap, now) if !nextExpiry.IsZero() { tmrDuration := nextExpiry.Sub(now) + 10*time.Second + // From time package's docs: "The canonical way to strip a + // monotonic clock reading is to use t = t.Round(0)." + b.nmExpiryAt = now.Add(tmrDuration).Round(0) b.nmExpiryTimer = b.clock.AfterFunc(tmrDuration, func() { b.handleNetmapExpiry(c, st, currCall, tmrDuration) }) @@ -2007,7 +2019,7 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c b.blockEngineUpdatesLocked(false) } - if st.LoggedIn && (wasBlocked || authWasInProgress) { + if st.LoggedIn && !b.keyExpired && (wasBlocked || authWasInProgress) { if wasBlocked { // Auth completed, unblock the engine b.blockEngineUpdatesLocked(false) @@ -2042,7 +2054,7 @@ func (b *LocalBackend) setControlClientStatusLocked(c controlclient.Client, st c prefs.Persist = st.Persist.AsStruct() } } - if st.LoggedIn { + if st.LoggedIn && !b.keyExpired { if authWasInProgress { b.resetAuthURLLocked() // Interactive login finished successfully (URL visited). diff --git a/ipn/ipnlocal/local_test.go b/ipn/ipnlocal/local_test.go index 09428dc6e..0c40e11ad 100644 --- a/ipn/ipnlocal/local_test.go +++ b/ipn/ipnlocal/local_test.go @@ -3115,18 +3115,22 @@ type expiryCallbackClock struct { tstime.StdClock now time.Time afterFunc func() + resets []time.Duration // durations passed to the timer's Reset } -type expiryCallbackTimer struct{} +type expiryCallbackTimer struct{ c *expiryCallbackClock } -func (*expiryCallbackTimer) Reset(time.Duration) bool { return false } -func (*expiryCallbackTimer) Stop() bool { return true } +func (t *expiryCallbackTimer) Reset(d time.Duration) bool { + t.c.resets = append(t.c.resets, d) + return false +} +func (*expiryCallbackTimer) Stop() bool { return true } func (c *expiryCallbackClock) Now() time.Time { return c.now } func (c *expiryCallbackClock) AfterFunc(_ time.Duration, f func()) tstime.TimerController { c.afterFunc = f - return new(expiryCallbackTimer) + return &expiryCallbackTimer{c} } func TestNetmapExpiryTimerPreservesPeerDeltas(t *testing.T) { diff --git a/ipn/ipnlocal/state_test.go b/ipn/ipnlocal/state_test.go index 87bfcb873..f15769331 100644 --- a/ipn/ipnlocal/state_test.go +++ b/ipn/ipnlocal/state_test.go @@ -1647,6 +1647,178 @@ func TestEngineReconfigOnStateChange(t *testing.T) { } } +func TestExpiredKeyLoggedInStatusDoesNotUnblockEngine(t *testing.T) { + connect := &ipn.MaskedPrefs{ + WantRunning: true, + WantRunningSet: true, + } + + validNetmap := buildNetmapWithPeers( + makePeer( + 1, + withName("self"), + withAddresses(netip.MustParsePrefix("100.64.1.1/32")), + ), + ) + + lb, engine, cc := newLocalBackendWithMockEngineAndControl(t, false) + + mustDo(t)(lb.Start(ipn.Options{})) + mustDo2(t)(lb.EditPrefs(connect)) + cc().authenticated(validNetmap) + + expiredNetmap := *validNetmap + expiredSelf := validNetmap.SelfNode.AsStruct() + expiredSelf.KeyExpiry = time.Now().Add(-time.Minute) + expiredNetmap.SelfNode = expiredSelf.View() + + cc().send(sendOpt{nm: &expiredNetmap}) + + if got, want := lb.State(), ipn.NeedsLogin; got != want { + t.Fatalf("state after expiry = %v; want %v", got, want) + } + if got, want := lb.isEngineBlocked(), true; got != want { + t.Fatalf("engine blocked after expiry = %v; want %v", got, want) + } + addresses := engine.Config().Addresses + if got, want := len(addresses), 0; got != want { + t.Fatalf("engine address count after expiry = %d; want %d (addresses: %v)", got, want, addresses) + } + + // A subsequent control status can still say LoggedIn even though the + // node key remains expired. This must not be treated as completed + // reauthentication, including when an interactive login is pending. + cc().sendAuthURL(&expiredNetmap) + cc().send(sendOpt{ + loginFinished: true, + nm: &expiredNetmap, + }) + + if got, want := lb.State(), ipn.NeedsLogin; got != want { + t.Errorf("state after stale LoggedIn status = %v; want %v", got, want) + } + if got, want := lb.isEngineBlocked(), true; got != want { + t.Errorf("engine blocked after stale LoggedIn status = %v; want %v", got, want) + } + addresses = engine.Config().Addresses + if got, want := len(addresses), 0; got != want { + t.Errorf("engine address count after stale LoggedIn status = %d; want %d (addresses: %v)", got, want, addresses) + } + lb.mu.Lock() + authURL := lb.authURL + lb.mu.Unlock() + if authURL == "" { + t.Error("stale LoggedIn status reset the pending auth URL") + } +} + +func TestTimeJumpRechecksSelfKeyExpiry(t *testing.T) { + tests := []struct { + name string + wakeAfter time.Duration + wantReset time.Duration // new duration of the expiry timer + wantState ipn.State + wantBlocked bool + wantConfigured bool + }{ + { + name: "before_expiry", + wakeAfter: 4 * time.Minute, + wantReset: time.Minute + 10*time.Second, + wantState: ipn.Running, + wantBlocked: false, + wantConfigured: true, + }, + { + name: "after_expiry", + wakeAfter: 7 * time.Minute, + wantReset: 0, + wantState: ipn.NeedsLogin, + wantBlocked: true, + wantConfigured: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + c := qt.New(t) + now := time.Unix(1_800_000_000, 0) + clock := &expiryCallbackClock{now: now} + + connect := &ipn.MaskedPrefs{ + WantRunning: true, + WantRunningSet: true, + } + + self := makePeer( + 1, + withName("self"), + withAddresses(netip.MustParsePrefix("100.64.1.1/32")), + func(n *tailcfg.Node) { + n.MachineAuthorized = true + n.KeyExpiry = now.Add(5 * time.Minute) + }, + ) + nm := buildNetmapWithPeers(self) + + lb, engine, cc := newLocalBackendWithMockEngineAndControl(t, false) + lb.ForTest().SetClock(clock) + + mustDo(t)(lb.Start(ipn.Options{})) + mustDo2(t)(lb.EditPrefs(connect)) + cc().authenticated(nm) + + // Give the fake engine a live DERP connection so the backend + // reaches Running before the simulated sleep. + lb.setWgengineStatus(&wgengine.Status{ + DERPs: 1, + AsOf: now, + }, nil) + + if got, want := lb.State(), ipn.Running; got != want { + t.Fatalf("state before sleep = %v; want %v", got, want) + } + + // Advance wall time without invoking the scheduled expiry + // callback, modeling a timer suspended while the machine sleeps. + clock.now = now.Add(tt.wakeAfter) + + networkState := &netmon.State{} + delta, err := netmon.NewChangeDelta( + networkState, + networkState, + tt.wakeAfter, + true, + ) + c.Assert(err, qt.IsNil) + c.Assert(delta.TimeJumped(), qt.Equals, true) + c.Assert(delta.RebindLikelyRequired, qt.Equals, false) + + lb.linkChange(delta) + + if got, want := clock.resets, []time.Duration{tt.wantReset}; !slices.Equal(got, want) { + t.Fatalf("expiry timer resets = %v; want %v", got, want) + } + if tt.wantReset == 0 { + // The rescheduled timer fires immediately. + clock.afterFunc() + } + + if got, want := lb.State(), tt.wantState; got != want { + t.Errorf("state after wake = %v; want %v", got, want) + } + if got, want := lb.isEngineBlocked(), tt.wantBlocked; got != want { + t.Errorf("engine blocked after wake = %v; want %v", got, want) + } + + cfg := engine.Config() + if got, want := cfg != nil && len(cfg.Addresses) != 0, tt.wantConfigured; got != want { + t.Errorf("engine configured after wake = %v; want %v", got, want) + } + }) + } +} + // TestPeerConfigUpdatedOnPeerRouteDelta tests that a netmap delta that // changes a peer's allowed IPs is visible through the live per-peer // config source that LocalBackend installs on the engine.