Skip to content

Commit 9733f5e

Browse files
erich-wangisra-fel
andauthored
fix issue that error happens if there's no write permission to user profile path (#13416)
Co-authored-by: Yeming Liu <[email protected]>
1 parent e8fd3c6 commit 9733f5e

File tree

8 files changed

+94
-53
lines changed

8 files changed

+94
-53
lines changed

src/Accounts/Accounts/Account/ConnectAzureRmAccount.cs

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -431,7 +431,11 @@ public override void ExecuteCmdlet()
431431
}
432432
else
433433
{
434-
WriteWarning(Resources.SuggestToUseDeviceCodeAuth);
434+
if (ParameterSetName == UserParameterSet && UseDeviceAuthentication == false)
435+
{
436+
//Display only if user is using Interactive auth
437+
WriteWarning(Resources.SuggestToUseDeviceCodeAuth);
438+
}
435439
WriteDebug(ex.ToString());
436440
throw;
437441
}
@@ -489,23 +493,24 @@ private void SetContextWithOverwritePrompt(Action<AzureRmProfile, RMProfileClien
489493
originalShouldRefreshContextsFromCache = profile.ShouldRefreshContextsFromCache;
490494
profile.ShouldRefreshContextsFromCache = false;
491495
}
492-
if (!CheckForExistingContext(profile, name)
493-
|| Force.IsPresent
494-
|| ShouldContinue(string.Format(Resources.ReplaceContextQuery, name),
495-
string.Format(Resources.ReplaceContextCaption, name)))
496-
{
497-
ModifyContext((prof, client) => setContextAction(prof, client, name));
496+
if (!CheckForExistingContext(profile, name)
497+
|| Force.IsPresent
498+
|| ShouldContinue(string.Format(Resources.ReplaceContextQuery, name),
499+
string.Format(Resources.ReplaceContextCaption, name)))
500+
{
501+
ModifyContext((prof, client) => setContextAction(prof, client, name));
502+
}
498503
}
499-
}
500504
finally
501505
{
502-
if(profile != null && originalShouldRefreshContextsFromCache.HasValue)
506+
if (profile != null && originalShouldRefreshContextsFromCache.HasValue)
503507
{
504508
profile.ShouldRefreshContextsFromCache = originalShouldRefreshContextsFromCache.Value;
505509
}
506510
}
507511
}
508512

