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
26 changes: 16 additions & 10 deletions src/Accounts/Accounts.Test/AutosaveTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.Common.Authentication;
// TODO: Remove IfDef
#if NETSTANDARD
using Microsoft.Azure.Commands.Common.Authentication.Core;
#endif
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.ServiceManagement.Common.Models;
using Microsoft.WindowsAzure.Commands.Common.Test.Mocks;
Expand All @@ -29,6 +25,7 @@
using Microsoft.Azure.Commands.Profile.Context;
using Microsoft.Azure.Commands.ScenarioTest;
using Microsoft.Azure.Commands.ResourceManager.Common;
using Microsoft.Azure.Commands.Common.Authentication.Authentication.Clients;

namespace Microsoft.Azure.Commands.Profile.Test
{
Expand All @@ -49,10 +46,11 @@ void ResetState()

TestExecutionHelpers.SetUpSessionAndProfile();
ResourceManagerProfileProvider.InitializeResourceManagerProfile(true);
// prevent token acquisition
AzureRmProfileProvider.Instance.GetProfile<AzureRmProfile>().ShouldRefreshContextsFromCache = false;
AzureSession.Instance.DataStore = dataStore;
AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process;
AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory();
AzureSession.Instance.TokenCache = new AuthenticationStoreTokenCache(new AzureTokenCache());
Environment.SetEnvironmentVariable("Azure_PS_Data_Collection", "false");
}

Expand All @@ -70,9 +68,12 @@ public void EnableAutosaveWhenDisabled()
cmdlet.ExecuteCmdlet();
cmdlet.InvokeEndProcessing();
Assert.Equal(ContextSaveMode.CurrentUser, AzureSession.Instance.ARMContextSaveMode);
Assert.Equal(typeof(ProtectedFileTokenCache), AzureSession.Instance.TokenCache.GetType());
Assert.Equal(typeof(ProtectedProfileProvider), AzureRmProfileProvider.Instance.GetType());
}
catch (PlatformNotSupportedException)
{
// swallow exception when test env (Linux server) doesn't support token cache persistence
}
finally
{
ResetState();
Expand All @@ -94,9 +95,12 @@ public void EnableAutosaveWhenEnabled()
cmdlet.ExecuteCmdlet();
cmdlet.InvokeEndProcessing();
Assert.Equal(ContextSaveMode.CurrentUser, AzureSession.Instance.ARMContextSaveMode);
Assert.Equal(typeof(ProtectedFileTokenCache), AzureSession.Instance.TokenCache.GetType());
Assert.Equal(typeof(ProtectedProfileProvider), AzureRmProfileProvider.Instance.GetType());
}
catch (PlatformNotSupportedException)
{
// swallow exception when test env (Linux server) doesn't support token cache persistence
}
finally
{
ResetState();
Expand All @@ -119,7 +123,8 @@ public void DisableAutosaveWhenEnabled()
cmdlet.ExecuteCmdlet();
cmdlet.InvokeEndProcessing();
Assert.Equal(ContextSaveMode.Process, AzureSession.Instance.ARMContextSaveMode);
Assert.Equal(typeof(AuthenticationStoreTokenCache), AzureSession.Instance.TokenCache.GetType());
Assert.True(AzureSession.Instance.TryGetComponent(AuthenticationClientFactory.AuthenticationClientFactoryKey, out AuthenticationClientFactory factory));
Assert.Equal(typeof(InMemoryTokenCacheClientFactory), factory.GetType());
Assert.Equal(typeof(ResourceManagerProfileProvider), AzureRmProfileProvider.Instance.GetType());
}
finally
Expand All @@ -130,7 +135,7 @@ public void DisableAutosaveWhenEnabled()

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void DisableAutoSsaveWhenDisabled()
public void DisableAutoSaveWhenDisabled()
{
ResetState();
try
Expand All @@ -142,7 +147,8 @@ public void DisableAutoSsaveWhenDisabled()
cmdlet.ExecuteCmdlet();
cmdlet.InvokeEndProcessing();
Assert.Equal(ContextSaveMode.Process, AzureSession.Instance.ARMContextSaveMode);
Assert.Equal(typeof(AuthenticationStoreTokenCache), AzureSession.Instance.TokenCache.GetType());
Assert.True(AzureSession.Instance.TryGetComponent(AuthenticationClientFactory.AuthenticationClientFactoryKey, out AuthenticationClientFactory factory));
Assert.Equal(typeof(InMemoryTokenCacheClientFactory), factory.GetType());
Assert.Equal(typeof(ResourceManagerProfileProvider), AzureRmProfileProvider.Instance.GetType());
}
finally
Expand Down
97 changes: 38 additions & 59 deletions src/Accounts/Accounts.Test/AzureRMProfileTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.Common.Authentication;
// TODO: Remove IfDef
#if NETSTANDARD
using Microsoft.Azure.Commands.Common.Authentication.Core;
#endif
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Factories;
using Microsoft.Azure.Commands.Common.Authentication.Models;
Expand Down Expand Up @@ -497,19 +493,6 @@ public void NoSubscriptionsInListDoesNotThrow()
Assert.False(client.TryGetSubscriptionByName(DefaultTenant.ToString(), "random-name", out subValue));
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void SetContextPreservesTokenCache()
{
AzureRmProfile profile = null;
AzureContext context = new AzureContext(null, null, null, null);
Assert.Throws<ArgumentNullException>(() => profile.SetContextWithCache(context));
profile = new AzureRmProfile();
Assert.Throws<ArgumentNullException>(() => profile.SetContextWithCache(null));
profile.SetContextWithCache(context);
Assert.Equal(AzureSession.Instance.TokenCache.CacheData, profile.DefaultContext.TokenCache.CacheData);
}

