Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/Accounts/Accounts.Test/AzureSessionTestInitializer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.PowerShell.Authenticators;
using Microsoft.Azure.PowerShell.Authenticators.Factories;

namespace Microsoft.Azure.Commands.Profile.Test
{
internal class AzureSessionTestInitializer
{
public static void Initialize()
{
AzureSession.Instance.DataStore = new MemoryDataStore();
AzureRmProfileProvider.Instance.Profile = new AzureRmProfile();

PowerShellTokenCacheProvider tokenCacheProvider = new InMemoryTokenCacheProvider();
AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => tokenCacheProvider);
AzureSession.Instance.RegisterComponent(nameof(PowerShellTokenCache), () => tokenCacheProvider.GetTokenCache());
IAuthenticatorBuilder builder = new DefaultAuthenticatorBuilder();
AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => builder);
AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => new AzureCredentialFactory());
AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => new MsalAccessTokenAcquirerFactory());
}

}
}
148 changes: 116 additions & 32 deletions src/Accounts/Accounts.Test/LoginCmdletTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,41 +12,47 @@
// limitations under the License.
// ----------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Management.Automation;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Sockets;
using System.Reflection;
using System.Security;

using Azure.Identity;

using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.Commands.ScenarioTest;
using Microsoft.Azure.ServiceManagement.Common.Models;
using Microsoft.WindowsAzure.Commands.Common.Test.Mocks;
using Microsoft.WindowsAzure.Commands.ScenarioTest;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using System.Management.Automation;
using System.Reflection;

using Moq;

using Xunit;
using Xunit.Abstractions;
using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Diagnostics;
using System;
using System.Security;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.Commands.ScenarioTest;
using System.Linq;

