diff --git a/client/tailscale/apitype/apitype.go b/client/tailscale/apitype/apitype.go index 12293762b..4524bf9ba 100644 --- a/client/tailscale/apitype/apitype.go +++ b/client/tailscale/apitype/apitype.go @@ -103,6 +103,12 @@ type OptionalFeatures struct { // Disabled features may be absent from the map. (That is, false values // are not guaranteed to be present.) Features map[string]bool + + // Disabled is the list of features disabled at runtime via the + // TS_DISABLE_FEATURE environment variable, whether or not this build + // contains them. A name listed here that is absent from Features + // either named an unknown feature or one not linked into this build. + Disabled []string `json:",omitempty"` } // ServiceClientPrefRequest is the body POSTed to the LocalAPI endpoint /localapi/v0/prefs/service-clients. diff --git a/cmd/stund/depaware.txt b/cmd/stund/depaware.txt index 107dc260b..642d98a03 100644 --- a/cmd/stund/depaware.txt +++ b/cmd/stund/depaware.txt @@ -83,7 +83,7 @@ tailscale.com/cmd/stund dependencies: (generated by github.com/tailscale/depawar tailscale.com/util/mak from tailscale.com/syncs+ tailscale.com/util/nocasemaps from tailscale.com/types/ipproto tailscale.com/util/rands from tailscale.com/tsweb - tailscale.com/util/set from tailscale.com/types/key + tailscale.com/util/set from tailscale.com/types/key+ tailscale.com/util/slicesx from tailscale.com/tailcfg tailscale.com/util/testenv from tailscale.com/types/logger+ tailscale.com/util/vizerror from tailscale.com/tailcfg+ diff --git a/feature/README.md b/feature/README.md index cea8407c6..a38e67455 100644 --- a/feature/README.md +++ b/feature/README.md @@ -42,6 +42,72 @@ When you touch one of these features, prefer to keep migrating code into its `feature/` package rather than adding more to the old location. But do not feel obligated to finish the migration in one PR. +## Runtime disabling: `TS_DISABLE_FEATURE` + +The `TS_DISABLE_FEATURE` environment variable disables features at +runtime, even if they're compiled in. It is the runtime analog of the +`ts_omit_` build tags: a mitigation knob (for when a feature has, +say, a security bug that most users don't need to be exposed to) and a +way to shrink attack surface on appliances. + + TS_DISABLE_FEATURE=ssh,taildrop + +Names are matched leniently: surrounding spaces, mixed case, a +`ts_omit_` prefix, and underscores in place of dashes are all accepted. +A name that this build doesn't know about, or that names a feature not +linked in, is ignored rather than fatal. + +A disabled feature behaves as if it had not been linked: it is absent +from [`feature.IsRegistered`](https://pkg.go.dev/tailscale.com/feature#IsRegistered), +its hooks are unset, and its extensions and handlers are not +registered. The compile-time `buildfeatures.HasFoo` constants are +unaffected (the code is still in the binary), so keep pairing them with +`IsRegistered` as described above. + +The mechanism, in order of authority: + +1. [`feature.Register(name)`](https://pkg.go.dev/tailscale.com/feature#Register) + reports false and records nothing. Feature packages gate their + registration init on it: + + func init() { + if !feature.Register("foo") { + return + } + // ... set hooks, register extensions and handlers ... + } + + A package with more than one registration init should consolidate + them into one gated init, or guard the others with + [`feature.Disabled(name)`](https://pkg.go.dev/tailscale.com/feature#Disabled). +2. [`ipnext.RegisterExtension`](https://pkg.go.dev/tailscale.com/ipn/ipnext#RegisterExtension) + silently ignores a disabled feature's extension. +3. `feature.Hook.Set` and `feature.Hooks.Add` walk the call stack, and + if the caller is a package under `tailscale.com/feature/` whose + feature is disabled, they silently skip the registration. This + catches sub-packages of a feature (such as + `feature/captiveportal/netcheckhook`), which cannot call `Register` + themselves without colliding with their parent feature, and future + packages whose authors never added the gate. + +All of this happens during package init, so the variable must be set +when the process starts (in the systemd unit's `EnvironmentFile`, the +container's environment, and so on). The legacy per-feature knobs like +`TS_DISABLE_SSH_SERVER` and `TS_DISABLE_TAILDROP` keep working +independently of this one. + +The state is visible in the `debug-optional-features` LocalAPI endpoint +(`tailscaled`'s registered set plus what `TS_DISABLE_FEATURE` listed), +and `feature/register_disable_test.go` locks the behavior down: it +disables every registered feature in a subprocess and fails if any of +them register anyway, so a feature that ignores the variable cannot +land. + +Not everything with a `ts_omit_*` tag is runtime-disableable: code that +registers itself from outside a `feature/` package without going +through the mechanisms above (for example the `osrouter` router hooks) +is not covered. + ## The registry: `feature/featuretags` [`featuretags/featuretags.go`](featuretags/featuretags.go) is the single @@ -164,7 +230,10 @@ exposes the small runtime API used by feature packages and their callers: - [`feature.Register(name)`](https://pkg.go.dev/tailscale.com/feature#Register): a feature package calls this from its `init` to record that it was - linked in. Callers use + linked in and to find out whether it should register itself at all + (it reports false when disabled via + [`TS_DISABLE_FEATURE`](#runtime-disabling-ts_disable_feature), as + described below). Callers use [`feature.IsRegistered(name)`](https://pkg.go.dev/tailscale.com/feature#IsRegistered) to check. - [`feature.Hook[Func]`](https://pkg.go.dev/tailscale.com/feature#Hook): @@ -343,8 +412,15 @@ Tests come in three flavors: including any `Deps`. 2. Run `./tool/go generate ./feature/buildfeatures` (or `make generate`). 3. Create `feature//` with the code, and register hooks and any - `ipnext.Extension` from its `init`. Call `feature.Register("")` - from `init` too. + `ipnext.Extension` from its `init`, gated as described in + ["Runtime disabling: `TS_DISABLE_FEATURE`](#runtime-disabling-ts_disable_feature): + + func init() { + if !feature.Register("") { + return + } + // ... set hooks, register extensions and handlers ... + } 4. If the feature should be on by default in `tailscaled`, add `feature/condregister/maybe_.go` with `//go:build !ts_omit_` and a blank import of `tailscale.com/feature/`. diff --git a/feature/ace/ace.go b/feature/ace/ace.go index b99516657..6c7779596 100644 --- a/feature/ace/ace.go +++ b/feature/ace/ace.go @@ -8,11 +8,15 @@ import ( "net/netip" "tailscale.com/control/controlhttp" + "tailscale.com/feature" "tailscale.com/net/ace" "tailscale.com/net/netx" ) func init() { + if !feature.Register("ace") { + return + } controlhttp.HookMakeACEDialer.Set(mkDialer) } diff --git a/feature/acme/acme.go b/feature/acme/acme.go index 0b240a9b1..4dd364df4 100644 --- a/feature/acme/acme.go +++ b/feature/acme/acme.go @@ -40,7 +40,9 @@ import ( const featureName = "acme" func init() { - feature.Register(featureName) + if !feature.Register(featureName) { + return + } ipnext.RegisterExtension(featureName, newExtension) ipnlocal.HookGetCertPEM.Set(getCertPEMHook) diff --git a/feature/androidbin/cacerts.go b/feature/androidbin/cacerts.go index 602e23620..6f7258879 100644 --- a/feature/androidbin/cacerts.go +++ b/feature/androidbin/cacerts.go @@ -5,7 +5,11 @@ package androidbin -import "os" +import ( + "os" + + "tailscale.com/feature" +) // Android keeps its CA roots in /system/etc/security/cacerts as PEM // files, a path Go's crypto/x509 knows about in GOOS=android builds @@ -18,6 +22,9 @@ import "os" // Termux does when its ca-certificates package is installed), leave // their configuration alone. func init() { + if feature.Disabled("androidbin") { + return + } if !onAndroid() { return } diff --git a/feature/androidbin/register.go b/feature/androidbin/register.go index 9fdeb976c..eca215fc3 100644 --- a/feature/androidbin/register.go +++ b/feature/androidbin/register.go @@ -5,10 +5,16 @@ package androidbin -import "tailscale.com/net/netmon" +import ( + "tailscale.com/feature" + "tailscale.com/net/netmon" +) // The hook is not registered in GOOS=android cgo builds (the Android // app), which register a Java-backed interface getter of their own. func init() { + if !feature.Register("androidbin") { + return + } netmon.HookInterfacesFallback.Set(fallbackInterfaces) } diff --git a/feature/androiddns/auto.go b/feature/androiddns/auto.go index 332a6a8bb..b2894a8f7 100644 --- a/feature/androiddns/auto.go +++ b/feature/androiddns/auto.go @@ -9,6 +9,8 @@ import ( "net" "os" "runtime" + + "tailscale.com/feature" ) // This init runs in GOOS=android builds without cgo and in all @@ -24,6 +26,9 @@ import ( // Android (see onAndroid) plus a successful connection to the // dnsproxyd socket before touching the default resolver. func init() { + if !feature.Register("androiddns") { + return + } if resolvConfExists() || !onAndroid() || !available() { return } diff --git a/feature/appconnectors/appconnectors.go b/feature/appconnectors/appconnectors.go index 82d29ce0e..696eefcef 100644 --- a/feature/appconnectors/appconnectors.go +++ b/feature/appconnectors/appconnectors.go @@ -8,11 +8,15 @@ import ( "encoding/json" "net/http" + "tailscale.com/feature" "tailscale.com/ipn/ipnlocal" "tailscale.com/tailcfg" ) func init() { + if !feature.Register("appconnectors") { + return + } ipnlocal.RegisterC2N("GET /appconnector/routes", handleC2NAppConnectorDomainRoutesGet) } diff --git a/feature/awsparamstore/awsparamstore.go b/feature/awsparamstore/awsparamstore.go index f63f546ed..f390e03f9 100644 --- a/feature/awsparamstore/awsparamstore.go +++ b/feature/awsparamstore/awsparamstore.go @@ -21,7 +21,9 @@ import ( ) func init() { - feature.Register("awsparamstore") + if !feature.Register("awsparamstore") { + return + } tailscale.HookResolveValueFromParameterStore.Set(ResolveValue) } diff --git a/feature/bird/bird.go b/feature/bird/bird.go index 13b5fb065..b6f36f625 100644 --- a/feature/bird/bird.go +++ b/feature/bird/bird.go @@ -19,7 +19,9 @@ import ( ) func init() { - feature.Register("bird") + if !feature.Register("bird") { + return + } wgengine.HookNewBird.Set(newBird) } diff --git a/feature/c2n/c2n.go b/feature/c2n/c2n.go index 331a9af95..4597c0a4f 100644 --- a/feature/c2n/c2n.go +++ b/feature/c2n/c2n.go @@ -12,12 +12,16 @@ import ( "time" "tailscale.com/control/controlclient" + "tailscale.com/feature" "tailscale.com/tailcfg" "tailscale.com/tempfork/httprec" "tailscale.com/types/logger" ) func init() { + if !feature.Register("c2n") { + return + } controlclient.HookAnswerC2NPing.Set(answerC2NPing) } diff --git a/feature/captiveportal/captiveportal.go b/feature/captiveportal/captiveportal.go index b97df5146..115552509 100644 --- a/feature/captiveportal/captiveportal.go +++ b/feature/captiveportal/captiveportal.go @@ -26,7 +26,9 @@ import ( const featureName = "captiveportal" func init() { - feature.Register(featureName) + if !feature.Register(featureName) { + return + } ipnext.RegisterExtension(featureName, newExtension) } diff --git a/feature/capture/capture.go b/feature/capture/capture.go index d7145e7c1..1da171232 100644 --- a/feature/capture/capture.go +++ b/feature/capture/capture.go @@ -20,7 +20,9 @@ import ( ) func init() { - feature.Register("capture") + if !feature.Register("capture") { + return + } localapi.Register("debug-capture", serveLocalAPIDebugCapture) } diff --git a/feature/clientupdate/clientupdate.go b/feature/clientupdate/clientupdate.go index 4bbd5e1ba..c041a2ffd 100644 --- a/feature/clientupdate/clientupdate.go +++ b/feature/clientupdate/clientupdate.go @@ -36,7 +36,9 @@ import ( ) func init() { - feature.Register("clientupdate") + if !feature.Register("clientupdate") { + return + } ipnext.RegisterExtension("clientupdate", newExt) // C2N diff --git a/feature/conn25/conn25.go b/feature/conn25/conn25.go index 8e2053dd7..ee4ebd35b 100644 --- a/feature/conn25/conn25.go +++ b/feature/conn25/conn25.go @@ -78,7 +78,9 @@ func normalizeDNSName(name string) (dnsname.FQDN, error) { } func init() { - feature.Register(featureName) + if !feature.Register(featureName) { + return + } ipnext.RegisterExtension(featureName, func(logf logger.Logf, sb ipnext.SafeBackend) (ipnext.Extension, error) { return &extension{ conn25: newConn25(logger.WithPrefix(logf, "conn25: ")), diff --git a/feature/connreject/connreject.go b/feature/connreject/connreject.go index f1e919f9d..c6879f822 100644 --- a/feature/connreject/connreject.go +++ b/feature/connreject/connreject.go @@ -33,7 +33,9 @@ import ( const featureName = "connreject" func init() { - feature.Register(featureName) + if !feature.Register(featureName) { + return + } ipnext.RegisterExtension(featureName, newExtension) localapi.Register("debug-rejects", serveDebugRejects) ipnlocal.RegisterC2N("GET /debug/rejects", handleC2NDebugRejects) diff --git a/feature/debugportmapper/debugportmapper.go b/feature/debugportmapper/debugportmapper.go index 1b3bf83f7..6d27f8172 100644 --- a/feature/debugportmapper/debugportmapper.go +++ b/feature/debugportmapper/debugportmapper.go @@ -15,6 +15,7 @@ import ( "sync" "time" + "tailscale.com/feature" "tailscale.com/ipn/localapi" "tailscale.com/net/netmon" "tailscale.com/net/portmapper" @@ -24,6 +25,9 @@ import ( ) func init() { + if !feature.Register("debugportmapper") { + return + } localapi.Register("debug-portmap", serveDebugPortmap) } diff --git a/feature/disable.go b/feature/disable.go new file mode 100644 index 000000000..b96046850 --- /dev/null +++ b/feature/disable.go @@ -0,0 +1,139 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package feature + +import ( + "runtime" + "slices" + "strings" + "sync" + + "tailscale.com/envknob" + "tailscale.com/util/set" +) + +// disabledEnv is the TS_DISABLE_FEATURE environment variable: a comma +// separated list of feature names to disable in this process, even if +// they're compiled in. It's a mitigation and attack-surface-reduction +// knob, the runtime analog of the ts_omit_ build tags. For +// example, on a system where the tailscaled unit loads environment +// from /etc/default/tailscaled: +// +// TS_DISABLE_FEATURE=ssh,taildrop +// +// The value is read once, at first use, which in practice is during +// package initialization; setting it later has no effect, because +// features register themselves from init. +var disabledEnv = envknob.RegisterString("TS_DISABLE_FEATURE") + +// disabledByEnv is the set of normalized feature names listed in +// TS_DISABLE_FEATURE, parsed once on first use. +var disabledByEnv = sync.OnceValue(func() set.Set[string] { + return set.SetOf(parseDisabledList(disabledEnv())) +}) + +// parseDisabledList splits a TS_DISABLE_FEATURE value into normalized +// feature names, skipping empty entries. +func parseDisabledList(s string) []string { + var names []string + for _, ent := range strings.Split(s, ",") { + if name := normalizeFeatureName(ent); name != "" { + names = append(names, name) + } + } + return names +} + +// normalizeFeatureName canonicalizes a feature name whether it came +// from TS_DISABLE_FEATURE or from code. It trims spaces, lowercases, +// drops an optional ts_omit_ build-tag prefix, and maps underscores to +// dashes. Registered names use dashes by convention (for example +// "desktop-sessions"), but their corresponding build tags use +// underscores, so both spellings are accepted. +func normalizeFeatureName(s string) string { + s = strings.TrimSpace(s) + s = strings.ToLower(s) + s = strings.TrimPrefix(s, "ts_omit_") + return strings.ReplaceAll(s, "_", "-") +} + +// Disabled reports whether the named feature has been disabled for +// this process via the TS_DISABLE_FEATURE environment variable. A +// disabled feature behaves as if it had not been linked in: [Register] +// reports false, and hooks and extensions registered by its package +// are ignored. +func Disabled(name string) bool { + return disabledByEnv().Contains(normalizeFeatureName(name)) +} + +// EnvDisabled returns the sorted feature names listed in the +// TS_DISABLE_FEATURE environment variable, whether or not they name +// features that this build contains. It is for diagnostics, such as +// the debug-features LocalAPI endpoint. +func EnvDisabled() []string { + names := disabledByEnv().Slice() + slices.Sort(names) + return names +} + +// featurePkgPrefix is the import path prefix of the feature package +// tree. The name of a package under it is the first path element after +// the prefix, so sub-packages of a feature (such as +// feature/captiveportal/netcheckhook) count as their parent feature. +const featurePkgPrefix = "tailscale.com/feature/" + +// mechanismPkgPrefix is the prefix of symbol names belonging to the +// registration machinery itself (this package), which the stack walk +// in callerFeatureName steps over to find the registering feature. It +// matches both plain functions (tailscale.com/feature.callerFeatureName) +// and methods (tailscale.com/feature.(*Hook[...]).Set). +const mechanismPkgPrefix = "tailscale.com/feature." + +// callerFeatureDisabled reports whether the feature package calling +// into this package has been disabled via TS_DISABLE_FEATURE. It backs +// the silent skip in [Hook.Set] and [Hooks.Add] so that a feature +// package which registers hooks without first consulting [Register] +// still gets disabled. If the caller is not a feature package, it +// reports false. +func callerFeatureDisabled() bool { + name, ok := callerFeatureName() + return ok && Disabled(name) +} + +// callerFeatureName walks up the call stack, starting just above this +// package's own frames, and returns the name of the first calling +// package under tailscale.com/feature/. The second result is false if +// no calling feature package is found, which means the caller is +// ordinary code and its registration is always wanted. +// +// Frames are matched by symbol name prefix rather than by parsing out +// package paths, because the symbol name of a Hook.Set frame includes +// its type parameters, which themselves contain import paths. +func callerFeatureName() (string, bool) { + var pcs [16]uintptr + n := runtime.Callers(1, pcs[:]) + frames := runtime.CallersFrames(pcs[:n]) + for { + frame, more := frames.Next() + fn := frame.Function + switch { + case fn == "": + return "", false + case strings.HasPrefix(fn, mechanismPkgPrefix): + // A frame of the registration machinery; look above it. + case strings.HasPrefix(fn, featurePkgPrefix): + rest := strings.TrimPrefix(fn, featurePkgPrefix) + if i := strings.IndexAny(rest, "/."); i >= 0 { + rest = rest[:i] + } + return rest, true + default: + // A frame outside the feature tree; the search is over. + return "", false + } + if !more { + return "", false + } + } +} diff --git a/feature/disable_test.go b/feature/disable_test.go new file mode 100644 index 000000000..c3988445f --- /dev/null +++ b/feature/disable_test.go @@ -0,0 +1,58 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package feature + +import "testing" + +func TestNormalizeFeatureName(t *testing.T) { + tests := []struct { + in, want string + }{ + {"taildrop", "taildrop"}, + {" taildrop ", "taildrop"}, + {"Taildrop", "taildrop"}, + {"TAILDROP", "taildrop"}, + {"ts_omit_taildrop", "taildrop"}, + {"TS_OMIT_TAILDROP", "taildrop"}, + {"desktop_sessions", "desktop-sessions"}, + {"ts_omit_desktop_sessions", "desktop-sessions"}, + {"", ""}, + {" ", ""}, + {",", ","}, + } + for _, tt := range tests { + if got := normalizeFeatureName(tt.in); got != tt.want { + t.Errorf("normalizeFeatureName(%q) = %q, want %q", tt.in, got, tt.want) + } + } +} + +func TestParseDisabledList(t *testing.T) { + tests := []struct { + in string + want []string + }{ + {"", nil}, + {",", nil}, + {" , ", nil}, + {"taildrop", []string{"taildrop"}}, + {"ssh,taildrop", []string{"ssh", "taildrop"}}, + {" ssh , taildrop ", []string{"ssh", "taildrop"}}, + {"ssh,,taildrop,", []string{"ssh", "taildrop"}}, + {"TS_OMIT_SSH,TailnetLock", []string{"ssh", "tailnetlock"}}, + } + for _, tt := range tests { + got := parseDisabledList(tt.in) + if len(got) != len(tt.want) { + t.Errorf("parseDisabledList(%q) = %q, want %q", tt.in, got, tt.want) + continue + } + for i := range got { + if got[i] != tt.want[i] { + t.Errorf("parseDisabledList(%q) = %q, want %q", tt.in, got, tt.want) + break + } + } + } +} diff --git a/feature/dnsresolvecache/dnsresolvecache.go b/feature/dnsresolvecache/dnsresolvecache.go index 65d36ec9f..1b0156ab3 100644 --- a/feature/dnsresolvecache/dnsresolvecache.go +++ b/feature/dnsresolvecache/dnsresolvecache.go @@ -60,7 +60,9 @@ import ( ) func init() { - feature.Register("dnsresolvecache") + if !feature.Register("dnsresolvecache") { + return + } dnscache.HookSetCacheDir.Set(setCacheDir) dnscache.HookPersistResolution.Set(persist) dnscache.HookLookupDiskCache.Set(lookup) diff --git a/feature/doctor/doctor.go b/feature/doctor/doctor.go index 26c3ff0d1..58ba7164b 100644 --- a/feature/doctor/doctor.go +++ b/feature/doctor/doctor.go @@ -16,12 +16,16 @@ import ( "tailscale.com/doctor/ethtool" "tailscale.com/doctor/permissions" "tailscale.com/doctor/routetable" + "tailscale.com/feature" "tailscale.com/ipn/ipnlocal" "tailscale.com/net/tsaddr" "tailscale.com/types/logger" ) func init() { + if !feature.Register("doctor") { + return + } ipnlocal.HookDoctor.Set(visitDoctor) ipnlocal.RegisterPeerAPIHandler("/v0/doctor", handleServeDoctor) } diff --git a/feature/favorites/favorites.go b/feature/favorites/favorites.go index ef8411e47..9c1d1beab 100644 --- a/feature/favorites/favorites.go +++ b/feature/favorites/favorites.go @@ -14,6 +14,7 @@ import ( "tailscale.com/ipn" "tailscale.com/ipn/ipnext" "tailscale.com/ipn/ipnlocal" + "tailscale.com/ipn/localapi" "tailscale.com/ipn/store" "tailscale.com/ipn/store/mem" "tailscale.com/types/logger" @@ -23,8 +24,11 @@ import ( const featureName = "favorites" func init() { - feature.Register(featureName) + if !feature.Register(featureName) { + return + } ipnext.RegisterExtension(featureName, newExtension) + localapi.Register("pins", servePins) } // newExtension is the [ipnext.NewExtensionFn] for this feature. diff --git a/feature/favorites/local_api.go b/feature/favorites/local_api.go index e659639eb..b03cd2fad 100644 --- a/feature/favorites/local_api.go +++ b/feature/favorites/local_api.go @@ -13,10 +13,6 @@ import ( "tailscale.com/util/httpm" ) -func init() { - localapi.Register("pins", servePins) -} - // servePins handles GET and POST /localapi/v0/pins for the current profile: GET returns the pinned // favorites, POST applies a [pintype.SetRequest] and returns the updated set. func servePins(h *localapi.Handler, w http.ResponseWriter, r *http.Request) { diff --git a/feature/feature.go b/feature/feature.go index 305f31a12..2ab985dde 100644 --- a/feature/feature.go +++ b/feature/feature.go @@ -29,12 +29,35 @@ func Registered() map[string]bool { return in } // in which case its init does not run. func IsRegistered(name string) bool { return in[name] } -// Register notes that the named feature is linked into the binary. -func Register(name string) { +// Register notes that the named feature is linked into the binary and +// reports whether it should initialize itself. It reports false if the +// feature was disabled via the TS_DISABLE_FEATURE environment variable, +// in which case the feature is not recorded as registered and the +// caller should skip the rest of its registration, such as setting +// hooks and registering extensions and handlers. The typical use is at +// the top of a feature package's init: +// +// func init() { +// if !feature.Register("foo") { +// return +// } +// // ... set hooks, register extensions and handlers ... +// } +// +// A feature package with more than one init that registers things puts +// this gate in one of them and guards the others with [Disabled], or +// better, consolidates them into a single init. +// +// Register panics if the feature is already registered. +func Register(name string) bool { + if Disabled(name) { + return false + } if _, ok := in[name]; ok { panic("duplicate feature registration for " + name) } in[name] = true + return true } // Hook is a func that can only be set once. @@ -54,7 +77,15 @@ func (h *Hook[Func]) IsSet() bool { // or f is the zero value. // // It's meant to be called in init. +// +// As a backstop for feature packages that forget to consult +// [Register], if the caller is a package under tailscale.com/feature/ +// whose feature was disabled via TS_DISABLE_FEATURE, the call is +// silently ignored and the hook is left unset. func (h *Hook[Func]) Set(f Func) { + if callerFeatureDisabled() { + return + } if h.ok { panic("Set on already-set feature hook") } @@ -110,7 +141,13 @@ type Hooks[Func any] []Func // Add should only be called during early program // startup before Tailscale has started. // It is not safe for concurrent use. +// +// Like [Hook.Set], it is silently ignored if the calling feature +// package was disabled via TS_DISABLE_FEATURE. func (h *Hooks[Func]) Add(f Func) { + if callerFeatureDisabled() { + return + } if reflect.ValueOf(f).IsZero() { panic("Add with zero value") } diff --git a/feature/identityfederation/identityfederation.go b/feature/identityfederation/identityfederation.go index c7eb8960f..4e41f45f5 100644 --- a/feature/identityfederation/identityfederation.go +++ b/feature/identityfederation/identityfederation.go @@ -23,7 +23,9 @@ import ( ) func init() { - feature.Register("identityfederation") + if !feature.Register("identityfederation") { + return + } tailscale.HookResolveAuthKeyViaWIF.Set(resolveAuthKey) tailscale.HookExchangeJWTForTokenViaWIF.Set(exchangeJWTForToken) } diff --git a/feature/linkspeed/linkspeed_linux.go b/feature/linkspeed/linkspeed_linux.go index 4e36e281c..d5c2979b3 100644 --- a/feature/linkspeed/linkspeed_linux.go +++ b/feature/linkspeed/linkspeed_linux.go @@ -10,10 +10,14 @@ import ( "github.com/mdlayher/netlink" "github.com/tailscale/wireguard-go/tun" "golang.org/x/sys/unix" + "tailscale.com/feature" "tailscale.com/net/tstun" ) func init() { + if !feature.Register("linkspeed") { + return + } tstun.HookSetLinkAttrs.Set(setLinkAttrs) } diff --git a/feature/linuxdnsfight/linuxdnsfight.go b/feature/linuxdnsfight/linuxdnsfight.go index ea37ed7a5..143a3144a 100644 --- a/feature/linuxdnsfight/linuxdnsfight.go +++ b/feature/linuxdnsfight/linuxdnsfight.go @@ -12,10 +12,14 @@ import ( "fmt" "github.com/illarion/gonotify/v3" + "tailscale.com/feature" "tailscale.com/net/dns" ) func init() { + if !feature.Register("linuxdnsfight") { + return + } dns.HookWatchFile.Set(watchFile) } diff --git a/feature/netlog/netlog.go b/feature/netlog/netlog.go index 2f85d671c..27d7adb02 100644 --- a/feature/netlog/netlog.go +++ b/feature/netlog/netlog.go @@ -19,7 +19,9 @@ import ( ) func init() { - feature.Register("netlog") + if !feature.Register("netlog") { + return + } wgengine.HookNewNetLogger.Set(newNetLogger) } diff --git a/feature/oauthkey/oauthkey.go b/feature/oauthkey/oauthkey.go index d2e6d050c..cbc540fb0 100644 --- a/feature/oauthkey/oauthkey.go +++ b/feature/oauthkey/oauthkey.go @@ -19,7 +19,9 @@ import ( ) func init() { - feature.Register("oauthkey") + if !feature.Register("oauthkey") { + return + } tailscale.HookResolveAuthKey.Set(resolveAuthKey) } diff --git a/feature/portlist/portlist.go b/feature/portlist/portlist.go index 8068783b4..c6e815e01 100644 --- a/feature/portlist/portlist.go +++ b/feature/portlist/portlist.go @@ -10,6 +10,7 @@ import ( "sync/atomic" "tailscale.com/envknob" + "tailscale.com/feature" "tailscale.com/ipn" "tailscale.com/ipn/ipnext" "tailscale.com/ipn/ipnlocal" @@ -22,6 +23,9 @@ import ( ) func init() { + if !feature.Register("portlist") { + return + } ipnext.RegisterExtension("portlist", newExtension) } diff --git a/feature/portmapper/portmapper.go b/feature/portmapper/portmapper.go index 3d2004993..87735e9d0 100644 --- a/feature/portmapper/portmapper.go +++ b/feature/portmapper/portmapper.go @@ -15,7 +15,9 @@ import ( ) func init() { - feature.Register("portmapper") + if !feature.Register("portmapper") { + return + } portmappertype.HookNewPortMapper.Set(newPortMapper) } diff --git a/feature/posture/posture.go b/feature/posture/posture.go index 0c60d38b0..1a72be496 100644 --- a/feature/posture/posture.go +++ b/feature/posture/posture.go @@ -11,6 +11,7 @@ import ( "fmt" "net/http" + "tailscale.com/feature" "tailscale.com/health" "tailscale.com/ipn/ipnext" "tailscale.com/ipn/ipnlocal" @@ -23,6 +24,9 @@ import ( ) func init() { + if !feature.Register("posture") { + return + } ipnext.RegisterExtension("posture", newExtension) ipnlocal.RegisterC2N("GET /posture/identity", handleC2NPostureIdentityGet) } diff --git a/feature/register_disable_test.go b/feature/register_disable_test.go new file mode 100644 index 000000000..dd6390a84 --- /dev/null +++ b/feature/register_disable_test.go @@ -0,0 +1,126 @@ +// Copyright (c) Tailscale Inc & contributors +// SPDX-License-Identifier: BSD-3-Clause + +package feature_test + +import ( + "encoding/json" + "os" + "os/exec" + "slices" + "strings" + "testing" + + // Link all the features that tailscaled links, so that this test + // binary registers the same set that the daemon does. + _ "tailscale.com/feature/condregister" + + "tailscale.com/feature" + "tailscale.com/net/netcheck" +) + +// childModeEnv, when set in this test binary's own environment, makes +// it print its feature registration state as JSON and exit, instead of +// running tests. TestDisableFeature runs the test binary as a child +// process with TS_DISABLE_FEATURE set, because features register +// themselves from package init, before any test could run. +const childModeEnv = "TS_TEST_FEATURE_DISABLE_CHILD" + +// childReport is the JSON printed by the test binary in child mode. +type childReport struct { + Registered []string `json:"registered"` + + // CaptivePortalHookSet reports whether + // netcheck.HookStartCaptivePortalDetection was set. That hook is + // set from the init of feature/captiveportal/netcheckhook, a + // sub-package with no feature.Register gate of its own, so it + // verifies the stack-walking backstop in feature.Hook.Set. + CaptivePortalHookSet bool `json:"captivePortalHookSet"` +} + +func TestMain(m *testing.M) { + if os.Getenv(childModeEnv) != "" { + printChildReport() + os.Exit(0) + } + os.Exit(m.Run()) +} + +func printChildReport() { + var rep childReport + for name := range feature.Registered() { + rep.Registered = append(rep.Registered, name) + } + slices.Sort(rep.Registered) + rep.CaptivePortalHookSet = netcheck.HookStartCaptivePortalDetection.IsSet() + json.NewEncoder(os.Stdout).Encode(rep) +} + +// childReportForEnv runs this test binary as a child process with +// TS_DISABLE_FEATURE set to disableEnv (or unset, if empty), and +// returns its report. +func childReportForEnv(t *testing.T, disableEnv string) childReport { + t.Helper() + cmd := exec.Command(os.Args[0]) + cmd.Env = append(os.Environ(), childModeEnv+"=1", "TS_DISABLE_FEATURE="+disableEnv) + cmd.Stderr = os.Stderr + out, err := cmd.Output() + if err != nil { + t.Fatalf("running child test binary: %v", err) + } + var rep childReport + if err := json.Unmarshal(out, &rep); err != nil { + t.Fatalf("parsing child report %q: %v", out, err) + } + return rep +} + +func TestDisableFeature(t *testing.T) { + // Baseline: with the env var unset, everything this binary links + // registers itself. + base := childReportForEnv(t, "") + if len(base.Registered) == 0 { + t.Fatal("no features registered in child; this test binary links no features") + } + if !base.CaptivePortalHookSet { + t.Fatal("captive portal netcheck hook not set at baseline") + } + + // Disabling every registered feature must disable every one of + // them. A feature that ignores TS_DISABLE_FEATURE shows up here as + // still registered. + all := childReportForEnv(t, strings.Join(base.Registered, ",")) + for _, name := range all.Registered { + t.Errorf("feature %q still registered after being disabled", name) + } + if all.CaptivePortalHookSet { + t.Error("captive portal netcheck hook still set after captiveportal was disabled") + } + + // Spot checks of individual features, including the accepted + // spellings: the ts_omit_ build-tag prefix, underscores in place of + // dashes, surrounding spaces, and mixed case. + tests := []struct { + disableEnv string + feature string + }{ + {"ssh", "ssh"}, + {"taildrop", "taildrop"}, + {"acme", "acme"}, + {" TS_OMIT_TAILDROP , tailNETLock ", "tailnetlock"}, + } + for _, tt := range tests { + rep := childReportForEnv(t, tt.disableEnv) + if slices.Contains(rep.Registered, tt.feature) { + t.Errorf("feature %q still registered with TS_DISABLE_FEATURE=%q", tt.feature, tt.disableEnv) + } + } + + // An unknown feature name is ignored, not fatal: everything else + // still registers. + unknown := childReportForEnv(t, "not-a-feature") + if len(unknown.Registered) != len(base.Registered) { + t.Errorf("TS_DISABLE_FEATURE=not-a-feature registered %d features; want %d (the full baseline set)", + len(unknown.Registered), len(base.Registered)) + } +} diff --git a/feature/relayserver/relayserver.go b/feature/relayserver/relayserver.go index 4ed84e4c6..1fd9602ec 100644 --- a/feature/relayserver/relayserver.go +++ b/feature/relayserver/relayserver.go @@ -34,7 +34,9 @@ import ( const featureName = "relayserver" func init() { - feature.Register(featureName) + if !feature.Register(featureName) { + return + } ipnext.RegisterExtension(featureName, newExtension) localapi.Register("debug-peer-relay-sessions", servePeerRelayDebugSessions) } diff --git a/feature/remoteconfig/remoteconfig.go b/feature/remoteconfig/remoteconfig.go index 07baa9c94..847689c89 100644 --- a/feature/remoteconfig/remoteconfig.go +++ b/feature/remoteconfig/remoteconfig.go @@ -42,7 +42,9 @@ const c2nPrefix = "/remoteapi/localapi/" const localAPIStrip = "/remoteapi" func init() { - feature.Register("remoteconfig") + if !feature.Register("remoteconfig") { + return + } ipnlocal.RegisterC2NPrefix(c2nPrefix, handleC2NRemoteAPI) } diff --git a/feature/routecheck/localapi.go b/feature/routecheck/localapi.go index 6f0df7ef6..7e2b1e780 100644 --- a/feature/routecheck/localapi.go +++ b/feature/routecheck/localapi.go @@ -19,11 +19,6 @@ import ( "tailscale.com/util/httpm" ) -func init() { - localapi.Register("routecheck", serveRouteCheck) - localapi.HookRouteCheckRefresh.Set(routeCheckRefresh) -} - // ServeRouteCheck handles the API endpoint that serves the routecheck Report. // If the probe form field is true, then this handler will refresh the Report // before serving it. diff --git a/feature/routecheck/routecheck.go b/feature/routecheck/routecheck.go index e4682c0d5..18ca38e01 100644 --- a/feature/routecheck/routecheck.go +++ b/feature/routecheck/routecheck.go @@ -18,8 +18,10 @@ import ( "fmt" "sync" + "tailscale.com/feature" "tailscale.com/ipn/ipnext" "tailscale.com/ipn/ipnlocal" + "tailscale.com/ipn/localapi" "tailscale.com/net/routecheck" "tailscale.com/tailcfg" "tailscale.com/types/logger" @@ -31,6 +33,9 @@ import ( const featureName = "routecheck" func init() { + if !feature.Register(featureName) { + return + } ipnext.RegisterExtension(featureName, func(logf logger.Logf, b ipnext.SafeBackend) (ipnext.Extension, error) { return &Extension{ logf: logger.WithPrefix(logf, featureName+": "), @@ -39,6 +44,8 @@ func init() { }) ipnlocal.HookRouteCheckReport.Set(routeCheckReport) + localapi.Register("routecheck", serveRouteCheck) + localapi.HookRouteCheckRefresh.Set(routeCheckRefresh) } // Extension implements the [ipnext.Extension] interface. diff --git a/feature/runtimemetrics/runtimemetrics.go b/feature/runtimemetrics/runtimemetrics.go index fd9b54ee9..508383414 100644 --- a/feature/runtimemetrics/runtimemetrics.go +++ b/feature/runtimemetrics/runtimemetrics.go @@ -15,7 +15,9 @@ import ( ) func init() { - feature.Register("runtimemetrics") + if !feature.Register("runtimemetrics") { + return + } ipnlocal.HookSetRuntimeMetricsEnabled.Set(setEnabled) } diff --git a/feature/sdnotify/sdnotify_linux.go b/feature/sdnotify/sdnotify_linux.go index 6a3df8796..ee1fe3008 100644 --- a/feature/sdnotify/sdnotify_linux.go +++ b/feature/sdnotify/sdnotify_linux.go @@ -16,6 +16,9 @@ import ( ) func init() { + if !feature.Register("sdnotify") { + return + } feature.HookSystemdReady.Set(ready) feature.HookSystemdStatus.Set(status) } diff --git a/feature/serviceclientprefs/local_api.go b/feature/serviceclientprefs/local_api.go index b99de295e..303cf5a32 100644 --- a/feature/serviceclientprefs/local_api.go +++ b/feature/serviceclientprefs/local_api.go @@ -15,10 +15,6 @@ import ( "tailscale.com/util/httpm" ) -func init() { - localapi.Register("prefs/service-clients", serveServiceClientPrefs) -} - // serveServiceClientPrefs handles GET and POST /localapi/v0/prefs/service-clients. GET returns all // of the current profile's service client prefs. POST merges one [apitype.ServiceClientPrefRequest] // into the saved service client prefs and returns the full updated set. diff --git a/feature/serviceclientprefs/serviceclientprefs.go b/feature/serviceclientprefs/serviceclientprefs.go index 88a2d2cfe..260debb35 100644 --- a/feature/serviceclientprefs/serviceclientprefs.go +++ b/feature/serviceclientprefs/serviceclientprefs.go @@ -14,6 +14,7 @@ import ( "tailscale.com/ipn" "tailscale.com/ipn/ipnext" "tailscale.com/ipn/ipnlocal" + "tailscale.com/ipn/localapi" "tailscale.com/ipn/store" "tailscale.com/ipn/store/mem" "tailscale.com/types/logger" @@ -25,8 +26,11 @@ const featureName = "serviceclientprefs" const storeKey = "service-client-prefs" func init() { - feature.Register(featureName) + if !feature.Register(featureName) { + return + } ipnext.RegisterExtension(featureName, newExtension) + localapi.Register("prefs/service-clients", serveServiceClientPrefs) } // newExtension is the [ipnext.NewExtensionFn] for this feature. diff --git a/feature/ssh/ssh.go b/feature/ssh/ssh.go index bd2200591..b772db004 100644 --- a/feature/ssh/ssh.go +++ b/feature/ssh/ssh.go @@ -7,5 +7,14 @@ // management and the SSH server. package ssh -// Register implementations of various SSH hooks. -import _ "tailscale.com/ssh/tailssh" +import ( + "tailscale.com/feature" + "tailscale.com/ssh/tailssh" +) + +func init() { + if !feature.Register("ssh") { + return + } + tailssh.Register() +} diff --git a/feature/syslog/syslog.go b/feature/syslog/syslog.go index b3301beb6..89961a499 100644 --- a/feature/syslog/syslog.go +++ b/feature/syslog/syslog.go @@ -18,7 +18,9 @@ import ( ) func init() { - feature.Register("syslog") + if !feature.Register("syslog") { + return + } feature.HookRegisterLogSinkFlags.Set(registerFlags) feature.HookLogSink.Set(logSink) } diff --git a/feature/syspolicy/syspolicy.go b/feature/syspolicy/syspolicy.go index dce2eb0b1..044e294e9 100644 --- a/feature/syspolicy/syspolicy.go +++ b/feature/syspolicy/syspolicy.go @@ -4,4 +4,12 @@ // Package syspolicy provides an interface for system-wide policy management. package syspolicy -import _ "tailscale.com/util/syspolicy" // for its registration side effects +import ( + "tailscale.com/feature" + + _ "tailscale.com/util/syspolicy" // for its registration side effects +) + +func init() { + feature.Register("syspolicy") +} diff --git a/feature/taildrop/ext.go b/feature/taildrop/ext.go index c95832cec..1f79e302a 100644 --- a/feature/taildrop/ext.go +++ b/feature/taildrop/ext.go @@ -18,9 +18,12 @@ import ( "tailscale.com/client/tailscale/apitype" "tailscale.com/cmd/tailscaled/tailscaledhooks" + "tailscale.com/feature" "tailscale.com/ipn" "tailscale.com/ipn/ipnext" + "tailscale.com/ipn/ipnlocal" "tailscale.com/ipn/ipnstate" + "tailscale.com/ipn/localapi" "tailscale.com/tailcfg" "tailscale.com/tailcfg/nodecap" "tailscale.com/tailcfg/peercap" @@ -32,7 +35,14 @@ import ( ) func init() { + if !feature.Register("taildrop") { + return + } ipnext.RegisterExtension("taildrop", newExtension) + ipnlocal.RegisterPeerAPIHandler("/v0/put/", handlePeerPut) + localapi.Register("file-put/", serveFilePut) + localapi.Register("files/", serveFiles) + localapi.Register("file-targets", serveFileTargets) if runtime.GOOS == "windows" { tailscaledhooks.UninstallSystemDaemonWindows.Add(func() { diff --git a/feature/taildrop/localapi.go b/feature/taildrop/localapi.go index b11482b10..1d5296323 100644 --- a/feature/taildrop/localapi.go +++ b/feature/taildrop/localapi.go @@ -32,12 +32,6 @@ import ( "tailscale.com/util/rands" ) -func init() { - localapi.Register("file-put/", serveFilePut) - localapi.Register("files/", serveFiles) - localapi.Register("file-targets", serveFileTargets) -} - var ( metricFilePutCalls = clientmetric.NewCounter("localapi_file_put") ) diff --git a/feature/taildrop/peerapi.go b/feature/taildrop/peerapi.go index 53ea10dd9..62a51ae65 100644 --- a/feature/taildrop/peerapi.go +++ b/feature/taildrop/peerapi.go @@ -19,10 +19,6 @@ import ( "tailscale.com/util/httphdr" ) -func init() { - ipnlocal.RegisterPeerAPIHandler("/v0/put/", handlePeerPut) -} - var ( metricPutCalls = clientmetric.NewCounter("peerapi_put") ) diff --git a/feature/tailnetlock/tailnetlock.go b/feature/tailnetlock/tailnetlock.go index 928e48886..872f3fc71 100644 --- a/feature/tailnetlock/tailnetlock.go +++ b/feature/tailnetlock/tailnetlock.go @@ -18,7 +18,9 @@ import ( ) func init() { - feature.Register("tailnetlock") + if !feature.Register("tailnetlock") { + return + } ipnlocal.RegisterC2N("/debug/tka/log", handleC2NDebugTKALog) } diff --git a/feature/tap/tap_linux.go b/feature/tap/tap_linux.go index 2b4210761..87953fbdb 100644 --- a/feature/tap/tap_linux.go +++ b/feature/tap/tap_linux.go @@ -23,6 +23,7 @@ import ( "gvisor.dev/gvisor/pkg/tcpip/network/ipv4" "gvisor.dev/gvisor/pkg/tcpip/network/ipv6" "gvisor.dev/gvisor/pkg/tcpip/transport/udp" + "tailscale.com/feature" "tailscale.com/net/netaddr" "tailscale.com/net/packet" "tailscale.com/net/tsaddr" @@ -41,6 +42,9 @@ var ourMAC = net.HardwareAddr{0x30, 0x2D, 0x66, 0xEC, 0x7A, 0x93} const tapDebug = tstun.TAPDebug func init() { + if !feature.Register("tap") { + return + } tstun.CreateTAP.Set(createTAPLinux) } diff --git a/feature/tpm/tpm.go b/feature/tpm/tpm.go index a30bb1134..fdf392057 100644 --- a/feature/tpm/tpm.go +++ b/feature/tpm/tpm.go @@ -41,7 +41,9 @@ var ( ) func init() { - feature.Register("tpm") + if !feature.Register("tpm") { + return + } feature.HookTPMAvailable.Set(tpmSupportedOnce) feature.HookHardwareAttestationAvailable.Set(tpmSupportedOnce) diff --git a/feature/tundevstats/tundevstats_linux.go b/feature/tundevstats/tundevstats_linux.go index 13d5169c2..30a536aad 100644 --- a/feature/tundevstats/tundevstats_linux.go +++ b/feature/tundevstats/tundevstats_linux.go @@ -24,7 +24,9 @@ import ( ) func init() { - feature.Register("tundevstats") + if !feature.Register("tundevstats") { + return + } if runtime.GOOS != "linux" { // Exclude Android for now. There's no reason this shouldn't work on // Android, but it needs to be tested, and justified from a battery diff --git a/feature/useproxy/useproxy.go b/feature/useproxy/useproxy.go index 96be23710..d386096f2 100644 --- a/feature/useproxy/useproxy.go +++ b/feature/useproxy/useproxy.go @@ -10,6 +10,9 @@ import ( ) func init() { + if !feature.Register("useproxy") { + return + } feature.HookProxyFromEnvironment.Set(tshttpproxy.ProxyFromEnvironment) feature.HookProxyInvalidateCache.Set(tshttpproxy.InvalidateCache) feature.HookProxyGetAuthHeader.Set(tshttpproxy.GetAuthHeader) diff --git a/feature/wakeonlan/wakeonlan.go b/feature/wakeonlan/wakeonlan.go index 52c961eed..a8e567ef7 100644 --- a/feature/wakeonlan/wakeonlan.go +++ b/feature/wakeonlan/wakeonlan.go @@ -25,7 +25,9 @@ import ( ) func init() { - feature.Register("wakeonlan") + if !feature.Register("wakeonlan") { + return + } ipnlocal.RegisterC2N("POST /wol", handleC2NWoL) ipnlocal.RegisterPeerAPIHandler("/v0/wol", handlePeerAPIWakeOnLAN) hostinfo.RegisterHostinfoNewHook(func(h *tailcfg.Hostinfo) { diff --git a/ipn/auditlog/extension.go b/ipn/auditlog/extension.go index 293d3742c..e403f145d 100644 --- a/ipn/auditlog/extension.go +++ b/ipn/auditlog/extension.go @@ -25,7 +25,9 @@ import ( const featureName = "auditlog" func init() { - feature.Register(featureName) + if !feature.Register(featureName) { + return + } ipnext.RegisterExtension(featureName, newExtension) } diff --git a/ipn/desktop/extension.go b/ipn/desktop/extension.go index 1d51b37ec..97a192091 100644 --- a/ipn/desktop/extension.go +++ b/ipn/desktop/extension.go @@ -31,7 +31,9 @@ import ( const featureName = "desktop-sessions" func init() { - feature.Register(featureName) + if !feature.Register(featureName) { + return + } ipnext.RegisterExtension(featureName, newDesktopSessionsExt) } diff --git a/ipn/ipnext/ipnext.go b/ipn/ipnext/ipnext.go index 1e817c084..32565b2c0 100644 --- a/ipn/ipnext/ipnext.go +++ b/ipn/ipnext/ipnext.go @@ -115,7 +115,14 @@ var extensions mapx.OrderedMap[string, *Definition] // // It panics if newExt is nil or if an extension with the same name // has already been registered. +// +// As a backstop for feature packages that forget to consult +// feature.Register, it does nothing if the named feature was disabled +// via the TS_DISABLE_FEATURE environment variable. func RegisterExtension(name string, newExt NewExtensionFn) { + if feature.Disabled(name) { + return + } if newExt == nil { panic(fmt.Sprintf("ipnext: newExt is nil: %q", name)) } diff --git a/ipn/localapi/debug.go b/ipn/localapi/debug.go index 4d99e1778..6b304b752 100644 --- a/ipn/localapi/debug.go +++ b/ipn/localapi/debug.go @@ -565,6 +565,7 @@ func (h *Handler) serveDebugLog(w http.ResponseWriter, r *http.Request) { func (h *Handler) serveDebugOptionalFeatures(w http.ResponseWriter, r *http.Request) { of := &apitype.OptionalFeatures{ Features: feature.Registered(), + Disabled: feature.EnvDisabled(), } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(of) diff --git a/ipn/store/awsstore/store_aws.go b/ipn/store/awsstore/store_aws.go index 43d8e059c..67fecb087 100644 --- a/ipn/store/awsstore/store_aws.go +++ b/ipn/store/awsstore/store_aws.go @@ -19,6 +19,7 @@ import ( "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/service/ssm" ssmTypes "github.com/aws/aws-sdk-go-v2/service/ssm/types" + "tailscale.com/feature" "tailscale.com/ipn" "tailscale.com/ipn/store" "tailscale.com/ipn/store/mem" @@ -26,6 +27,9 @@ import ( ) func init() { + if !feature.Register("aws") { + return + } store.Register("arn:", func(logf logger.Logf, arg string) (ipn.StateStore, error) { ssmARN, opts, err := ParseARNAndOpts(arg) if err != nil { diff --git a/ipn/store/kubestore/store_kube.go b/ipn/store/kubestore/store_kube.go index bfc287baa..992a3e052 100644 --- a/ipn/store/kubestore/store_kube.go +++ b/ipn/store/kubestore/store_kube.go @@ -17,6 +17,7 @@ import ( "time" "tailscale.com/envknob" + "tailscale.com/feature" "tailscale.com/ipn" "tailscale.com/ipn/store" "tailscale.com/ipn/store/mem" @@ -29,6 +30,9 @@ import ( ) func init() { + if !feature.Register("kube") { + return + } store.Register("kube:", func(logf logger.Logf, path string) (ipn.StateStore, error) { secretName := strings.TrimPrefix(path, "kube:") return New(logf, secretName) diff --git a/ssh/tailssh/incubator.go b/ssh/tailssh/incubator.go index 5eb409a5f..d502b8b5f 100644 --- a/ssh/tailssh/incubator.go +++ b/ssh/tailssh/incubator.go @@ -54,7 +54,10 @@ const ( windows = "windows" ) -func init() { +// registerIncubator registers the incubator child process handlers. +// It is called from [Register], which is called from the init of +// tailscale.com/feature/ssh. +func registerIncubator() { childproc.Add("ssh", beIncubator) childproc.Add("sftp", beSFTP) } diff --git a/ssh/tailssh/incubator_plan9.go b/ssh/tailssh/incubator_plan9.go index 4eb945914..65bc3575e 100644 --- a/ssh/tailssh/incubator_plan9.go +++ b/ssh/tailssh/incubator_plan9.go @@ -31,7 +31,10 @@ import ( "tailscale.com/types/logger" ) -func init() { +// registerIncubator registers the incubator child process handlers. +// It is called from [Register], which is called from the init of +// tailscale.com/feature/ssh. +func registerIncubator() { childproc.Add("ssh", beIncubator) childproc.Add("sftp", beSFTP) childproc.Add("plan9-netshell", beNetshell) diff --git a/ssh/tailssh/listen.go b/ssh/tailssh/listen.go index 8c98127f2..d9ab13318 100644 --- a/ssh/tailssh/listen.go +++ b/ssh/tailssh/listen.go @@ -16,8 +16,13 @@ import ( "tailscale.com/types/logger" ) -func init() { +// Register installs tailssh's hooks and child process handlers. It is +// called from the init of tailscale.com/feature/ssh, which skips it if +// the ssh feature was disabled via TS_DISABLE_FEATURE or omitted from +// the build. +func Register() { ipnlocal.HookListenSSH.Set(listenSSH) + registerIncubator() } // listenSSH wraps rawLn with an SSH server that resolves Tailscale peer diff --git a/util/syspolicy/syspolicy_windows.go b/util/syspolicy/syspolicy_windows.go index 80c84b457..836ed0bd5 100644 --- a/util/syspolicy/syspolicy_windows.go +++ b/util/syspolicy/syspolicy_windows.go @@ -8,6 +8,7 @@ import ( "fmt" "os/user" + "tailscale.com/feature" "tailscale.com/util/syspolicy/internal" "tailscale.com/util/syspolicy/rsop" "tailscale.com/util/syspolicy/setting" @@ -31,7 +32,14 @@ func init() { // External code, such as the ipnlocal package, may choose to register // additional policy stores, such as config files and policies received from // the control plane. + // + // The syspolicy feature is registered by tailscale.com/feature/syspolicy; + // its default store registration here respects TS_DISABLE_FEATURE in case + // this package is linked by something other than the feature system. internal.Init.MustDefer(func() error { + if feature.Disabled("syspolicy") { + return nil + } // Do not register or use default policy stores during tests. // Each test should set up its own necessary configurations. if testenv.InTest() {