513+
//This method may throw exception because of permission issue, exception should be handled from caller
509514
private static IAzureContextContainer GetAzureContextContainer()
510515
{
511516
var provider = new ProtectedProfileProvider();
@@ -522,7 +527,7 @@ public void OnImport()
522527
{
523528
#endif
524529
AzureSessionInitializer.InitializeAzureSession();
525-
AzureSessionInitializer.MigrateAdalCache(AzureSession.Instance, GetAzureContextContainer);
530+
AzureSessionInitializer.MigrateAdalCache(AzureSession.Instance, GetAzureContextContainer, WriteInitializationWarnings);
526531
#if DEBUG
527532
if (!TestMockSupport.RunningMocked)
528533
{
@@ -540,11 +545,21 @@ public void OnImport()
540545
autoSaveEnabled = localAutosave;
541546
}
542547

543-
if (autoSaveEnabled && !SharedTokenCacheProvider.SupportCachePersistence(out string message))
548+
try
549+
{
550+
if (autoSaveEnabled && !SharedTokenCacheProvider.SupportCachePersistence(out string message))
551+
{
552+
// If token cache persistence is not supported, fall back to plain text persistence, and print a warning
553+
// We cannot just throw an exception here because this is called when importing the module
554+
WriteInitializationWarnings(Resources.TokenCacheEncryptionNotSupportedWithFallback);
555+
}
556+
}
557+
catch(Exception ex)
544558
{
545-
// If token cache persistence is not supported, fall back to plain text persistence, and print a warning
546-
// We cannot just throw an exception here because this is called when importing the module
547-
WriteInitializationWarnings(Resources.TokenCacheEncryptionNotSupportedWithFallback);
559+
//Likely the exception is related permission, fall back context save mode to process
560+
autoSaveEnabled = false;
561+
AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process;
562+
WriteInitializationWarnings(Resources.FallbackContextSaveModeDueCacheCheckError.FormatInvariant(ex.Message));
548563
}
549564

550565
if(!InitializeProfileProvider(autoSaveEnabled))

src/Accounts/Accounts/ChangeLog.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
- Additional information about change #1
1919
-->
2020
## Upcoming Release
21+
* Fixed an issue that error happens if user profile path is inaccessible
2122
* Fixed an issue causing Write-Object error during Connect-AzAccount [#13419]
2223
* Added parameter "ContainerRegistryEndpointSuffix" to: `Add-AzEnvironment`, `Set-AzEnvironment`
2324
* Supported interrupting login by hitting <kbd>CTRL</kbd>+<kbd>C</kbd>

src/Accounts/Accounts/Common/AzureContextModificationCmdlet.cs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -127,12 +127,9 @@ internal bool InitializeProfileProvider(bool useAutoSaveProfile = false)
127127
{
128128
ProtectedProfileProvider.InitializeResourceManagerProfile();
129129
}
130-
catch (SystemException e)
130+
catch (Exception e)
131131
{
132-
if (!(e is IOException) && !(e is UnauthorizedAccessException))
133-
{
134-
throw e;
135-
}
132+
//Likely the exception is related to IO or permission, fallback to Process save mode
136133
WriteInitializationWarnings(string.Format(Resources.ProfileFileNotAccessible, e.Message));
137134
ResourceManagerProfileProvider.InitializeResourceManagerProfile(true);
138135
}

src/Accounts/Accounts/Properties/Resources.Designer.cs

Lines changed: 11 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Accounts/Accounts/Properties/Resources.resx

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -496,10 +496,10 @@
496496
<value>Context autosave is not supported in current environment. Please disable it using 'Disable-AzContextSave'.</value>
497497
</data>
498498
<data name="TokenCacheEncryptionNotSupportedWithFallback" xml:space="preserve">
499-
<value>Token cache encryption is not supported in current environment and token cache will be fallen back as plain text.</value>
499+
<value>INITIALIZATION: Token cache encryption is not supported in current environment and token cache will be fallen back as plain text.</value>
500500
</data>
501501
<data name="ProfileFileNotAccessible" xml:space="preserve">
502-
<value>Fail to access profile file and will try to use process ContextAutosaveSetting mode. Detailed error: '{0}'</value>
502+
<value>INITIALIZATION: Fail to access profile file and will try to use process ContextAutosaveSetting mode. Detailed error: '{0}'</value>
503503
</data>
504504
<data name="AzurePowerShellFeedback" xml:space="preserve">
505505
<value>The Azure PowerShell team is listening, please let us know how we are doing: {0}.</value>
@@ -519,4 +519,7 @@
519519
<data name="SuggestToUseDeviceCodeAuth" xml:space="preserve">
520520
<value>Please run 'Connect-AzAccount -DeviceCode' if browser is not supported in this session.</value>
521521
</data>
522+
<data name="FallbackContextSaveModeDueCacheCheckError" xml:space="preserve">
523+
<value>INITIALIZATION: Fallback context save mode to process because of error during checking token cache persistence: {0}.</value>
524+
</data>
522525
</root>

src/Accounts/Authentication/AzureSessionInitializer.cs

Lines changed: 34 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -99,39 +99,46 @@ static bool MigrateSettings(IDataStore store, string oldProfileDirectory, string
9999
return false;
100100
}
101101

102-
public static void MigrateAdalCache(IAzureSession session, Func<IAzureContextContainer> getContextContainer)
102+
public static void MigrateAdalCache(IAzureSession session, Func<IAzureContextContainer> getContextContainer, Action<string> writeWarning)
103103
{
104-
if (session.ARMContextSaveMode == ContextSaveMode.Process)
104+
try
105105
{
106-
// Don't attempt to migrate if context autosave is disabled
107-
return;
108-
}
106+
if (session.ARMContextSaveMode == ContextSaveMode.Process)
107+
{
108+
// Don't attempt to migrate if context autosave is disabled
109+
return;
110+
}
109111

110-
var adalCachePath = Path.Combine(session.ProfileDirectory, "TokenCache.dat");
111-
var msalCachePath = Path.Combine(session.TokenCacheDirectory, "msal.cache");
112-
var store = session.DataStore;
113-
if (!store.FileExists(adalCachePath) || store.FileExists(msalCachePath))
114-
{
115-
// Return if
116-
// (1) The ADAL cache doesn't exist (nothing to migrate), or
117-
// (2) The MSAL cache does exist (don't override existing cache)
118-
return;
119-
}
112+
var adalCachePath = Path.Combine(session.ProfileDirectory, "TokenCache.dat");
113+
var msalCachePath = Path.Combine(session.TokenCacheDirectory, "msal.cache");
114+
var store = session.DataStore;
115+
if (!store.FileExists(adalCachePath) || store.FileExists(msalCachePath))
116+
{
117+
// Return if
118+
// (1) The ADAL cache doesn't exist (nothing to migrate), or
119+
// (2) The MSAL cache does exist (don't override existing cache)
120+
return;
121+
}
120122

121-
byte[] adalData;
122-
try
123-
{
124-
adalData = File.ReadAllBytes(adalCachePath);
125-
}
126-
catch
127-
{
128-
// Return if there was an error converting the ADAL data safely
129-
return;
130-
}
123+
byte[] adalData;
124+
try
125+
{
126+
adalData = File.ReadAllBytes(adalCachePath);
127+
}
128+
catch
129+
{
130+
// Return if there was an error converting the ADAL data safely
131+
return;
132+
}
131133

132-
if(adalData != null && adalData.Length > 0)
134+
if (adalData != null && adalData.Length > 0)
135+
{
136+
new AdalTokenMigrator(adalData, getContextContainer).MigrateFromAdalToMsal();
137+
}
138+
}
139+
catch(Exception e)
133140
{
134-
new AdalTokenMigrator(adalData, getContextContainer).MigrateFromAdalToMsal();
141+
writeWarning(Resources.FailedToMigrateAdal2Msal.FormatInvariant(e.Message));
135142
}
136143
}
137144

src/Accounts/Authentication/Properties/Resources.Designer.cs

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/Accounts/Authentication/Properties/Resources.resx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -352,13 +352,13 @@
352352
<data name="UnableToLaunchBrowser" xml:space="preserve">
353353
<value>Unable to launch a browser for authorization code login. Reverting to device code login.</value>
354354
</data>
355-
<data name="EnvironmentNotFound" xml:space="preserve">
356-
<value>The environment name '{0}' is not found.</value>
357-
</data>
358355
<data name="AutosaveNotSupportedWithSuggestion" xml:space="preserve">
359356
<value>Context autosave is not supported on current environment. Please disable it using 'Disable-AzContextSave'.</value>
360357
</data>
361358
<data name="MissingPasswordAndNoCache" xml:space="preserve">
362359
<value>Password is missing and no cache found for the current user.</value>
363360
</data>
361+
<data name="FailedToMigrateAdal2Msal" xml:space="preserve">
362+
<value>INITIALZATION: Failed to migrate ADAL token to MSAL token with error : {0}</value>
363+
</data>
364364
</root>

0 commit comments

Comments
 (0)