Skip to content

Fix error happens if there's no write permission to user profile path #13416

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 10, 2020
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
43 changes: 29 additions & 14 deletions src/Accounts/Accounts/Account/ConnectAzureRmAccount.cs
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,11 @@ public override void ExecuteCmdlet()
}
else
{
WriteWarning(Resources.SuggestToUseDeviceCodeAuth);
if (ParameterSetName == UserParameterSet && UseDeviceAuthentication == false)
{
//Display only if user is using Interactive auth
WriteWarning(Resources.SuggestToUseDeviceCodeAuth);
}
WriteDebug(ex.ToString());
throw;
}
Expand Down Expand Up @@ -489,23 +493,24 @@ private void SetContextWithOverwritePrompt(Action<AzureRmProfile, RMProfileClien
originalShouldRefreshContextsFromCache = profile.ShouldRefreshContextsFromCache;
profile.ShouldRefreshContextsFromCache = false;
}
if (!CheckForExistingContext(profile, name)
|| Force.IsPresent
|| ShouldContinue(string.Format(Resources.ReplaceContextQuery, name),
string.Format(Resources.ReplaceContextCaption, name)))
{
ModifyContext((prof, client) => setContextAction(prof, client, name));
if (!CheckForExistingContext(profile, name)
|| Force.IsPresent
|| ShouldContinue(string.Format(Resources.ReplaceContextQuery, name),
string.Format(Resources.ReplaceContextCaption, name)))
{
ModifyContext((prof, client) => setContextAction(prof, client, name));
}
}
}
finally
{
if(profile != null && originalShouldRefreshContextsFromCache.HasValue)
if (profile != null && originalShouldRefreshContextsFromCache.HasValue)
{
profile.ShouldRefreshContextsFromCache = originalShouldRefreshContextsFromCache.Value;
}
}
}

