feature/captiveportal: detect captive portals before the backend is Running

The detection loop only ran in the Running state, and was only
triggered by warnings that impact connectivity. A node restarted behind
a captive portal never receives a netmap, so it stays in NoState with
no home DERP, and its only warning is login-state.

Run the loop for the lifetime of the extension, and also trigger
detection when logging in to the control plane fails. Detection remains
limited to profiles with WantRunning set.

Signed-off-by: Nick Khyl <nickk@tailscale.com>
This commit is contained in:
Nick Khyl committed 2026-11-28 23:54:54 +00:00
1 parent 859921eb34
commit 4c032ef105
2 files changed
+74 -72

No files matched your search

+26 -72
View File
@@ -13,10 +13,8 @@ import (
"tailscale.com/feature"
_ "tailscale.com/feature/captiveportal/netcheckhook" // install the netcheck probe hook too
"tailscale.com/health"
"tailscale.com/ipn"
"tailscale.com/ipn/ipnext"
"tailscale.com/net/captivedetection"
"tailscale.com/syncs"
"tailscale.com/tailcfg"
"tailscale.com/types/logger"
"tailscale.com/util/clientmetric"
@@ -57,16 +55,9 @@ type Extension struct {
health *health.Tracker
ec *eventbus.Client
mu syncs.Mutex
// captiveCtx and captiveCancel are used to control captive portal
// detection. They are protected by 'mu' and can be changed during the
// lifetime of the extension.
//
// captiveCtx will always be non-nil, though it might be a canceled
// context. captiveCancel is non-nil if checkCaptivePortalLoop is
// running, and is set to nil after being canceled.
captiveCtx context.Context
captiveCancel context.CancelFunc
// ctx is canceled by cancel on Shutdown to stop checkCaptivePortalLoop.
ctx context.Context
cancel context.CancelFunc
// needsCaptiveDetection is a channel that is used to signal either
// that captive portal detection is required (sending true) or that the
@@ -76,16 +67,13 @@ type Extension struct {
}
func newExtension(logf logger.Logf, sb ipnext.SafeBackend) (ipnext.Extension, error) {
// Initialize the context used to control the captive portal detection
// goroutine in a canceled state, so that it is always non-nil and safe
// to wait on even before the loop has ever started.
ctx, cancel := context.WithCancel(context.Background())
cancel()
return &Extension{
logf: logf,
sb: sb,
health: sb.Sys().HealthTracker.Get(),
captiveCtx: ctx,
ctx: ctx,
cancel: cancel,
needsCaptiveDetection: make(chan bool),
}, nil
}
@@ -94,85 +82,51 @@ func (e *Extension) Name() string { return featureName }
func (e *Extension) Init(h ipnext.Host) error {
e.host = h
h.Hooks().BackendStateChange.Add(e.onBackendStateChange)
e.ec = e.sb.Sys().Bus.Get().Client("captiveportal")
eventbus.SubscribeFunc(e.ec, e.onHealthChange)
go e.checkCaptivePortalLoop(e.ctx)
return nil
}
func (e *Extension) Shutdown() error {
e.mu.Lock()
if e.captiveCancel != nil {
e.captiveCancel()
e.captiveCancel = nil
}
e.mu.Unlock()
e.cancel()
if e.ec != nil {
e.ec.Close()
}
return nil
}
// onBackendStateChange starts or stops the captive portal detection loop as
// the backend enters or leaves the Running state. It is called with
// LocalBackend's mutex held, so it must not call back into LocalBackend.
func (e *Extension) onBackendStateChange(st ipn.State) {
e.mu.Lock()
defer e.mu.Unlock()
if st == ipn.Running {
// Start a captive portal detection loop if none has been
// started.
if e.captiveCancel == nil {
e.captiveCtx, e.captiveCancel = context.WithCancel(context.Background())
go e.checkCaptivePortalLoop(e.captiveCtx)
// isConnectivityImpacted reports whether state has a warning, other than
// the captive portal one, that a captive portal could be the cause of.
func isConnectivityImpacted(state *health.State) bool {
for _, w := range state.Warnings {
switch {
case w.WarnableCode == captivePortalWarnable.Code:
// Ignore the captive portal warnable itself.
case w.ImpactsConnectivity:
return true
case w.WarnableCode == health.LoginStateWarnable.Code && w.Args[health.ArgError] != "":
// Until the node has received its first netmap, it has no
// home DERP, and a failure to log in to the control plane
// is the only sign of a captive portal.
return true
}
} else if e.captiveCancel != nil {
// Transitioning away from Running; stop any existing captive
// portal detection loop.
e.captiveCancel()
e.captiveCancel = nil
// NOTE: don't set captiveCtx to nil here, to ensure that we
// always have a (canceled) context to wait on in
// onHealthChange.
}
return false
}
// onHealthChange is called (via the eventbus) whenever the node's health
// state changes. If connectivity appears to be impacted, it signals the
// detection loop to check for a captive portal.
func (e *Extension) onHealthChange(health.Change) {
state := e.health.CurrentState()
isConnectivityImpacted := false
for _, w := range state.Warnings {
// Ignore the captive portal warnable itself.
if w.ImpactsConnectivity && w.WarnableCode != captivePortalWarnable.Code {
isConnectivityImpacted = true
break
}
}
// captiveCtx can be changed, and is protected with 'mu'; grab that
// before we start our select, below.
//
// It is guaranteed to be non-nil.
e.mu.Lock()
ctx := e.captiveCtx
e.mu.Unlock()
// If the context is canceled, we don't need to do anything.
if ctx.Err() != nil {
return
}
if isConnectivityImpacted {
if e.shouldRunCaptivePortalDetection() && isConnectivityImpacted(e.health.CurrentState()) {
e.logf("health: connectivity impacted; triggering captive portal detection")
// Ensure that we select on captiveCtx so that we can time out
// Ensure that we select on ctx so that we can time out
// triggering captive portal detection if the loop is shut down.
select {
case e.needsCaptiveDetection <- true:
case <-ctx.Done():
case <-e.ctx.Done():
}
} else {
// If connectivity is not impacted, we know for sure we're not behind a captive portal,
@@ -180,7 +134,7 @@ func (e *Extension) onHealthChange(health.Change) {
e.health.SetHealthy(captivePortalWarnable)
select {
case e.needsCaptiveDetection <- false:
case <-ctx.Done():
case <-e.ctx.Done():
}
}
}
@@ -0,0 +1,48 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package captiveportal
import (
"context"
"errors"
"testing"
"testing/synctest"
"time"
"tailscale.com/health"
"tailscale.com/util/eventbus/eventbustest"
)
func TestIsConnectivityImpacted(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
ht := health.NewTracker(eventbustest.NewBus(t))
check := func(want bool) {
t.Helper()
if got := isConnectivityImpacted(ht.CurrentState()); got != want {
t.Errorf("got %v; want %v", got, want)
}
}
// The node was restarted and hasn't received a netmap yet.
ht.SetIPNState("NoState", true)
time.Sleep(time.Minute)
check(false)
ht.SetAuthRoutineInError(errors.New("x509: certificate is valid for portal.example.com, not controlplane.tailscale.com"))
check(true)
ht.SetAuthRoutineInError(context.Canceled)
check(false)
ht.SetAuthRoutineInError(nil)
check(false)
ht.SetUnhealthy(captivePortalWarnable, nil)
check(false)
ht.SetAnyInterfaceUp(false)
time.Sleep(health.NetworkStatusWarnable.TimeToVisible)
check(true)
})
}