feature: add TS_DISABLE_FEATURE to disable features at runtime

The ts_omit_<name> build tags omit a feature at build time; there has
been no way to do the same at runtime. Some users (either proactively
or in response to a security announcement) might like a way to disable
a feature that's linked-in in their binaries that they're not using.
Then a mitigation announcement can say "set this env var" without
asking users to rebuild or wait for a new release.

This adds env var TS_DISABLE_FEATURE, a comma-separated list of
feature names to disable, and the listed set is reported by the
debug-optional-features LocalAPI endpoint next to the registered set.
The legacy per-feature knobs such as TS_DISABLE_SSH_SERVER and
TS_DISABLE_TAILDROP keep working independently.

A disabled feature behaves as if it had not been linked: it is absent
from feature.IsRegistered, its hooks are unset, and its extensions and
handlers are not registered. Three pieces make that happen:

  * feature.Register now returns bool, false when disabled, and
    feature packages gate their registration init on it. It was added
    to the feature packages that never called it (including taildrop
    and ssh), which also completes the picture reported by
    debug-optional-features. taildrop, routecheck, favorites, and
    serviceclientprefs had registration split across several inits and
    now register from one gated init.
  * ipnext.RegisterExtension ignores a disabled feature's extension.
  * feature.Hook.Set and feature.Hooks.Add walk the call stack and
    silently skip when the calling package under feature/<name> is
    disabled. This covers sub-packages such as
    feature/captiveportal/netcheckhook, which cannot call Register
    themselves without colliding with their parent, and future
    packages whose authors forget the gate.

ssh/tailssh's registrations moved from its inits into tailssh.Register,
called from feature/ssh's gated init. The aws and kube state stores and
syspolicy's Windows store registration are gated too.

feature/register_disable_test.go runs this test binary as a child
process (it links condregister, as tailscaled does) with
TS_DISABLE_FEATURE set to every registered feature at once, and fails
if any of them register anyway, so a feature that ignores the variable
cannot land.

Updates #12614

Signed-off-by: Brad Fitzpatrick <[email protected]>
Change-Id: I720af6ccab844ae060a9dfd1539fee577fd483e3
This commit is contained in:
Brad Fitzpatrick authored and Brad Fitzpatrick committed 2026-09-15 08:37:47 -07:00
1 parent 1a311b7e3c
commit 2ee809d10d
64 files changed
+668 -62

No files matched your search