[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void AzurePSComletMessageQueue()
Expand Down Expand Up @@ -547,15 +530,15 @@ public void GetAzureRmSubscriptionPaginatedResult()
var profile = new AzureRmProfile();
profile.EnvironmentTable.Add("foo", new AzureEnvironment(AzureEnvironment.PublicEnvironments.Values.FirstOrDefault()));
profile.DefaultContext = Context;
var cmdlt = new GetAzureRMSubscriptionCommand();
var cmdlet = new GetAzureRMSubscriptionCommand();
// Setup
cmdlt.DefaultProfile = profile;
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlet.DefaultProfile = profile;
cmdlet.CommandRuntime = commandRuntimeMock;

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

var subscriptionName = MockSubscriptionClientFactory.GetSubscriptionNameFromId(secondList[0]);

Expand Down Expand Up @@ -593,16 +576,16 @@ public void GetAzureRmSubscriptionByIdMultiplePages()
var profile = new AzureRmProfile();
profile.EnvironmentTable.Add("foo", new AzureEnvironment(AzureEnvironment.PublicEnvironments.Values.FirstOrDefault()));
profile.DefaultContext = Context;
var cmdlt = new GetAzureRMSubscriptionCommand();
var cmdlet = new GetAzureRMSubscriptionCommand();
// Setup
cmdlt.DefaultProfile = profile;
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.SubscriptionId = secondTenantSubscriptions[2];
cmdlet.DefaultProfile = profile;
cmdlet.CommandRuntime = commandRuntimeMock;
cmdlet.SubscriptionId = secondTenantSubscriptions[2];

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

Assert.True(commandRuntimeMock.OutputPipeline.Count == 1);

Expand Down Expand Up @@ -643,16 +626,16 @@ public void GetAzureRmSubscriptionByNameMultiplePages()
var profile = new AzureRmProfile();
profile.EnvironmentTable.Add("foo", new AzureEnvironment(AzureEnvironment.PublicEnvironments.Values.FirstOrDefault()));
profile.DefaultContext = Context;
var cmdlt = new GetAzureRMSubscriptionCommand();
var cmdlet = new GetAzureRMSubscriptionCommand();
// Setup
cmdlt.DefaultProfile = profile;
cmdlt.CommandRuntime = commandRuntimeMock;
cmdlt.SubscriptionName = subscriptionName;
cmdlet.DefaultProfile = profile;
cmdlet.CommandRuntime = commandRuntimeMock;
cmdlet.SubscriptionName = subscriptionName;

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

Assert.True(commandRuntimeMock.OutputPipeline.Count == 1);

Expand Down Expand Up @@ -696,16 +679,16 @@ public void GetAzureRmSubscriptionManagedService()
profile.DefaultContext.Tenant.Id = DefaultTenant.ToString();

profile.DefaultContext.Account.Type = "User";
var cmdlt = new GetAzureRMSubscriptionCommand();
var cmdlet = new GetAzureRMSubscriptionCommand();
// Setup
cmdlt.DefaultProfile = profile;
cmdlt.CommandRuntime = commandRuntimeMock;
Assert.Null(cmdlt.TenantId);
cmdlet.DefaultProfile = profile;
cmdlet.CommandRuntime = commandRuntimeMock;
Assert.Null(cmdlet.TenantId);
// Act
cmdlt.InvokeBeginProcessing();
cmdlt.ExecuteCmdlet();
cmdlt.InvokeEndProcessing();
Assert.Null(cmdlt.TenantId);
cmdlet.InvokeBeginProcessing();
cmdlet.ExecuteCmdlet();
cmdlet.InvokeEndProcessing();
Assert.Null(cmdlet.TenantId);
Assert.True(commandRuntimeMock.OutputPipeline.Count == 8);

// TEST WITH MANAGEDSERVICE
Expand All @@ -722,16 +705,16 @@ public void GetAzureRmSubscriptionManagedService()
profile.DefaultContext.Tenant.Id = DefaultTenant.ToString();

profile.DefaultContext.Account.Type = "ManagedService";
cmdlt = new GetAzureRMSubscriptionCommand();
cmdlet = new GetAzureRMSubscriptionCommand();
// Setup
cmdlt.DefaultProfile = profile;
cmdlt.CommandRuntime = commandRuntimeMock;
Assert.Null(cmdlt.TenantId);
cmdlet.DefaultProfile = profile;
cmdlet.CommandRuntime = commandRuntimeMock;
Assert.Null(cmdlet.TenantId);
// Act
cmdlt.InvokeBeginProcessing();
cmdlt.ExecuteCmdlet();
cmdlt.InvokeEndProcessing();
Assert.NotNull(cmdlt.TenantId);
cmdlet.InvokeBeginProcessing();
cmdlet.ExecuteCmdlet();
cmdlet.InvokeEndProcessing();
Assert.NotNull(cmdlet.TenantId);
Assert.True(commandRuntimeMock.OutputPipeline.Count == 4);
}

