feature/tailnetsyspolicy,tailcfg,util/syspolicy: add a nodeAttr-based policy store

Add the TailnetSysPolicy (https://tailscale.com/cap/tailnet-syspolicy)
node attribute, whose values map policy setting keys to values,
and an extension that exposes them as a policy store in the current
profile's scope. The store is replaced whenever the self node's attribute
changes and removed as soon as another profile becomes current,
before the policy is applied to that profile's prefs.

The store is only registered if the new AllowTailnetSysPolicy device policy
setting is enabled. Only profile and user settings can be configured this way,
and settings configured for the device, such as via MDM, take precedence.

Updates tailscale/corp#51945

Change-Id: Ic27f180f599d374f9a719877a3037a5f2df30365
Signed-off-by: Nick Khyl <[email protected]>
This commit is contained in:
Nick Khyl committed 2026-11-25 15:07:49 -08:00
1 parent 285f0f038b
commit 88a4fe129f
7 files changed
+540

No files matched your search

+1
View File
@@ -337,6 +337,7 @@ tailscale.com/cmd/tailscaled dependencies: (generated by github.com/tailscale/de
tailscale.com/feature/taildrop from tailscale.com/feature/condregister
tailscale.com/feature/tailnetlock from tailscale.com/feature/condregister
tailscale.com/feature/tailnetlock/tslockjsonv1 from tailscale.com/feature/tailnetlock
tailscale.com/feature/tailnetsyspolicy from tailscale.com/feature/condregister
L tailscale.com/feature/tap from tailscale.com/feature/condregister
tailscale.com/feature/tpm from tailscale.com/feature/condregister
L 💣 tailscale.com/feature/tundevstats from tailscale.com/feature/condregister
@@ -0,0 +1,12 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
// Apple and Android GUI clients need more work to support tailnet system policy.
// Omit this feature until support is added for those platforms.
//go:build !ts_omit_syspolicy && !ts_macext && !android
package condregister
import (
_ "tailscale.com/feature/tailnetsyspolicy"
)
@@ -0,0 +1,151 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
// Package tailnetsyspolicy registers a policy store with the policy settings
// that the control plane sent to the current profile's node
// in the [nodecap.TailnetSysPolicy] node attribute.
package tailnetsyspolicy
import (
"encoding/json"
"sync"
"tailscale.com/feature"
"tailscale.com/ipn"
"tailscale.com/ipn/ipnext"
"tailscale.com/tailcfg"
"tailscale.com/tailcfg/nodecap"
"tailscale.com/types/logger"
"tailscale.com/types/views"
"tailscale.com/util/syspolicy/pkey"
"tailscale.com/util/syspolicy/policyclient"
"tailscale.com/util/syspolicy/rsop"
"tailscale.com/util/syspolicy/setting"
"tailscale.com/util/syspolicy/source"
)
const featureName = "tailnet-syspolicy"
func init() {
if feature.Register(featureName) {
ipnext.RegisterExtension(featureName, newExtension)
}
}
func newExtension(logf logger.Logf, sb ipnext.SafeBackend) (ipnext.Extension, error) {
return &extension{
logf: logger.WithPrefix(logf, featureName+": "),
polc: sb.Sys().PolicyClientOrDefault(),
}, nil
}
// extension keeps a [setting.CurrentProfileScope] policy store in sync with
// the self node's [nodecap.TailnetSysPolicy] values. The store is only registered
// if [pkey.AllowTailnetSysPolicy] is enabled and the node has the attribute.
// Settings in the store are overridden by those configured for the device,
// such as via MDM.
type extension struct {
logf logger.Logf
polc policyclient.Client
host ipnext.Host
unregisterPolicyCb func()
mu sync.Mutex // lock order: LocalBackend.mu, then e.mu
shutdown bool // whether Shutdown has been called
reg *rsop.StoreRegistration // or nil if the store is not registered
vals views.Slice[tailcfg.RawMessage] // values the registered store was created from
}
func (e *extension) Name() string { return featureName }
func (e *extension) Init(h ipnext.Host) error {
e.host = h
unregister, err := e.polc.RegisterChangeCallback("", e.policyChanged)
if err != nil {
return err
}
e.unregisterPolicyCb = unregister
h.Hooks().OnSelfChange.Add(func(tailcfg.NodeView) { e.update() })
h.Hooks().ProfileStateChange.Add(func(ipn.LoginProfileView, ipn.PrefsView, bool) { e.update() })
e.update()
return nil
}
func (e *extension) Shutdown() error {
e.unregisterPolicyCb()
e.mu.Lock()
defer e.mu.Unlock()
e.shutdown = true
reg := e.reg
e.reg, e.vals = nil, views.Slice[tailcfg.RawMessage]{}
if reg == nil {
return nil
}
return reg.Unregister()
}
func (e *extension) policyChanged(pc policyclient.PolicyChange) {
if pc.HasChanged(pkey.AllowTailnetSysPolicy) {
e.update()
}
}
// update registers, replaces or unregisters the store if the current node's
// [nodecap.TailnetSysPolicy] values or [pkey.AllowTailnetSysPolicy] have changed.
//
// When called by LocalBackend, LocalBackend.mu is held, and the store is
// updated before update returns, so on a profile switch the old profile's
// policy settings are gone before LocalBackend applies the policy to the
// new profile's prefs.
func (e *extension) update() {
e.mu.Lock()
defer e.mu.Unlock()
if e.shutdown {
// A policy change callback or a hook may still be running
// after Shutdown and must not register the store again.
return
}
var vals views.Slice[tailcfg.RawMessage]
if allowed, _ := e.polc.GetBoolean(pkey.AllowTailnetSysPolicy, false); allowed {
if self := e.host.NodeBackend().Self(); self.Valid() {
vals = self.CapMap().Get(nodecap.TailnetSysPolicy)
}
}
if views.SliceEqual(vals, e.vals) {
return
}
var reg *rsop.StoreRegistration
var err error
switch {
case vals.Len() == 0:
err = e.reg.Unregister()
case e.reg == nil:
reg, err = rsop.RegisterStore("Tailnet", setting.CurrentProfileScope, source.NewJSONPolicyStore(e.parse(vals)))
default:
reg, err = e.reg.ReplaceStore(source.NewJSONPolicyStore(e.parse(vals)))
}
if err != nil {
e.logf("failed to update the policy store: %v", err)
return
}
e.reg, e.vals = reg, vals
}
// parse returns policy settings merged from vals, each of which is a JSON
// object that maps policy setting keys to values. If more than one of them
// has a value for the same key, the last one wins.
//
// Device settings and unknown keys are not filtered out here: a store in
// [setting.CurrentProfileScope] can only configure profile and user settings.
func (e *extension) parse(vals views.Slice[tailcfg.RawMessage]) map[string]any {
var settings map[string]any
for _, v := range vals.All() {
if err := json.Unmarshal([]byte(v), &settings); err != nil {
e.logf("ignoring an invalid %q value: %v", nodecap.TailnetSysPolicy, err)
}
}
return settings
}
@@ -0,0 +1,355 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package tailnetsyspolicy
import (
"net/netip"
"testing"
"time"
"tailscale.com/ipn"
"tailscale.com/ipn/ipnlocal"
"tailscale.com/ipn/ipnlocal/ipnlocaltest"
"tailscale.com/tailcfg"
"tailscale.com/tailcfg/nodecap"
"tailscale.com/tsd"
"tailscale.com/tstest"
"tailscale.com/types/key"
"tailscale.com/types/netmap"
"tailscale.com/types/persist"
"tailscale.com/util/eventbus/eventbustest"
"tailscale.com/util/syspolicy/pkey"
"tailscale.com/util/syspolicy/policyclient"
"tailscale.com/util/syspolicy/ptype"
"tailscale.com/util/syspolicy/rsop"
"tailscale.com/util/syspolicy/setting"
"tailscale.com/util/syspolicy/source"
)
// newTestBackend returns a backend with the extension initialized and
// [pkey.AllowTailnetSysPolicy] set to allow in a device policy store.
func newTestBackend(t *testing.T, allow bool) *ipnlocal.LocalBackend {
t.Helper()
err := setting.SetDefinitionsForTest(t,
setting.NewDefinition(pkey.AllowTailnetSysPolicy, setting.DeviceSetting, setting.BooleanValue),
setting.NewDefinition(pkey.ControlURL, setting.DeviceSetting, setting.StringValue),
setting.NewDefinition(pkey.AllowedSuggestedExitNodes, setting.ProfileSetting, setting.StringListValue),
setting.NewDefinition(pkey.AllowExitNodeOverride, setting.ProfileSetting, setting.BooleanValue),
setting.NewDefinition(pkey.EnableTailscaleDNS, setting.ProfileSetting, setting.PreferenceOptionValue),
setting.NewDefinition(pkey.EnableTailscaleSubnets, setting.ProfileSetting, setting.PreferenceOptionValue),
setting.NewDefinition(pkey.ExitNodeAllowLANAccess, setting.ProfileSetting, setting.PreferenceOptionValue),
setting.NewDefinition(pkey.ExitNodeID, setting.ProfileSetting, setting.StringValue),
setting.NewDefinition(pkey.ReconnectAfter, setting.ProfileSetting, setting.DurationValue),
setting.NewDefinition(pkey.KeyExpirationNoticeTime, setting.UserSetting, setting.DurationValue),
)
if err != nil {
t.Fatalf("SetDefinitionsForTest: %v", err)
}
allowStore = source.NewTestStoreOf(t, source.TestSettingOf(pkey.AllowTailnetSysPolicy, allow))
if _, err := rsop.RegisterStoreForTest(t, "Allow", setting.DeviceScope, allowStore); err != nil {
t.Fatalf("RegisterStoreForTest: %v", err)
}
sys := tsd.NewSystemWithBus(eventbustest.NewBus(t))
sys.PolicyClient.Set(testPolicyClient{})
b := ipnlocaltest.NewBackendWithSys(t, sys)
b.ForTest().InitExtensions()
if err := b.ForTest().SetPersist(&persist.Persist{}); err != nil {
t.Fatalf("SetPersist: %v", err)
}
return b
}
// allowStore is the device policy store with [pkey.AllowTailnetSysPolicy]
// registered by newTestBackend.
var allowStore *source.TestStore
// numTailnetSettings returns the number of settings in the effective policy
// other than [pkey.AllowTailnetSysPolicy].
func numTailnetSettings(t *testing.T) int {
t.Helper()
return effectivePolicy(t).Len() - 1
}
func testNetMap(policy ...tailcfg.RawMessage) *netmap.NetworkMap {
self := &tailcfg.Node{
ID: 10,
StableID: "self",
Key: key.NewNode().Public(),
Name: "self.example.ts.net.",
Hostinfo: (&tailcfg.Hostinfo{}).View(),
Addresses: []netip.Prefix{netip.MustParsePrefix("100.64.0.1/32")},
MachineAuthorized: true,
}
if policy != nil {
self.CapMap = tailcfg.NodeCapMap{nodecap.TailnetSysPolicy: policy}
}
return &netmap.NetworkMap{SelfNode: self.View()}
}
// testPolicyClient is a [policyclient.Client] that reads the effective policy
// from the registered stores, as tailscaled's client does outside of tests.
type testPolicyClient struct {
policyclient.NoPolicyClient
}
func policyFor(uid string) (*rsop.Policy, error) {
if uid != "" {
return rsop.PolicyFor(setting.UserScopeOf(uid))
}
return rsop.PolicyFor(setting.DefaultScope())
}
func getSetting[T any](key pkey.Key, def T) (T, error) {
policy, err := policyFor("")
if err != nil {
return def, err
}
if v, ok := policy.Get().Get(key).(T); ok {
return v, nil
}
return def, nil
}
func (testPolicyClient) GetString(key pkey.Key, def string) (string, error) {
return getSetting(key, def)
}
func (testPolicyClient) GetStringArray(key pkey.Key, def []string) ([]string, error) {
return getSetting(key, def)
}
func (testPolicyClient) GetBoolean(key pkey.Key, def bool) (bool, error) {
return getSetting(key, def)
}
func (testPolicyClient) GetDuration(key pkey.Key, def time.Duration) (time.Duration, error) {
return getSetting(key, def)
}
func (testPolicyClient) GetPreferenceOption(key pkey.Key, def ptype.PreferenceOption) (ptype.PreferenceOption, error) {
return getSetting(key, def)
}
func (testPolicyClient) GetPolicySnapshot(uid string) (*policyclient.PolicySnapshot, error) {
policy, err := policyFor(uid)
if err != nil {
return nil, err
}
return policy.Get(), nil
}
func (testPolicyClient) RegisterChangeCallback(uid string, cb func(policyclient.PolicyChange)) (func(), error) {
policy, err := policyFor(uid)
if err != nil {
return nil, err
}
return policy.RegisterChangeCallback(cb), nil
}
// effectivePolicy returns the policy for the scope used by LocalBackend.
func effectivePolicy(t *testing.T) *setting.Snapshot {
t.Helper()
policy, err := policyFor("")
if err != nil {
t.Fatalf("PolicyFor: %v", err)
}
return policy.Get()
}
func waitForPrefs(t *testing.T, b *ipnlocal.LocalBackend, what string, cond func(ipn.PrefsView) bool) {
t.Helper()
err := tstest.WaitFor(10*time.Second, func() error {
if !cond(b.Prefs()) {
return errNotYet
}
return nil
})
if err != nil {
t.Fatalf("timed out waiting for prefs: %s; got %v", what, b.Prefs().Pretty())
}
}
type notYetError struct{}
func (notYetError) Error() string { return "not yet" }
var errNotYet = notYetError{}
func TestSettings(t *testing.T) {
b := newTestBackend(t, true)
b.ForTest().ApplyNetMap(testNetMap(
`{
"AllowedSuggestedExitNodes": ["node1", "node2"],
"ExitNode.AllowOverride": true,
"ExitNodeAllowLANAccess": "always",
"ExitNodeID": "node1",
"KeyExpirationNotice": "48h",
"ReconnectAfter": "5m",
"UseTailscaleDNSSettings": "never",
"UseTailscaleSubnets": "never",
"LoginURL": "https://login.example.com"
}`,
))
// The effective policy is updated by the time the netmap is applied.
got := effectivePolicy(t)
want := map[pkey.Key]any{
pkey.AllowedSuggestedExitNodes: []string{"node1", "node2"},
pkey.AllowExitNodeOverride: true,
pkey.ExitNodeAllowLANAccess: ptype.AlwaysByPolicy,
pkey.ExitNodeID: "node1",
pkey.ReconnectAfter: 5 * time.Minute,
pkey.EnableTailscaleDNS: ptype.NeverByPolicy,
pkey.EnableTailscaleSubnets: ptype.NeverByPolicy,
pkey.KeyExpirationNoticeTime: 48 * time.Hour,
}
for k, want := range want {
got, err := got.GetErr(k)
if err != nil {
t.Errorf("%s: %v", k, err)
continue
}
if gotList, ok := got.([]string); ok {
if wantList := want.([]string); len(gotList) != len(wantList) || gotList[0] != wantList[0] || gotList[1] != wantList[1] {
t.Errorf("%s = %v; want %v", k, gotList, wantList)
}
} else if got != want {
t.Errorf("%s = %v; want %v", k, got, want)
}
}
// Device settings cannot be configured via the node attribute.
if v, err := got.GetErr(pkey.ControlURL); err == nil {
t.Errorf("%s = %v; want it not configured", pkey.ControlURL, v)
}
// User settings also apply to the users' policies sent to the clients.
userPolicy, err := policyFor("user1")
if err != nil {
t.Fatalf("PolicyFor: %v", err)
}
if got, want := userPolicy.Get().Get(pkey.KeyExpirationNoticeTime), 48*time.Hour; got != want {
t.Errorf("user policy: %s = %v; want %v", pkey.KeyExpirationNoticeTime, got, want)
}
waitForPrefs(t, b, "policy applied", func(p ipn.PrefsView) bool {
return p.ExitNodeID() == "node1" && p.ExitNodeAllowLANAccess() && !p.CorpDNS() && !p.RouteAll()
})
// A change to the node attribute replaces the settings.
b.ForTest().ApplyNetMap(testNetMap(`{"UseTailscaleDNSSettings": "always"}`))
got = effectivePolicy(t)
if numTailnetSettings(t) != 1 || got.Get(pkey.EnableTailscaleDNS) != ptype.AlwaysByPolicy {
t.Errorf("policy = %v; want only %s", got, pkey.EnableTailscaleDNS)
}
waitForPrefs(t, b, "CorpDNS", func(p ipn.PrefsView) bool { return p.CorpDNS() })
}
func TestMultipleValues(t *testing.T) {
b := newTestBackend(t, true)
b.ForTest().ApplyNetMap(testNetMap(
`{"ExitNodeID": "node1", "UseTailscaleSubnets": "never"}`,
`not JSON`,
`{"ExitNodeID": "node2"}`,
))
got := effectivePolicy(t)
if got, want := got.Get(pkey.ExitNodeID), "node2"; got != want {
t.Errorf("%s = %v; want %v", pkey.ExitNodeID, got, want)
}
if got, want := got.Get(pkey.EnableTailscaleSubnets), ptype.NeverByPolicy; got != want {
t.Errorf("%s = %v; want %v", pkey.EnableTailscaleSubnets, got, want)
}
}
func TestDevicePolicyWins(t *testing.T) {
b := newTestBackend(t, true)
store := source.NewTestStoreOf(t, source.TestSettingOf(pkey.ExitNodeID, "device-node"))
if _, err := rsop.RegisterStoreForTest(t, "Device", setting.DeviceScope, store); err != nil {
t.Fatalf("RegisterStoreForTest: %v", err)
}
b.ForTest().ApplyNetMap(testNetMap(`{"ExitNodeID": "node1", "ReconnectAfter": "5m"}`))
got := effectivePolicy(t)
if got, want := got.Get(pkey.ExitNodeID), "device-node"; got != want {
t.Errorf("%s = %v; want %v", pkey.ExitNodeID, got, want)
}
if got, want := got.Get(pkey.ReconnectAfter), 5*time.Minute; got != want {
t.Errorf("%s = %v; want %v", pkey.ReconnectAfter, got, want)
}
}
// TestProfileSwitch verifies that the settings stop applying as soon as
// another profile becomes the current one.
func TestProfileSwitch(t *testing.T) {
b := newTestBackend(t, true)
b.ForTest().ApplyNetMap(testNetMap(`{"ExitNodeID": "node1", "UseTailscaleDNSSettings": "never"}`))
waitForPrefs(t, b, "policy applied", func(p ipn.PrefsView) bool {
return p.ExitNodeID() == "node1" && !p.CorpDNS()
})
oldProfile := b.CurrentProfile().ID()
if err := b.NewProfile(); err != nil {
t.Fatalf("NewProfile: %v", err)
}
if numTailnetSettings(t) != 0 {
t.Errorf("policy after a profile switch = %v; want none", effectivePolicy(t))
}
if p := b.Prefs(); p.ExitNodeID() != "" || !p.CorpDNS() {
t.Errorf("new profile's prefs = %v; want them unaffected by the old profile's policy", p.Pretty())
}
// The old profile keeps the prefs the policy set, as with any other policy
// that no longer applies, and gets the settings back with its netmap.
if err := b.SwitchProfile(oldProfile); err != nil {
t.Fatalf("SwitchProfile: %v", err)
}
if numTailnetSettings(t) != 0 {
t.Errorf("policy before the netmap is received = %v; want none", effectivePolicy(t))
}
b.ForTest().ApplyNetMap(testNetMap(`{"ExitNodeID": "node2"}`))
waitForPrefs(t, b, "ExitNodeID", func(p ipn.PrefsView) bool { return p.ExitNodeID() == "node2" })
}
// TestAllowTailnetSysPolicy verifies that the node attribute is only used
// while [pkey.AllowTailnetSysPolicy] is enabled.
func TestAllowTailnetSysPolicy(t *testing.T) {
b := newTestBackend(t, false)
b.ForTest().ApplyNetMap(testNetMap(`{"ExitNodeID": "node1"}`))
if numTailnetSettings(t) != 0 {
t.Fatalf("policy = %v; want no tailnet settings", effectivePolicy(t))
}
waitForExitNodeID := func(want any) {
t.Helper()
err := tstest.WaitFor(10*time.Second, func() error {
if effectivePolicy(t).Get(pkey.ExitNodeID) != want {
return errNotYet
}
return nil
})
if err != nil {
t.Fatalf("timed out waiting for %s = %v; policy = %v", pkey.ExitNodeID, want, effectivePolicy(t))
}
}
allowStore.SetBooleans(source.TestSettingOf(pkey.AllowTailnetSysPolicy, true))
waitForExitNodeID("node1")
waitForPrefs(t, b, "ExitNodeID", func(p ipn.PrefsView) bool { return p.ExitNodeID() == "node1" })
allowStore.SetBooleans(source.TestSettingOf(pkey.AllowTailnetSysPolicy, false))
waitForExitNodeID(nil)
}
// TestNoStoreAfterShutdown verifies that the store is not registered
// by an update that arrives after the extension has been shut down.
func TestNoStoreAfterShutdown(t *testing.T) {
b := newTestBackend(t, true)
e, ok := b.FindExtensionByName(featureName).(*extension)
if !ok {
t.Fatalf("extension %q not found", featureName)
}
if err := e.Shutdown(); err != nil {
t.Fatalf("Shutdown: %v", err)
}
b.ForTest().ApplyNetMap(testNetMap(`{"ExitNodeID": "node1"}`))
if numTailnetSettings(t) != 0 {
t.Errorf("policy after Shutdown = %v; want no tailnet settings", effectivePolicy(t))
}
}
+15
View File
@@ -106,6 +106,21 @@ const (
// e.g. https://tailscale.com/cap/funnel-ports?ports=80,443,8080-8090
FunnelPorts Cap = "https://tailscale.com/cap/funnel-ports"
// TailnetSysPolicy configures policy settings that apply while the profile
// of the node it is granted to is the current profile. Each CapMap value
// is a JSON object that maps policy setting keys, as defined in
// [tailscale.com/util/syspolicy/pkey], to their values, such as
// {"ExitNodeID": "auto:any", "ExitNode.AllowOverride": true}.
// If more than one value configures the same setting, the last one wins.
//
// Only profile and user settings are supported; the rest are ignored.
// A setting that is also configured for the device, such as via MDM,
// keeps its device value.
//
// The attribute is ignored unless the AllowTailnetSysPolicy device policy
// setting is enabled.
TailnetSysPolicy Cap = "https://tailscale.com/cap/tailnet-syspolicy"
// OnlyTCP443 specifies that the client should not attempt to generate
// any outbound traffic that isn't TCP on port 443 (HTTPS). This is used for
// clients in restricted environments where only HTTPS traffic is allowed
+5
View File
@@ -54,6 +54,11 @@ const (
// On other platforms, it is the client's responsibility to restart tailscaled.
AllowTailscaledRestart Key = "AllowTailscaledRestart"
// AllowTailnetSysPolicy is a boolean key that controls whether policy settings
// received from the control plane for the current profile's tailnet are used.
// The default is false. See [tailscale.com/tailcfg/nodecap.TailnetSysPolicy].
AllowTailnetSysPolicy Key = "AllowTailnetSysPolicy"
// ExitNodeID is the exit node's node id. default ""; if blank, no exit node is forced.
// Exit node ID takes precedence over exit node IP.
// To find the node ID, go to /api.md#device.
+1
View File
@@ -15,6 +15,7 @@ import (
// This includes the first time a policy needs to be read from any source.
var implicitDefinitions = []*setting.Definition{
// Device policy settings (can only be configured on a per-device basis):
setting.NewDefinition(pkey.AllowTailnetSysPolicy, setting.DeviceSetting, setting.BooleanValue),
setting.NewDefinition(pkey.AllowTailscaledRestart, setting.DeviceSetting, setting.BooleanValue),
setting.NewDefinition(pkey.AlwaysOn, setting.DeviceSetting, setting.BooleanValue),
setting.NewDefinition(pkey.AlwaysOnOverrideWithReason, setting.DeviceSetting, setting.BooleanValue),