func()

in pkg/auth/auth.go [215:261]


func (c *podIdentityCredential) GetToken(ctx context.Context, _ policy.TokenRequestOptions) (azcore.AccessToken, error) {
	// For usePodIdentity mode, the CSI driver makes an authorization request to fetch token for a resource from the NMI host endpoint (http://127.0.0.1:2579/host/token/).
	// The request includes the pod namespace `podns` and the pod name `podname` in the request header and the resource endpoint of the resource requesting the token.
	// The NMI server identifies the pod based on the `podns` and `podname` in the request header and then queries k8s (through MIC) for a matching azure identity.
	// Then nmi makes an adal request to get a token for the resource in the request, returns the `token` and the `clientid` as a response to the CSI request.
	klog.V(5).InfoS("using pod identity to retrieve token", "pod", klog.ObjectRef{Namespace: c.podNamespace, Name: c.podName})

	endpoint := fmt.Sprintf("http://localhost:%s/host/token/?resource=%s", c.nmiPort, c.resource)
	client := &http.Client{}
	req, err := http.NewRequest(http.MethodGet, endpoint, nil)
	if err != nil {
		return azcore.AccessToken{}, err
	}
	req.Header.Add(podNamespaceHeader, c.podNamespace)
	req.Header.Add(podNameHeader, c.podName)
	req = req.WithContext(ctx)

	resp, err := client.Do(req)
	if err != nil {
		return azcore.AccessToken{}, err
	}
	defer resp.Body.Close()
	bodyBytes, err := io.ReadAll(resp.Body)
	if err != nil {
		return azcore.AccessToken{}, err
	}

	if resp.StatusCode != http.StatusOK {
		return azcore.AccessToken{}, fmt.Errorf("nmi response failed with status code: %d, response body: %+v", resp.StatusCode, string(bodyBytes))
	}

	podIdentityResponse := &PodIdentityResponse{}
	if err = json.Unmarshal(bodyBytes, &podIdentityResponse); err != nil {
		return azcore.AccessToken{}, err
	}
	klog.V(5).InfoS("successfully acquired access token", "accessToken", utils.RedactSecureString(podIdentityResponse.Token.AccessToken), "clientID", utils.RedactSecureString(podIdentityResponse.ClientID), "pod", klog.ObjectRef{Namespace: c.podNamespace, Name: c.podName})

	token, clientID := podIdentityResponse.Token, podIdentityResponse.ClientID
	if token.AccessToken == "" || clientID == "" {
		return azcore.AccessToken{}, fmt.Errorf("nmi did not return expected values in response: token and clientid")
	}

	return azcore.AccessToken{
		Token:     token.AccessToken,
		ExpiresOn: podIdentityResponse.Token.Expires(),
	}, nil
}