[Feature] Workload identity federation support
Use case
Without WIF, even using pre-signed auth keys leaves long-lived persistent state that can be exfiltrated. Even though WIF is typically considered an "enterprise" feature, it's becoming the go to measure against credential theft even for homelab deployments.
Description
Implement a simplified OIDC workload identity federation support. We don't actually need to implement RFC 8693. Just OIDC issuer trust establishment and verification.
Contribution
- I can write the design doc for this feature
- I can contribute this feature
How can it be implemented?
Here's a design for WIF support, grounded in the existing code structure.
What WIF Means Here
A workload (Kubernetes pod, GitHub Actions runner, GCP VM, etc.) already holds a short-lived JWT from its platform's identity provider. Instead of a pre-auth key, it passes that JWT as the --authkey argument to tailscale up. Headscale verifies the JWT against a configured trusted issuer and registers the node non-interactively — no browser, no pre-auth key management.
Existing Machinery That Transfers Directly
| Existing component | Where | Reuse |
|---|---|---|
oidc.NewProvider() + Verifier() |
hscontrol/oidc.go:74 |
Token verification against any OIDC-compliant issuer's JWKS |
OIDCClaims + Identifier() |
hscontrol/types/users.go:265-325 |
Stable iss/sub identity, already URL-aware |
createOrUpdateUserFromClaim() |
hscontrol/oidc.go:559 |
User create/update from claims |
GetUserByOIDCIdentifier() |
hscontrol/db/users.go:145 |
User lookup by iss+sub |
User.ProviderIdentifier |
hscontrol/types/users.go:88 |
Already stores iss/sub |
HandleNodeFromAuthPath() |
hscontrol/state/state.go:1717 |
Node registration from auth path |
doOIDCAuthorization() |
hscontrol/oidc.go:514 |
Allowed groups/domains/users filtering |
handleRegisterWithAuthKey() dispatch |
hscontrol/auth.go:338 |
Model for synchronous registration |
The AuthProvider interface 1 is the clean abstraction boundary. The existing isAuthKey() check 2 is where WIF token detection slots in.
Design
New Config (hscontrol/types/config.go)
type WIFIssuerConfig struct {
Issuer string // e.g. "https://token.actions.githubusercontent.com"
Audience string // expected aud claim
AllowedSubjects []string // empty = allow all subjects from this issuer
UserClaim string // claim to use as username, default "sub"
Tags []string // auto-assign ACL tags (makes node tagged)
Ephemeral bool // register as ephemeral node
}
type WIFConfig struct {
Issuers []WIFIssuerConfig
}Add WIF WIFConfig to the top-level Config struct. 3
New Provider (hscontrol/wif.go)
type AuthProviderWIF struct {
h *Headscale
cfg *types.WIFConfig
providers map[string]*oidc.Provider // keyed by issuer URL
}Key functions:
isWIFToken(key string) bool— detect a JWT by checking for two.separators and valid base64 segments. Pre-auth keys are prefixedhskey-auth-4 so there's no ambiguity.handleRegisterWithWIFToken(req, machineKey)— the main handler:- Decode the JWT header/payload (no verification yet) to extract
iss - Find the matching
WIFIssuerConfigby issuer URL - Verify the full token using
providers[iss].Verifier(&oidc.Config{ClientID: cfg.Audience}) - Validate
audmatches configured audience - Validate
subagainstAllowedSubjectsif non-empty - Build
OIDCClaimsfrom the verified token 5 - Call
createOrUpdateUserFromClaim()— reused verbatim 6 - If
Tagsconfigured: create a tagged-node registration (like a tagged pre-auth key) - Call
HandleNodeFromAuthPath()or a newHandleNodeFromWIF()that mirrorsHandleNodeFromPreAuthKey7 - Return
RegisterResponse{MachineAuthorized: true}synchronously
- Decode the JWT header/payload (no verification yet) to extract
Dispatch in handleRegister (hscontrol/auth.go8 )
// After the isAuthKey() check, before handleRegisterInteractive():
if h.wifProvider != nil && h.wifProvider.isWIFToken(req.Auth.AuthKey) {
return h.handleRegisterWithWIFToken(req, machineKey)
}Proto + RegisterMethod
Add REGISTER_METHOD_WIF = 4 to proto/headscale/v1/node.proto 9 and RegisterMethodWIF = "wif" to hscontrol/util/const.go.
Router
No new HTTP routes needed. WIF is entirely within the existing Noise RegistrationHandler path. 10
Flow Diagram
sequenceDiagram
participant W as "Workload (tailscaled)"
participant H as "Headscale (Noise)"
participant IdP as "External IdP (e.g. GitHub)"
W->>IdP: "Get OIDC token (platform-native)"
IdP-->>W: "JWT (iss=github, sub=repo:org/repo:...)"
W->>H: "RegisterRequest{Auth.AuthKey = JWT}"
H->>H: "isWIFToken() → true"
H->>H: "Decode JWT header → extract iss"
H->>H: "Find WIFIssuerConfig for iss"
H->>IdP: "Fetch JWKS (cached by go-oidc)"
IdP-->>H: "JWKS"
H->>H: "Verify JWT signature + aud + sub"
H->>H: "createOrUpdateUserFromClaim()"
H->>H: "HandleNodeFromAuthPath()"
H-->>W: "RegisterResponse{MachineAuthorized: true}"Work Estimate
| Area | Complexity | Notes |
|---|---|---|
| Config types + loading + validation | Small | ~50 lines, mirrors OIDCConfig |
JWT detection (isWIFToken) |
Trivial | String parsing |
AuthProviderWIF + issuer pool init |
Small | Mostly oidc.NewProvider() calls at startup |
handleRegisterWithWIFToken |
Medium | Token verify + claim extraction; user/node logic is reused |
| Tagged-node support via WIF | Medium | Needs a HandleNodeFromWIF variant that accepts tags, similar to HandleNodeFromPreAuthKey 7 |
Dispatch wiring in handleRegister |
Trivial | 5 lines |
| Proto + codegen | Small | One enum value, regenerate |
| Tests | Medium | Unit tests for JWT detection, issuer matching, claim mapping; integration test for full flow |
| Docs | Small | Config reference + example for GitHub Actions, Kubernetes |
The bulk of the logic (token verification, user management, node registration) is already implemented and tested in the OIDC path. The new code is primarily the non-interactive dispatch and multi-issuer config — the parts the existing OIDC flow doesn't need because it uses OAuth2 redirects. The tagged-node path is the trickiest piece since it needs to bypass user creation and go straight to tagged-device ownership, mirroring what tagged pre-auth keys do. 11
Citations
File: hscontrol/auth.go (L21-26)
type AuthProvider interface {
RegisterHandler(w http.ResponseWriter, r *http.Request)
AuthHandler(w http.ResponseWriter, r *http.Request)
RegisterURL(authID types.AuthID) string
AuthURL(authID types.AuthID) string
}File: hscontrol/auth.go (L110-133)
// Pre authenticated keys are handled slightly different than interactive
// logins as they can be done fully sync and we can respond to the node with
// the result as it is waiting.
if isAuthKey(req) {
resp, err := h.handleRegisterWithAuthKey(req, machineKey)
if err != nil {
// Preserve HTTPError types so they can be handled properly by the HTTP layer
if httpErr, ok := errors.AsType[HTTPError](err); ok {
return nil, httpErr
}
return nil, fmt.Errorf("handling register with auth key: %w", err)
}
return resp, nil
}
resp, err := h.handleRegisterInteractive(req, machineKey)
if err != nil {
return nil, fmt.Errorf("handling register interactive: %w", err)
}
return resp, nil
}File: hscontrol/auth.go (L231-233)
func isAuthKey(req tailcfg.RegisterRequest) bool {
return req.Auth != nil && req.Auth.AuthKey != ""
}File: hscontrol/types/config.go (L59-106)
type Config struct {
ServerURL string
Addr string
MetricsAddr string
GRPCAddr string
GRPCAllowInsecure bool
EphemeralNodeInactivityTimeout time.Duration
PrefixV4 *netip.Prefix
PrefixV6 *netip.Prefix
IPAllocation IPAllocationStrategy
NoisePrivateKeyPath string
BaseDomain string
Log LogConfig
DisableUpdateCheck bool
Database DatabaseConfig
DERP DERPConfig
TLS TLSConfig
ACMEURL string
ACMEEmail string
// DNSConfig is the headscale representation of the DNS configuration.
// It is kept in the config update for some settings that are
// not directly converted into a tailcfg.DNSConfig.
DNSConfig DNSConfig
// TailcfgDNSConfig is the tailcfg representation of the DNS configuration,
// it can be used directly when sending Netmaps to clients.
TailcfgDNSConfig *tailcfg.DNSConfig
UnixSocket string
UnixSocketPermission fs.FileMode
OIDC OIDCConfig
LogTail LogTailConfig
RandomizeClientPort bool
Taildrop TaildropConfig
CLI CLIConfig
Policy PolicyConfig
Tuning Tuning
}File: hscontrol/db/preauth_keys.go (L37-41)
const (
authKeyPrefix = "hskey-auth-"
authKeyPrefixLength = 12
authKeyLength = 64
)File: hscontrol/types/users.go (L265-277)
type OIDCClaims struct {
// Sub is the user's unique identifier at the provider.
Sub string `json:"sub"`
Iss string `json:"iss"`
// Name is the user's full name.
Name string `json:"name,omitempty"`
Groups []string `json:"groups,omitempty"`
Email string `json:"email,omitempty"`
EmailVerified FlexibleBoolean `json:"email_verified,omitempty"`
ProfilePictureURL string `json:"picture,omitempty"`
Username string `json:"preferred_username,omitempty"`
}File: hscontrol/oidc.go (L559-600)
func (a *AuthProviderOIDC) createOrUpdateUserFromClaim(
claims *types.OIDCClaims,
) (*types.User, change.Change, error) {
var (
user *types.User
err error
newUser bool
c change.Change
)
user, err = a.h.state.GetUserByOIDCIdentifier(claims.Identifier())
if err != nil && !errors.Is(err, db.ErrUserNotFound) {
return nil, change.Change{}, fmt.Errorf("creating or updating user: %w", err)
}
// if the user is still not found, create a new empty user.
// TODO(kradalby): This context is not inherited from the request, which is probably not ideal.
// However, we need a context to use the OIDC provider.
if user == nil {
newUser = true
user = &types.User{}
}
user.FromClaim(claims, a.cfg.EmailVerifiedRequired)
if newUser {
user, c, err = a.h.state.CreateUser(*user)
if err != nil {
return nil, change.Change{}, fmt.Errorf("creating user: %w", err)
}
} else {
_, c, err = a.h.state.UpdateUser(types.UserID(user.ID), func(u *types.User) error {
*u = *user
return nil
})
if err != nil {
return nil, change.Change{}, fmt.Errorf("updating user: %w", err)
}
}
return user, c, nil
}File: hscontrol/state/state.go (L1913-1944)
func (s *State) HandleNodeFromPreAuthKey(
regReq tailcfg.RegisterRequest,
machineKey key.MachinePublic,
) (types.NodeView, change.Change, error) {
pak, err := s.GetPreAuthKey(regReq.Auth.AuthKey)
if err != nil {
return types.NodeView{}, change.Change{}, err
}
// Helper to get username for logging (handles nil User for tags-only keys)
pakUsername := func() string {
if pak.User != nil {
return pak.User.Username()
}
return types.TaggedDevices.Name
}
existingNodeSameUser, existsSameUser := s.findExistingNodeForPAK(machineKey, pak)
// For existing nodes, skip validation if:
// 1. MachineKey matches (cryptographic proof of machine identity)
// 2. User/tag ownership matches (from the PAK being used)
// 3. Not a NodeKey rotation (rotation requires fresh validation)
//
// Security: MachineKey is the cryptographic identity. If someone has the MachineKey,
// they control the machine. The PAK was only needed to authorize initial join.
// We don't check which specific PAK was used originally because:
// - Container restarts may use different PAKs (e.g., env var changed)
// - Original PAK may be deleted
// - MachineKey + ownership is sufficient to prove this is the same node
isExistingNodeReregistering := existsSameUser && existingNodeSameUser.Valid()File: proto/headscale/v1/node.proto (L10-15)
enum RegisterMethod {
REGISTER_METHOD_UNSPECIFIED = 0;
REGISTER_METHOD_AUTH_KEY = 1;
REGISTER_METHOD_CLI = 2;
REGISTER_METHOD_OIDC = 3;
}File: hscontrol/noise.go (L589-646)
// RegistrationHandler handles the actual registration process of a node.
func (ns *noiseServer) RegistrationHandler(
writer http.ResponseWriter,
req *http.Request,
) {
if req.Method != http.MethodPost {
httpError(writer, errMethodNotAllowed)
return
}
registerRequest, registerResponse := func() (*tailcfg.RegisterRequest, *tailcfg.RegisterResponse) { //nolint:contextcheck
var resp *tailcfg.RegisterResponse
var regReq tailcfg.RegisterRequest
err := json.NewDecoder(req.Body).Decode(®Req)
if err != nil {
return ®Req, regErr(err)
}
ns.nodeKey = regReq.NodeKey
resp, err = ns.headscale.handleRegister(req.Context(), regReq, ns.conn.Peer())
if err != nil {
if httpErr, ok := errors.AsType[HTTPError](err); ok {
resp = &tailcfg.RegisterResponse{
Error: httpErr.Msg,
}
return ®Req, resp
}
return ®Req, regErr(err)
}
return ®Req, resp
}()
// Reject unsupported versions
if rejectUnsupported(writer, registerRequest.Version, ns.machineKey, registerRequest.NodeKey) {
return
}
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
writer.WriteHeader(http.StatusOK)
err := json.NewEncoder(writer).Encode(registerResponse)
if err != nil {
log.Error().Caller().Err(err).Msg("noise registration handler: failed to encode RegisterResponse")
return
}
// Ensure response is flushed to client
if flusher, ok := writer.(http.Flusher); ok {
flusher.Flush()
}
}File: hscontrol/types/preauth_key.go (L38-44)
// Tags to assign to nodes registered with this key.
// Tags are copied to the node during registration.
// If non-empty, this creates tagged nodes (not user-owned).
Tags []string `gorm:"serializer:json"`
CreatedAt *time.Time
Expiration *time.TimeSource: juanfont/headscale