public void DisableAutoSaveWhenSettingFileBreaks()
        {
            string faker = Path.Combine(Directory.GetParent(profileBasePath).ToString(), "faker");

            faker = Path.Combine(faker, Resources.AzureDirectoryName);
            var backupPath = HookSettingFile(faker);

            try
            {
                AzureSessionInitializer.CreateOrReplaceSession(dataStore);
                TestMockSupport.RunningMocked = true;
                var cmdlet = new ConnectAzureRmAccountCommand();
                cmdlet.OnImport();
                Assert.Equal(ContextSaveMode.Process, AzureSession.Instance.ARMContextSaveMode);
                Assert.Equal(typeof(ResourceManagerProfileProvider), AzureRmProfileProvider.Instance.GetType());
                var afterModified = dataStore.ReadFileAsText(settingsPath);
                var newSetting    = JsonConvert.DeserializeObject <ContextAutosaveSettings>(afterModified) as ContextAutosaveSettings;
                Assert.NotNull(newSetting);
                Assert.Equal(ContextSaveMode.CurrentUser, newSetting.Mode);
                //Assert.Equal(typeof(AzureTokenCache), AzureSession.Instance.TokenCache.GetType());
            }
            finally
            {
                RestoreSetting(backupPath);
            }
        }
Beispiel #2
0
 public void DataCollectionSettingPreventsFileWrite()
 {
     try
     {
         Environment.SetEnvironmentVariable("Azure_PS_Data_Collection", "true");
         var store = SetupStore();
         store.Setup(f => f.FileExists(It.IsAny <string>())).Returns(false);
         store.Setup(f => f.WriteFile(It.IsAny <string>(), It.IsAny <string>())).Throws(new IOException("Cannot access file"));
         store.Setup(f => f.WriteFile(It.IsAny <string>(), It.IsAny <byte[]>())).Throws(new IOException("Cannot access file"));
         store.Setup(f => f.WriteFile(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <Encoding>())).Throws(new IOException("Cannot access file"));
         AzureSessionInitializer.CreateOrReplaceSession(store.Object);
         var session = AzureSession.Instance;
         Assert.NotNull(session);
         Assert.Equal(ContextSaveMode.Process, session.ARMContextSaveMode);
         Assert.NotNull(session.TokenCache);
         Assert.Equal(typeof(AuthenticationStoreTokenCache), session.TokenCache.GetType());
         Assert.NotNull(AzureRmProfileProvider.Instance);
         Assert.Equal(typeof(ResourceManagerProfileProvider), AzureRmProfileProvider.Instance.GetType());
         store.Verify(f => f.WriteFile(It.IsAny <string>(), It.IsAny <string>()), Times.Once);
     }
     finally
     {
         ResetState();
     }
 }
        public void InitializerCreatesTokenCacheFile()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAzureSession oldSession = null;

            try
            {
                oldSession = AzureSession.Instance;
            }
            catch { }
            try
            {
                var store    = new MemoryDataStore();
                var path     = Path.Combine(AzureSession.Instance.ARMProfileDirectory, ContextAutosaveSettings.AutoSaveSettingsFile);
                var settings = new ContextAutosaveSettings {
                    Mode = ContextSaveMode.CurrentUser
                };
                var content = JsonConvert.SerializeObject(settings);
                store.VirtualStore[path] = content;
                AzureSessionInitializer.CreateOrReplaceSession(store);
                var session        = AzureSession.Instance;
                var tokenCacheFile = Path.Combine(session.ProfileDirectory, session.TokenCacheFile);
                Assert.True(store.FileExists(tokenCacheFile));
            }
            finally
            {
                AzureSession.Initialize(() => oldSession, true);
            }
        }
Beispiel #4
0
        public void SilentReauthenticateSuccess()
        {
            try
            {
                // Setup
                InitializeSession();
                cmdlet.TenantId = Guid.NewGuid().ToString();
                var mockAzureCredentialFactory = new Mock <AzureCredentialFactory>();
                mockAzureCredentialFactory.Setup(f => f.CreateSharedTokenCacheCredentials(It.IsAny <SharedTokenCacheCredentialOptions>())).Returns(() => new TokenCredentialMock(
                                                                                                                                                       (firstTime) =>
                {
                    return(new ValueTask <AccessToken>(new AccessToken(fakeToken, DateTimeOffset.Now.AddHours(1))));
                }));

                AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true);
                AzureSession.Instance.ClientFactory.AddHandler(new HttpMockHandler(
                                                                   (times) =>
                {
                    HttpResponseMessage response = null;
                    if (times == 0)
                    {
                        response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                        {
                            Content = new StringContent(body401, Encoding.UTF8, "application/json"),
                        };
                        response.Headers.Add("WWW-Authenticate", WwwAuthenticateIP);
                    }
                    else
                    {
                        response = new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new StringContent(string.Format(body200, cmdlet.TenantId), Encoding.UTF8, "application/json"),
                        };
                    }
                    return(response);
                }));

                // Act
                cmdlet.InvokeBeginProcessing();
                cmdlet.ExecuteCmdlet();
                cmdlet.InvokeEndProcessing();

                //Verify
                Assert.Single(OutputPipeline);
                Assert.True(OutputPipeline.First() is PSAzureTenant);
                Assert.Equal(cmdlet.TenantId, ((PSAzureTenant)OutputPipeline.First()).Id.ToString());
                Assert.Equal(2, ((PSAzureTenant)OutputPipeline.First()).Domains.Length);
                Assert.Equal("AzureSDKTeam.onmicrosoft.com,azdevextest.com", string.Join(",", ((PSAzureTenant)OutputPipeline.First()).Domains));
                Assert.Equal("Home", ((PSAzureTenant)OutputPipeline.First()).TenantCategory);
            }
            finally
            {
                //Dispose
                AzureSessionInitializer.CreateOrReplaceSession(new MemoryDataStore());
            }
        }
