Files
tailscale/ipn/backend_test.go
T
Brendan Creane cd8532f160 ipn/ipnlocal: send one Notify per control status update (#22441)
A full netmap from control produced up to five separate ipn.Notify
messages: LoginFinished, the login prefs, the self node and peers, the
exit node suggestion, and the re-resolved exit node prefs. A GUI that
applied each one on arrival briefly showed the state between them.

setControlClientStatusLocked now collects all of them into one Notify,
sent from a deferred call when any field is set. suggestExitNodeLocked
no longer sends. It records a changed suggestion in a Notify that its
caller passes in, and the caller sends it with its other changes. The
two netmap blocks after the prefs save are merged. Nothing between them
ran unlocked.

Fixes #22206

Signed-off-by: Brendan Creane <[email protected]>
2026-12-03 08:11:18 -08:00

317 lines
8.0 KiB
Go

// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package ipn
import (
"encoding/json"
"go/types"
"maps"
"math/bits"
"reflect"
"slices"
"strconv"
"strings"
"testing"
"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
value Notify
expected string
}{
{
name: "notify-empty",
value: Notify{},
expected: "Notify{}",
},
{
name: "notify-with-login-finished",
value: Notify{LoginFinished: &empty.Message{}},
expected: "Notify{LoginFinished}",
},
{
name: "notify-with-multiple-fields",
value: Notify{LoginFinished: &empty.Message{}, Health: &health.State{}},
expected: "Notify{LoginFinished Health{...}}",
},
} {
t.Run(tt.name, func(t *testing.T) {
actual := tt.value.String()
if actual != tt.expected {
t.Fatalf("expected=%q, actual=%q", tt.expected, actual)
}
})
}
}
func TestPeerWireGuardStateJSON(t *testing.T) {
tests := []struct {
state PeerWireGuardState
json string
}{
{PeerWireGuardStateNone, `"none"`},
{PeerWireGuardStateHandshake, `"handshake"`},
{PeerWireGuardStateEstablished, `"established"`},
{PeerWireGuardStateExpired, `"expired"`},
}
for _, tt := range tests {
t.Run(tt.state.String(), func(t *testing.T) {
got, err := json.Marshal(tt.state)
if err != nil {
t.Fatalf("Marshal: %v", err)
}
if string(got) != tt.json {
t.Errorf("Marshal(%v) = %s; want %s", tt.state, got, tt.json)
}
var back PeerWireGuardState
if err := json.Unmarshal(got, &back); err != nil {
t.Fatalf("Unmarshal: %v", err)
}
if back != tt.state {
t.Errorf("round-trip = %v; want %v", back, tt.state)
}
})
}
var bad PeerWireGuardState
if err := json.Unmarshal([]byte(`"bogus"`), &bad); err == nil {
t.Errorf("Unmarshal of bogus value did not return an error")
}
}
func TestValidateNotifyWatchOpt(t *testing.T) {
tests := []struct {
name string
mask NotifyWatchOpt
wantErr bool
}{
{
name: "peer-changes",
mask: NotifyPeerChanges | NotifyPeerPatches | NotifyNoNetMap | NotifyInitialStatus,
},
{
name: "in-process-no-disconnect",
mask: NotifyInProcessNoDisconnect | NotifyPeerChanges,
},
{
name: "suspend-when-behind",
mask: NotifySuspendWhenBehind | NotifyInitialState | NotifyPeerChanges,
},
{
name: "suspend-when-behind-without-initial-state",
mask: NotifySuspendWhenBehind | NotifyPeerChanges,
wantErr: true,
},
{
name: "suspend-when-behind-with-in-process-no-disconnect",
mask: NotifySuspendWhenBehind | NotifyInitialState | NotifyInProcessNoDisconnect,
wantErr: true,
},
{
name: "obsolete-rate-limit-only",
mask: ObsoleteNotifyRateLimit,
wantErr: true,
},
{
name: "obsolete-rate-limit-with-peer-changes",
mask: ObsoleteNotifyRateLimit | NotifyPeerChanges,
wantErr: true,
},
{
name: "obsolete-initial-netmap",
mask: ObsoleteNotifyInitialNetMap,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateNotifyWatchOpt(tt.mask)
if gotErr := err != nil; gotErr != tt.wantErr {
t.Fatalf("ValidateNotifyWatchOpt(%v) error = %v; wantErr %v", tt.mask, err, tt.wantErr)
}
})
}
}
func TestNotifyWatchOptString(t *testing.T) {
consts := findNotifyWatchOptConstants(t)
t.Logf("consts = %#v", consts)
t.Run("zero", func(t *testing.T) {
var zero NotifyWatchOpt
want := "ipn.NotifyWatchOpt(0x0)"
if got := zero.String(); got != want {
t.Errorf("NotifyWatchOpt(%#v).String() = %q, want %q", zero, got, want)
}
})
t.Run("unknown", func(t *testing.T) {
msb := NotifyWatchOpt(1 << 63)
want := "ipn.NotifyWatchOpt(0x8000000000000000)"
if got := msb.String(); got != want {
t.Errorf("NotifyWatchOpt(%#v).String() = %q, want %q", msb, got, want)
}
})
t.Run("simple", func(t *testing.T) {
for _, c := range slices.Sorted(maps.Keys(consts)) {
if bits.OnesCount64(uint64(c)) > 1 {
continue // multiple bits comes later
}
want := "ipn." + consts[c]
if got := c.String(); got != want {
t.Errorf("NotifyWatchOpt(%#v).String() = %q, want %q", c, got, want)
}
}
})
t.Run("composite", func(t *testing.T) {
for _, tc := range []struct {
name string
value NotifyWatchOpt
want string
}{
{
name: "single",
value: NotifyWatchEngineUpdates,
want: "ipn.NotifyWatchEngineUpdates",
},
{
name: "double",
value: NotifyWatchEngineUpdates | NotifyInitialState,
want: "(ipn.NotifyWatchEngineUpdates | ipn.NotifyInitialState)",
},
{
name: "triple",
value: NotifyWatchEngineUpdates | NotifyInitialState | NotifyInitialPrefs,
want: "(ipn.NotifyWatchEngineUpdates | ipn.NotifyInitialState | ipn.NotifyInitialPrefs)",
},
{
name: "unknown",
value: NotifyWatchEngineUpdates | NotifyWatchOpt(1<<63),
want: "(ipn.NotifyWatchEngineUpdates | ipn.NotifyWatchOpt(0x8000000000000000))",
},
} {
t.Run(tc.name, func(t *testing.T) {
if got := tc.value.String(); got != tc.want {
t.Errorf("NotifyWatchOpt(%#v).String() = %q, want %q", tc.value, got, tc.want)
}
})
}
})
// Check that every named NotifyWatchOpt value is mapped inside [NotifyWatchOpt.String].
t.Run("all", func(t *testing.T) {
var all NotifyWatchOpt
var names []string // names are sorted and only contain simple consts
for _, c := range slices.Sorted(maps.Keys(consts)) {
all |= c
if bits.OnesCount64(uint64(c)) == 1 {
names = append(names, "ipn."+consts[c])
}
}
want := "(" + strings.Join(names, " | ") + ")"
if got := all.String(); got != want {
t.Errorf("all.String() = %q, want %q", got, want)
}
})
}
func findNotifyWatchOptConstants(t *testing.T) map[NotifyWatchOpt]string {
t.Helper()
// Load the current package.
cfg := &packages.Config{
Mode: packages.NeedTypes,
}
pkgs, err := packages.Load(cfg, ".")
if err != nil {
t.Fatalf("failed to load packages: %v", err)
}
// Find all the [NotifyWatchOpt] constants that represent this enum.
var found map[NotifyWatchOpt]string
for _, pkg := range pkgs {
if len(pkg.Errors) > 0 {
t.Fatalf("package %s has errors: %v", pkg.Name, pkg.Errors)
}
wantType := pkg.Types.Path() + ".NotifyWatchOpt"
scope := pkg.Types.Scope()
for _, name := range scope.Names() {
obj := scope.Lookup(name)
if obj == nil || obj.Type().String() != wantType {
continue
}
c, ok := obj.(*types.Const)
if !ok {
continue
}
s := c.Val().ExactString()
val, err := strconv.ParseUint(s, 10, 64)
if err != nil {
t.Fatalf("cannot parse %q: %v", s, err)
}
mak.Set(&found, NotifyWatchOpt(val), name)
}
}
if len(found) == 0 {
t.Fatal("could not find NotifyWatchOpt constants")
}
return found
}