diff --git a/CHANGELOG.md b/CHANGELOG.md index fce35f738..b8d64e8f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -231,6 +231,7 @@ the `tailscale.com/cap/tailsql` app capability lets a user query it; see - Policy `tests` reject `autogroup:member` as a source. [#3649](https://github.com/juanfont/headscale/pull/3649) - Document `ssh-behavior-v1`. Headscale does not set it. [#3649](https://github.com/juanfont/headscale/pull/3649) - The v2 API sorts device lists by name. Devices report `connectedToControl`, `lastSeen` and `blocksIncomingConnections`. `fields=all` adds `sshEnabled`, `distro` and `clientConnectivity`. Add `POST /device/{id}/expire`. Settings report `routeSelection`. Errors use Tailscale's text and content types. A JSON policy read returns valid JSON. [#3649](https://github.com/juanfont/headscale/pull/3649) +- Key expiry is a switch beside the expiry time, as on Tailscale. Tagged nodes register with it off and keep a time. The v2 `POST /device/{id}/key` turns it on or off and keeps the time. The v2 `POST /device/{id}/expire` writes the time only, so a node with expiry off stays logged in. The v1 expire and a client logout turn it on and log the node out. [#3707](https://github.com/juanfont/headscale/pull/3707) - The v2 API adds `GET /device/{id}/attributes`, scoped `devices:posture_attributes:read`. It reports `ip:publicAddress`: the source IP of the node's latest control connection, stored on the node. Behind a reverse proxy, set `trusted_proxies` or it reports the proxy. [#3419](https://github.com/juanfont/headscale/pull/3419) - PostgreSQL connection settings are assembled into a `postgres://` URL with proper escaping, so a password (or host, user, database name) containing spaces, quotes or other reserved characters no longer truncates the DSN [#3477](https://github.com/juanfont/headscale/pull/3477) - Expiring or deleting a non-existent pre-auth key now returns an error instead of silently succeeding [#3324](https://github.com/juanfont/headscale/pull/3324) diff --git a/hscontrol/api/v1/nodes.go b/hscontrol/api/v1/nodes.go index a2c1ee11e..f6ea5b55a 100644 --- a/hscontrol/api/v1/nodes.go +++ b/hscontrol/api/v1/nodes.go @@ -322,7 +322,8 @@ func registerNodeWriteOps(api huma.API, b Backend) { expiry = *customExpiry } - node, nodeChange, err := b.State.SetNodeExpiry(nodeID, &expiry) + // As before key expiry could be turned off: the node expires. + node, nodeChange, err := b.State.ExpireNodeAt(nodeID, expiry) b.Change(nodeChange) if err != nil { @@ -626,8 +627,8 @@ func nodeFromView(view types.NodeView) Node { n.LastSeen = &ls } - if view.Expiry().Valid() { - exp := view.Expiry().Get() + // A node with key expiry off shows none, as before the switch existed. + if exp, ok := view.KeyExpiry(); ok { n.Expiry = &exp } diff --git a/hscontrol/api/v2/devices.go b/hscontrol/api/v2/devices.go index bd4a3adde..e012dd2dc 100644 --- a/hscontrol/api/v2/devices.go +++ b/hscontrol/api/v2/devices.go @@ -438,15 +438,7 @@ func registerDevices(api huma.API, b Backend) { return nil, err } - // Only disabling expiry maps cleanly (expiry=nil never expires). - // Re-enabling has no target expiry in the Tailscale request and Headscale - // stores no original, so it is accepted as a no-op (keeps Terraform - // destroy working) rather than guessing a lifetime. - if !in.Body.KeyExpiryDisabled { - return &emptyOutput{}, nil - } - - _, nodeChange, err := b.State.SetNodeExpiry(node.ID(), nil) + _, nodeChange, err := b.State.SetNodeKeyExpiryDisabled(node.ID(), in.Body.KeyExpiryDisabled) b.Change(nodeChange) if err != nil { @@ -650,7 +642,7 @@ func deviceFromView(view types.NodeView, allFields bool, baseDomain string) Devi Authorized: true, // Headscale has no post-registration de-auth state. User: deviceUser(view), Tags: emptyIfNil(view.Tags().AsSlice()), - KeyExpiryDisabled: !view.Expiry().Valid(), + KeyExpiryDisabled: view.KeyExpiryDisabled(), Created: view.CreatedAt(), Hostname: view.Hostname(), IsEphemeral: view.IsEphemeral(), diff --git a/hscontrol/apiv1_nodes_test.go b/hscontrol/apiv1_nodes_test.go index 5418be403..ead4009f6 100644 --- a/hscontrol/apiv1_nodes_test.go +++ b/hscontrol/apiv1_nodes_test.go @@ -238,6 +238,23 @@ func TestAPIV1NodeExpire(t *testing.T) { assert.NotNil(t, got.Node["expiry"]) }) + // As before the key expiry switch existed: v1 expire logs the node out. + t.Run("huma expires a node with key expiry off", func(t *testing.T) { + h := newAPIV1Harness(t) + seedNodes(newNodeSeed("alice", "node-a"))(t, h.app) + + _, _, err := h.app.state.SetNodeKeyExpiryDisabled(1, true) + require.NoError(t, err) + + res := h.callHuma(http.MethodPost, "/api/v1/node/1/expire", nil) + require.Equal(t, http.StatusOK, res.status) + + node, ok := h.app.state.GetNodeByID(1) + require.True(t, ok) + assert.False(t, node.KeyExpiryDisabled()) + assert.True(t, node.IsExpired()) + }) + t.Run("huma refuses an unencodable expiry", func(t *testing.T) { h := newAPIV1Harness(t) seedNodes(newNodeSeed("alice", "node-a"))(t, h.app) diff --git a/hscontrol/apiv2_devices_test.go b/hscontrol/apiv2_devices_test.go index fefebdf04..3d9c0da48 100644 --- a/hscontrol/apiv2_devices_test.go +++ b/hscontrol/apiv2_devices_test.go @@ -155,7 +155,7 @@ func TestAPIv2Device_Get(t *testing.T) { assert.True(t, dev.Authorized) assert.Equal(t, e.user.Username(), dev.User) assert.NotNil(t, dev.Tags) - assert.True(t, dev.KeyExpiryDisabled, "seeded node has no expiry") + assert.False(t, dev.KeyExpiryDisabled, "a user node's key expiry is on") assert.NotEmpty(t, dev.Addresses) // Server-side cross-check. @@ -340,23 +340,37 @@ func TestAPIv2Device_SetTags(t *testing.T) { assert.Equal(t, []string{"tag:prod"}, e.srvNode(t).Tags().AsSlice()) } +// As on Tailscale (capture expire-key-expiry K1-K5, X1-X5): the key switch +// keeps the expiry time, and expire writes the time whatever the switch says. func TestAPIv2Device_SetKey(t *testing.T) { e := newDeviceTestEnv(t) - e.seedExpiry(t, time.Now().Add(24*time.Hour)) + at := time.Now().Add(24 * time.Hour).UTC().Truncate(time.Second) + e.seedExpiry(t, at) + + setKey := func(disabled bool) { + t.Helper() + require.Equal(t, http.StatusOK, + e.api.Post("/api/v2/device/"+e.deviceID+"/key", map[string]any{"keyExpiryDisabled": disabled}).Code) + } - require.True(t, e.srvNode(t).Expiry().Valid(), "precondition: node has an expiry") assert.False(t, getDevice(t, e.api, e.deviceID).KeyExpiryDisabled) - require.Equal(t, http.StatusOK, - e.api.Post("/api/v2/device/"+e.deviceID+"/key", map[string]any{"keyExpiryDisabled": true}).Code) - assert.True(t, getDevice(t, e.api, e.deviceID).KeyExpiryDisabled) - assert.False(t, e.srvNode(t).Expiry().Valid(), "expiry cleared") + setKey(true) - // Re-enable is accepted as a no-op; expiry stays cleared. - require.Equal(t, http.StatusOK, - e.api.Post("/api/v2/device/"+e.deviceID+"/key", map[string]any{"keyExpiryDisabled": false}).Code) - assert.True(t, getDevice(t, e.api, e.deviceID).KeyExpiryDisabled) - assert.False(t, e.srvNode(t).Expiry().Valid()) + d := getDevice(t, e.api, e.deviceID) + assert.True(t, d.KeyExpiryDisabled) + require.NotNil(t, d.Expires) + assert.True(t, at.Equal(*d.Expires), "the time is kept") + + // Expire writes the time; the switch keeps the node logged in. + require.Equal(t, http.StatusOK, e.api.Post("/api/v2/device/"+e.deviceID+"/expire", map[string]any{}).Code) + assert.False(t, e.srvNode(t).IsExpired(), "a node with key expiry off stays") + assert.True(t, getDevice(t, e.api, e.deviceID).Expires.Before(time.Now().Add(time.Second))) + + // Turning the switch off lets the past time count. + setKey(false) + assert.False(t, getDevice(t, e.api, e.deviceID).KeyExpiryDisabled) + assert.True(t, e.srvNode(t).IsExpired()) } func TestAPIv2Device_SetRoutes(t *testing.T) { diff --git a/hscontrol/auth.go b/hscontrol/auth.go index d2d5304d8..793fd986c 100644 --- a/hscontrol/auth.go +++ b/hscontrol/auth.go @@ -288,7 +288,7 @@ func (h *Headscale) handleLogout( expiry = now } - updatedNode, c, err := h.state.SetNodeExpiry(node.ID(), &expiry) + updatedNode, c, err := h.state.ExpireNodeAt(node.ID(), expiry) h.Change(c) if err != nil { diff --git a/hscontrol/auth_tags_test.go b/hscontrol/auth_tags_test.go index 7cf261035..7ac712c10 100644 --- a/hscontrol/auth_tags_test.go +++ b/hscontrol/auth_tags_test.go @@ -535,7 +535,7 @@ func TestTaggedPreAuthKeyDisablesKeyExpiry(t *testing.T) { // Critical assertion: Tagged nodes should have expiry disabled assert.True(t, node.IsTagged(), "Node should be tagged") - assert.False(t, node.Expiry().Valid(), "Tagged node should have expiry disabled (nil)") + assert.True(t, node.KeyExpiryDisabled(), "Tagged node should have key expiry off") } // TestUntaggedPreAuthKeyPreservesKeyExpiry tests that nodes registered with @@ -619,7 +619,7 @@ func TestTaggedNodeReauthPreservesDisabledExpiry(t *testing.T) { node, found := app.state.GetNodeByNodeKey(nodeKey.Public()) require.True(t, found) require.True(t, node.IsTagged()) - require.False(t, node.Expiry().Valid(), "Initial registration should have expiry disabled") + require.True(t, node.KeyExpiryDisabled(), "Initial registration should have key expiry off") // Re-authenticate with a NEW expiry request (should be ignored for tagged nodes) newRequestedExpiry := time.Now().Add(48 * time.Hour) @@ -644,8 +644,8 @@ func TestTaggedNodeReauthPreservesDisabledExpiry(t *testing.T) { // Critical assertion: Tagged node should preserve disabled expiry on re-auth assert.True(t, nodeAfterReauth.IsTagged(), "Node should still be tagged") - assert.False(t, nodeAfterReauth.Expiry().Valid(), - "Tagged node should have expiry PRESERVED as disabled after re-auth") + assert.True(t, nodeAfterReauth.KeyExpiryDisabled(), + "Tagged node should keep key expiry off after re-auth") } // TestTaggedNodeRestartPreservesNilExpiry tests that a tagged node whose @@ -857,8 +857,8 @@ func TestExpiryDuringPersonalToTaggedConversion(t *testing.T) { require.True(t, nodeAfter.IsTagged(), "Node should be tagged after conversion") // CRITICAL ASSERTION: Tagged nodes should NOT have expiry - assert.False(t, nodeAfter.Expiry().Valid(), - "Tagged node should have expiry cleared to nil") + assert.True(t, nodeAfter.KeyExpiryDisabled(), + "Tagged node should have key expiry off") } // TestExpiryDuringTaggedToPersonalConversion tests that when a tagged node @@ -1088,8 +1088,8 @@ func TestTaggedAuthKeyIgnoresNodeExpiry(t *testing.T) { require.True(t, found) assert.True(t, node.IsTagged()) - assert.False(t, node.Expiry().Valid(), - "tagged node should have expiry disabled (nil) even with node.expiry configured") + assert.True(t, node.KeyExpiryDisabled(), + "tagged node should have key expiry off even with node.expiry configured") } // TestNodeExpiryZeroDisablesDefault tests that setting node.expiry to 0 diff --git a/hscontrol/servertest/apiv2_devices_test.go b/hscontrol/servertest/apiv2_devices_test.go index 04f8d1d46..10409b2c0 100644 --- a/hscontrol/servertest/apiv2_devices_test.go +++ b/hscontrol/servertest/apiv2_devices_test.go @@ -146,11 +146,11 @@ func apiv2DevicesGoClient(t *testing.T, srv *servertest.TestServer, baseURL, api dev, err = dr.Get(ctx, deviceID) require.NoError(t, err) assert.True(t, dev.KeyExpiryDisabled) - assert.False(t, srvNodeView(t, srv, id).Expiry().Valid()) + assert.True(t, srvNodeView(t, srv, id).KeyExpiryDisabled()) + assert.True(t, srvNodeView(t, srv, id).Expiry().Valid(), "the time is kept") - // Re-enable is a no-op; expiry stays cleared. require.NoError(t, dr.SetKey(ctx, deviceID, tsclient.DeviceKey{KeyExpiryDisabled: false})) - assert.False(t, srvNodeView(t, srv, id).Expiry().Valid()) + assert.False(t, srvNodeView(t, srv, id).KeyExpiryDisabled()) // SetTags — flips ownership to the tags; the user is dropped, and the // device shows the login that made its key. @@ -314,7 +314,7 @@ func apiv2DevicesTSCLI(t *testing.T, srv *servertest.TestServer, baseURL, apiKey run("set", "device", "key", "--device", deviceID, "--disable-expiry") assert.Contains(t, run("get", "device", "--device", deviceID, "-o", "json"), `"keyExpiryDisabled": true`) - assert.False(t, srvNodeView(t, srv, id).Expiry().Valid()) + assert.True(t, srvNodeView(t, srv, id).KeyExpiryDisabled()) // Tags — flips to tag ownership. run("set", "device", "tags", "--device", deviceID, "--tag", "tag:ci") diff --git a/hscontrol/servertest/grants_test.go b/hscontrol/servertest/grants_test.go index 2149b8a8f..3cbcabf60 100644 --- a/hscontrol/servertest/grants_test.go +++ b/hscontrol/servertest/grants_test.go @@ -1297,7 +1297,10 @@ func TestGrantViaSubnetFailover(t *testing.T) { require.True(t, changed, "a via health change must trigger a recompute") srv.App.Change(change.PolicyChange()) case "expired": - setExpiry(t, srv, router1ID, new(time.Now().Add(-time.Minute))) + // The routers are tagged, so expiry is turned on with it. + _, c, err := srv.State().ExpireNodeAt(router1ID, time.Now().Add(-time.Minute)) + require.NoError(t, err) + srv.App.Change(c) } clients["client"].WaitForCondition(t, "route moves to router-2", diff --git a/hscontrol/state/auth_tagged_expiry_test.go b/hscontrol/state/auth_tagged_expiry_test.go index 0fef92f7f..597263879 100644 --- a/hscontrol/state/auth_tagged_expiry_test.go +++ b/hscontrol/state/auth_tagged_expiry_test.go @@ -1096,8 +1096,8 @@ func TestIssue3371_TaggedNodePastExpirySelfHealsOnReregister(t *testing.T) { reloaded, ok := s2.GetNodeByID(nodeID) require.True(t, ok) - require.True(t, reloaded.IsExpired(), - "precondition: a persisted past expiry survives restart and re-triggers the lockout") + require.False(t, reloaded.IsExpired(), + "a tagged node's key expiry is off, so a stale past expiry does not lock it out") // Re-register (rotating the node key). The stale past expiry must be cleared. reregReq := tailcfg.RegisterRequest{ @@ -1110,8 +1110,8 @@ func TestIssue3371_TaggedNodePastExpirySelfHealsOnReregister(t *testing.T) { require.True(t, healed.IsTagged(), "node stays tagged") require.False(t, healed.IsExpired(), "issue #3371: re-registration must self-heal a tagged node broken by an older version") - require.Nil(t, healed.AsStruct().Expiry, - "issue #3371: self-healed tagged node must have key-expiry disabled (DB NULL)") + require.True(t, healed.KeyExpiryDisabled(), + "issue #3371: a tagged node keeps key expiry off") require.Equal(t, nodeID, healed.ID(), "must be the same node") } @@ -1123,7 +1123,7 @@ func TestExpiredTaggedNodeRequiresValidPreAuthKey(t *testing.T) { require.NoError(t, err) c := registerForPAKRereg(t, s, pak) past := time.Now().Add(-time.Hour) - _, _, err = s.SetNodeExpiry(c.node.ID(), &past) + _, _, err = s.ExpireNodeAt(c.node.ID(), past) require.NoError(t, err) nsBefore, rowBefore := c.fields(t) require.Equal(t, past.UnixNano(), nsBefore.Expiry) @@ -1147,14 +1147,15 @@ func TestExpiredTaggedNodeRequiresValidPreAuthKey(t *testing.T) { require.NoError(t, err) require.Equal(t, c.node.ID(), node.ID()) - require.False(t, node.Expiry().Valid(), "a valid key disables tagged node expiry") + require.True(t, node.KeyExpiryDisabled(), "a valid tagged key turns key expiry off") + require.False(t, node.IsExpired(), "a valid key renews the node") current, ok := s.GetNodeByID(c.node.ID()) require.True(t, ok) - require.False(t, current.Expiry().Valid()) + require.False(t, current.IsExpired()) stored, err := s.db.GetNodeByID(c.node.ID()) require.NoError(t, err) - require.Nil(t, stored.Expiry) + require.False(t, stored.IsExpired()) }) } } @@ -1562,6 +1563,7 @@ func TestExpiredTaggedNodeReauthRetags(t *testing.T) { past := time.Now().Add(-1 * time.Hour) _, ok := s.nodeStore.UpdateNode(first.ID(), func(n *types.Node) { n.Expiry = &past + n.KeyExpiryDisabled = false }) require.True(t, ok) @@ -1576,8 +1578,8 @@ func TestExpiredTaggedNodeReauthRetags(t *testing.T) { require.NoError(t, err) require.Equal(t, []string{"tag:tag2"}, second.Tags().AsSlice(), "an expired (stale logout stamp) tagged node must retag on fresh-key re-auth") - require.Nil(t, second.AsStruct().Expiry, - "retag must clear a stale expiry: the node is tagged and tagged nodes never expire") + require.True(t, second.KeyExpiryDisabled(), + "a tagged key turns key expiry off, as on Tailscale SaaS") require.False(t, second.IsExpired(), "a retagged node must not remain expired") } @@ -2760,7 +2762,7 @@ func TestPAKReregisterRollbackKeepsConcurrentWrites(t *testing.T) { pending = append(pending, expiryDone) go func() { - _, _, err := s.SetNodeExpiry(b.node.ID(), &expiry) + _, _, err := s.ExpireNodeAt(b.node.ID(), expiry) expiryDone <- err }() @@ -3280,7 +3282,7 @@ func TestUserKeyOnTaggedMachine(t *testing.T) { switch mode { case "expired": past := time.Now().Add(-time.Hour) - _, _, err = s.SetNodeExpiry(c.node.ID(), &past) + _, _, err = s.ExpireNodeAt(c.node.ID(), past) require.NoError(t, err) case "rotated": req.NodeKey = key.NewNode().Public() @@ -3350,7 +3352,7 @@ func TestPAKWakeRechecksAuthorityAtMutation(t *testing.T) { view, pak := c.lookup(t, guestKey.Key) past := time.Now().Add(-time.Hour) - _, _, err = s.SetNodeExpiry(c.node.ID(), &past) + _, _, err = s.ExpireNodeAt(c.node.ID(), past) require.NoError(t, err) beforeCache, beforeDB := c.fields(t) @@ -3386,7 +3388,7 @@ func TestExpiredNodeSameKeyLoginAsksForNewKey(t *testing.T) { c := registerForPAKRereg(t, s, pak) past := time.Now().Add(-time.Hour) - _, _, err = s.SetNodeExpiry(c.node.ID(), &past) + _, _, err = s.ExpireNodeAt(c.node.ID(), past) require.NoError(t, err) beforeCache, beforeDB := c.fields(t) diff --git a/hscontrol/state/debug.go b/hscontrol/state/debug.go index c0ef74348..73f013972 100644 --- a/hscontrol/state/debug.go +++ b/hscontrol/state/debug.go @@ -305,7 +305,7 @@ func (s *State) DebugOverviewJSON() DebugOverviewInfo { info.Nodes.Online++ } - if node.Expiry().Valid() && node.Expiry().Get().Before(now) { + if node.IsExpiredAt(now) { info.Nodes.Expired++ } diff --git a/hscontrol/state/node_store.go b/hscontrol/state/node_store.go index 979c2156b..dcd57386d 100644 --- a/hscontrol/state/node_store.go +++ b/hscontrol/state/node_store.go @@ -263,6 +263,7 @@ func updateChanges(pre, post *types.Node) (bool, bool) { } return false, pre.Online() != post.Online() || + pre.KeyExpiryDisabled != post.KeyExpiryDisabled || !preView.Expiry().GetOr(time.Time{}).Equal(postView.Expiry().GetOr(time.Time{})) || pre.Unhealthy != post.Unhealthy || !pre.SessionStart.Equal(post.SessionStart) diff --git a/hscontrol/state/node_store_test.go b/hscontrol/state/node_store_test.go index c1ce9ae56..9b27f75a0 100644 --- a/hscontrol/state/node_store_test.go +++ b/hscontrol/state/node_store_test.go @@ -1967,7 +1967,7 @@ var nodeFieldImpact = map[string]string{ "LastControlAddress": "payload", "RegisterMethod": "payload", "AuthKeyID": "payload", "AuthKey": "payload", "Ephemeral": "payload", - "Expiry": "election", "LastSeen": "payload", "CreatedAt": "payload", + "Expiry": "election", "KeyExpiryDisabled": "election", "LastSeen": "payload", "CreatedAt": "payload", "UpdatedAt": "payload", "DeletedAt": "payload", "ActiveSessions": "payload", "SessionEpoch": "payload", "SessionStart": "election", "CapVer": "payload", diff --git a/hscontrol/state/state.go b/hscontrol/state/state.go index b04de9ed0..6f5c60a44 100644 --- a/hscontrol/state/state.go +++ b/hscontrol/state/state.go @@ -115,6 +115,7 @@ var nodeUpdateColumns = []string{ "Tags", "Ephemeral", "Expiry", + "KeyExpiryDisabled", "LastSeen", "ApprovedRoutes", "AutoApprovedRoutes", @@ -1273,10 +1274,50 @@ func (s *State) ListEphemeralNodes() views.Slice[types.NodeView] { return views.SliceOf(ephemeralNodes) } -// SetNodeExpiry updates the expiration time for a node. -// If expiry is nil, the node's expiry is disabled (node will never expire). +// SetNodeExpiry updates the expiration time for a node and leaves the key +// expiry switch as it is. A nil expiry never expires. func (s *State) SetNodeExpiry(nodeID types.NodeID, expiry *time.Time) (types.NodeView, change.Change, error) { - return s.setNodeExpiry(nodeID, expiry, nil) + if expiry != nil { + utc, err := types.ValidateExpiry(*expiry) + if err != nil { + return types.NodeView{}, change.Change{}, err + } + + expiry = &utc + } + + return s.updateNodeExpiry(nodeID, func(node *types.Node) bool { + node.Expiry = expiry + + return true + }) +} + +// ExpireNodeAt sets the node's expiry and turns key expiry on, so the node +// logs out at expiry whatever the switch held. A client logout and +// `headscale nodes expire` do this. +func (s *State) ExpireNodeAt(nodeID types.NodeID, expiry time.Time) (types.NodeView, change.Change, error) { + expiry, err := types.ValidateExpiry(expiry) + if err != nil { + return types.NodeView{}, change.Change{}, err + } + + return s.updateNodeExpiry(nodeID, func(node *types.Node) bool { + node.Expiry = &expiry + node.KeyExpiryDisabled = false + + return true + }) +} + +// SetNodeKeyExpiryDisabled turns key expiry off or on and keeps the stored +// expiry, which counts again once expiry is on. +func (s *State) SetNodeKeyExpiryDisabled(nodeID types.NodeID, disabled bool) (types.NodeView, change.Change, error) { + return s.updateNodeExpiry(nodeID, func(node *types.Node) bool { + node.KeyExpiryDisabled = disabled + + return true + }) } // BringNodeExpiryForward stores the expiry a client asks for when the node @@ -1288,8 +1329,19 @@ func (s *State) BringNodeExpiryForward( nodeKey key.NodePublic, expiry time.Time, ) (types.NodeView, change.Change, error) { - return s.setNodeExpiry(nodeID, &expiry, func(node *types.Node) bool { - return canBringExpiryForward(node, nodeKey, expiry) + expiry, err := types.ValidateExpiry(expiry) + if err != nil { + return types.NodeView{}, change.Change{}, err + } + + return s.updateNodeExpiry(nodeID, func(node *types.Node) bool { + if !canBringExpiryForward(node, nodeKey, expiry) { + return false + } + + node.Expiry = &expiry + + return true }) } @@ -1298,22 +1350,12 @@ func canBringExpiryForward(node *types.Node, nodeKey key.NodePublic, expiry time (node.Expiry == nil || node.Expiry.IsZero() || expiry.Before(*node.Expiry)) } -// setNodeExpiry sets the node's expiry. A non-nil allow decides on the node -// as the writer holds it; a refusal writes nothing. -func (s *State) setNodeExpiry( +// updateNodeExpiry applies update to the node as the writer holds it; an +// update that returns false writes nothing. +func (s *State) updateNodeExpiry( nodeID types.NodeID, - expiry *time.Time, - allow func(*types.Node) bool, + update func(*types.Node) bool, ) (types.NodeView, change.Change, error) { - if expiry != nil { - utc, err := types.ValidateExpiry(*expiry) - if err != nil { - return types.NodeView{}, change.Change{}, err - } - - expiry = &utc - } - var onlineChanged, expired, refused bool genBefore := s.polMan.NodesGeneration() @@ -1323,14 +1365,13 @@ func (s *State) setNodeExpiry( // must make the exact same change. If the database update fails, the [NodeStore] // change will remain, and the change describing it is returned with the error. n, ok := s.nodeStore.UpdateNode(nodeID, func(node *types.Node) { - if allow != nil && !allow(node) { + wasOnline := node.Online() + + if !update(node) { refused = true return } - - wasOnline := node.Online() - node.Expiry = expiry // Control stays connected in NeedsLogin so an expiry extension can // recover the client, but an expired key is not online. node.IsOnline = new(node.ShouldBeOnline()) @@ -2556,7 +2597,7 @@ type authNodeUpdateParams struct { Hostname string // Auth user; may differ from ExistingNode.User() on conversion. User *types.User - // Overrides RegData.Expiry; ignored for tagged nodes. + // Overrides RegData.Expiry. Expiry *time.Time // Only used when IsConvertFromTag=true. RegisterMethod string @@ -2694,19 +2735,22 @@ func (s *State) applyAuthNodeUpdate(params authNodeUpdateParams) (types.NodeView // This ensures expiry is correctly set/cleared based on the NEW tagged status isTagged := node.IsTagged() - switch { - case !isTagged: - // User-owned nodes take the expiry from this authentication. - node.Expiry = cmp.Or(params.Expiry, regData.Expiry) - case !wasTagged || node.IsExpired(): - // Becoming tagged disables expiry; reauth clears a past expiry. - node.Expiry = nil + // Becoming tagged turns key expiry off and keeps a time for when it + // is turned on again, as on Tailscale SaaS. + if isTagged != wasTagged { + // A device a user takes back from its tags expires again. + node.KeyExpiryDisabled = isTagged } - // Tagged → Tagged and not expired: keep existing expiry - no action. - // Apply default node expiry for non-tagged nodes when the - // resolved expiry is still nil or zero (e.g., CLI registration - // where the client did not request a specific expiry). + // A tagged node that has not expired keeps its expiry; every other + // node takes it from this authentication. + if !isTagged || !wasTagged || node.IsExpired() { + node.Expiry = cmp.Or(params.Expiry, regData.Expiry) + } + + // Apply the default node expiry when the resolved expiry is still + // nil or zero (e.g., CLI registration where the client did not + // request a specific expiry). if s.needsDefaultNodeExpiry(node) { exp := time.Now().Add(s.cfg.Node.Expiry) node.Expiry = &exp @@ -2810,9 +2854,7 @@ func (s *State) createAndSaveNewNode(params newNodeParams) (types.NodeView, erro // Tagged nodes are owned by their tags, not a user. // UserID is intentionally left nil. nodeToRegister.Tags = tags - - // Tagged nodes have key expiry disabled. - nodeToRegister.Expiry = nil + nodeToRegister.KeyExpiryDisabled = true } else { // USER-OWNED NODE nodeToRegister.UserID = ¶ms.PreAuthKey.User.ID @@ -2850,8 +2892,7 @@ func (s *State) createAndSaveNewNode(params newNodeParams) (types.NodeView, erro nodeToRegister.UserID = nil nodeToRegister.User = nil - // Tagged nodes have key expiry disabled. - nodeToRegister.Expiry = nil + nodeToRegister.KeyExpiryDisabled = true log.Info(). Str(zf.NodeName, nodeToRegister.Hostname). @@ -2860,9 +2901,9 @@ func (s *State) createAndSaveNewNode(params newNodeParams) (types.NodeView, erro } } - // Apply default node expiry for non-tagged nodes when the client - // did not request a specific expiry. - // Tagged nodes are exempt — they never expire. + // Apply the default node expiry when the client did not request a + // specific expiry. A tagged node keeps it for when its expiry is turned + // on, as on Tailscale SaaS. if s.needsDefaultNodeExpiry(&nodeToRegister) { exp := time.Now().Add(s.cfg.Node.Expiry) nodeToRegister.Expiry = &exp @@ -2953,7 +2994,7 @@ func (s *State) validateRequestTags(node types.NodeView, requestTags []string) [ } func (s *State) needsDefaultNodeExpiry(node *types.Node) bool { - return !node.IsTagged() && (node.Expiry == nil || node.Expiry.IsZero()) && s.cfg.Node.Expiry > 0 + return (node.Expiry == nil || node.Expiry.IsZero()) && s.cfg.Node.Expiry > 0 } func (s *State) canApplyReauthTag(node types.NodeView, authUser types.UserView, tag string) bool { @@ -3801,23 +3842,14 @@ func (s *State) reregisterNodeWithPAK( tags, retag = requestedTags, !slices.Equal(node.Tags, requestedTags) } - if retag { - wasUserOwned := !node.IsTagged() + // Read before the switch below can hide it. + wasExpired := node.IsExpiredAt(now) + becameTagged := retag && !node.IsTagged() + if retag { node.Tags = tags node.UserID = nil node.User = nil - - // Converting a user-owned node to tagged drops the user's key - // expiry (tagged nodes disable it by default). But retagging an - // already-tagged node must preserve a deliberate FUTURE expiry - // set via `headscale nodes expire` - that is a node property, not - // tied to the auth key - and only clear a past expiry with a valid key. This - // keeps the retag path symmetric with the same-key relogin path - // below rather than silently overriding an admin decision. - if wasUserOwned || node.IsExpiredAt(now) { - node.Expiry = nil - } } else if preAuthKeyClaimsTaggedNode(node, pak, requestedTags, prior.NodeKey) { // A user key that speaks for a tagged node, with a new node key, // takes it back as that user's device, as on Tailscale SaaS. A @@ -3827,6 +3859,13 @@ func (s *State) reregisterNodeWithPAK( node.UserID = &pak.User.ID node.User = pak.User node.Ephemeral = false + node.KeyExpiryDisabled = false + } + + // A login that tags the node, or with a tagged key, turns key expiry + // off, as on Tailscale SaaS; an admin may turn it on again. + if node.IsTagged() && (becameTagged || len(pak.Tags) > 0) { + node.KeyExpiryDisabled = true } node.AuthKey = pak.AsCredential() @@ -3844,13 +3883,10 @@ func (s *State) reregisterNodeWithPAK( // clear the expiry so the database holds NULL instead of // a pointer to zero time. switch { - case node.IsTagged(): - // Tagged nodes keep their expiry; a valid key lifts a past one. A - // future administrative expiry has not taken effect and stays. - if node.IsExpiredAt(now) { - node.Expiry = nil - } - case prior.NodeKey == regReq.NodeKey: + case node.IsTagged() && !becameTagged && !wasExpired: + // A tagged node keeps its expiry: a future administrative one has + // not taken effect. A valid key renews a past one below. + case !node.IsTagged() && prior.NodeKey == regReq.NodeKey: // A node that keeps its node key keeps its expiry, as on Tailscale // SaaS: renewal comes with a new node key. case !regReq.Expiry.IsZero(): @@ -3965,6 +4001,10 @@ func (s *State) undoReregistration(prior, written *types.Node) { n.Expiry = prior.Expiry } + if n.KeyExpiryDisabled == written.KeyExpiryDisabled { + n.KeyExpiryDisabled = prior.KeyExpiryDisabled + } + if reflect.DeepEqual(n.AuthKeyID, written.AuthKeyID) && reflect.DeepEqual(n.AuthKey, written.AuthKey) { n.AuthKey = prior.AuthKey @@ -4022,7 +4062,7 @@ func reauthChange(node types.NodeView, r relogin, policyChanged bool) change.Cha // cut the node off when the old one passes. func reloginChanged(before, after types.NodeView, now time.Time) relogin { expiry := func(n types.NodeView) time.Time { - e, _ := n.Expiry().GetOk() + e, _ := n.KeyExpiry() return e } @@ -4030,7 +4070,9 @@ func reloginChanged(before, after types.NodeView, now time.Time) relogin { // What a peer patch cannot carry. expiredChanged := before.IsExpiredAt(now) != after.IsExpiredAt(now) hostinfoChanged := !peerHostinfoEqual(before.Hostinfo(), after.Hostinfo()) - expiryRemoved := before.Expiry().Valid() && !after.Expiry().Valid() + _, hadExpiry := before.KeyExpiry() + _, hasExpiry := after.KeyExpiry() + expiryRemoved := hadExpiry && !hasExpiry // What a peer patch carries. keysSame := before.NodeKey() == after.NodeKey() && before.DiscoKey() == after.DiscoKey() diff --git a/hscontrol/types/change/change.go b/hscontrol/types/change/change.go index b9dd8224a..a113ebb39 100644 --- a/hscontrol/types/change/change.go +++ b/hscontrol/types/change/change.go @@ -630,10 +630,8 @@ func NodeKeyRotated(node types.NodeView) Change { // It does not clear [tailcfg.Node.Expired]. It is sent in UTC, as // [types.NodeView.TailNode] sends it: the stored zone depends on the // database. - var expiry time.Time - if e, ok := node.Expiry().GetOk(); ok { - expiry = e.UTC() - } + expiry, _ := node.KeyExpiry() + expiry = expiry.UTC() // Peers get an expired node without its endpoints. var endpoints []netip.AddrPort diff --git a/hscontrol/types/config.go b/hscontrol/types/config.go index efaeb25eb..cf49cd948 100644 --- a/hscontrol/types/config.go +++ b/hscontrol/types/config.go @@ -127,11 +127,12 @@ type PreAuthKeysConfig struct { // NodeConfig contains configuration for node lifecycle and expiry. type NodeConfig struct { - // Expiry is the key expiry given to a non-tagged node that registers - // without one, whatever the method (auth key, CLI, web, OIDC). An - // expiry the client asks for, `oidc.use_expiry_from_token` and an - // admin's `headscale nodes expire` still apply. Tagged nodes never get - // this default. Zero or negative disables the default. + // Expiry is the key expiry given to a node that registers without one, + // whatever the method (auth key, CLI, web, OIDC). An expiry the client + // asks for, `oidc.use_expiry_from_token` and an admin's `headscale nodes + // expire` still apply. A tagged node registers with key expiry turned + // off and keeps this time for when it is turned on. Zero or negative + // disables the default. Expiry time.Duration `example:"\"2160h\"" koanf:"expiry"` // Ephemeral covers ephemeral nodes, which register with an ephemeral