namespace Microsoft.Azure.Commands.Profile.Test
{
public class LoginCmdletTests
{
private MemoryDataStore dataStore;
private MockCommandRuntime commandRuntimeMock;

public LoginCmdletTests(ITestOutputHelper output)
{
TestExecutionHelpers.SetUpSessionAndProfile();
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
dataStore = new MemoryDataStore();
AzureSession.Instance.DataStore = dataStore;
commandRuntimeMock = new MockCommandRuntime();
AzureRmProfileProvider.Instance.Profile = new AzureRmProfile();

AzureSessionTestInitializer.Initialize();
}

[Fact]
Expand Down Expand Up @@ -113,10 +119,13 @@ public void LoginWithInvalidSubscriptionAndTenantThrowsCloudException()
// Setup
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.Subscription = "2c224e7e-3ef5-431d-a57b-e71f4662e3a5";
cmdlt.MyInvocation.BoundParameters.Add(nameof(cmdlt.Subscription), "2c224e7e-3ef5-431d-a57b-e71f4662e3a5");
cmdlt.Tenant = "72f988bf-86f1-41af-91ab-2d7cd011db47";
cmdlt.MyInvocation.BoundParameters.Add(nameof(cmdlt.Tenant), "72f988bf-86f1-41af-91ab-2d7cd011db47");
cmdlt.SetParameterSet("UserWithSubscriptionId");

// Act

cmdlt.InvokeBeginProcessing();
Assert.Throws<PSInvalidOperationException>(() => cmdlt.ExecuteCmdlet());
cmdlt.InvokeEndProcessing();
Expand All @@ -129,7 +138,9 @@ public void LoginWithSubscriptionAndNoTenant()
var cmdlt = new ConnectAzureRmAccountCommand();
// Setup
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.Subscription = "2c224e7e-3ef5-431d-a57b-e71f4662e3a6";
var subscriptionId = "9e223dbe-3399-4e19-88eb-0975f02ac87f";
cmdlt.Subscription = subscriptionId;
cmdlt.MyInvocation.BoundParameters.Add(nameof(cmdlt.Subscription), subscriptionId);
cmdlt.SetParameterSet("UserWithSubscriptionId");

// Act
Expand All @@ -140,6 +151,45 @@ public void LoginWithSubscriptionAndNoTenant()
Assert.NotNull(AzureRmProfileProvider.Instance.Profile.DefaultContext);
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
//Verify https://github.com/Azure/azure-powershell/issues/13340
public void LoginUseInteractiveThruNonDesktop()
{
var cmdlt = new ConnectAzureRmAccountCommand();

// Setup
CommonUtilities commonUtilities;
AzureSession.Instance.TryGetComponent(nameof(CommonUtilities), out commonUtilities);
try
{
var mockUtilities = new Mock<CommonUtilities>();
mockUtilities.Setup(u => u.IsDesktopSession()).Returns(false);
AzureSession.Instance.RegisterComponent(nameof(CommonUtilities),
() => mockUtilities.Object, true);
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.SetParameterSet("UserWithSubscriptionId");

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

//Verify
Assert.Single(commandRuntimeMock.WarningStream);
Assert.Equal("Interactive authentication is not supported in this session, please run cmdlet 'Connect-AzAccount -UseDeviceAuthentication'.", commandRuntimeMock.WarningStream[0]);
Assert.Null(AzureRmProfileProvider.Instance.Profile.DefaultContext);
}
finally
{
if(commonUtilities != null)
{
AzureSession.Instance.RegisterComponent(nameof(CommonUtilities),
() => commonUtilities, true);
}
}
}

[Fact]
[Trait(Category.RunType, Category.LiveOnly)]
public void LoginWithNoSubscriptionAndNoTenant()
Expand All @@ -157,14 +207,45 @@ public void LoginWithNoSubscriptionAndNoTenant()
Assert.NotNull(AzureRmProfileProvider.Instance.Profile.DefaultContext);
}

[Fact]
[Trait(Category.RunType, Category.LiveOnly)]
//Verify https://github.com/Azure/azure-powershell/issues/13419
public void LoginWithNoSubscriptionAndNoTenantAndFirstPortNotAvailable()
{
var listener = new TcpListener(IPAddress.Loopback, 8400);

try
{
listener.Start();

var cmdlt = new ConnectAzureRmAccountCommand();
// Setup
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.SetParameterSet("UserWithSubscriptionId");

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

Assert.NotNull(AzureRmProfileProvider.Instance.Profile.DefaultContext);
}
finally
{
listener.Stop();
}
}

[Fact]
[Trait(Category.RunType, Category.LiveOnly)]
public void LoginWithNoSubscriptionAndTenant()
{
var cmdlt = new ConnectAzureRmAccountCommand();
// Setup
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.Tenant = "72f988bf-86f1-41af-91ab-2d7cd011db47";
var tenantId = "72f988bf-86f1-41af-91ab-2d7cd011db47";
cmdlt.Tenant = tenantId;
cmdlt.MyInvocation.BoundParameters.Add(nameof(cmdlt.Tenant), tenantId);
cmdlt.SetParameterSet("UserWithSubscriptionId");

// Act
Expand All @@ -182,7 +263,9 @@ public void LoginWithNoSubscriptionAndTenantDomain()
var cmdlt = new ConnectAzureRmAccountCommand();
// Setup
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.Tenant = "microsoft.onmicrosoft.com";
var tenantName = "microsoft.onmicrosoft.com";
cmdlt.Tenant = tenantName;
cmdlt.MyInvocation.BoundParameters.Add(nameof(cmdlt.Tenant), tenantName);
cmdlt.SetParameterSet("UserWithSubscriptionId");

// Act
Expand Down Expand Up @@ -238,14 +321,16 @@ public void LoginWithRbacTenantOnly()
[Trait(Category.RunType, Category.LiveOnly)]
public void LoginWithRbacSPNAndCertificateOnly()
{
AzureSession.Instance.DataStore = new DiskDataStore();
var cmdlt = new ConnectAzureRmAccountCommand();
// Setup
// NOTE: Use rbac SPN credentials for this test case
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.ServicePrincipal = true;
cmdlt.Tenant = "54826b22-38d6-4fb2-bad9-b7b93a3e9c5a";
cmdlt.ApplicationId = "99edf981-74c0-4284-bddf-3e9d092ba4e2";
cmdlt.CertificateThumbprint = "F064B7C7EACC942D10662A5115E047E94FA18498";
cmdlt.Tenant = "72f988bf-86f1-41af-91ab-2d7cd011db47";
cmdlt.ApplicationId = "343d1f33-e5bc-4857-9216-a50144e7da46";
//You must have this cert installed on your machine
cmdlt.CertificateThumbprint = "15385B6BF747423330CD8CA5B34022F7AC60B86C";
cmdlt.SetParameterSet("ServicePrincipalCertificateWithSubscriptionId");

// Act
Expand Down Expand Up @@ -282,7 +367,7 @@ public void GetMultipleTenantsOnLogin()
Assert.NotNull(AzureRmProfileProvider.Instance.Profile.DefaultContext.Account);
var tenants = AzureRmProfileProvider.Instance.Profile.DefaultContext.Account.GetTenants();
Assert.NotNull(tenants);
Assert.Equal(2, tenants.Length);
Assert.True(tenants.Length >= 2);
}

[Fact]
Expand All @@ -292,7 +377,9 @@ public void LoginWithEnvironementName()
var cmdlt = new ConnectAzureRmAccountCommand();
// Setup
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.Environment = "AzureUSGovernment";
var environmentName = "AzureUSGovernment";
cmdlt.Environment = environmentName;
cmdlt.MyInvocation.BoundParameters.Add(nameof(cmdlt.Environment), environmentName);
cmdlt.SetParameterSet("UserWithSubscriptionId");

// Act
Expand All @@ -302,7 +389,7 @@ public void LoginWithEnvironementName()

Assert.NotNull(AzureRmProfileProvider.Instance.Profile.DefaultContext);
Assert.NotNull(AzureRmProfileProvider.Instance.Profile.DefaultContext.Environment);
Assert.Equal("AzureUSGovernment", AzureRmProfileProvider.Instance.Profile.DefaultContext.Environment.Name);
Assert.Equal(environmentName, AzureRmProfileProvider.Instance.Profile.DefaultContext.Environment.Name);
}

[Fact]
Expand Down Expand Up @@ -333,13 +420,10 @@ public void LoginWithCredentialParameterAndMSA()
cmdlt.ExecuteCmdlet();
cmdlt.InvokeEndProcessing();
}
catch (AadAuthenticationFailedException ex)
catch (AuthenticationFailedException ex)
{
Assert.NotNull(ex);
Assert.Equal("-Credential parameter can only be used with Organization ID credentials. " +
"For more information, please refer to http://go.microsoft.com/fwlink/?linkid=331007&clcid=0x409 " +
"for more information about the difference between an organizational account and a Microsoft account.",
ex.Message);
Assert.Contains("UsernamePasswordCredential authentication failed", ex.Message);
}
}