//This method may throw exception because of permission issue, exception should be handled from caller
private static IAzureContextContainer GetAzureContextContainer()
{
var provider = new ProtectedProfileProvider();
Expand All @@ -522,7 +527,7 @@ public void OnImport()
{
#endif
AzureSessionInitializer.InitializeAzureSession();
AzureSessionInitializer.MigrateAdalCache(AzureSession.Instance, GetAzureContextContainer);
AzureSessionInitializer.MigrateAdalCache(AzureSession.Instance, GetAzureContextContainer, WriteInitializationWarnings);
#if DEBUG
if (!TestMockSupport.RunningMocked)
{
Expand All @@ -540,11 +545,21 @@ public void OnImport()
autoSaveEnabled = localAutosave;
}

if (autoSaveEnabled && !SharedTokenCacheProvider.SupportCachePersistence(out string message))
try
{
if (autoSaveEnabled && !SharedTokenCacheProvider.SupportCachePersistence(out string message))
{
// If token cache persistence is not supported, fall back to plain text persistence, and print a warning
// We cannot just throw an exception here because this is called when importing the module
WriteInitializationWarnings(Resources.TokenCacheEncryptionNotSupportedWithFallback);
}
}
catch(Exception ex)
{
// If token cache persistence is not supported, fall back to plain text persistence, and print a warning
// We cannot just throw an exception here because this is called when importing the module
WriteInitializationWarnings(Resources.TokenCacheEncryptionNotSupportedWithFallback);
//Likely the exception is related permission, fall back context save mode to process
autoSaveEnabled = false;
AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process;
WriteInitializationWarnings(Resources.FallbackContextSaveModeDueCacheCheckError.FormatInvariant(ex.Message));
}

if(!InitializeProfileProvider(autoSaveEnabled))
Expand Down
1 change: 1 addition & 0 deletions src/Accounts/Accounts/ChangeLog.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
- Additional information about change #1
-->
## Upcoming Release
* Fixed an issue that error happens if user profile path is inaccessible
* Fixed an issue causing Write-Object error during Connect-AzAccount [#13419]
* Added parameter "ContainerRegistryEndpointSuffix" to: `Add-AzEnvironment`, `Set-AzEnvironment`
* Supported interrupting login by hitting <kbd>CTRL</kbd>+<kbd>C</kbd>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,12 +127,9 @@ internal bool InitializeProfileProvider(bool useAutoSaveProfile = false)
{
ProtectedProfileProvider.InitializeResourceManagerProfile();
}
catch (SystemException e)
catch (Exception e)
{
if (!(e is IOException) && !(e is UnauthorizedAccessException))
{
throw e;
}
//Likely the exception is related to IO or permission, fallback to Process save mode
WriteInitializationWarnings(string.Format(Resources.ProfileFileNotAccessible, e.Message));
ResourceManagerProfileProvider.InitializeResourceManagerProfile(true);
}
Expand Down
13 changes: 11 additions & 2 deletions src/Accounts/Accounts/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions src/Accounts/Accounts/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -496,10 +496,10 @@
<value>Context autosave is not supported in current environment. Please disable it using 'Disable-AzContextSave'.</value>
</data>
<data name="TokenCacheEncryptionNotSupportedWithFallback" xml:space="preserve">
<value>Token cache encryption is not supported in current environment and token cache will be fallen back as plain text.</value>
<value>INITIALIZATION: Token cache encryption is not supported in current environment and token cache will be fallen back as plain text.</value>
</data>
<data name="ProfileFileNotAccessible" xml:space="preserve">
<value>Fail to access profile file and will try to use process ContextAutosaveSetting mode. Detailed error: '{0}'</value>
<value>INITIALIZATION: Fail to access profile file and will try to use process ContextAutosaveSetting mode. Detailed error: '{0}'</value>
</data>
<data name="AzurePowerShellFeedback" xml:space="preserve">
<value>The Azure PowerShell team is listening, please let us know how we are doing: {0}.</value>
Expand All @@ -519,4 +519,7 @@
<data name="SuggestToUseDeviceCodeAuth" xml:space="preserve">
<value>Please run 'Connect-AzAccount -DeviceCode' if browser is not supported in this session.</value>
</data>
<data name="FallbackContextSaveModeDueCacheCheckError" xml:space="preserve">
<value>INITIALIZATION: Fallback context save mode to process because of error during checking token cache persistence: {0}.</value>
</data>
</root>
61 changes: 34 additions & 27 deletions src/Accounts/Authentication/AzureSessionInitializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,39 +99,46 @@ static bool MigrateSettings(IDataStore store, string oldProfileDirectory, string
return false;
}

public static void MigrateAdalCache(IAzureSession session, Func<IAzureContextContainer> getContextContainer)
public static void MigrateAdalCache(IAzureSession session, Func<IAzureContextContainer> getContextContainer, Action<string> writeWarning)
{
if (session.ARMContextSaveMode == ContextSaveMode.Process)
try
{
// Don't attempt to migrate if context autosave is disabled
return;
}
if (session.ARMContextSaveMode == ContextSaveMode.Process)
{
// Don't attempt to migrate if context autosave is disabled
return;
}

var adalCachePath = Path.Combine(session.ProfileDirectory, "TokenCache.dat");
var msalCachePath = Path.Combine(session.TokenCacheDirectory, "msal.cache");
var store = session.DataStore;
if (!store.FileExists(adalCachePath) || store.FileExists(msalCachePath))
{
// Return if
// (1) The ADAL cache doesn't exist (nothing to migrate), or
// (2) The MSAL cache does exist (don't override existing cache)
return;
}
var adalCachePath = Path.Combine(session.ProfileDirectory, "TokenCache.dat");
var msalCachePath = Path.Combine(session.TokenCacheDirectory, "msal.cache");
var store = session.DataStore;
if (!store.FileExists(adalCachePath) || store.FileExists(msalCachePath))
{
// Return if
// (1) The ADAL cache doesn't exist (nothing to migrate), or
// (2) The MSAL cache does exist (don't override existing cache)
return;
}

byte[] adalData;
try
{
adalData = File.ReadAllBytes(adalCachePath);
}
catch
{
// Return if there was an error converting the ADAL data safely
return;
}
byte[] adalData;
try
{
adalData = File.ReadAllBytes(adalCachePath);
}
catch
{
// Return if there was an error converting the ADAL data safely
return;
}

if(adalData != null && adalData.Length > 0)
if (adalData != null && adalData.Length > 0)
{
new AdalTokenMigrator(adalData, getContextContainer).MigrateFromAdalToMsal();
}
}
catch(Exception e)
{
new AdalTokenMigrator(adalData, getContextContainer).MigrateFromAdalToMsal();
writeWarning(Resources.FailedToMigrateAdal2Msal.FormatInvariant(e.Message));
}
}

Expand Down
9 changes: 9 additions & 0 deletions src/Accounts/Authentication/Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions src/Accounts/Authentication/Properties/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -352,13 +352,13 @@
<data name="UnableToLaunchBrowser" xml:space="preserve">
<value>Unable to launch a browser for authorization code login. Reverting to device code login.</value>
</data>
<data name="EnvironmentNotFound" xml:space="preserve">
<value>The environment name '{0}' is not found.</value>
</data>
<data name="AutosaveNotSupportedWithSuggestion" xml:space="preserve">
<value>Context autosave is not supported on current environment. Please disable it using 'Disable-AzContextSave'.</value>
</data>
<data name="MissingPasswordAndNoCache" xml:space="preserve">
<value>Password is missing and no cache found for the current user.</value>
</data>
<data name="FailedToMigrateAdal2Msal" xml:space="preserve">
<value>INITIALZATION: Failed to migrate ADAL token to MSAL token with error : {0}</value>
</data>
</root>