diff --git a/apps/managedidentity/managedidentity.go b/apps/managedidentity/managedidentity.go index 8334a704..11743fd0 100644 --- a/apps/managedidentity/managedidentity.go +++ b/apps/managedidentity/managedidentity.go @@ -55,8 +55,6 @@ const ( systemAssignedManagedIdentity = "system_assigned_managed_identity" // Azure Arc - // SonarQube: Suppress warning for hardcoded IP address - // sonar-ignore: S1313 azureArcEndpoint = "http://127.0.0.1:40342/metadata/identity/oauth2/token" azureArcAPIVersion = "2020-06-01" azureArcFileExtension = ".key" @@ -211,7 +209,7 @@ func New(id ID, options ...ClientOption) (Client, error) { return client, nil } -// getSource detects and returns the managed identity source available on the environment. +// GetSource detects and returns the managed identity source available on the environment. func getSource() (Source, error) { identityEndpoint := os.Getenv(identityEndpointEnvVar) identityHeader := os.Getenv(identityHeaderEnvVar) @@ -315,10 +313,6 @@ func acquireTokenForAzureArc(ctx context.Context, client Client, resource string return authResultFromToken(client.authParams, tokenResponse) } -// func handleAzureArcExpectedError(ctx context.Context, client Client, resource string, fakeAuthParams authority.AuthParams, err error) (base.AuthResult, error) { - -// } - func createFakeAuthParams(client Client) (authority.AuthParams, error) { fakeAuthInfo, err := authority.NewInfoFromAuthorityURI("https://login.microsoftonline.com/managed_identity", false, true) if err != nil { @@ -428,48 +422,6 @@ func createAzureArcAuthRequest(ctx context.Context, resource string, key string) return nil, fmt.Errorf("couldn't parse %q: %s", identityEndpoint, parseErr) } - // Check if the imds endpoint is set to the default for file detection - if imdsEndpoint == himdsExecutableHelperString { - println(fmt.Sprintf("[Managed Identity] AzureArc managed identity is available through file detection. Defaulting to known AzureArc endpoint: %s. Creating AzureArc managed identity.", azureArcEndpoint)) - } else { - // Both the identity and imds endpoints are defined without file detection; validate them - validatedIdentityEndpoint, identityErr := getValidatedEnvVariableUrlString(IdentityEndpointEnvVar, identityEndpoint, string(AzureArc)) - if identityErr != nil { - return nil, identityErr - } - - validatedIdentityEndpoint = strings.TrimSuffix(validatedIdentityEndpoint, "/") - - _, imdsErr := getValidatedEnvVariableUrlString(ArcIMDSEnvVar, imdsEndpoint, string(AzureArc)) - if imdsErr != nil { - return nil, imdsErr - } - - println(fmt.Sprintf("[Managed Identity] Environment variables validation passed for AzureArc managed identity. Endpoint URI: %s. Creating AzureArc managed identity.", validatedIdentityEndpoint)) - } - - if _, ok := id.(systemAssignedValue); !ok { - return nil, errors.New("unable to create AzureArc") - } - - msiEndpoint, parseErr := url.Parse(identityEndpoint) - - if parseErr != nil { - return nil, fmt.Errorf("couldn't parse %q: %s", identityEndpoint, parseErr) - } - // envEndpoint, ok := os.LookupEnv(IdentityEndpointEnvVar) - // if !ok { - // msiEndpoint, err = url.Parse(azureArcEndpoint) - // if err != nil { - // return nil, fmt.Errorf("couldn't parse %q: %s", envEndpoint, err) - // } - // } else { - // msiEndpoint, err = url.Parse(envEndpoint) - // if err != nil { - // return nil, fmt.Errorf("couldn't parse %q: %s", envEndpoint, err) - // } - // } - msiParameters := msiEndpoint.Query() msiParameters.Set(apiVersionQueryParameterName, azureArcAPIVersion) resource = strings.TrimSuffix(resource, "/.default") @@ -489,22 +441,6 @@ func createAzureArcAuthRequest(ctx context.Context, resource string, key string) return req, nil } -func validateAzureArcEnvironment(identityEndpoint, imdsEndpoint string, platform string) bool { - if identityEndpoint != "" && imdsEndpoint != "" { - return true - } - - himdsFilePath := getAzureArcFilePath(platform) - - if himdsFilePath != "" { - if _, err := os.Stat(himdsFilePath); !os.IsNotExist(err) { - return true - } - } - - return false -} - func isAzureArcEnvironment(identityEndpoint, imdsEndpoint string, platform string) bool { if identityEndpoint != "" && imdsEndpoint != "" { return true @@ -570,45 +506,3 @@ func (c *Client) getAzureArcSecretKey(response *http.Response, platform string) return string(secret), nil } - -func handleSecretFile(wwwAuthenticateHeader, expectedSecretFilePath string) ([]byte, error) { - // split the header to get the secret file path - parts := strings.Split(wwwAuthenticateHeader, "Basic realm=") - if len(parts) < 2 { - return "", fmt.Errorf("basic realm= not found in the string, instead found: %s", wwwAuthenticateHeader) - } - - secretFilePath := parts - - // check that the file in the file path is a .key file - fileName := filepath.Base(secretFilePath[1]) - - if !strings.HasSuffix(fileName, azureArcFileExtension) { - return "", fmt.Errorf("invalid file extension, expected %s, got %s", azureArcFileExtension, filepath.Ext(fileName)) - } - - // check that file path from header matches the expected file path for the platform - if strings.TrimSpace(filepath.Dir(expectedSecretFilePath)) != filepath.Dir(secretFilePath[1]) { - return nil, fmt.Errorf("invalid file path, expected %s, got %s", secretFilePath, filepath.Dir(expectedSecretFilePath)) - } - - fileInfo, err := os.Stat(secretFilePath[1]) - if err != nil { - return nil, fmt.Errorf("failed to get metadata for %q due to error: %s", secretFilePath, err) - } - - secretFileSize := fileInfo.Size() - - // Throw an error if the secret file's size is greater than 4096 bytes - if s := fileInfo.Size(); s > azureArcMaxFileSizeBytes { - return "", fmt.Errorf("invalid secret file size, expected %d, file size was %d", azureArcMaxFileSizeBytes, secretFileSize) - } - - // Attempt to read the contents of the secret file - secret, err := os.ReadFile(secretFilePath[1]) - if err != nil { - return nil, fmt.Errorf("failed to read %q due to error: %s", secretFilePath, err) - } - - return string(secret), nil -} diff --git a/apps/managedidentity/managedidentity_test.go b/apps/managedidentity/managedidentity_test.go index e2ef0077..b3d7288c 100644 --- a/apps/managedidentity/managedidentity_test.go +++ b/apps/managedidentity/managedidentity_test.go @@ -5,12 +5,10 @@ package managedidentity import ( "context" "encoding/json" - "fmt" "net/http" "net/url" "os" "path/filepath" - "runtime" "strings" "testing" "time" @@ -88,388 +86,6 @@ func createMockFile(t *testing.T, path string, size int64) { } } - f.Close() -} - -func createMockFileWithSize(path string, size int64) { - createMockFile(path, size) -} - -func setEnvVars(t *testing.T, source Source) { - switch source { - case AzureArc: - t.Setenv(identityEndpointEnvVar, "http://127.0.0.1:40342/metadata/identity/oauth2/token") - t.Setenv(imdsEndVar, "http://169.254.169.254/metadata/identity/oauth2/token") - case AppService: - t.Setenv(identityEndpointEnvVar, "http://127.0.0.1:41564/msi/token") - t.Setenv(identityHeaderEnvVar, "secret") - case CloudShell: - t.Setenv(msiEndpointEnvVar, "http://localhost:40342/metadata/identity/oauth2/token") - case ServiceFabric: - t.Setenv(identityEndpointEnvVar, "http://localhost:40342/metadata/identity/oauth2/token") - t.Setenv(identityHeaderEnvVar, "secret") - t.Setenv(identityServerThumbprintEnvVar, "thumbprint") - } -} - -func unsetEnvVars(t *testing.T) { - t.Setenv(identityEndpointEnvVar, "") - t.Setenv(identityHeaderEnvVar, "") - t.Setenv(identityServerThumbprintEnvVar, "") - t.Setenv(imdsEndVar, "") - t.Setenv(msiEndpointEnvVar, "") -} - -func setCustomAzureArcPlatformPath(path string) func() { - originalFunc := getAzureArcPlatformPath - getAzureArcPlatformPath = func(string) string { - return path - } - - return func() { getAzureArcPlatformPath = originalFunc } -} - -func setCustomAzureArcFilePath(path string) func() { - originalFunc := getAzureArcFilePath - getAzureArcFilePath = func(string) string { - return path - } - - return func() { getAzureArcFilePath = originalFunc } -} - -func TestGetSource(t *testing.T) { - // todo update as required - testCases := []struct { - name string - source Source - endpoint string - expectedSource Source - miType ID - }{ - {name: "testAzureArcSystemAssigned", source: AzureArc, endpoint: imdsDefaultEndpoint, expectedSource: AzureArc, miType: SystemAssigned()}, - {name: "testAzureArcUserClientAssigned", source: AzureArc, endpoint: imdsDefaultEndpoint, expectedSource: AzureArc, miType: UserAssignedClientID("clientId")}, - {name: "testAzureArcUserResourceAssigned", source: AzureArc, endpoint: imdsDefaultEndpoint, expectedSource: AzureArc, miType: UserAssignedResourceID("resourceId")}, - {name: "testAzureArcUserObjectAssigned", source: AzureArc, endpoint: imdsDefaultEndpoint, expectedSource: AzureArc, miType: UserAssignedObjectID("objectId")}, - {name: "testDefaultToImds", source: DefaultToIMDS, endpoint: imdsDefaultEndpoint, expectedSource: DefaultToIMDS, miType: SystemAssigned()}, - {name: "testDefaultToImdsClientAssigned", source: DefaultToIMDS, endpoint: imdsDefaultEndpoint, expectedSource: DefaultToIMDS, miType: UserAssignedClientID("clientId")}, - {name: "testDefaultToImdsResourceAssigned", source: DefaultToIMDS, endpoint: imdsDefaultEndpoint, expectedSource: DefaultToIMDS, miType: UserAssignedResourceID("resourceId")}, - {name: "testDefaultToImdsObjectAssigned", source: DefaultToIMDS, endpoint: imdsDefaultEndpoint, expectedSource: DefaultToIMDS, miType: UserAssignedObjectID("objectId")}, - {name: "testDefaultToImdsEmptyEndpoint", source: DefaultToIMDS, endpoint: "", expectedSource: DefaultToIMDS, miType: SystemAssigned()}, - {name: "testDefaultToImdsLinux", source: DefaultToIMDS, endpoint: imdsDefaultEndpoint, expectedSource: DefaultToIMDS, miType: SystemAssigned()}, - {name: "testDefaultToImdsEmptyEndpointLinux", source: DefaultToIMDS, endpoint: "", expectedSource: DefaultToIMDS, miType: SystemAssigned()}, - } - - for _, testCase := range testCases { - t.Run(string(testCase.source), func(t *testing.T) { - unsetEnvVars(t) - setEnvVars(t, testCase.source) - - if runtime.GOOS == "linux" { - restoreFunc := setCustomAzureArcFilePath("fake/fake") - defer restoreFunc() - } - - actualSource, err := GetSource(testCase.miType) - if err != nil { - t.Fatalf("error while getting source: %s", err.Error()) - } - - if actualSource != testCase.expectedSource { - t.Errorf(errorExpectedButGot, testCase.expectedSource, actualSource) - } - }) - } -} - -func TestAzureArcReturnsWhenHimdsFound(t *testing.T) { - if runtime.GOOS == "darwin" { - t.Skip("Skipping test on macOS as HIMDS is not supported") - } - - testCases := []struct { - name string - source Source - endpoint string - expectedSource Source - miType ID - }{ - {name: "testAzureArcSystemAssigned", source: AzureArc, endpoint: "imdsDefaultEndpoint", expectedSource: AzureArc, miType: SystemAssigned()}, - } - - for _, testCase := range testCases { - t.Run(string(testCase.source), func(t *testing.T) { - unsetEnvVars(t) - - actualSource, err := GetSource(testCase.miType) - if err != nil { - t.Fatalf("error while getting source: %s", err.Error()) - } - - if actualSource != testCase.expectedSource { - t.Errorf(errorExpectedButGot, testCase.expectedSource, actualSource) - } - }) - } -} - -func TestIMDSAcquireTokenReturnsTokenSuccess(t *testing.T) { - testCases := []struct { - source Source - endpoint string - resource string - miType ID - apiVersion string - }{ - {source: DefaultToIMDS, endpoint: imdsDefaultEndpoint, resource: resource, miType: SystemAssigned(), apiVersion: imdsAPIVersion}, - {source: DefaultToIMDS, endpoint: imdsDefaultEndpoint, resource: resourceDefaultSuffix, miType: SystemAssigned(), apiVersion: imdsAPIVersion}, - {source: DefaultToIMDS, endpoint: imdsDefaultEndpoint, resource: resource, miType: UserAssignedClientID("clientId"), apiVersion: imdsAPIVersion}, - {source: DefaultToIMDS, endpoint: imdsDefaultEndpoint, resource: resourceDefaultSuffix, miType: UserAssignedResourceID("resourceId"), apiVersion: imdsAPIVersion}, - {source: DefaultToIMDS, endpoint: imdsDefaultEndpoint, resource: resourceDefaultSuffix, miType: UserAssignedObjectID("objectId"), apiVersion: imdsAPIVersion}, - {source: AzureArc, endpoint: azureArcEndpoint, resource: resource, miType: SystemAssigned(), apiVersion: azureArcAPIVersion}, - {source: AzureArc, endpoint: azureArcEndpoint, resource: resourceDefaultSuffix, miType: SystemAssigned(), apiVersion: azureArcAPIVersion}, - {source: AzureArc, endpoint: azureArcEndpoint, resource: resource, miType: UserAssignedClientID("clientId"), apiVersion: azureArcAPIVersion}, - {source: AzureArc, endpoint: azureArcEndpoint, resource: resource, miType: UserAssignedObjectID("objectId"), apiVersion: azureArcAPIVersion}, - {source: AzureArc, endpoint: azureArcEndpoint, resource: resource, miType: UserAssignedResourceID("resourceId"), apiVersion: azureArcAPIVersion}, - } - for _, testCase := range testCases { - - t.Run(string(testCase.source), func(t *testing.T) { - unsetEnvVars(t) - setEnvVars(t, testCase.source) - - if runtime.GOOS == "linux" { - restoreFunc := setCustomAzureArcFilePath("fake/fake") - defer restoreFunc() - } - - var localUrl *url.URL - mockClient := mock.Client{} - responseBody, err := getSuccessfulResponse(resource) - if err != nil { - t.Fatalf(errorFormingJsonResponse, err.Error()) - } - mockClient.AppendResponse(mock.WithHTTPStatusCode(http.StatusOK), mock.WithBody(responseBody), mock.WithCallback(func(r *http.Request) { - localUrl = r.URL - })) - client, err := New(testCase.miType, WithHTTPClient(&mockClient)) - - if err != nil { - t.Fatal(err) - } - result, err := client.AcquireToken(context.Background(), testCase.resource) - if err != nil { - if testCase.source == AzureArc && err.Error() == "Azure Arc doesn't support user assigned managed identities" { - return - } - } - if !strings.HasPrefix(localUrl.String(), testCase.endpoint) { - t.Fatalf("url request is not on %s got %s", testCase.endpoint, localUrl) - } - - if !strings.Contains(localUrl.String(), testCase.miType.value()) { - t.Fatalf("url request does not contain the %s got %s", testCase.endpoint, localUrl) - } - query := localUrl.Query() - - if query.Get(apiVersionQueryParameterName) != testCase.apiVersion { - t.Fatalf("api-version not on %s got %s", testCase.apiVersion, query.Get(apiVersionQueryParameterName)) - } - if query.Get(resourceQueryParameterName) != strings.TrimSuffix(testCase.resource, "/.default") { - t.Fatal("suffix /.default was not removed.") - } - switch i := testCase.miType.(type) { - case UserAssignedClientID: - if query.Get(miQueryParameterClientId) != i.value() { - t.Fatalf("resource client-id is incorrect, wanted %s got %s", i.value(), query.Get(miQueryParameterClientId)) - } - case UserAssignedResourceID: - if query.Get(miQueryParameterResourceId) != i.value() { - t.Fatalf("resource resource-id is incorrect, wanted %s got %s", i.value(), query.Get(miQueryParameterResourceId)) - } - case UserAssignedObjectID: - if query.Get(miQueryParameterObjectId) != i.value() { - t.Fatalf("resource objectid is incorrect, wanted %s got %s", i.value(), query.Get(miQueryParameterObjectId)) - } - } - if err != nil { - t.Fatal(err) - } - if result.AccessToken != token { - t.Fatalf("wanted %q, got %q", token, result.AccessToken) - } - - }) - } -} - -// func Test_AzureArc_AcquireToken_Returns_Token_Success(t *testing.T) { -// testCaseFilePath, err := getMockFilePath(t) -// if err != nil { -// t.Fatalf("failed to get mock file path: %v", err) -// } - -// testCases := []struct { -// source Source -// endpoint string -// resource string -// miType ID -// apiVersion string -// failFirstResponse bool -// }{ -// // {source: AzureArc, endpoint: azureArcEndpoint, resource: resource, miType: SystemAssigned(), apiVersion: azureArcAPIVersion, failFirstResponse: false}, -// // {source: AzureArc, endpoint: azureArcEndpoint, resource: resourceDefaultSuffix, miType: SystemAssigned(), apiVersion: azureArcAPIVersion, failFirstResponse: false}, -// {source: AzureArc, endpoint: azureArcEndpoint, resource: resource, miType: SystemAssigned(), apiVersion: azureArcAPIVersion, failFirstResponse: true}, -// } - -// for _, testCase := range testCases { -// t.Run(string(testCase.source)+"-"+testCase.miType.value(), func(t *testing.T) { -// unsetEnvVars(t) -// setEnvVars(t, testCase.source) -// setCustomAzureArcFilePath(t, "fake/fake") - -// var localUrl *url.URL -// mockClient := mock.Client{} -// responseBody, err := getSuccessfulResponse(resource) -// if err != nil { -// t.Fatalf("error while forming json response : %s", err.Error()) -// } - -// if testCase.failFirstResponse { -// response := &http.Response{ -// StatusCode: http.StatusUnauthorized, -// Header: make(http.Header), -// } - -// response.Header.Set(wwwAuthenticateHeaderName, "Basic realm="+filepath.Join(testCaseFilePath, "secret.key")) - -// mockFilePath := filepath.Join(testCaseFilePath, "secret.key") -// setCustomAzureArcPlatformPath(t, testCaseFilePath) -// createMockFile(t, mockFilePath, 0) - -// defer os.Remove(mockFilePath) - -// mockClient.AppendResponse(mock.WithHTTPStatusCode(http.StatusUnauthorized), mock.WithBody(responseBody), mock.WithCallback(func(r *http.Request) { -// localUrl = r.URL -// })) -// } - -// mockClient.AppendResponse(mock.WithHTTPStatusCode(http.StatusOK), mock.WithBody(responseBody), mock.WithCallback(func(r *http.Request) { -// localUrl = r.URL -// })) - -// // resetting cache -// before := cacheManager -// defer func() { cacheManager = before }() -// cacheManager = storage.New(nil) - -// client, err := New(testCase.miType, WithHTTPClient(&mockClient)) -// if err != nil { -// t.Fatal(err) -// } - -// result, err := client.AcquireToken(context.Background(), testCase.resource) - -// if err != nil { -// t.Fatal(err) -// } -// if localUrl == nil || !strings.HasPrefix(localUrl.String(), testCase.endpoint) { -// t.Fatalf("url request is not on %s got %s", testCase.endpoint, localUrl) -// } -// if testCase.miType.value() != systemAssignedManagedIdentity { -// if !strings.Contains(localUrl.String(), testCase.miType.value()) { -// t.Fatalf("url request does not contain the %s got %s", testCase.endpoint, testCase.miType.value()) -// } -// } - -// query := localUrl.Query() - -// if query.Get(apiVersionQueryParameterName) != testCase.apiVersion { -// t.Fatalf("api-version not on %s got %s", testCase.apiVersion, query.Get(apiVersionQueryParameterName)) -// } -// if query.Get(resourceQueryParameterName) != strings.TrimSuffix(testCase.resource, "/.default") { -// t.Fatal("suffix /.default was not removed.") -// } -// switch i := testCase.miType.(type) { -// case UserAssignedClientID: -// if query.Get(miQueryParameterClientId) != i.value() { -// t.Fatalf("resource client-id is incorrect, wanted %s got %s", i.value(), query.Get(miQueryParameterClientId)) -// } -// case UserAssignedResourceID: -// if query.Get(miQueryParameterResourceId) != i.value() { -// t.Fatalf("resource resource-id is incorrect, wanted %s got %s", i.value(), query.Get(miQueryParameterResourceId)) -// } -// case UserAssignedObjectID: -// if query.Get(miQueryParameterObjectId) != i.value() { -// t.Fatalf("resource objectid is incorrect, wanted %s got %s", i.value(), query.Get(miQueryParameterObjectId)) -// } -// } -// if result.Metadata.TokenSource != base.IdentityProvider { -// t.Fatalf("expected IndenityProvider tokensource, got %d", result.Metadata.TokenSource) -// } -// if result.AccessToken != token { -// t.Fatalf("wanted %q, got %q", token, result.AccessToken) -// } -// result, err = client.AcquireToken(context.Background(), testCase.resource) -// if err != nil { -// t.Fatal(err) -// } -// if result.Metadata.TokenSource != base.Cache { -// t.Fatalf("wanted cache token source, got %d", result.Metadata.TokenSource) -// } -// secondFakeClient, err := New(testCase.miType, WithHTTPClient(&mockClient)) -// if err != nil { -// t.Fatal(err) -// } -// result, err = secondFakeClient.AcquireToken(context.Background(), testCase.resource) -// if err != nil { -// t.Fatal(err) -// } -// if result.Metadata.TokenSource != base.Cache { -// t.Fatalf("cache result wanted cache token source, got %d", result.Metadata.TokenSource) -// } -// }) -// } -// } - -func TestSystemAssignedReturnsAcquireTokenFailure(t *testing.T) { - testCases := []struct { - code int - err string - desc string - correlationID string - }{ - {code: http.StatusNotFound, - err: "", - desc: "", - correlationID: "121212"}, - {code: http.StatusNotImplemented, - err: "", - desc: "", - correlationID: "121212"}, - {code: http.StatusServiceUnavailable, - err: "", - desc: "", - correlationID: "121212"}, - {code: http.StatusBadRequest, - err: "invalid_request", - desc: "Identity not found", - correlationID: "121212", - }, - } - - f, err := os.Create(path) - if err != nil { - t.Fatalf("failed to create file: %v", err) - } - defer f.Close() // Ensure the file is closed - - if size > 0 { - if err := f.Truncate(size); err != nil { - t.Fatalf("failed to truncate file: %v", err) - } - } - // Write the content to the file if _, err := f.WriteString("secret file data"); err != nil { t.Fatalf("failed to write to file: %v", err) @@ -541,14 +157,7 @@ func TestAzureArcReturnsWhenHimdsFound(t *testing.T) { // Create the mock himds file createMockFile(t, mockFilePath, 1024) - // Ensure file is deleted after test - t.Cleanup(func() { - if err := os.Remove(mockFilePath); err != nil { - t.Fatalf("failed to delete mock file: %s", err) - } - }) - - actualSource, err := GetSource() + actualSource, err := getSource() if err != nil { t.Fatalf("error while getting source: %s", err.Error()) } @@ -592,24 +201,11 @@ func TestIMDSAcquireTokenReturnsTokenSuccess(t *testing.T) { client, err := New(testCase.miType, WithHTTPClient(&mockClient)) if err != nil { - if testCase.request.shouldFail { - if err.Error() != testCase.request.expectedError { - t.Fatalf(`expected error: "%v" got error: "%v"`, testCase.request.expectedError, err) - } - } else { - t.Fatal(err) - } + t.Fatal(err) } result, err := client.AcquireToken(context.Background(), testCase.resource) - if testCase.request.shouldFail { - if err == nil || err.Error() != testCase.request.expectedError { - t.Fatalf(`expected error: "%v" got error: "%v"`, testCase.request.expectedError, err) - } - return - - } if err != nil { t.Fatal(err) } @@ -755,7 +351,6 @@ func TestAzureArc(t *testing.T) { } func TestAzureArcOnlySystemAssignedSupported(t *testing.T) { - setEnvVars(t, AzureArc) mockClient := mock.Client{} @@ -990,22 +585,3 @@ func TestCreatingIMDSClient(t *testing.T) { }) } } - -func TestAzureArcUserAssignedFailure(t *testing.T) { - for _, id := range []ID{UserAssignedClientID("clientID"), - UserAssignedResourceID("resourceID"), - UserAssignedObjectID("objectID")} { - t.Run(fmt.Sprintf("%T", id), func(t *testing.T) { - unsetEnvVars(t) - setEnvVars(t, AzureArc) - _, err := New(id) - if err == nil { - t.Fatal("client New() should return a error but did not.") - } - if err.Error() != "azure Arc doesn't support user assigned managed identities" { - t.Fatalf("expected error message 'azure Arc doesn't support user assigned managed identities', got %s", err.Error()) - } - - }) - } -} diff --git a/apps/tests/devapps/managedidentity/managedidentity_sample.go b/apps/tests/devapps/managedidentity/managedidentity_sample.go index 310cf195..bda8f068 100644 --- a/apps/tests/devapps/managedidentity/managedidentity_sample.go +++ b/apps/tests/devapps/managedidentity/managedidentity_sample.go @@ -119,81 +119,6 @@ func getSecretFromAzureVault() { println(fmt.Sprintf("The secret, %s, has a value of: %s", secretName, string(body))) } -func runIMDSUserAssignedObjectID() { - miUserAssigned, err := mi.New(mi.UserAssignedObjectID("YOUR_MANAGED_IDENTITY_CLIENT_ID")) - if err != nil { - fmt.Println(err) - } - result, err := miUserAssigned.AcquireToken(context.Background(), "https://management.azure.com/") - if err != nil { - fmt.Println(err) - } - fmt.Println("token expire at : ", result.ExpiresOn) -} - -func runIMDSUserAssignedResourceID() { - miUserAssigned, err := mi.New(mi.UserAssignedResourceID("YOUR_MANAGED_IDENTITY_CLIENT_ID")) - if err != nil { - fmt.Println(err) - } - result, err := miUserAssigned.AcquireToken(context.Background(), "https://management.azure.com/") - if err != nil { - fmt.Println(err) - } - fmt.Println("token expire at : ", result.ExpiresOn) -} - -func runAzureArcSystemAssigned() { - setEnvironmentVariablesIfRequired(mi.AzureArc) - - miAzureArc, err := mi.New(mi.SystemAssigned()) - if err != nil { - fmt.Println(err) - } - result, err := miAzureArc.AcquireToken(context.Background(), "https://management.azure.com/") - if err != nil { - fmt.Println(err) - } - fmt.Println("token expire at : ", result.ExpiresOn) -} - -func runAzureArcUserAssignedClientID() { - setEnvironmentVariablesIfRequired(mi.AzureArc) - - _, err := mi.New(mi.UserAssignedClientID("This should fail")) - if err != nil { - fmt.Println(err) - } -} - -func runAzureArcUserAssignedObjectID() { - setEnvironmentVariablesIfRequired(mi.AzureArc) - - _, err := mi.New(mi.UserAssignedObjectID("This should fail")) - if err != nil { - fmt.Println(err) - } -} - -func runAzureArcUserAssignedResourceID() { - setEnvironmentVariablesIfRequired(mi.AzureArc) - - _, err := mi.New(mi.UserAssignedResourceID("This should fail")) - if err != nil { - fmt.Println(err) - } -} - -func setEnvironmentVariablesIfRequired(source mi.Source) { - if isLocalTest { - switch source { - case mi.AzureArc: - os.Setenv(mi.IdentityEndpointEnvVar, "identityEndpointVar") - os.Setenv(mi.ArcIMDSEnvVar, "imdsEnvVar") - } - } -} - func main() { var exampleType string fmt.Println("Enter the example type (1-9):")