github.com/Azure/aad-pod-identity@v1.8.17/cmd/demo/main.go (about)

     1  package main
     2  
     3  import (
     4  	"context"
     5  	"flag"
     6  	"io"
     7  	"net/http"
     8  	"time"
     9  
    10  	"github.com/Azure/go-autorest/autorest/adal"
    11  	"k8s.io/klog/v2"
    12  )
    13  
    14  const (
    15  	timeout = 80 * time.Second
    16  )
    17  
    18  var (
    19  	period           time.Duration
    20  	resourceName     string
    21  	subscriptionID   string
    22  	resourceGroup    string
    23  	identityClientID string
    24  )
    25  
    26  func main() {
    27  	flag.DurationVar(&period, "period", 100*time.Second, "The period that the demo is being executed")
    28  	flag.StringVar(&resourceName, "resource-name", "https://management.azure.com/", "The resource name to grant the access token")
    29  	flag.StringVar(&subscriptionID, "subscription-id", "", "The Azure subscription ID")
    30  	flag.StringVar(&resourceGroup, "resource-group", "", "The resource group name which the user-assigned identity read access to")
    31  	flag.StringVar(&identityClientID, "identity-client-id", "", "The user-assigned identity client ID")
    32  	flag.Parse()
    33  
    34  	ticker := time.NewTicker(period)
    35  	defer ticker.Stop()
    36  
    37  	for ; true; <-ticker.C {
    38  		curlIMDSMetadataInstanceEndpoint()
    39  		t1 := getTokenFromIMDSWithUserAssignedID()
    40  		if t1 == nil {
    41  			klog.Error("Failed to acquire token from IMDS with identity client ID")
    42  		} else {
    43  			klog.Infof("Try decoding your token %s at https://jwt.io", t1.AccessToken)
    44  		}
    45  	}
    46  }
    47  
    48  func getTokenFromIMDSWithUserAssignedID() *adal.Token {
    49  	managedIdentityOpts := &adal.ManagedIdentityOptions{ClientID: identityClientID}
    50  	spt, err := adal.NewServicePrincipalTokenFromManagedIdentity(resourceName, managedIdentityOpts)
    51  	if err != nil {
    52  		klog.Errorf("failed to acquire a token from IMDS using user-assigned identity, error: %+v", err)
    53  		return nil
    54  	}
    55  
    56  	ctx, cancel := context.WithTimeout(context.Background(), timeout)
    57  	defer cancel()
    58  
    59  	if err := spt.RefreshWithContext(ctx); err != nil {
    60  		klog.Errorf("failed to refresh the service principal token, error: %+v", err)
    61  		return nil
    62  	}
    63  
    64  	token := spt.Token()
    65  	if token.IsZero() {
    66  		klog.Errorf("%+v is a zero token", token)
    67  		return nil
    68  	}
    69  
    70  	klog.Infof("successfully acquired a service principal token from IMDS using a user-assigned identity (%s)", identityClientID)
    71  	return &token
    72  }
    73  
    74  func curlIMDSMetadataInstanceEndpoint() {
    75  	client := &http.Client{
    76  		Timeout: timeout,
    77  	}
    78  	req, err := http.NewRequest("GET", "http://169.254.169.254/metadata/instance?api-version=2017-08-01", nil)
    79  	if err != nil {
    80  		klog.Errorf("failed to create a new HTTP request, error: %+v", err)
    81  		return
    82  	}
    83  	req.Header.Add("Metadata", "true")
    84  
    85  	resp, err := client.Do(req)
    86  	if err != nil {
    87  		klog.Error(err)
    88  		return
    89  	}
    90  	defer resp.Body.Close()
    91  
    92  	body, err := io.ReadAll(resp.Body)
    93  	if err != nil {
    94  		klog.Errorf("failed to read response body, error: %+v", err)
    95  		return
    96  	}
    97  
    98  	klog.Infof(`curl -H Metadata:true "http://169.254.169.254/metadata/instance?api-version=2017-08-01": %s`, body)
    99  }