Beispiel #5
0
        public void SilentReauthenticateFailure()
        {
            try
            {
                // Setup
                InitializeSession();
                var mockAzureCredentialFactory = new Mock <AzureCredentialFactory>();
                mockAzureCredentialFactory.Setup(f => f.CreateSharedTokenCacheCredentials(It.IsAny <SharedTokenCacheCredentialOptions>())).Returns(() => new TokenCredentialMock(
                                                                                                                                                       (times) =>
                {
                    if (times < 1)
                    {
                        return(new ValueTask <AccessToken>(new AccessToken(fakeToken, DateTimeOffset.Now.AddHours(1))));
                    }
                    throw new CredentialUnavailableException("Exception from Azure Identity.");
                }
                                                                                                                                                       ));
                AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => mockAzureCredentialFactory.Object, true);
                AzureSession.Instance.ClientFactory.AddHandler(new HttpMockHandler(
                                                                   (times) =>
                {
                    var response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
                    {
                        Content = new StringContent(body401, Encoding.UTF8, "application/json"),
                    };
                    response.Headers.Add("WWW-Authenticate", WwwAuthenticateIP);
                    return(response);
                }));

                cmdlet.TenantId = Guid.NewGuid().ToString();

                // Act
                cmdlet.InvokeBeginProcessing();
                AuthenticationFailedException e = Assert.Throws <AuthenticationFailedException>(() => cmdlet.ExecuteCmdlet());
                string errorMessage             = $"Exception from Azure Identity.{Environment.NewLine}authorization_uri: https://login.windows.net/{Environment.NewLine}error: invalid_token{Environment.NewLine}error_description: Tenant IP Policy validate failed.{Environment.NewLine}claims: eyJhY2Nlc3NfdG9rZW4iOnsibmJmIjp7ImVzc2VudGlhbCI6dHJ1ZSwidmFsdWUiOiIxNjEzOTgyNjA2In0sInhtc19ycF9pcGFkZHIiOnsidmFsdWUiOiIxNjcuMjIwLjI1NS40MSJ9fX0={Environment.NewLine}";
                Assert.Equal(errorMessage, e.Message);
                cmdlet.InvokeEndProcessing();
            }
            finally
            {
                //Dispose
                AzureSessionInitializer.CreateOrReplaceSession(new MemoryDataStore());
            }
        }
 public void TestInitializationCannotCheckFileExistence()
 {
     try
     {
         var store = SetupStore();
         store.Setup(f => f.FileExists(It.IsAny <string>())).Throws(new IOException("Cannot access directory"));
         AzureSessionInitializer.CreateOrReplaceSession(store.Object);
         var session = AzureSession.Instance;
         Assert.NotNull(session);
         Assert.Equal(ContextSaveMode.Process, session.ARMContextSaveMode);
         Assert.NotNull(AzureRmProfileProvider.Instance);
         Assert.Equal(typeof(ResourceManagerProfileProvider), AzureRmProfileProvider.Instance.GetType());
         store.Verify(f => f.FileExists(It.IsAny <string>()), Times.AtLeastOnce);
     }
     finally
     {
         ResetState();
     }
 }
Beispiel #7
0
        private void InitializeSession()
        {
            AzureSessionInitializer.CreateOrReplaceSession(new MemoryDataStore());
            AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process;
            PowerShellTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider();

            AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => cacheProvider, true);
            if (!AzureSession.Instance.TryGetComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, out IAuthenticatorBuilder builder))
            {
                builder = new DefaultAuthenticatorBuilder();
                AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => builder);
            }
            var profile = new AzureRmProfile
            {
                DefaultContext = defaultContext
            };

            cmdlet.profileClient = new RMProfileClient(profile);
        }
Beispiel #8
0
 public void TestInitializationCannotRead()
 {
     try
     {
         var store = SetupStore();
         store.Setup(f => f.ReadFileAsText(It.IsAny <string>())).Throws(new IOException("Cannot access file"));
         store.Setup(f => f.ReadFileAsBytes(It.IsAny <string>())).Throws(new IOException("Cannot access file"));
         AzureSessionInitializer.CreateOrReplaceSession(store.Object);
         var session = AzureSession.Instance;
         Assert.NotNull(session);
         Assert.Equal(ContextSaveMode.Process, session.ARMContextSaveMode);
         Assert.NotNull(session.TokenCache);
         Assert.Equal(typeof(AuthenticationStoreTokenCache), session.TokenCache.GetType());
         Assert.NotNull(AzureRmProfileProvider.Instance);
         Assert.Equal(typeof(ResourceManagerProfileProvider), AzureRmProfileProvider.Instance.GetType());
         store.Verify(f => f.ReadFileAsText(It.IsAny <string>()), Times.AtLeastOnce);
     }
     finally
     {
         ResetState();
     }
 }
        public void InitializerCreatesTokenCacheFile()
        {
            AzureSessionInitializer.InitializeAzureSession();
            IAzureSession oldSession = null;

            try
            {
                oldSession = AzureSession.Instance;
            }
            catch { }
            try
            {
                var store = new MemoryDataStore();
                AzureSessionInitializer.CreateOrReplaceSession(store);
                var session        = AzureSession.Instance;
                var tokenCacheFile = Path.Combine(session.ProfileDirectory, session.TokenCacheFile);
                Assert.True(store.FileExists(tokenCacheFile));
            }
            finally
            {
                AzureSession.Initialize(() => oldSession, true);
            }
        }