+6
View File
@@ -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.
+1 -1
View File
@@ -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+
+79 -3
View File
@@ -42,6 +42,72 @@ When you touch one of these features, prefer to keep migrating code into
its `feature/<name>` 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_<name>` 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/<x>` 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/<name>/` with the code, and register hooks and any
`ipnext.Extension` from its `init`. Call `feature.Register("<name>")`
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("<name>") {
return
}
// ... set hooks, register extensions and handlers ...
}
4. If the feature should be on by default in `tailscaled`, add
`feature/condregister/maybe_<name>.go` with `//go:build !ts_omit_<name>`
and a blank import of `tailscale.com/feature/<name>`.
+4
View File
@@ -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)
}
+3 -1
View File
@@ -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)
+8 -1
View File
@@ -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
}
+7 -1
View File
@@ -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)
}
+5
View File
@@ -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
}
+4
View File
@@ -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)
}
+3 -1
View File
@@ -21,7 +21,9 @@ import (
)
func init() {
feature.Register("awsparamstore")
if !feature.Register("awsparamstore") {
return
}
tailscale.HookResolveValueFromParameterStore.Set(ResolveValue)
}
+3 -1
View File
@@ -19,7 +19,9 @@ import (
)
func init() {
feature.Register("bird")
if !feature.Register("bird") {
return
}
wgengine.HookNewBird.Set(newBird)
}
+4
View File
@@ -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)
}
+3 -1
View File
@@ -26,7 +26,9 @@ import (
const featureName = "captiveportal"
func init() {
feature.Register(featureName)
if !feature.Register(featureName) {
return
}
ipnext.RegisterExtension(featureName, newExtension)
}
+3 -1
View File
@@ -20,7 +20,9 @@ import (
)
func init() {
feature.Register("capture")
if !feature.Register("capture") {
return
}
localapi.Register("debug-capture", serveLocalAPIDebugCapture)
}
+3 -1
View File
@@ -36,7 +36,9 @@ import (
)
func init() {
feature.Register("clientupdate")
if !feature.Register("clientupdate") {
return
}
ipnext.RegisterExtension("clientupdate", newExt)
// C2N
+3 -1
View File
@@ -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: ")),
+3 -1
View File
@@ -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)
@@ -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)
}
+139
View File
@@ -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_<name> 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
}
}
}
+58
View File
@@ -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
}
}
}
}
+3 -1
View File
@@ -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)
+4
View File
@@ -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)
}
+5 -1
View File
@@ -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.
-4
View File
@@ -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) {
+39 -2
View File
@@ -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")
}
@@ -23,7 +23,9 @@ import (
)
func init() {
feature.Register("identityfederation")
if !feature.Register("identityfederation") {
return
}
tailscale.HookResolveAuthKeyViaWIF.Set(resolveAuthKey)
tailscale.HookExchangeJWTForTokenViaWIF.Set(exchangeJWTForToken)
}
+4
View File
@@ -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)
}
+4
View File
@@ -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)
}
+3 -1
View File
@@ -19,7 +19,9 @@ import (
)
func init() {
feature.Register("netlog")
if !feature.Register("netlog") {
return
}
wgengine.HookNewNetLogger.Set(newNetLogger)
}
+3 -1
View File
@@ -19,7 +19,9 @@ import (
)
func init() {
feature.Register("oauthkey")
if !feature.Register("oauthkey") {
return
}
tailscale.HookResolveAuthKey.Set(resolveAuthKey)
}
+4
View File
@@ -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)
}
+3 -1
View File
@@ -15,7 +15,9 @@ import (
)
func init() {
feature.Register("portmapper")
if !feature.Register("portmapper") {
return
}
portmappertype.HookNewPortMapper.Set(newPortMapper)
}
+4
View File
@@ -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)
}
+126
View File
@@ -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))
}
}
+3 -1
View File
@@ -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)
}
+3 -1
View File
@@ -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)
}
-5
View File
@@ -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.
+7
View File
@@ -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.
+3 -1
View File
@@ -15,7 +15,9 @@ import (
)
func init() {
feature.Register("runtimemetrics")
if !feature.Register("runtimemetrics") {
return
}
ipnlocal.HookSetRuntimeMetricsEnabled.Set(setEnabled)
}
+3
View File
@@ -16,6 +16,9 @@ import (
)
func init() {
if !feature.Register("sdnotify") {
return
}
feature.HookSystemdReady.Set(ready)
feature.HookSystemdStatus.Set(status)
}
-4
View File
@@ -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.
@@ -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.
+11 -2
View File
@@ -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()
}
+3 -1
View File
@@ -18,7 +18,9 @@ import (
)
func init() {
feature.Register("syslog")
if !feature.Register("syslog") {
return
}
feature.HookRegisterLogSinkFlags.Set(registerFlags)
feature.HookLogSink.Set(logSink)
}
+9 -1
View File
@@ -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")
}
+10
View File
@@ -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() {
-6
View File
@@ -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")
)
-4
View File
@@ -19,10 +19,6 @@ import (
"tailscale.com/util/httphdr"
)
func init() {
ipnlocal.RegisterPeerAPIHandler("/v0/put/", handlePeerPut)
}
var (
metricPutCalls = clientmetric.NewCounter("peerapi_put")
)
+3 -1
View File
@@ -18,7 +18,9 @@ import (
)
func init() {
feature.Register("tailnetlock")
if !feature.Register("tailnetlock") {
return
}
ipnlocal.RegisterC2N("/debug/tka/log", handleC2NDebugTKALog)
}
+4
View File
@@ -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)
}
+3 -1
View File
@@ -41,7 +41,9 @@ var (
)
func init() {
feature.Register("tpm")
if !feature.Register("tpm") {
return
}
feature.HookTPMAvailable.Set(tpmSupportedOnce)
feature.HookHardwareAttestationAvailable.Set(tpmSupportedOnce)
+3 -1
View File
@@ -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
+3
View File
@@ -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)
+3 -1
View File
@@ -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) {
+3 -1
View File
@@ -25,7 +25,9 @@ import (
const featureName = "auditlog"
func init() {
feature.Register(featureName)
if !feature.Register(featureName) {
return
}
ipnext.RegisterExtension(featureName, newExtension)
}
+3 -1
View File
@@ -31,7 +31,9 @@ import (
const featureName = "desktop-sessions"
func init() {
feature.Register(featureName)
if !feature.Register(featureName) {
return
}
ipnext.RegisterExtension(featureName, newDesktopSessionsExt)
}
+7
View File
@@ -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))
}
+1
View File
@@ -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)
+4
View File
@@ -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 {
+4
View File
@@ -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)
+4 -1
View File
@@ -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)
}
+4 -1
View File
@@ -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)
+6 -1
View File
@@ -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
+8
View File
@@ -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() {