api/v2: answer as Tailscale where Headscale can

Tag, scope and token refusals, publicAddress, client listing as captured.
If-Match is checked under the policy lock; kept differences documented.
This commit is contained in:
Kristoffer Dalby committed 2026-11-20 23:02:54 +01:00
1 parent 0afe30f524
commit 11bbb0992c
15 files changed
+508 -108

No files matched your search

+21 -1
View File
@@ -41,7 +41,9 @@ headscale's own conventions. The headscale-native admin API stays at `/api/v1`
token is scope-limited**, the middleware checks the operation's declared scope
against the token's grant (`scope.Grants`, where a write scope subsumes its
`:read` and `all`/`all:read` are super-scopes). The two are told apart by
credential prefix.
credential prefix. A token without the scope is refused as Tailscale does
(`scopeRefusal`): 403 when it holds the `:read` half of a write scope, 404
`"not found"` otherwise.
- Resolve one entity by id with a typed getter (`GetNodeByID`, `GetUserByID`,
`GetAPIKeyByID`, `GetPreAuthKeyByID`); add one to state/db if it is missing
rather than scanning a `List`. Build responses from the view accessors
@@ -93,6 +95,24 @@ tolerating `RequestTags` that are a subset of the key's tags.
code through this; `.github/workflows/tailscale-action-integration.yaml` covers
the GitHub Action. User-facing setup is in `docs/ref/api.md`.
## Intentional differences from Tailscale
Each has a test whose comment gives Tailscale's answer, Headscale's, the
reason and the recording (`hscontrol/testdata/tailscale_api/probe-*`).
- `POST /device/{id}/tags` with `[]` or `null` is 200 and changes nothing;
Tailscale answers 400. Terraform's destroy sends it.
`TestAPIv2DeviceTagsEmptyIsNoChange`.
- `POST /device/{id}/authorized` with `false` is 400: Headscale has no device
approval (#2176). `TestAPIv2DeviceDeauthorizeRefused`.
- `POST /device/{id}/routes` with one exit prefix approves and reports both.
`TestAPIv2DeviceOneExitPrefix`.
- A key description over 50 characters is refused (422); Tailscale truncates it to 50. Tailscale refuses characters such as `.` `:` `@`; Headscale accepts all.
`TestAPIv2KeyDescription`.
Known differences not yet removed are listed with a reason in
`apiv2CompatSkipReasons` (`hscontrol/apiv2_compat_test.go`).
## Adding an endpoint
Worked example: the keys resource (`keys.go`) = Tailscale auth keys = Headscale
+13 -7
View File
@@ -125,20 +125,26 @@ func registerACL(api huma.API, b Backend) {
)
}
// Checked under the policy lock, so two writers holding the same ETag
// cannot both pass.
var match func(string) bool
if in.IfMatch != "" {
current, err := currentPolicy(b)
if err != nil {
return nil, err
}
match = func(stored string) bool {
if stored == "" {
stored = defaultPolicy
}
if !etagMatches(in.IfMatch, current) {
return nil, huma.Error412PreconditionFailed("precondition failed, invalid old hash")
return etagMatches(in.IfMatch, []byte(stored))
}
}
updated, cs, err := b.State.UpdatePolicy(in.RawBody)
updated, cs, err := b.State.UpdatePolicyIf(in.RawBody, match)
b.Change(cs...)
if errors.Is(err, state.ErrPolicyPrecondition) {
return nil, huma.Error412PreconditionFailed("precondition failed, invalid old hash")
}
if err != nil {
return nil, mapError("setting policy", err)
}
+15 -2
View File
@@ -204,8 +204,8 @@ func authMiddleware(api huma.API, b Backend) func(huma.Context, func(huma.Contex
}
if want, ok := requiredScope(ctx.Operation()); ok && !scope.Grants(scope.Parse(at.Scopes), want) {
_ = huma.WriteErr(api, ctx, http.StatusForbidden,
"token is missing the required scope "+string(want))
refusal := scopeRefusal(scope.Parse(at.Scopes), want)
_ = huma.WriteErr(api, ctx, refusal.GetStatus(), refusal.Error())
return
}
@@ -331,6 +331,19 @@ func requireScope(op huma.Operation, s scope.Scope) huma.Operation {
return op
}
// scopeRefusal is Tailscale's answer to a token without want: 403 when the
// token can read what it may not write, otherwise 404, as if nothing were there
// (probe-U U5, probe-V Y1, Y2).
func scopeRefusal(granted []scope.Scope, want scope.Scope) huma.StatusError {
if want.IsWrite() && scope.Grants(granted, want+":read") {
return huma.Error403Forbidden(errNotEnoughPermissions)
}
return huma.Error404NotFound("not found")
}
const errNotEnoughPermissions = "calling actor does not have enough permissions to perform this function"
// requiredScope returns the scope an operation declared via requireScope, if any.
func requiredScope(op *huma.Operation) (scope.Scope, bool) {
if op == nil || op.Metadata == nil {
+2 -1
View File
@@ -722,7 +722,8 @@ func deviceFromView(view types.NodeView, allFields bool, baseDomain string) Devi
func devicePostureAttributesFromView(view types.NodeView) DevicePostureAttributes {
attributes := make(map[string]any)
if addr := view.LastControlAddress(); addr.Valid() {
attributes["ip:publicAddress"] = addr.Get().String()
// Tailscale's typed value (probe-J J16).
attributes["ip:publicAddress"] = map[string]string{"type": "IpAddr", "value": addr.Get().String()}
}
return DevicePostureAttributes{Attributes: attributes}
+18
View File
@@ -137,6 +137,24 @@ func unownedTags(b Backend, tags, tokenTags []string) []string {
return out
}
// undefinedTagsRefused refuses the tags no policy defines, as Tailscale does
// for any caller (probe-A A1, probe-R).
func undefinedTagsRefused(b Backend, tags []string) error {
var refused []string
for _, tag := range tags {
if !b.State.TagExists(tag) {
refused = append(refused, tag)
}
}
if len(refused) > 0 {
return tagsRefused("", refused)
}
return nil
}
// tagsRefused is Tailscale's 400 for tags a token may not apply.
func tagsRefused(prefix string, tags []string) error {
return huma.Error400BadRequest(
+61 -43
View File
@@ -2,6 +2,7 @@ package apiv2
import (
"context"
"fmt"
"net/http"
"strconv"
"time"
@@ -187,12 +188,19 @@ func registerKeys(api huma.API, b Backend) {
}
scopes, isOAuth := principalScopes(ctx)
readAuth := !isOAuth || scope.Grants(scope.Parse(scopes), scope.AuthKeysRead)
readClients := !isOAuth || scope.Grants(scope.Parse(scopes), scope.OAuthKeysRead)
// As Tailscale (probe-U U5m): a token that can read no kind of key.
if !readAuth && !readClients {
return nil, huma.Error403Forbidden(errNotEnoughPermissions)
}
out := &listKeysOutput{}
out.Body.Keys = []Key{}
// A token sees the key kinds it has read scope for; an admin key sees all.
if !isOAuth || scope.Grants(scope.Parse(scopes), scope.AuthKeysRead) {
if readAuth {
keys, err := b.State.ListPreAuthKeys()
if err != nil {
return nil, huma.Error500InternalServerError("listing auth keys", err)
@@ -211,13 +219,20 @@ func registerKeys(api huma.API, b Backend) {
}
}
if !isOAuth || scope.Grants(scope.Parse(scopes), scope.OAuthKeysRead) {
// As Tailscale (probe-T H5, H7b; probe-U U6): an admin key lists clients
// only with all=true, a token whenever it may read them, and a revoked
// client never.
if readClients && (isOAuth || in.All) {
clients, err := b.State.ListOAuthClients()
if err != nil {
return nil, huma.Error500InternalServerError("listing oauth clients", err)
}
for i := range clients {
if clients[i].Revoked != nil {
continue
}
out.Body.Keys = append(out.Body.Keys, oauthClientToKey(&clients[i], ""))
}
}
@@ -289,11 +304,16 @@ func registerKeys(api huma.API, b Backend) {
return nil, err
}
// Gated on oauth_keys (write) for the same no-existence-oracle reason as
// getKey: a token without it must not learn that an id is an OAuth client.
if requireKeyScope(ctx, scope.OAuthKeys) == nil {
// Gated on oauth_keys:read for the same no-existence-oracle reason as
// getKey; a reader that may not write is then refused (probe-U U5k).
if requireKeyScope(ctx, scope.OAuthKeysRead) == nil {
_, err = b.State.GetOAuthClientByClientID(in.KeyID)
if err == nil {
err = requireKeyScope(ctx, scope.OAuthKeys)
if err != nil {
return nil, err
}
err = b.State.RevokeOAuthClient(in.KeyID)
if err != nil {
return nil, mapError("deleting oauth client", err)
@@ -342,7 +362,7 @@ func requireKeyScope(ctx context.Context, need scope.Scope) error {
}
if !scope.Grants(scope.Parse(scopes), need) {
return huma.Error403Forbidden("token is missing the required scope " + string(need))
return scopeRefusal(scope.Parse(scopes), need)
}
return nil
@@ -354,8 +374,13 @@ func requireCreateKeyScope(api huma.API) func(huma.Context, func(huma.Context))
return func(ctx huma.Context, next func(huma.Context)) {
if requireKeyScope(ctx.Context(), scope.AuthKeys) != nil &&
requireKeyScope(ctx.Context(), scope.OAuthKeys) != nil {
_ = huma.WriteErr(api, ctx, http.StatusForbidden,
"token is missing the required scope auth_keys or oauth_keys")
status, message := http.StatusNotFound, "not found"
if requireKeyScope(ctx.Context(), scope.AuthKeysRead) == nil ||
requireKeyScope(ctx.Context(), scope.OAuthKeysRead) == nil {
status, message = http.StatusForbidden, errNotEnoughPermissions
}
_ = huma.WriteErr(api, ctx, status, message)
return
}
@@ -392,11 +417,15 @@ func createAuthKey(ctx context.Context, b Backend, body CreateKeyRequest) (*keyO
switch {
case len(create.Tags) > 0:
// A key minted by an OAuth token may only carry tags within the token's
// grant (held directly, or owned by a held tag) and defined in policy,
// matching SetNodeTags. An admin key keeps the historical behaviour of
// validating only tag syntax (db.validateACLTags), and records its
// user as the key's creator.
// Every tag must be defined in policy, also for an admin key (probe-A
// A1). A key minted by an OAuth token may only carry tags within the
// token's grant (held directly, or owned by a held tag), matching
// SetNodeTags. An admin key records its user as the key's creator.
err = undefinedTagsRefused(b, create.Tags)
if err != nil {
return nil, err
}
if !isOAuth {
if uid, ok := ownerUser(ctx); ok {
userID = &uid
@@ -404,12 +433,6 @@ func createAuthKey(ctx context.Context, b Backend, body CreateKeyRequest) (*keyO
}
if isOAuth {
for _, tag := range create.Tags {
if !b.State.TagExists(tag) {
return nil, huma.Error400BadRequest("tag " + tag + " is not defined in policy")
}
}
if refused := unownedTags(b, create.Tags, tokenTags); len(refused) > 0 {
return nil, tagsRefused("", refused)
}
@@ -417,8 +440,8 @@ func createAuthKey(ctx context.Context, b Backend, body CreateKeyRequest) (*keyO
case isOAuth:
// OAuth-minted keys are tailnet/tag-owned; an untagged (user-owned) key
// cannot be created from a token.
return nil, huma.Error403Forbidden("an OAuth client must create tagged auth keys")
// cannot be created from a token (probe-U U2d, U2e).
return nil, huma.Error400BadRequest("tailnet-owned auth key must have tags set")
default:
uid, ok := ownerUser(ctx)
@@ -479,37 +502,32 @@ func createOAuthClient(ctx context.Context, b Backend, body CreateKeyRequest) (*
)
}
// A client created by an OAuth token may not be granted authority the token
// lacks: its scopes must each be within the token's grant, and its tags within
// the token's tags and defined in policy (matching SetNodeTags). Otherwise an
// oauth_keys token could mint an all-access client and escalate. An admin API
// key (not an OAuth token) is unrestricted and keeps the historical tag
// behaviour (syntax-only validation).
// A client created by an OAuth token may not be granted a scope the token
// lacks, or an oauth_keys token could mint an all-access client and
// escalate. Its tags must be within the token's tags. Every caller, an admin
// API key too, may only name tags defined in policy (probe-R).
if tokenScopes, isOAuth := principalScopes(ctx); isOAuth {
var refused []string
for _, s := range body.Scopes {
if !scope.Grants(scope.Parse(tokenScopes), scope.Scope(s)) {
return nil, huma.Error403Forbidden(
"client may not be granted scope " + s + " beyond the creating token",
)
refused = append(refused, s)
}
}
tokenTags, _ := principalTags(ctx)
// An untagged "all" client may mint tokens for any tag (narrowTags), so a
// tag-limited token would escape its tags one client away.
if len(tokenTags) > 0 && canAssignAnyTag(body.Tags, body.Scopes) {
return nil, huma.Error403Forbidden(
"client may not be granted scope all without tags by a tagged token",
)
if len(refused) > 0 {
return nil, huma.Error403Forbidden(fmt.Sprintf("actor cannot set scopes: %v", refused))
}
}
for _, tag := range body.Tags {
if !b.State.TagExists(tag) {
return nil, huma.Error400BadRequest("tag " + tag + " is not defined in policy")
}
}
err = undefinedTagsRefused(b, body.Tags)
if err != nil {
return nil, err
}
// A tagged token may still create an untagged "all" client, whose tokens
// then take any tag: Tailscale allows it (probe-U U1a, U1h-U1j).
if tokenTags, isOAuth := principalTags(ctx); isOAuth {
if refused := unownedTags(b, body.Tags, tokenTags); len(refused) > 0 {
return nil, tagsRefused("", refused)
}
+8 -18
View File
@@ -45,15 +45,6 @@ import (
// when the call flips. v1-* checks are TestAPIV1PolicyVerdictCompat's. A
// listed check that matches fails, so a fix must delete its entry.
var apiv2CompatSkipReasons = map[string]string{
"oauth/R2/4/status": missingScopeNotFound,
"oauth/R3/1/status": missingScopeNotFound,
"oauth/R3/2/status": missingScopeNotFound,
"oauth/R3/3/status": missingScopeNotFound,
"oauth/K3/0/status": missingScopeNotFound,
"oauth/J2/0/status": missingScopeNotFound,
"oauth/K4/0/status": missingScopeNotFound,
"oauth/D1/0/message": missingScopeText,
"oauth/O3/0/status": mintScopeRefusalStatus,
"oauth/O4/0/scope": unknownScopeGranted,
"oauth/O4/0/tags": unknownScopeGranted,
@@ -64,8 +55,6 @@ var apiv2CompatSkipReasons = map[string]string{
"oauth/D0/1/listed": emptyKeyListNull,
"oauth/D7/2/status": deletedClientGone,
"oauth/D7/2/outcome": deletedClientGone,
"oauth/D7/3/message": deletedClientCredentialText,
"oauth/D7/4/message": deletedClientCredentialText,
"oauth/B7/0/message": deletedClientCredentialText,
@@ -94,10 +83,7 @@ var apiv2CompatNotCompared = []string{
// apiv2CompatNotReplayed lists steps left out, keyed <test_id>/<step>, with
// the objects only they create, which listings then leave out: SaaS's answer
// there is in doubt, so it is no reference.
var apiv2CompatNotReplayed = map[string][]string{
"oauth/E7": {"{client:C-all-2}"},
"oauth/E9b": {"{key:K-E9b}"},
}
var apiv2CompatNotReplayed = map[string][]string{}
// notCompared reports whether key falls under one of prefixes.
func notCompared(prefixes []string, key string) bool {
@@ -112,16 +98,13 @@ const (
mintTagsSorted = "TOKEN_TAGS_SORTED: SaaS's token answer names the tags in the order its client was made with; headscale stores a client's tags sorted"
unknownKeyType = "UNKNOWN_KEY_TYPE: SaaS refuses an unknown keyType with 400 before it checks scopes; headscale checks the scope first and answers 403"
emptyKeyListNull = "EMPTY_KEY_LIST_NULL: SaaS answers a listing that holds no key with keys null; headscale with []"
deletedClientGone = "DELETED_CLIENT_GONE: SaaS keeps a deleted OAuth client readable as invalid and revoked; headscale removes it"
deletedClientCredentialText = "DELETED_CLIENT_CREDENTIAL_TEXT: SaaS refuses a deleted client's secret and tokens with API token invalid; headscale says invalid client credentials and unauthorized"
missingScopeText = "MISSING_SCOPE_TEXT: SaaS refuses a delete outside the token's scopes with calling actor does not have enough permissions; headscale names the missing scope"
hujsonFormatted = "HUJSON_FORMATTED: SaaS stores a HuJSON policy formatted, comments kept; headscale stores the bytes as sent"
)
// SaaS behaviour recorded as it is; following it is the maintainer's call.
const (
deviceOAuthClientMaker = "DEVICE_OAUTH_CLIENT_ID: SaaS names, in oauthClientId, the OAuth client whose token made the device's key; headscale does not record which client that was, so it leaves the field out"
missingScopeNotFound = "MISSING_SCOPE_NOT_FOUND: SaaS answers a call outside the token's scopes with 404 not found; headscale answers 403"
unknownScopeGranted = "UNKNOWN_SCOPE_GRANTED: SaaS ignores an unknown requested scope and grants the client's own; headscale grants the unknown scope alone"
)
@@ -284,6 +267,13 @@ func newAPIReplay(t *testing.T, c *testcapture.Capture, useV1 bool) *apiReplay {
r.v2, _ = apiv2.Handler(apiv2.Backend{State: app.state, Change: app.Change, Cfg: app.cfg})
// SaaS held this policy before the first step, so its tags exist for
// the keys a setup step makes before it writes a policy.
if c.Input.FullPolicy != "" {
_, _, err := app.state.UpdatePolicy(r.policyBody(t, json.RawMessage(c.Input.FullPolicy)))
require.NoError(t, err)
}
return r
}
+1 -1
View File
@@ -231,7 +231,7 @@ func TestAPIv2Device_GetPostureAttributes(t *testing.T) {
))
attrs := getDevicePostureAttributes(t, e.api, e.deviceID)
assert.Equal(t, test.addr, attrs.Attributes["ip:publicAddress"])
assert.Equal(t, map[string]any{"type": "IpAddr", "value": test.addr}, attrs.Attributes["ip:publicAddress"])
assert.Empty(t, attrs.Expiries)
})
}
+4
View File
@@ -35,6 +35,10 @@ func newKeyTestAPI(t *testing.T) (*Headscale, humatest.TestAPI) {
app := createTestApp(t)
// A key may only carry tags the policy defines.
_, _, err := app.state.UpdatePolicy([]byte(`{"tagOwners":{"tag:test":[]}}`))
require.NoError(t, err)
_, api := humatest.New(t, apiv2.Config())
apiv2.Register(api, apiv2.Backend{State: app.state})
+22 -8
View File
@@ -52,12 +52,18 @@ func apiReq(t *testing.T, method, target, bearer string, body any) (int, []byte)
}
// scopeDenied reports whether a response is a scope-enforcement denial. The scope
// gate runs in the middleware before the handler, so a denial is exactly a 403
// carrying this message; any other status (200, or a 400/404 from the handler on
// minimal input) means the request passed the scope gate.
// gate runs in the middleware before the handler and answers as Tailscale: 403
// when the token holds the read half of a write scope, otherwise 404 "not
// found". Any other answer means the request passed the scope gate.
func scopeDenied(status int, body []byte) bool {
return status == http.StatusForbidden &&
strings.Contains(string(body), "missing the required scope")
switch status {
case http.StatusForbidden:
return strings.Contains(string(body), "calling actor does not have enough permissions")
case http.StatusNotFound:
return strings.Contains(string(body), `"message":"not found"`)
}
return false
}
// mintScopedToken creates an OAuth client holding exactly scope s (tagged tag:ci so
@@ -146,9 +152,8 @@ func TestAPIv2OAuthMatrix_Enforcement(t *testing.T) {
wantDenied := !scope.Grants([]scope.Scope{s}, op.need)
// A multiplexed keys op denies via uniform not-found (no existence
// oracle), so denial is "resource not returned"; every other op
// denies with the middleware's scope-403.
// A multiplexed keys op denies in its handler, so denial is
// "resource not returned"; every other op denies in the middleware.
denied := scopeDenied(status, body)
if op.multiplexed {
denied = status != http.StatusOK
@@ -157,6 +162,15 @@ func TestAPIv2OAuthMatrix_Enforcement(t *testing.T) {
assert.Equalf(t, wantDenied, denied,
"op %s with scope %q (needs %q): status=%d body=%s",
op.name, s, op.need, status, body)
if wantDenied && !op.multiplexed {
wantStatus := http.StatusNotFound
if op.need.IsWrite() && scope.Grants([]scope.Scope{s}, op.need+":read") {
wantStatus = http.StatusForbidden
}
assert.Equalf(t, wantStatus, status, "op %s with scope %q: body=%s", op.name, s, body)
}
}
}
}
+21 -16
View File
@@ -551,10 +551,11 @@ func TestAPIv2OAuth_ScopeEnforcement(t *testing.T) {
assert.Equal(t, http.StatusForbidden, createTaggedKey(t, baseURL, readTok, []string{"tag:ci"}),
"read scope denied write")
// The wrong write scope (devices:core) cannot create auth keys.
// The wrong write scope (devices:core) cannot create auth keys; with no
// key scope at all it is told not found (probe-U U5n).
_, devSecret := createClient(t, baseURL, admin, []string{"devices:core"}, []string{"tag:ci"})
devTok := tokenFor(t, baseURL, devSecret)
assert.Equal(t, http.StatusForbidden, createTaggedKey(t, baseURL, devTok, []string{"tag:ci"}),
assert.Equal(t, http.StatusNotFound, createTaggedKey(t, baseURL, devTok, []string{"tag:ci"}),
"wrong scope denied")
// The "all" super-scope grants auth_keys.
@@ -595,13 +596,13 @@ func TestAPIv2OAuth_ClientManagementScopes(t *testing.T) {
statusDeny, _ := apiPost(t, baseURL+"/api/v2/tailnet/-/keys", akTok, apiv2.CreateKeyRequest{
KeyType: "client", Scopes: []string{"auth_keys"}, Tags: []string{"tag:ci"},
})
assert.Equal(t, http.StatusForbidden, statusDeny, "auth_keys (no oauth_keys) cannot create a client")
assert.Equal(t, http.StatusNotFound, statusDeny, "auth_keys (no oauth_keys) cannot create a client")
}
// TestAPIv2OAuth_TaggedAllClientStaysInTags asserts an all-scope client with
// tags mints tokens only inside its tags, and that a tagged token cannot
// escape them through an untagged all-scope child, whose tokens may take any
// tag.
// tags mints tokens only inside its tags. A tagged token may still create an
// untagged all-scope child, whose tokens take any tag: Tailscale allows this
// (probe-U U1a, U1h-U1j, U1'a-U1'i), and the maintainer chose to follow it.
func TestAPIv2OAuth_TaggedAllClientStaysInTags(t *testing.T) {
_, baseURL, admin := newOAuthTestServer(t)
@@ -623,9 +624,9 @@ func TestAPIv2OAuth_TaggedAllClientStaysInTags(t *testing.T) {
createClient(t, baseURL, tok, []string{"auth_keys", "oauth_keys"}, []string{"tag:a"})
st, body := apiPost(t, baseURL+"/api/v2/tailnet/-/keys", tok,
apiv2.CreateKeyRequest{KeyType: "client", Scopes: []string{"all"}})
assert.Equalf(t, http.StatusForbidden, st, "untagged all-scope child: %s", body)
_, child := createClient(t, baseURL, tok, []string{"all"}, nil)
st, m = mintTokenWithTags(t, baseURL, child, "tag:b")
assert.Equalf(t, http.StatusOK, st, "untagged all-scope child takes any tag: %v", m)
// An admin API key still creates an untagged all-scope client, whose
// tokens may take any tag.
@@ -737,9 +738,9 @@ func TestAPIv2OAuth_SetDeviceTagsGrant(t *testing.T) {
assert.Equal(t, []string{"tag:other"}, got.Tags().AsSlice())
}
// TestAPIv2OAuth_UndefinedTagRejected asserts an OAuth token cannot create a
// client or auth key carrying a tag absent from policy (matching SetNodeTags),
// while an admin key retains the historical syntax-only validation.
// TestAPIv2OAuth_UndefinedTagRejected asserts no caller, an admin API key
// included, can create a client or auth key carrying a tag absent from policy:
// Tailscale answers 400 for each (probe-A A1, probe-R R2-R5).
func TestAPIv2OAuth_UndefinedTagRejected(t *testing.T) {
_, baseURL, admin := newOAuthTestServer(t)
@@ -757,10 +758,14 @@ func TestAPIv2OAuth_UndefinedTagRejected(t *testing.T) {
})
assert.Equal(t, http.StatusBadRequest, st, "token may not create a client with an undefined tag")
// An admin key keeps the historical behaviour: a syntactically valid but
// undefined tag is accepted (consistent with the v1/CLI pre-auth-key path).
assert.Equal(t, http.StatusOK, createTaggedKey(t, baseURL, admin, []string{"tag:adminhistorical"}),
"admin retains syntax-only tag validation")
assert.Equal(t, http.StatusBadRequest, createTaggedKey(t, baseURL, admin, []string{"tag:undefined"}),
"admin may not create an auth key with an undefined tag")
st, body := apiPost(t, baseURL+"/api/v2/tailnet/-/keys", admin, apiv2.CreateKeyRequest{
KeyType: "client", Scopes: []string{"devices:core:read"}, Tags: []string{"tag:ci", "tag:undefined"},
})
assert.Equal(t, http.StatusBadRequest, st, "admin may not create a read client with an undefined tag")
assert.JSONEq(t, `{"message":"requested tags [tag:undefined] are invalid or not permitted","status":400}`, string(body))
}
// TestAPIv2OAuth_DenialBranches covers the token-endpoint and bearer-dispatch
+283
View File
@@ -0,0 +1,283 @@
package hscontrol
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"sync"
"testing"
apiv2 "github.com/juanfont/headscale/hscontrol/api/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The probe-* recordings cited here are raw captures of the live Tailscale
// API, kept in testdata/tailscale_api (see its README).
// TestAPIv2KeysScopeRefusal: a token without the scope a keys call needs is
// told 404 "not found" when it holds nothing for that kind of key, and 403
// "calling actor does not have enough permissions…" when it may read the
// kind but not write it, as on Tailscale (probe-U U5a-U5n). Listing keys
// with no key read scope at all is 403 there too (U5m), though creating one
// is 404 (U5n). Where the refusal falls through to an unknown auth key
// only the status is compared: Headscale names it "auth key not found".
func TestAPIv2KeysScopeRefusal(t *testing.T) {
_, baseURL, admin := newOAuthTestServer(t)
keys := baseURL + "/api/v2/tailnet/-/keys"
clientID, _ := createClient(t, baseURL, admin, []string{"devices:core:read"}, nil)
authKeyID := createAdminAuthKey(t, baseURL, admin)
token := func(scopes ...string) string {
_, secret := createClient(t, baseURL, admin, scopes, []string{"tag:ci"})
return tokenFor(t, baseURL, secret)
}
authRead := token("auth_keys:read")
oauthRead := token("oauth_keys:read")
authWrite := token("auth_keys")
coreRead := token("devices:core:read")
const forbidden = `{"message":"calling actor does not have enough permissions to perform this function","status":403}`
const notFound = `{"message":"not found","status":404}`
for _, tc := range []struct {
name, method, target, bearer string
body any
want string
statusOnly bool
}{
{"U5a auth_keys:read creates a key", http.MethodPost, keys, authRead, map[string]any{"capabilities": taggedCaps("tag:ci")}, forbidden, false},
{"U5b auth_keys:read deletes a key", http.MethodDelete, keys + "/" + authKeyID, authRead, nil, forbidden, false},
{"U5d auth_keys:read reads a client", http.MethodGet, keys + "/" + clientID, authRead, nil, notFound, true},
{"U5i oauth_keys:read reads an auth key", http.MethodGet, keys + "/" + authKeyID, oauthRead, nil, notFound, false},
{"U5k oauth_keys:read deletes a client", http.MethodDelete, keys + "/" + clientID, oauthRead, nil, forbidden, false},
{"U5l auth_keys deletes a client", http.MethodDelete, keys + "/" + clientID, authWrite, nil, notFound, true},
{"U5m devices:core:read lists keys", http.MethodGet, keys, coreRead, nil, forbidden, false},
{"U5n devices:core:read creates a key", http.MethodPost, keys, coreRead, map[string]any{"capabilities": taggedCaps("tag:ci")}, notFound, false},
{"U5o devices:core:read creates a client", http.MethodPost, keys, coreRead, map[string]any{"keyType": "client", "scopes": []string{"devices:core:read"}}, notFound, false},
} {
t.Run(tc.name, func(t *testing.T) {
st, body := apiReq(t, tc.method, tc.target, tc.bearer, tc.body)
if tc.statusOnly {
assert.Equalf(t, http.StatusNotFound, st, "%s", body)
return
}
assert.JSONEq(t, tc.want, string(body))
})
}
}
// TestAPIv2TokenRuleRefusals: a token that breaks a token rule is refused as
// on Tailscale: 400 for a key without tags (probe-U U2d, U2e, U1k) and 403
// naming the scopes for a client with scopes the token lacks (U3a-U3h).
func TestAPIv2TokenRuleRefusals(t *testing.T) {
_, baseURL, admin := newOAuthTestServer(t)
keys := baseURL + "/api/v2/tailnet/-/keys"
_, secret := createClient(t, baseURL, admin, []string{"all"}, []string{"tag:ci"})
tok := tokenFor(t, baseURL, secret)
st, body := apiPost(t, keys, tok, map[string]any{})
assert.Equal(t, http.StatusBadRequest, st)
assert.JSONEq(t, `{"message":"tailnet-owned auth key must have tags set","status":400}`, string(body))
_, secret = createClient(t, baseURL, admin, []string{"oauth_keys"}, nil)
tok = tokenFor(t, baseURL, secret)
st, body = apiPost(t, keys, tok, apiv2.CreateKeyRequest{
KeyType: "client", Scopes: []string{"oauth_keys", "devices:core:read", "all"},
})
assert.Equal(t, http.StatusForbidden, st)
assert.JSONEq(t, `{"message":"actor cannot set scopes: [devices:core:read all]","status":403}`, string(body))
}
// TestAPIv2OAuthClientSoftDelete: DELETE revokes an OAuth client rather than
// removing it, as Tailscale does and as auth keys already do. The client stays
// readable by ID as revoked and invalid, a repeated DELETE succeeds (probe-G
// H6-H8, probe-T H6-H8), and its tokens stop working (probe-Q Q4-Q7). The key
// list never shows a revoked client (probe-T H7b), and shows live clients to
// an admin API key only with all=true (probe-T H5, H5b), while a token that
// may read clients sees them either way (probe-U U6).
func TestAPIv2OAuthClientSoftDelete(t *testing.T) {
_, baseURL, admin := newOAuthTestServer(t)
keys := baseURL + "/api/v2/tailnet/-/keys"
listed := func(bearer, query, id string) bool {
t.Helper()
st, body := apiReq(t, http.MethodGet, keys+query, bearer, nil)
require.Equalf(t, http.StatusOK, st, "%s", body)
var out struct{ Keys []apiv2.Key }
require.NoError(t, json.Unmarshal(body, &out))
for _, k := range out.Keys {
if k.ID == id {
return true
}
}
return false
}
id, secret := createClient(t, baseURL, admin, []string{"oauth_keys:read"}, nil)
tok := tokenFor(t, baseURL, secret)
assert.False(t, listed(admin, "", id), "admin key, default list")
assert.True(t, listed(admin, "?all=true", id), "admin key, all=true")
assert.True(t, listed(tok, "", id), "oauth_keys:read token, default list")
st, body := apiReq(t, http.MethodDelete, keys+"/"+id, admin, nil)
require.Equalf(t, http.StatusOK, st, "%s", body)
st, body = apiReq(t, http.MethodGet, keys+"/"+id, admin, nil)
require.Equalf(t, http.StatusOK, st, "%s", body)
var got apiv2.Key
require.NoError(t, json.Unmarshal(body, &got))
assert.True(t, got.Invalid)
assert.NotNil(t, got.Revoked)
st, _ = apiReq(t, http.MethodDelete, keys+"/"+id, admin, nil)
assert.Equal(t, http.StatusOK, st, "a repeated DELETE succeeds")
assert.False(t, listed(admin, "?all=true", id), "a revoked client is never listed")
st, _ = apiReq(t, http.MethodGet, keys, tok, nil)
assert.Equal(t, http.StatusUnauthorized, st, "the revoked client's token is gone")
}
// TestAPIv2ACLIfMatchConcurrent: writers holding the same ETag race; exactly
// one may win. The ETag is compared under the lock the write takes, so the
// rest see the policy the winner wrote and get 412.
func TestAPIv2ACLIfMatchConcurrent(t *testing.T) {
app := createTestApp(t)
api := registerAPIV2(t, app)
etag := setACL(t, api, allowAllPolicy, "application/json").Header().Get("Etag")
const writers = 8
codes := make([]int, writers)
var wg sync.WaitGroup
for i := range writers {
wg.Go(func() {
body := fmt.Sprintf(`{"hosts":{"h":"100.64.0.%d"},"acls":[{"action":"accept","src":["*"],"dst":["*:*"]}]}`, i+1)
codes[i] = setACL(t, api, body, "application/json", "If-Match: "+etag).Code
})
}
wg.Wait()
won := 0
for _, c := range codes {
if c == http.StatusOK {
won++
} else {
assert.Equal(t, http.StatusPreconditionFailed, c)
}
}
assert.Equal(t, 1, won, "codes: %v", codes)
}
// TestAPIv2DeviceTagsEmptyIsNoChange documents an intentional difference from Tailscale.
//
// Tailscale: POST /device/{id}/tags with "tags":[] on a tagged node answers
// 400 "tagged nodes cannot be untagged without reauth" (probe-J J7).
//
// Headscale: [] and null are accepted with 200 and change nothing. The node
// cannot become untagged either way (tags-as-identity is one-way), but the
// Terraform provider's destroy of tailscale_device_tags sends "tags":null,
// and a 400 there would leave every such resource impossible to destroy.
func TestAPIv2DeviceTagsEmptyIsNoChange(t *testing.T) {
e := newDeviceTestEnv(t)
target := "/api/v2/device/" + e.deviceID + "/tags"
require.Equal(t, http.StatusOK, e.api.Post(target, map[string]any{"tags": []string{"tag:ci"}}).Code)
for _, body := range []string{`{"tags":[]}`, `{"tags":null}`} {
resp := e.api.Post(target, "Content-Type: application/json", strings.NewReader(body))
assert.Equalf(t, http.StatusOK, resp.Code, "%s: %s", body, resp.Body)
assert.Equal(t, []string{"tag:ci"}, e.srvNode(t).Tags().AsSlice(), body)
}
}
// TestAPIv2DeviceDeauthorizeRefused documents an intentional difference from Tailscale.
//
// Tailscale: POST /device/{id}/authorized with false answers 200 and the
// device reads back authorized=false (probe-J J17); it is cut off until
// approved again.
//
// Headscale: 400, and the device stays authorized. Headscale has no device
// approval, so there is no state to put it in; answering 200 would let a
// caller believe the device is fenced off when it is not. Device approval is
// juanfont/headscale#2176; when it lands this should follow Tailscale.
func TestAPIv2DeviceDeauthorizeRefused(t *testing.T) {
e := newDeviceTestEnv(t)
resp := e.api.Post("/api/v2/device/"+e.deviceID+"/authorized", map[string]any{"authorized": false})
assert.Equal(t, http.StatusBadRequest, resp.Code)
assert.True(t, getDevice(t, e.api, e.deviceID).Authorized)
}
// TestAPIv2DeviceOneExitPrefix documents an intentional difference from Tailscale.
//
// Tailscale: POST /device/{id}/routes with only "0.0.0.0/0" stores and
// reports exactly that in enabledRoutes, yet the node itself is sent both
// exit routes and offers itself as an exit node; with only "::/0" it is not
// an exit node at all (probe-N N2, N3; probe-P).
//
// Headscale: one exit prefix approves both, and enabledRoutes reports both.
// Headscale approves exit routes as a pair everywhere else (CLI, auto
// approval), and reporting what is actually in effect keeps the API and the
// node in agreement.
func TestAPIv2DeviceOneExitPrefix(t *testing.T) {
e := newDeviceTestEnv(t)
for _, prefix := range []string{"0.0.0.0/0", "::/0"} {
resp := e.api.Post("/api/v2/device/"+e.deviceID+"/routes", map[string]any{"routes": []string{prefix}})
require.Equalf(t, http.StatusOK, resp.Code, "%s", resp.Body)
var dr apiv2.DeviceRoutes
require.NoError(t, json.Unmarshal(resp.Body.Bytes(), &dr))
assert.ElementsMatch(t, []string{"0.0.0.0/0", "::/0"}, dr.Enabled, prefix)
assert.ElementsMatch(t, []string{"0.0.0.0/0", "::/0"}, approvedRouteStrings(e.srvNode(t)), prefix)
}
}
// TestAPIv2KeyDescription documents two intentional differences from Tailscale.
//
// Tailscale: a key or OAuth client description over 50 characters is silently
// truncated to 50, on create and on every read (probe-T A11-A13, A21,
// A22). It also refuses many characters, among them . : + , / ' @ ( ) = #
// and any non-ASCII letter, with 400 "keys: description had invalid
// characters" (probe-W D rows).
//
// Headscale: over 50 characters is refused with 422, so a caller never
// stores a text other than the one it sent. Any character is accepted. No
// change was asked for; this test records both.
func TestAPIv2KeyDescription(t *testing.T) {
_, api := newKeyTestAPI(t)
resp := api.Post("/api/v2/tailnet/-/keys", apiv2.CreateKeyRequest{
Description: strings.Repeat("a", 51),
Capabilities: taggedCaps("tag:test"),
})
assert.Equal(t, http.StatusUnprocessableEntity, resp.Code)
for _, desc := range []string{"a.b", "a:b", "a@b", "ünï"} {
key := createKey(t, api, apiv2.CreateKeyRequest{Description: desc, Capabilities: taggedCaps("tag:test")})
assert.Equal(t, desc, key.Description)
}
}
+1 -1
View File
@@ -420,7 +420,7 @@ func TestPollNetMapHandler_LastControlAddress(t *testing.T) {
api := registerAPIV2(t, app)
attrs := getDevicePostureAttributes(t, api, view.StringID())
assert.Equal(t, wantUnchanged.String(), attrs.Attributes["ip:publicAddress"])
assert.Equal(t, map[string]any{"type": "IpAddr", "value": wantUnchanged.String()}, attrs.Attributes["ip:publicAddress"])
encodedAttrs, err := json.Marshal(attrs)
require.NoError(t, err)
assert.NotContains(t, string(encodedAttrs), "198.51.100.77",
+10 -10
View File
@@ -164,7 +164,7 @@ resource "tailscale_tailnet_key" "k" {
tags: []string{"tag:ci"},
config: authKeyConfig,
deny: true,
denyContains: []string{"403", "Forbidden", "missing the required scope"},
denyContains: []string{"calling actor does not"},
},
{
name: "devices:core denies tailnet_key",
@@ -172,7 +172,7 @@ resource "tailscale_tailnet_key" "k" {
tags: []string{"tag:ci"},
config: authKeyConfig,
deny: true,
denyContains: []string{"403", "Forbidden", "missing the required scope"},
denyContains: []string{"not found (404)"},
},
{
name: "all allows tailnet_key",
@@ -186,7 +186,7 @@ resource "tailscale_tailnet_key" "k" {
tags: []string{"tag:ci"},
config: authKeyConfig,
deny: true,
denyContains: []string{"403", "Forbidden", "missing the required scope"},
denyContains: []string{"calling actor does not"},
},
// oauth_keys: managing OAuth clients. Read and wrong scopes are denied, and
@@ -201,7 +201,7 @@ resource "tailscale_tailnet_key" "k" {
scopes: []string{"oauth_keys:read"},
config: oauthClientConfig,
deny: true,
denyContains: []string{"403", "Forbidden", "missing the required scope"},
denyContains: []string{"calling actor does not"},
},
{
name: "auth_keys denies oauth_client",
@@ -209,14 +209,14 @@ resource "tailscale_tailnet_key" "k" {
tags: []string{"tag:ci"},
config: oauthClientConfig,
deny: true,
denyContains: []string{"403", "Forbidden", "missing the required scope"},
denyContains: []string{"not found (404)"},
},
{
name: "oauth_keys cannot escalate client scope",
scopes: []string{"oauth_keys"},
config: oauthClientEscalateConfig,
deny: true,
denyContains: []string{"403", "Forbidden", "beyond the creating token"},
denyContains: []string{"actor cannot set scopes: [devices:core:read]"},
},
// policy_file: write scope sets the ACL; read does not.
@@ -230,7 +230,7 @@ resource "tailscale_tailnet_key" "k" {
scopes: []string{"policy_file:read"},
config: aclConfig,
deny: true,
denyContains: []string{"403", "Forbidden", "missing the required scope"},
denyContains: []string{"calling actor does not"},
},
// devices:core:read reads the devices data source.
@@ -244,7 +244,7 @@ resource "tailscale_tailnet_key" "k" {
scopes: []string{"policy_file:read"},
config: devicesReadConfig,
deny: true,
denyContains: []string{"403", "Forbidden", "missing the required scope"},
denyContains: []string{"not found (404)"},
},
// devices:core: a write-scoped token authorizes a device; the read scope
@@ -261,14 +261,14 @@ resource "tailscale_tailnet_key" "k" {
scopes: []string{"devices:core:read"},
config: deviceAuthorizeConfig,
deny: true,
denyContains: []string{"403", "Forbidden", "missing the required scope"},
denyContains: []string{"calling actor does not"},
},
{
name: "policy_file denies device authorize",
scopes: []string{"policy_file"},
config: deviceAuthorizeConfig,
deny: true,
denyContains: []string{"403", "Forbidden", "missing the required scope"},
denyContains: []string{"not found (404)"},
},
// Tag owned-by: a tag:k8s-operator client may use its own tag and the
+28
View File
@@ -61,6 +61,10 @@ var ErrUnsupportedPolicyMode = errors.New("unsupported policy mode")
// [State.ValidatePolicy] for a policy they refuse.
var ErrInvalidPolicy = errors.New("invalid policy")
// ErrPolicyPrecondition is returned by [State.UpdatePolicyIf] when the stored
// policy fails the caller's check.
var ErrPolicyPrecondition = errors.New("policy precondition failed")
// invalidPolicyError marks a refusal as [ErrInvalidPolicy] and keeps the
// reason's own text, which API answers show as is.
type invalidPolicyError struct{ reason error }
@@ -1898,6 +1902,14 @@ func (s *State) ValidatePolicy(pol []byte) error {
// it untouched. The changes are returned alongside a reload error, as from
// [State.ReloadPolicy].
func (s *State) UpdatePolicy(pol []byte) (*types.Policy, []change.Change, error) {
return s.UpdatePolicyIf(pol, nil)
}
// UpdatePolicyIf is [State.UpdatePolicy] that first passes the stored policy
// data ("" when none is set) to match, under the same lock as the write, so
// two writers cannot both pass a check against the same policy. A false match
// returns [ErrPolicyPrecondition]; a nil match always passes.
func (s *State) UpdatePolicyIf(pol []byte, match func(stored string) bool) (*types.Policy, []change.Change, error) {
err := s.ValidatePolicy(pol)
if err != nil {
return nil, nil, err
@@ -1908,6 +1920,22 @@ func (s *State) UpdatePolicy(pol []byte) (*types.Policy, []change.Change, error)
s.policyMu.Lock()
defer s.policyMu.Unlock()
if match != nil {
current, err := s.db.GetPolicy()
if err != nil && !errors.Is(err, types.ErrPolicyNotFound) {
return nil, nil, fmt.Errorf("loading policy: %w", err)
}
var data string
if current != nil {
data = current.Data
}
if !match(data) {
return nil, nil, ErrPolicyPrecondition
}
}
stored, err := s.db.SetPolicy(string(pol))
if err != nil {
return nil, nil, fmt.Errorf("storing policy: %w", err)