Expand Down Expand Up @@ -778,7 +761,7 @@ public void ProfileSerializeDeserializeWorks()

currentProfile.DefaultContext = new AzureContext(sub, account, environment, tenant);
currentProfile.EnvironmentTable[environment.Name] = environment;
currentProfile.DefaultContext.TokenCache = new AzureTokenCache { CacheData = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 } };
currentProfile.DefaultContext.TokenCache = null;

AzureRmProfile deserializedProfile;
// Round-trip the exception: Serialize and de-serialize with a BinaryFormatter
Expand Down Expand Up @@ -900,9 +883,7 @@ public void SavingProfileWorks()
}
},
""VersionProfile"": null,
""TokenCache"": {
""CacheData"": ""AgAAAAAAAAA=""
},
""TokenCache"": null,
""ExtendedProperties"": {}
}
},
Expand Down Expand Up @@ -945,7 +926,6 @@ public void SavingProfileWorks()
};
profile.DefaultContext = new AzureContext(sub, account, environment, tenant);
profile.EnvironmentTable[environment.Name] = environment;
profile.DefaultContext.TokenCache = new AuthenticationStoreTokenCache(new AzureTokenCache { CacheData = new byte[] { 1, 2, 3, 4, 5, 6, 8, 9, 0 } });
profile.Save();
string actual = dataStore.ReadFileAsText(path).Substring(1).TrimEnd(new[] { '\0' });
#if NETSTANDARD
Expand Down Expand Up @@ -1013,7 +993,6 @@ public void LoadingProfileWorks()
Assert.Equal("testCloud", profile.DefaultContext.Environment.Name);
Assert.Equal("me@contoso.com", profile.DefaultContext.Account.Id);
Assert.Equal(AzureAccount.AccountType.User, profile.DefaultContext.Account.Type);
Assert.Null(profile.DefaultContext.TokenCache.CacheData); // token cache is handled by MSAL extensions lib, we don't possess it anymore
Assert.Equal(path, profile.ProfilePath);
}

Expand Down
1 change: 0 additions & 1 deletion src/Accounts/Accounts.Test/ContextCmdletTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,6 @@ public void ClearMultipleContexts()
Assert.NotNull(profile.DefaultContext);
Assert.Null(profile.DefaultContext.Account);
Assert.Null(profile.DefaultContext.Subscription);
Assert.NotNull(profile.DefaultContext.TokenCache);
}