Expand Down Expand Up @@ -371,8 +455,8 @@ public void LoginWithAccessToken()
public void LoginPopulatesContextList()
{
// Before running this test, make sure to clear the contexts on your machine by removing the following two files:
// - %APPDATA%/Windows Azure Powershell/AzureRmContext.json
// - %APPDATA%/Windows Azure Powershell/AzureRmContextSettings.json
// - %USERPROFILE%/.Azure/AzureRmContext.json
// - %USERPROFILE%/.Azure/AzureRmContextSettings.json
// This will clear all existing contexts on your machine so that this test can re-populate the list with a context for each subscription

var cmdlt = new ConnectAzureRmAccountCommand();
Expand All @@ -394,7 +478,7 @@ public void LoginPopulatesContextList()

foreach (var sub in profile.Subscriptions)
{
var contextName = string.Format("{0} - {1}", sub.Name, sub.Id);
var contextName = $"{sub.Name} ({sub.Id}) - {sub.ExtendedProperties["HomeTenant"]} - {sub.ExtendedProperties["Account"]}";
Assert.True(profile.Contexts.ContainsKey(contextName));
var context = profile.Contexts[contextName];
Assert.NotNull(context);
Expand Down
49 changes: 49 additions & 0 deletions src/Accounts/Accounts.Test/OnImportTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------

using System.IO;

using Microsoft.Azure.Commands.Common.Authentication;
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.WindowsAzure.Commands.ScenarioTest;

using Moq;

using Xunit;

namespace Microsoft.Azure.Commands.Profile.Test
{
public class OnImportTests
{

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
//Verify no error happens if user profile path is inaccessible
public void UserProfilePathInAccessible()
{
var cmdlt = new ConnectAzureRmAccountCommand();

// Setup
var mockChecker = new Mock<TokenCachePersistenceChecker>();
mockChecker.Setup(c => c.Verify()).Throws(new FileNotFoundException());
cmdlt.TokenCachePersistenceChecker = mockChecker.Object;

// Act
cmdlt.OnImport();

//Verify
Assert.Equal(AzureSession.Instance.ARMContextSaveMode, ContextSaveMode.Process);
}
}
}
Loading