func GetTenantID()

in pkg/cloud/azureclient.go [190:229]


func GetTenantID(subscriptionID string, client *http.Client) (string, error) {
	const hdrKey = "WWW-Authenticate"
	clientOpts := &armpolicy.ClientOptions{
		ClientOptions: azcore.ClientOptions{
			Transport: client,
		},
	}
	subscriptionsClient, err := armsubscriptions.NewClient(&dummyCredential{}, clientOpts)
	if err != nil {
		return "", errors.Wrap(err, "failed to create subscriptions client")
	}

	mlog.Debug("Resolving tenantID", "subscriptionID", subscriptionID)

	// we expect this request to fail (err != nil), but we are only interested
	// in headers, so surface the error if the Response is not present (i.e.
	// network error etc)
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute*150)
	defer cancel()

	_, err = subscriptionsClient.Get(ctx, subscriptionID, &armsubscriptions.ClientGetOptions{})
	var respErr *azcore.ResponseError
	if !errors.As(err, &respErr) {
		return "", errors.Errorf("unexpected response from get subscription: %v", err)
	}

	hdr := respErr.RawResponse.Header.Get(hdrKey)
	if hdr == "" {
		return "", errors.Errorf("header %q not found in get subscription response", hdrKey)
	}

	// Example value for hdr:
	//   Bearer authorization_uri="https://login.windows.net/996fe9d1-6171-40aa-945b-4c64b63bf655", error="invalid_token", error_description="The authentication failed because of missing 'Authorization' header."
	r := regexp.MustCompile(`authorization_uri=".*/([0-9a-f\-]+)"`)
	m := r.FindStringSubmatch(hdr)
	if m == nil {
		return "", errors.Errorf("Could not find the tenant ID in header: %s %q", hdrKey, hdr)
	}
	return m[1], nil
}