api/v1: report a pre-auth key without expiration as null

Zero time read as expired; API keys and 0.29 already emit null.
This commit is contained in:
Kristoffer Dalby committed 2026-11-05 12:41:50 +01:00
1 parent 92bc0b6226
commit 1a32d031bf
5 files changed
+126 -71

No files matched your search

+1 -1
View File
@@ -196,7 +196,6 @@ the ACME DNS-01 challenge through a built-in DNS provider: `acmedns`,
- 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)
- Fix API keys and pre-auth keys created without an expiration being stored as `0001-01-01` instead of NULL, which made them immediately rejected as expired [#3254](https://github.com/juanfont/headscale/pull/3254)
- Improve systemd service file hardening [#3341](https://github.com/juanfont/headscale/pull/3341)
- Fix `headscale users destroy`/`rename` reporting "multiple users match query" when no user matches; an ambiguous match now lists the matching users [#3476](https://github.com/juanfont/headscale/pull/3476)
- Deleting a user that still owns nodes now lists the nodes (ID and hostname) that must be deleted first [#3475](https://github.com/juanfont/headscale/pull/3475)
@@ -238,6 +237,7 @@ the ACME DNS-01 challenge through a built-in DNS provider: `acmedns`,
- With MagicDNS on, exit nodes refuse DNS queries for names under `dns.base_domain`, as on Tailscale SaaS. Clients cannot read the tailnet's names through an exit node. Reverse lookups still pass. [#3636](https://github.com/juanfont/headscale/pull/3636)
- Peers get a node's last seen time when it goes offline, not at the next full map. [#3636](https://github.com/juanfont/headscale/pull/3636)
- With MagicDNS on, stop sending reverse DNS routes for `prefixes` inside 100.64.0.0/10 and fd7a:115c:a1e0::/48, as on Tailscale SaaS; clients add them. A `prefixes.v4` subset such as 100.64.0.0/24 sent 256, which overflowed systemd-resolved's domain limit and dropped reverse DNS. An octet-aligned prefix outside the ranges gets one route instead of 256 [#3482](https://github.com/juanfont/headscale/pull/3482)
- The v1 API stores an API key or pre-auth key created without `expiration` as one that never expires, and reports its expiration as `null`. It was stored as already expired and rejected on first use. The CLI always sends an expiration and was not affected. Keys created this way before stay expired; create new ones [#3254](https://github.com/juanfont/headscale/pull/3254)
## 0.29.7 (2026-10-30)
+1 -3
View File
@@ -85,9 +85,7 @@ func registerApiKeys(api huma.API, b Backend) {
Tags: []string{"ApiKeys"},
Security: bearerAuth,
}, func(ctx context.Context, in *createApiKeyInput) (*createApiKeyOutput, error) {
// A missing expiration must persist as NULL, not the zero time, or the
// key is rejected as already-expired on first use. Body.Expiration is
// already *time.Time (nil when omitted), so pass it straight through.
// Omitted persists as NULL (never expires); the zero time reads as expired.
keyStr, _, err := b.State.CreateAPIKey(in.Body.Expiration)
if err != nil {
return nil, huma.Error500InternalServerError("creating api key", err)
+27 -34
View File
@@ -16,19 +16,20 @@ func init() {
registrations = append(registrations, registerPreAuthKeys)
}
// PreAuthKey is the v1 PreAuthKey message. User is a pointer with no omitempty
// so tagged (system-created) keys emit "user":null. Expiration and CreatedAt
// are always emitted, zero-stamped when unset.
// PreAuthKey is the v1 PreAuthKey message. User and Expiration are pointers
// with no omitempty so tagged (system-created) keys emit "user":null and keys
// that never expire emit "expiration":null. CreatedAt is always emitted,
// zero-stamped when unset.
type PreAuthKey struct {
User *User `json:"user"`
ID string `format:"uint64" json:"id"`
Key string `json:"key"`
Reusable bool `json:"reusable"`
Ephemeral bool `json:"ephemeral"`
Used bool `json:"used"`
Expiration time.Time `json:"expiration"`
CreatedAt time.Time `json:"createdAt"`
ACLTags []string `json:"aclTags" nullable:"false"`
User *User `json:"user"`
ID string `format:"uint64" json:"id"`
Key string `json:"key"`
Reusable bool `json:"reusable"`
Ephemeral bool `json:"ephemeral"`
Used bool `json:"used"`
Expiration *time.Time `json:"expiration" nullable:"true"`
CreatedAt time.Time `json:"createdAt"`
ACLTags []string `json:"aclTags" nullable:"false"`
}
// CreatePreAuthKeyRequestBody is the v1.CreatePreAuthKeyRequest body. Every
@@ -113,9 +114,7 @@ func registerPreAuthKeys(api huma.API, b Backend) {
userID = u.TypedID()
}
// A missing expiration must persist as NULL, not the zero time, or the
// key is rejected as already-expired on first use. Body.Expiration is
// already *time.Time (nil when omitted), so pass it straight through.
// Omitted persists as NULL (never expires); the zero time reads as expired.
preAuthKey, err := b.State.CreatePreAuthKey(
userID,
in.Body.Reusable,
@@ -217,11 +216,12 @@ func registerPreAuthKeys(api huma.API, b Backend) {
// plaintext key is returned only here; Used is always false.
func preAuthKeyNewToResponse(key *types.PreAuthKeyNew) PreAuthKey {
out := PreAuthKey{
ID: formatID(key.ID),
Key: key.Key,
Reusable: key.Reusable,
Ephemeral: key.Ephemeral,
ACLTags: nonNilTags(key.Tags),
ID: formatID(key.ID),
Key: key.Key,
Reusable: key.Reusable,
Ephemeral: key.Ephemeral,
ACLTags: nonNilTags(key.Tags),
Expiration: key.Expiration,
}
if key.User != nil {
@@ -229,10 +229,6 @@ func preAuthKeyNewToResponse(key *types.PreAuthKeyNew) PreAuthKey {
out.User = &u
}
if key.Expiration != nil {
out.Expiration = *key.Expiration
}
if key.CreatedAt != nil {
out.CreatedAt = *key.CreatedAt
}
@@ -244,12 +240,13 @@ func preAuthKeyNewToResponse(key *types.PreAuthKeyNew) PreAuthKey {
// field masked (see maskedPreAuthKey).
func preAuthKeyToResponse(key *types.PreAuthKey) PreAuthKey {
out := PreAuthKey{
ID: formatID(key.ID),
Key: maskedPreAuthKey(key.Prefix),
Reusable: key.Reusable,
Ephemeral: key.Ephemeral,
Used: key.Used,
ACLTags: nonNilTags(key.Tags),
ID: formatID(key.ID),
Key: maskedPreAuthKey(key.Prefix),
Reusable: key.Reusable,
Ephemeral: key.Ephemeral,
Used: key.Used,
ACLTags: nonNilTags(key.Tags),
Expiration: key.Expiration,
}
if key.User != nil {
@@ -257,10 +254,6 @@ func preAuthKeyToResponse(key *types.PreAuthKey) PreAuthKey {
out.User = &u
}
if key.Expiration != nil {
out.Expiration = *key.Expiration
}
if key.CreatedAt != nil {
out.CreatedAt = *key.CreatedAt
}
+42 -16
View File
@@ -55,24 +55,50 @@ func TestAPIV1ApiKeyCreate(t *testing.T) {
assert.NotEmpty(t, humBody.APIKey)
})
t.Run("no expiration is not immediately expired", func(t *testing.T) {
h := newAPIV1Harness(t)
t.Run("expiration stored and reported as sent", func(t *testing.T) {
future := time.Now().Add(time.Hour).UTC().Truncate(time.Second)
res := h.callHuma(http.MethodPost, "/api/v1/apikey", []byte(`{}`))
require.Equal(t, http.StatusOK, res.status)
for _, tc := range []struct {
name string
body string
want any
}{
{"omitted", `{}`, nil},
{"null", `{"expiration":null}`, nil},
{
"future",
`{"expiration":"` + future.Format(time.RFC3339) + `"}`,
future.Format(time.RFC3339),
},
} {
t.Run(tc.name, func(t *testing.T) {
h := newAPIV1Harness(t)
var got struct {
APIKey string `json:"apiKey"`
res := h.callHuma(http.MethodPost, "/api/v1/apikey", []byte(tc.body))
require.Equal(t, http.StatusOK, res.status)
var created struct {
APIKey string `json:"apiKey"`
}
require.NoError(t, json.Unmarshal(res.body, &created))
// The zero time is already past, so an omitted expiration must
// stay NULL for the key to be usable.
valid, err := h.app.state.ValidateAPIKey(created.APIKey)
require.NoError(t, err)
assert.True(t, valid)
res = h.callHuma(http.MethodGet, "/api/v1/apikey", nil)
require.Equal(t, http.StatusOK, res.status)
var listed struct {
APIKeys []map[string]any `json:"apiKeys"`
}
require.NoError(t, json.Unmarshal(res.body, &listed))
require.Len(t, listed.APIKeys, 1)
assert.Equal(t, tc.want, listed.APIKeys[0]["expiration"])
})
}
require.NoError(t, json.Unmarshal(res.body, &got))
require.NotEmpty(t, got.APIKey)
// A missing expiration must persist as NULL, not the zero time, or the
// key is rejected as already-expired on first use (regression for the
// fix that the gRPC handler received in #3254).
valid, err := h.app.state.ValidateAPIKey(got.APIKey)
require.NoError(t, err)
assert.True(t, valid, "api key created without expiration must not be expired")
})
}
@@ -117,7 +143,7 @@ func TestAPIV1ApiKeyList(t *testing.T) {
t.Run("zero expiration emitted as zero instant parity", func(t *testing.T) {
h := newAPIV1Harness(t)
// Non-nil zero expiration (as gRPC CreateApiKey does for a missing one)
// Older releases stored the zero time for an omitted expiration; it
// must render as the zero instant, not null.
var zero time.Time
+55 -17
View File
@@ -76,26 +76,64 @@ func TestAPIV1CreatePreAuthKey(t *testing.T) {
assert.Equal(t, []any{"tag:test"}, got.PreAuthKey["aclTags"])
})
t.Run("no expiration persists as NULL not zero-time", func(t *testing.T) {
h := newAPIV1Harness(t)
t.Run("expiration stored and reported as sent", func(t *testing.T) {
future := time.Now().Add(time.Hour).UTC().Truncate(time.Second)
// No expiration field in the body. The JSON response can't distinguish
// NULL from the zero time (both render as 0001-01-01), so inspect the
// stored key directly.
res := h.callHuma(http.MethodPost, "/api/v1/preauthkey",
[]byte(`{"aclTags":["tag:test"]}`))
require.Equal(t, http.StatusOK, res.status)
for _, tc := range []struct {
name string
body string
want *time.Time
}{
{"omitted", `{"aclTags":["tag:test"]}`, nil},
{"null", `{"aclTags":["tag:test"],"expiration":null}`, nil},
{
"future",
`{"aclTags":["tag:test"],"expiration":"` + future.Format(time.RFC3339) + `"}`,
&future,
},
} {
t.Run(tc.name, func(t *testing.T) {
h := newAPIV1Harness(t)
keys, err := h.app.state.ListPreAuthKeys()
require.NoError(t, err)
require.Len(t, keys, 1)
res := h.callHuma(http.MethodPost, "/api/v1/preauthkey", []byte(tc.body))
require.Equal(t, http.StatusOK, res.status)
// A missing expiration must persist as NULL, not the zero time, or the
// key is rejected as already-expired on first use (regression for the
// fix that the gRPC handler received in #3254).
assert.Nil(t, keys[0].Expiration, "expiration must be NULL when omitted")
assert.NoError(t, keys[0].Validate(),
"key created without expiration must be valid")
var created struct {
PreAuthKey map[string]any `json:"preAuthKey"`
}
require.NoError(t, json.Unmarshal(res.body, &created))
res = h.callHuma(http.MethodGet, "/api/v1/preauthkey", nil)
require.Equal(t, http.StatusOK, res.status)
var listed struct {
PreAuthKeys []map[string]any `json:"preAuthKeys"`
}
require.NoError(t, json.Unmarshal(res.body, &listed))
require.Len(t, listed.PreAuthKeys, 1)
keys, err := h.app.state.ListPreAuthKeys()
require.NoError(t, err)
require.Len(t, keys, 1)
// The zero time is already past, so an omitted expiration must
// stay NULL for the key to be usable.
require.NoError(t, keys[0].Validate())
if tc.want == nil {
assert.Nil(t, keys[0].Expiration)
assert.Nil(t, created.PreAuthKey["expiration"])
assert.Nil(t, listed.PreAuthKeys[0]["expiration"])
return
}
require.NotNil(t, keys[0].Expiration)
assert.True(t, tc.want.Equal(*keys[0].Expiration))
assert.Equal(t, future.Format(time.RFC3339), created.PreAuthKey["expiration"])
assert.Equal(t, future.Format(time.RFC3339), listed.PreAuthKeys[0]["expiration"])
})
}
})
t.Run("invalid tag parity", func(t *testing.T) {