[Fact]
Expand Down
32 changes: 27 additions & 5 deletions src/Accounts/Accounts/Account/ConnectAzureRmAccount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
using System.Threading;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Extensions.Msal;

namespace Microsoft.Azure.Commands.Profile
{
Expand Down Expand Up @@ -485,16 +486,37 @@ public void OnImport()
AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => builder);
}

AuthenticationClientFactory factory = null;
if (autoSaveEnabled)
{
AuthenticationClientFactory factory = new SharedTokenCacheClientFactory();
AzureSession.Instance.RegisterComponent(AuthenticationClientFactory.AuthenticationClientFactoryKey, () => factory);
try
{
factory = new SharedTokenCacheClientFactory();
}
catch (MsalCachePersistenceException)
{
// If token cache persistence is not supported, fall back to in-memory, and print a warning
// Cannot throw exception here because it is not displayed when user runs a cmdlet
// it only shows up when manually ipmo az.accounts, so it's useless
ModifyContext((profile, client) =>
{
AzureSession.Modify(session => {
FileUtilities.DataStore = session.DataStore;
session.ARMContextSaveMode = ContextSaveMode.Process;
});
});
autoSaveEnabled = false;
WriteInitializationWarnings(Resources.AutosaveNotSupportedWithFallback);
}
}
else

// if autosave is disabled, or the shared factory fails to initialize, we fallback to in memory
if (!autoSaveEnabled)
{
AuthenticationClientFactory factory = new InMemoryTokenCacheClientFactory();
AzureSession.Instance.RegisterComponent(AuthenticationClientFactory.AuthenticationClientFactoryKey, () => factory);
factory = new InMemoryTokenCacheClientFactory();

}
AzureSession.Instance.RegisterComponent(AuthenticationClientFactory.AuthenticationClientFactoryKey, () => factory);
#if DEBUG
}
catch (Exception) when (TestMockSupport.RunningMocked)
Expand Down
2 changes: 1 addition & 1 deletion src/Accounts/Accounts/Account/DisconnectAzureRmAccount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ public override void ExecuteCmdlet()
{
if (GetContextModificationScope() == ContextModificationScope.CurrentUser)
{
AzureSession.Instance.AuthenticationFactory.RemoveUser(azureAccount, AzureSession.Instance.TokenCache);
AzureSession.Instance.AuthenticationFactory.RemoveUser(azureAccount, null);
}

if (AzureRmProfileProvider.Instance.Profile != null)
Expand Down
19 changes: 1 addition & 18 deletions src/Accounts/Accounts/AutoSave/DisableAzureRmContextAutosave.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,6 @@
// ----------------------------------------------------------------------------------

using Microsoft.Azure.Commands.Common.Authentication;
// TODO: Remove IfDef
#if NETSTANDARD
using Microsoft.Azure.Commands.Common.Authentication.Core;
#endif
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Profile.Common;
using Microsoft.Azure.Commands.ResourceManager.Common;
Expand Down Expand Up @@ -68,7 +64,6 @@ public override void ExecuteCmdlet()

void DisableAutosave(IAzureSession session, bool writeAutoSaveFile, out ContextAutosaveSettings result)
{
var store = session.DataStore;
string tokenPath = Path.Combine(session.TokenCacheDirectory, session.TokenCacheFile);
result = new ContextAutosaveSettings
{
Expand All @@ -77,19 +72,7 @@ void DisableAutosave(IAzureSession session, bool writeAutoSaveFile, out ContextA

FileUtilities.DataStore = session.DataStore;
session.ARMContextSaveMode = ContextSaveMode.Process;
var memoryCache = session.TokenCache as AuthenticationStoreTokenCache;
if (memoryCache == null)
{
var diskCache = session.TokenCache as ProtectedFileTokenCache;
memoryCache = new AuthenticationStoreTokenCache(new AzureTokenCache());
if (diskCache != null)
{
memoryCache.CacheData = diskCache.CacheData;
}

session.TokenCache = memoryCache;
}


AuthenticationClientFactory authenticationClientFactory = new InMemoryTokenCacheClientFactory();
if (AzureSession.Instance.TryGetComponent(
AuthenticationClientFactory.AuthenticationClientFactoryKey,
Expand Down
Loading