wif: add identity token auto generation for Azure (#21808)

Extends the ability to auto detect Azure as the provider the client is running on and tries fetch the JWT to use with Workload Identity.

Updates https://github.com/tailscale/corp/issues/34528

Signed-off-by: Danni Popova <[email protected]>
This commit is contained in:
Danni Popova authored and GitHub committed 2026-11-23 17:51:43 +00:00
1 parent 940e4c2c67
commit b1f550ec56
4 files changed
+941 -7

No files matched your search

@@ -43,7 +43,7 @@ func resolveAuthKey(ctx context.Context, args tailscale.ResolveAuthKeyWIFArgs) (
}
providerIdToken, err := wif.ObtainProviderToken(ctx, args.Audience)
if err != nil {
return "", errors.New("federated identity authkeys require --id-token")
return "", fmt.Errorf("could not obtain an ID token for audience %q from the environment: %w; pass --id-token explicitly", args.Audience, err)
}
args.IDToken = providerIdToken
}
+300
View File
@@ -0,0 +1,300 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package wif
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path"
"strings"
"time"
"tailscale.com/util/httpm"
)
// Azure support covers three ways a workload can obtain a Microsoft Entra
// token without a stored secret:
//
// - Azure VMs, scale sets, Batch pools and Linux container instances expose
// the Instance Metadata Service (IMDS) at 169.254.169.254. The managed
// identity attached to the resource mints a token for a given "resource"
// (the audience).
// - App Service, Functions, Container Apps and similar hosts have no IMDS and
// instead inject IDENTITY_ENDPOINT and IDENTITY_HEADER, pointing at a local
// token service that speaks a near-identical protocol.
// - AKS pods using Microsoft Entra Workload ID get a projected Kubernetes
// service account token (AZURE_FEDERATED_TOKEN_FILE) that must be exchanged
// at the Entra token endpoint as a client assertion.
//
// In all three cases the audience passed to ObtainProviderToken must be an
// identifier Entra knows about: the client ID of an app registration in the
// workload's tenant, or one of that app's Application ID URIs (api://...).
// The app registration's requestedAccessTokenVersion decides whether the
// token is v1.0 (iss https://sts.windows.net/<tenant>/) or v2.0
// (iss https://login.microsoftonline.com/<tenant>/v2.0).
//
// AZURE_CLIENT_ID selects a user-assigned managed identity for the IMDS and
// IDENTITY_ENDPOINT paths (the same convention the Azure SDKs use); without
// it the system-assigned identity is used.
const (
azureIMDSDefaultBase = "http://169.254.169.254"
azureIMDSTokenAPIVersion = "2018-02-01"
azureIMDSInstanceAPIVersion = "2021-02-01"
azureIdentityEndpointAPIVersion = "2019-08-01"
azureDefaultAuthorityHost = "https://login.microsoftonline.com/"
)
// azureIMDSBase is the IMDS base URL; a variable so tests can point it at a
// local server.
var azureIMDSBase = azureIMDSDefaultBase
// hasAKSWorkloadIdentity reports whether the Microsoft Entra Workload ID
// webhook has injected its environment into this process.
func hasAKSWorkloadIdentity() bool {
return os.Getenv("AZURE_FEDERATED_TOKEN_FILE") != "" &&
os.Getenv("AZURE_CLIENT_ID") != "" &&
os.Getenv("AZURE_TENANT_ID") != ""
}
// hasAzureIdentityEndpoint reports whether the App Service family managed
// identity endpoint is available.
func hasAzureIdentityEndpoint() bool {
return os.Getenv("IDENTITY_ENDPOINT") != "" && os.Getenv("IDENTITY_HEADER") != ""
}
// detectAzureEnv reports whether environment variables alone identify this as
// an Azure host. It must run before any 169.254.169.254 probe: on AKS the
// node's IMDS is reachable from pods and would silently yield the node's
// identity instead of the pod's.
func detectAzureEnv() bool {
return hasAKSWorkloadIdentity() || hasAzureIdentityEndpoint()
}
// azureLocalHTTPClient returns a client for talking to IMDS and the local
// identity endpoint. Azure documents that IMDS must not be reached through a
// proxy, so the transport ignores proxy environment variables.
func azureLocalHTTPClient() *http.Client {
return &http.Client{
Timeout: 5 * time.Second,
Transport: &http.Transport{Proxy: nil},
}
}
// detectAzureIMDS probes the Azure Instance Metadata Service. Azure requires
// the "Metadata: true" header and answers with a JSON document whose
// azEnvironment field names the cloud; AWS and GCP metadata servers share the
// IP but return 404 (or reject the request) for this path.
func detectAzureIMDS(ctx context.Context, client *http.Client) bool {
u := azureIMDSBase + "/metadata/instance/compute?api-version=" + azureIMDSInstanceAPIVersion + "&format=json"
req, err := http.NewRequestWithContext(ctx, httpm.GET, u, nil)
if err != nil {
return false
}
req.Header.Set("Metadata", "true")
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return false
}
var compute struct {
AzEnvironment string `json:"azEnvironment"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 64<<10)).Decode(&compute); err != nil {
return false
}
return strings.HasPrefix(strings.ToUpper(compute.AzEnvironment), "AZURE")
}
// acquireAzureIDToken obtains a Microsoft Entra token whose aud claim is
// audience, using whichever Azure identity mechanism the host provides.
func acquireAzureIDToken(ctx context.Context, audience string) (string, error) {
audience = strings.TrimSpace(audience)
if audience == "" {
return "", errors.New("azure identity tokens require an audience")
}
switch {
case hasAKSWorkloadIdentity():
return acquireAzureWorkloadIdentityToken(ctx, audience)
case hasAzureIdentityEndpoint():
return acquireAzureIdentityEndpointToken(ctx, audience)
default:
return acquireAzureIMDSToken(ctx, audience)
}
}
// acquireAzureIdentityEndpointToken obtains a managed identity token from the
// local token service that App Service, Functions, Container Apps and similar
// hosts expose through the IDENTITY_ENDPOINT and IDENTITY_HEADER environment
// variables.
func acquireAzureIdentityEndpointToken(ctx context.Context, audience string) (string, error) {
u, err := url.Parse(os.Getenv("IDENTITY_ENDPOINT"))
if err != nil {
return "", fmt.Errorf("parse IDENTITY_ENDPOINT: %w", err)
}
q := u.Query()
q.Set("api-version", azureIdentityEndpointAPIVersion)
q.Set("resource", audience)
if cid := os.Getenv("AZURE_CLIENT_ID"); cid != "" {
q.Set("client_id", cid)
}
u.RawQuery = q.Encode()
return azureManagedIdentityToken(ctx, u.String(), http.Header{
"X-IDENTITY-HEADER": {os.Getenv("IDENTITY_HEADER")},
})
}
// acquireAzureIMDSToken obtains a managed identity token from the Azure
// Instance Metadata Service, which is available on VMs, scale sets and other
// compute that runs directly on an Azure host.
func acquireAzureIMDSToken(ctx context.Context, audience string) (string, error) {
q := url.Values{}
q.Set("api-version", azureIMDSTokenAPIVersion)
q.Set("resource", audience)
if cid := os.Getenv("AZURE_CLIENT_ID"); cid != "" {
q.Set("client_id", cid)
}
u := azureIMDSBase + "/metadata/identity/oauth2/token?" + q.Encode()
return azureManagedIdentityToken(ctx, u, http.Header{
"Metadata": {"true"},
})
}
// azureManagedIdentityToken calls a managed identity token endpoint (IMDS or
// IDENTITY_ENDPOINT) and returns the access token from its JSON response.
func azureManagedIdentityToken(ctx context.Context, fullURL string, headers http.Header) (string, error) {
req, err := http.NewRequestWithContext(ctx, httpm.GET, fullURL, nil)
if err != nil {
return "", fmt.Errorf("build request: %w", err)
}
for k, vs := range headers {
for _, v := range vs {
req.Header.Add(k, v)
}
}
return azureAccessToken(azureLocalHTTPClient(), req, "azure managed identity endpoint")
}
// azureAccessToken sends req with client and returns the access_token field
// of the JSON response.
func azureAccessToken(client *http.Client, req *http.Request, what string) (string, error) {
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("call %s: %w", what, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
return "", fmt.Errorf("%s returned %s: %s", what, resp.Status, strings.TrimSpace(string(b)))
}
var tr struct {
AccessToken string `json:"access_token"`
}
if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&tr); err != nil {
return "", fmt.Errorf("decode %s response: %w", what, err)
}
if strings.TrimSpace(tr.AccessToken) == "" {
return "", fmt.Errorf("%s returned empty token", what)
}
return tr.AccessToken, nil
}
// acquireAzureWorkloadIdentityToken implements the Microsoft Entra Workload ID
// flow used on AKS: the projected Kubernetes service account token is sent to
// the Entra v2.0 token endpoint as a client assertion for the federated client
// (AZURE_CLIENT_ID), and Entra returns a token for the audience.
func acquireAzureWorkloadIdentityToken(ctx context.Context, audience string) (string, error) {
clientID, tenantID := os.Getenv("AZURE_CLIENT_ID"), os.Getenv("AZURE_TENANT_ID")
if clientID == "" || tenantID == "" {
return "", errors.New("azure client assertion exchange requires AZURE_CLIENT_ID and AZURE_TENANT_ID")
}
// Kubernetes rotates the projected token in place; read it every time.
b, err := os.ReadFile(os.Getenv("AZURE_FEDERATED_TOKEN_FILE"))
if err != nil {
return "", fmt.Errorf("read AZURE_FEDERATED_TOKEN_FILE: %w", err)
}
assertion := strings.TrimSpace(string(b))
if assertion == "" {
return "", errors.New("azure client assertion is empty")
}
tokenURL, err := azureTokenEndpoint(tenantID)
if err != nil {
return "", err
}
form := url.Values{}
form.Set("grant_type", "client_credentials")
form.Set("client_id", clientID)
form.Set("scope", azureScopeForAudience(audience))
form.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer")
form.Set("client_assertion", assertion)
req, err := http.NewRequestWithContext(ctx, httpm.POST, tokenURL, strings.NewReader(form.Encode()))
if err != nil {
return "", fmt.Errorf("build request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
return azureAccessToken(httpClient(), req, "azure token endpoint")
}
// azureTokenEndpoint returns the Entra v2.0 token endpoint for tenantID,
// honouring AZURE_AUTHORITY_HOST (set by the AKS workload identity webhook,
// and different in national clouds). The authority must be an absolute https
// URL; plain http is accepted only for loopback hosts so tests can stand in
// for Entra.
func azureTokenEndpoint(tenantID string) (string, error) {
authority := os.Getenv("AZURE_AUTHORITY_HOST")
if authority == "" {
authority = azureDefaultAuthorityHost
}
u, err := url.Parse(authority)
if err != nil {
return "", fmt.Errorf("parse AZURE_AUTHORITY_HOST %q: %w", authority, err)
}
if u.Host == "" {
return "", fmt.Errorf("AZURE_AUTHORITY_HOST %q is not an absolute URL", authority)
}
switch u.Scheme {
case "https":
case "http":
if host := u.Hostname(); host != "localhost" && !net.ParseIP(host).IsLoopback() {
return "", fmt.Errorf("AZURE_AUTHORITY_HOST %q must use https", authority)
}
default:
return "", fmt.Errorf("AZURE_AUTHORITY_HOST %q must use https", authority)
}
u.Path = path.Join(u.Path, tenantID, "oauth2/v2.0/token")
u.RawQuery, u.Fragment = "", ""
return u.String(), nil
}
// azureScopeForAudience converts an audience (app client ID or Application ID
// URI) into the "<resource>/.default" scope the Entra v2.0 endpoint expects.
func azureScopeForAudience(audience string) string {
audience = strings.TrimSpace(audience)
if strings.HasSuffix(audience, "/.default") {
return audience
}
return strings.TrimSuffix(audience, "/") + "/.default"
}
+622
View File
@@ -0,0 +1,622 @@
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package wif
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
const (
testTenantID = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
testAudience = "11111111-2222-3333-4444-555555555555"
)
// clearAzureEnv unsets every env var the Azure code paths consult so a test
// starts from a clean, non-Azure environment.
func clearAzureEnv(t *testing.T) {
t.Helper()
for _, k := range []string{
"AZURE_CLIENT_ID", "AZURE_TENANT_ID", "AZURE_AUTHORITY_HOST", "AZURE_FEDERATED_TOKEN_FILE",
"IDENTITY_ENDPOINT", "IDENTITY_HEADER",
"ACTIONS_ID_TOKEN_REQUEST_URL", "ACTIONS_ID_TOKEN_REQUEST_TOKEN",
"ECS_CONTAINER_METADATA_URI_V4",
} {
t.Setenv(k, "")
}
}
func setAzureIMDSBase(t *testing.T, base string) {
t.Helper()
old := azureIMDSBase
azureIMDSBase = base
t.Cleanup(func() { azureIMDSBase = old })
}
// managedIdentityServer is a fake IMDS / IDENTITY_ENDPOINT token service. It
// records the last request and replies with handler if non-nil, or a token.
func managedIdentityServer(t *testing.T, handler http.HandlerFunc) (srv *httptest.Server, last **http.Request) {
t.Helper()
last = new(*http.Request)
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*last = r
if r.Method != "GET" {
t.Errorf("method = %q, want GET", r.Method)
}
if handler != nil {
handler(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"access_token": "eyJ.mi.token", "expires_in": "86399", "token_type": "Bearer", "resource": r.URL.Query().Get("resource"),
})
}))
t.Cleanup(srv.Close)
return srv, last
}
// entraServer is a fake Entra v2.0 token endpoint. It records the last
// request's path and form and replies with handler if non-nil, or a token.
func entraServer(t *testing.T, handler http.HandlerFunc) (srv *httptest.Server, lastPath *string, lastForm *map[string]string) {
t.Helper()
lastPath = new(string)
lastForm = new(map[string]string)
srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*lastPath = r.URL.Path
if r.Method != "POST" {
t.Errorf("entra method = %q, want POST", r.Method)
}
if ct := r.Header.Get("Content-Type"); ct != "application/x-www-form-urlencoded" {
t.Errorf("entra Content-Type = %q", ct)
}
if err := r.ParseForm(); err != nil {
t.Errorf("ParseForm: %v", err)
}
m := map[string]string{}
for k := range r.PostForm {
m[k] = r.PostForm.Get(k)
}
*lastForm = m
if handler != nil {
handler(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"token_type":"Bearer","expires_in":3599,"access_token":"eyJ.entra.token"}`))
}))
t.Cleanup(srv.Close)
return srv, lastPath, lastForm
}
func TestDetectEnvironmentAzureEnvVars(t *testing.T) {
tests := []struct {
name string
env map[string]string
want Environment
}{
{
name: "identity-endpoint",
env: map[string]string{
"IDENTITY_ENDPOINT": "http://127.0.0.1:41000/msi/token",
"IDENTITY_HEADER": "secret",
},
want: EnvAzure,
},
{
name: "workload-identity",
env: map[string]string{
"AZURE_FEDERATED_TOKEN_FILE": "/var/run/secrets/azure/tokens/azure-identity-token",
"AZURE_CLIENT_ID": "client",
"AZURE_TENANT_ID": testTenantID,
},
want: EnvAzure,
},
{
name: "github-wins-over-azure",
env: map[string]string{
"ACTIONS_ID_TOKEN_REQUEST_URL": "https://example.invalid/token",
"ACTIONS_ID_TOKEN_REQUEST_TOKEN": "gh",
"IDENTITY_ENDPOINT": "http://127.0.0.1:41000/msi/token",
"IDENTITY_HEADER": "secret",
},
want: EnvGitHub,
},
{
name: "azure-env-wins-over-ecs",
env: map[string]string{
"ECS_CONTAINER_METADATA_URI_V4": "http://169.254.170.2/v4/x",
"IDENTITY_ENDPOINT": "http://127.0.0.1:41000/msi/token",
"IDENTITY_HEADER": "secret",
},
want: EnvAzure,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
clearAzureEnv(t)
for k, v := range tt.env {
t.Setenv(k, v)
}
if got := detectEnvironment(context.Background()); got != tt.want {
t.Errorf("detectEnvironment() = %q, want %q", got, tt.want)
}
})
}
t.Run("incomplete-signals", func(t *testing.T) {
clearAzureEnv(t)
t.Setenv("IDENTITY_ENDPOINT", "http://127.0.0.1:41000/msi/token")
if detectAzureEnv() {
t.Error("detectAzureEnv() = true with IDENTITY_ENDPOINT but no IDENTITY_HEADER")
}
t.Setenv("IDENTITY_ENDPOINT", "")
t.Setenv("AZURE_FEDERATED_TOKEN_FILE", "/tmp/token")
if detectAzureEnv() {
t.Error("detectAzureEnv() = true with token file but no client/tenant")
}
})
}
func TestDetectAzureIMDS(t *testing.T) {
tests := []struct {
name string
handler http.HandlerFunc
want bool
}{
{
name: "azure",
handler: func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/metadata/instance/compute" {
t.Errorf("path = %q", r.URL.Path)
}
if r.URL.Query().Get("api-version") != azureIMDSInstanceAPIVersion {
t.Errorf("api-version = %q", r.URL.Query().Get("api-version"))
}
if r.Header.Get("Metadata") != "true" {
t.Errorf("Metadata header = %q, want true", r.Header.Get("Metadata"))
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"azEnvironment":"AZUREPUBLICCLOUD","name":"vm"}`))
},
want: true,
},
{
name: "azure-mixed-case",
handler: func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"azEnvironment":"AzureUSGovernmentCloud"}`))
},
want: true,
},
{
name: "aws-imds-404",
handler: func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", "EC2ws")
w.WriteHeader(http.StatusNotFound)
},
want: false,
},
{
name: "non-azure-json",
handler: func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"azEnvironment":"SomethingElse"}`))
},
want: false,
},
{
name: "malformed",
handler: func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`not json`))
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
srv := httptest.NewServer(tt.handler)
defer srv.Close()
setAzureIMDSBase(t, srv.URL)
if got := detectAzureIMDS(context.Background(), azureLocalHTTPClient()); got != tt.want {
t.Errorf("detectAzureIMDS() = %v, want %v", got, tt.want)
}
})
}
t.Run("unreachable", func(t *testing.T) {
setAzureIMDSBase(t, "http://127.0.0.1:1")
if detectAzureIMDS(context.Background(), azureLocalHTTPClient()) {
t.Error("detectAzureIMDS() = true for closed port")
}
})
}
// TestAcquireAzureIDTokenIMDS covers the VM flow: the managed identity token
// from IMDS for the audience is itself the ID token.
func TestAcquireAzureIDTokenIMDS(t *testing.T) {
tests := []struct {
name string
audience string
env map[string]string
imds http.HandlerFunc // nil: well-behaved IMDS
wantResource string
wantClientID string // expected client_id query param, "" for absent
want string
wantErr string
}{
{
name: "system-assigned",
audience: testAudience,
wantResource: testAudience,
want: "eyJ.mi.token",
},
{
name: "app-id-uri-audience",
audience: " api://" + testAudience + " ",
wantResource: "api://" + testAudience,
want: "eyJ.mi.token",
},
{
name: "user-assigned",
audience: testAudience,
env: map[string]string{"AZURE_CLIENT_ID": "user-assigned-mi"},
wantResource: testAudience,
wantClientID: "user-assigned-mi",
want: "eyJ.mi.token",
},
{
name: "imds-no-identity",
audience: testAudience,
imds: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error":"invalid_request","error_description":"Identity not found"}`))
},
wantErr: "azure managed identity endpoint returned 400 Bad Request: {\"error\":\"invalid_request\"",
},
{
name: "imds-malformed",
audience: testAudience,
imds: func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{`))
},
wantErr: "decode azure managed identity endpoint response",
},
{
name: "imds-empty-token",
audience: testAudience,
imds: func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"access_token":" "}`))
},
wantErr: "empty token",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
clearAzureEnv(t)
for k, v := range tt.env {
t.Setenv(k, v)
}
imds, last := managedIdentityServer(t, tt.imds)
setAzureIMDSBase(t, imds.URL)
got, err := acquireAzureIDToken(context.Background(), tt.audience)
checkResult(t, got, err, tt.want, tt.wantErr)
r := *last
if r == nil {
t.Fatal("IMDS was not called")
}
wantResource := tt.wantResource
if wantResource == "" {
wantResource = strings.TrimSpace(tt.audience)
}
if r.URL.Path != "/metadata/identity/oauth2/token" {
t.Errorf("path = %q", r.URL.Path)
}
q := r.URL.Query()
if q.Get("api-version") != azureIMDSTokenAPIVersion {
t.Errorf("api-version = %q", q.Get("api-version"))
}
if got := q.Get("resource"); got != wantResource {
t.Errorf("resource = %q, want %q", got, wantResource)
}
if got := q.Get("client_id"); got != tt.wantClientID {
t.Errorf("client_id = %q, want %q", got, tt.wantClientID)
}
if r.Header.Get("Metadata") != "true" {
t.Errorf("Metadata header = %q, want true", r.Header.Get("Metadata"))
}
})
}
}
// TestAcquireAzureIDTokenIdentityEndpoint covers the App Service / Functions /
// Container Apps flow, where the token comes from IDENTITY_ENDPOINT.
func TestAcquireAzureIDTokenIdentityEndpoint(t *testing.T) {
clearAzureEnv(t)
msi, last := managedIdentityServer(t, nil)
t.Setenv("IDENTITY_ENDPOINT", msi.URL+"/msi/token")
t.Setenv("IDENTITY_HEADER", "header-secret")
t.Setenv("AZURE_CLIENT_ID", "user-assigned-mi")
// IMDS must not be consulted when the identity endpoint is present.
setAzureIMDSBase(t, "http://127.0.0.1:1")
got, err := acquireAzureIDToken(context.Background(), testAudience)
checkResult(t, got, err, "eyJ.mi.token", "")
r := *last
if r == nil {
t.Fatal("identity endpoint was not called")
}
if r.URL.Path != "/msi/token" {
t.Errorf("path = %q", r.URL.Path)
}
q := r.URL.Query()
if q.Get("api-version") != azureIdentityEndpointAPIVersion {
t.Errorf("api-version = %q", q.Get("api-version"))
}
if q.Get("resource") != testAudience {
t.Errorf("resource = %q", q.Get("resource"))
}
if q.Get("client_id") != "user-assigned-mi" {
t.Errorf("client_id = %q", q.Get("client_id"))
}
if r.Header.Get("X-IDENTITY-HEADER") != "header-secret" {
t.Errorf("X-IDENTITY-HEADER = %q", r.Header.Get("X-IDENTITY-HEADER"))
}
if r.Header.Get("Metadata") != "" {
t.Errorf("unexpected Metadata header %q", r.Header.Get("Metadata"))
}
}
// TestAcquireAzureIDTokenWorkloadIdentity covers the AKS flow: the projected
// service account token is exchanged at Entra as a client assertion.
func TestAcquireAzureIDTokenWorkloadIdentity(t *testing.T) {
tests := []struct {
name string
assertion string // file contents; "" means no file
authority string // AZURE_AUTHORITY_HOST override; "" uses the fake Entra server
entra http.HandlerFunc
wantScope string
want string
wantErr string
}{
{
name: "ok",
assertion: "eyJ.k8s.token\n",
wantScope: testAudience + "/.default",
want: "eyJ.entra.token",
},
{
name: "missing-token-file",
wantErr: "read AZURE_FEDERATED_TOKEN_FILE",
},
{
name: "empty-token-file",
assertion: " \n",
wantErr: "client assertion is empty",
},
{
name: "authority-not-https",
assertion: "eyJ.k8s.token",
authority: "http://login.microsoftonline.com/",
wantErr: "must use https",
},
{
name: "entra-no-federated-credential",
assertion: "eyJ.k8s.token",
entra: func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error":"invalid_client","error_description":"AADSTS700213: No matching federated identity record found"}`))
},
wantErr: `azure token endpoint returned 401 Unauthorized: {"error":"invalid_client"`,
},
{
name: "entra-malformed",
assertion: "eyJ.k8s.token",
entra: func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>`))
},
wantErr: "decode azure token endpoint response",
},
{
name: "entra-empty-token",
assertion: "eyJ.k8s.token",
entra: func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`{"access_token":" "}`))
},
wantErr: "azure token endpoint returned empty token",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
clearAzureEnv(t)
tokenFile := filepath.Join(t.TempDir(), "azure-identity-token")
if tt.assertion != "" {
if err := os.WriteFile(tokenFile, []byte(tt.assertion), 0o600); err != nil {
t.Fatal(err)
}
}
t.Setenv("AZURE_FEDERATED_TOKEN_FILE", tokenFile)
t.Setenv("AZURE_CLIENT_ID", "federated-client")
t.Setenv("AZURE_TENANT_ID", testTenantID)
// Neither local endpoint may be consulted on this path.
setAzureIMDSBase(t, "http://127.0.0.1:1")
entra, entraPath, entraForm := entraServer(t, tt.entra)
if tt.authority != "" {
t.Setenv("AZURE_AUTHORITY_HOST", tt.authority)
} else {
t.Setenv("AZURE_AUTHORITY_HOST", entra.URL+"/")
}
got, err := acquireAzureIDToken(context.Background(), testAudience)
checkResult(t, got, err, tt.want, tt.wantErr)
if tt.wantErr != "" {
return
}
if want := "/" + testTenantID + "/oauth2/v2.0/token"; *entraPath != want {
t.Errorf("entra path = %q, want %q", *entraPath, want)
}
for k, want := range map[string]string{
"grant_type": "client_credentials",
"client_id": "federated-client",
"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
"client_assertion": strings.TrimSpace(tt.assertion),
"scope": tt.wantScope,
} {
if got := (*entraForm)[k]; got != want {
t.Errorf("entra form[%q] = %q, want %q", k, got, want)
}
}
})
}
}
func TestAzureTokenEndpoint(t *testing.T) {
tests := []struct {
name string
authority string // "" leaves AZURE_AUTHORITY_HOST unset
want string
wantErr string
}{
{
name: "default",
want: "https://login.microsoftonline.com/" + testTenantID + "/oauth2/v2.0/token",
},
{
name: "no-trailing-slash",
authority: "https://login.microsoftonline.us",
want: "https://login.microsoftonline.us/" + testTenantID + "/oauth2/v2.0/token",
},
{
name: "trailing-slash",
authority: "https://login.microsoftonline.us/",
want: "https://login.microsoftonline.us/" + testTenantID + "/oauth2/v2.0/token",
},
{
name: "query-and-fragment-dropped",
authority: "https://login.example.com/?x=1#f",
want: "https://login.example.com/" + testTenantID + "/oauth2/v2.0/token",
},
{
name: "http-loopback-ip",
authority: "http://127.0.0.1:8080/",
want: "http://127.0.0.1:8080/" + testTenantID + "/oauth2/v2.0/token",
},
{
name: "http-localhost",
authority: "http://localhost:8080",
want: "http://localhost:8080/" + testTenantID + "/oauth2/v2.0/token",
},
{
name: "http-ipv6-loopback",
authority: "http://[::1]:8080",
want: "http://[::1]:8080/" + testTenantID + "/oauth2/v2.0/token",
},
{
name: "http-remote",
authority: "http://login.microsoftonline.com/",
wantErr: "must use https",
},
{
name: "no-scheme",
authority: "login.microsoftonline.com",
wantErr: "is not an absolute URL",
},
{
name: "other-scheme",
authority: "ftp://login.microsoftonline.com/",
wantErr: "must use https",
},
{
name: "unparseable",
authority: "https://login.microsoftonline.com:bad/",
wantErr: "parse AZURE_AUTHORITY_HOST",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Setenv("AZURE_AUTHORITY_HOST", tt.authority)
got, err := azureTokenEndpoint(testTenantID)
checkResult(t, got, err, tt.want, tt.wantErr)
})
}
}
func TestAzureScopeForAudience(t *testing.T) {
tests := []struct {
audience string
want string
}{
{testAudience, testAudience + "/.default"},
{"api://tailscale-wif", "api://tailscale-wif/.default"},
{"api://tailscale-wif/", "api://tailscale-wif/.default"},
{"api://tailscale-wif/.default", "api://tailscale-wif/.default"},
{" api://tailscale-wif ", "api://tailscale-wif/.default"},
}
for _, tt := range tests {
t.Run(strings.NewReplacer("/", "_", ":", "", " ", "").Replace(tt.audience), func(t *testing.T) {
if got := azureScopeForAudience(tt.audience); got != tt.want {
t.Errorf("azureScopeForAudience(%q) = %q, want %q", tt.audience, got, tt.want)
}
})
}
}
func TestAcquireAzureIDTokenRequiresAudience(t *testing.T) {
clearAzureEnv(t)
setAzureIMDSBase(t, "http://127.0.0.1:1")
_, err := acquireAzureIDToken(context.Background(), " ")
if err == nil || !strings.Contains(err.Error(), "require an audience") {
t.Errorf("err = %v, want audience error", err)
}
}
func TestAcquireAzureIDTokenTimeout(t *testing.T) {
release := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-release:
case <-r.Context().Done():
}
}))
defer srv.Close()
defer close(release)
clearAzureEnv(t)
setAzureIMDSBase(t, srv.URL)
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
_, err := acquireAzureIDToken(ctx, testAudience)
if err == nil || !strings.Contains(err.Error(), "call azure managed identity endpoint") {
t.Errorf("err = %v, want request error", err)
}
}
func checkResult(t *testing.T, got string, err error, want, wantErr string) {
t.Helper()
if wantErr != "" {
if err == nil {
t.Fatalf("error = nil, want %q", wantErr)
}
if !strings.Contains(err.Error(), wantErr) {
t.Fatalf("error = %q, want containing %q", err.Error(), wantErr)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != want {
t.Errorf("token = %q, want %q", got, want)
}
}
+18 -6
View File
@@ -31,6 +31,7 @@ const (
EnvGitHub Environment = "github"
EnvAWS Environment = "aws"
EnvGCP Environment = "gcp"
EnvAzure Environment = "azure"
EnvNone Environment = "none"
)
@@ -38,10 +39,13 @@ const (
// and then tries to obtain an ID token for the audience that is passed as an argument
// To detect the environment, we do it in the following intentional order:
// 1. GitHub Actions (strongest env signals; may run atop any cloud)
// 2. AWS via IMDSv2 token endpoint (does not require env vars)
// 3. GCP via metadata header semantics
// 4. AWS ECS via ECS token endpoint and env vars provided by ECS
// 5. Azure via metadata endpoint
// 2. Azure hosts that announce themselves via env vars (AKS workload identity,
// App Service / Container Apps identity endpoint); these must precede the
// metadata probes because AKS pods can reach the node's IMDS
// 3. AWS via IMDSv2 token endpoint (does not require env vars)
// 4. GCP via metadata header semantics
// 5. Azure via IMDS (VMs, scale sets, container instances)
// 6. AWS ECS via ECS token endpoint and env vars provided by ECS
func ObtainProviderToken(ctx context.Context, audience string) (string, error) {
env := detectEnvironment(ctx)
@@ -52,8 +56,10 @@ func ObtainProviderToken(ctx context.Context, audience string) (string, error) {
return acquireAWSWebIdentityToken(ctx, audience)
case EnvGCP:
return acquireGCPMetadataIDToken(ctx, audience)
case EnvAzure:
return acquireAzureIDToken(ctx, audience)
default:
return "", errors.New("could not detect environment; provide --id-token explicitly")
return "", errors.New("could not detect environment")
}
}
@@ -62,6 +68,9 @@ func detectEnvironment(ctx context.Context) Environment {
os.Getenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN") != "" {
return EnvGitHub
}
if detectAzureEnv() {
return EnvAzure
}
client := httpClient()
if detectAWSIMDSv2(ctx, client) {
@@ -70,6 +79,9 @@ func detectEnvironment(ctx context.Context) Environment {
if detectGCPMetadata(ctx, client) {
return EnvGCP
}
if detectAzureIMDS(ctx, azureLocalHTTPClient()) {
return EnvAzure
}
if os.Getenv("ECS_CONTAINER_METADATA_URI_V4") != "" {
return EnvAWS
}
@@ -78,7 +90,7 @@ func detectEnvironment(ctx context.Context) Environment {
func httpClient() *http.Client {
return &http.Client{
Timeout: time.Second * 5,
Timeout: time.Second * 2,
}
}