Skip to content

Commit 4b391f1

Browse files
committed
fix issue that error happens if there's no write permission to user profile path
1 parent be89fc1 commit 4b391f1

File tree

8 files changed

+99
-58
lines changed

8 files changed

+99
-58
lines changed

src/Accounts/Accounts/Account/ConnectAzureRmAccount.cs

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -416,7 +416,11 @@ public override void ExecuteCmdlet()
416416
}
417417
else
418418
{
419-
WriteWarning(Resources.SuggestToUseDeviceCodeAuth);
419+
if (ParameterSetName == UserParameterSet && UseDeviceAuthentication == false)
420+
{
421+
//Display only if user is using Interactive auth
422+
WriteWarning(Resources.SuggestToUseDeviceCodeAuth);
423+
}
420424
WriteDebug(ex.ToString());
421425
throw;
422426
}
@@ -474,23 +478,24 @@ private void SetContextWithOverwritePrompt(Action<AzureRmProfile, RMProfileClien
474478
originalShouldRefreshContextsFromCache = profile.ShouldRefreshContextsFromCache;
475479
profile.ShouldRefreshContextsFromCache = false;
476480
}
477-
if (!CheckForExistingContext(profile, name)
478-
|| Force.IsPresent
479-
|| ShouldContinue(string.Format(Resources.ReplaceContextQuery, name),
480-
string.Format(Resources.ReplaceContextCaption, name)))
481-
{
482-
ModifyContext((prof, client) => setContextAction(prof, client, name));
481+
if (!CheckForExistingContext(profile, name)
482+
|| Force.IsPresent
483+
|| ShouldContinue(string.Format(Resources.ReplaceContextQuery, name),
484+
string.Format(Resources.ReplaceContextCaption, name)))
485+
{
486+
ModifyContext((prof, client) => setContextAction(prof, client, name));
487+
}
483488
}
484-
}
485489
finally
486490
{
487-
if(profile != null && originalShouldRefreshContextsFromCache.HasValue)
491+
if (profile != null && originalShouldRefreshContextsFromCache.HasValue)
488492
{
489493
profile.ShouldRefreshContextsFromCache = originalShouldRefreshContextsFromCache.Value;
490494
}
491495
}
492496
}
493497

498+
//This method may throw exception because of permission issue, exception should be handled from caller
494499
private static IAzureContextContainer GetAzureContextContainer()
495500
{
496501
var provider = new ProtectedProfileProvider();
@@ -507,7 +512,7 @@ public void OnImport()
507512
{
508513
#endif
509514
AzureSessionInitializer.InitializeAzureSession();
510-
AzureSessionInitializer.MigrateAdalCache(AzureSession.Instance, GetAzureContextContainer);
515+
AzureSessionInitializer.MigrateAdalCache(AzureSession.Instance, GetAzureContextContainer, WriteInitializationWarnings);
511516
#if DEBUG
512517
if (!TestMockSupport.RunningMocked)
513518
{
@@ -525,11 +530,21 @@ public void OnImport()
525530
autoSaveEnabled = localAutosave;
526531
}
527532

528-
if (autoSaveEnabled && !SharedTokenCacheProvider.SupportCachePersistence(out string message))
533+
try
534+
{
535+
if (autoSaveEnabled && !SharedTokenCacheProvider.SupportCachePersistence(out string message))
536+
{
537+
// If token cache persistence is not supported, fall back to plain text persistence, and print a warning
538+
// We cannot just throw an exception here because this is called when importing the module
539+
WriteInitializationWarnings(Resources.TokenCacheEncryptionNotSupportedWithFallback);
540+
}
541+
}
542+
catch(Exception ex)
529543
{
530-
// If token cache persistence is not supported, fall back to plain text persistence, and print a warning
531-
// We cannot just throw an exception here because this is called when importing the module
532-
WriteInitializationWarnings(Resources.TokenCacheEncryptionNotSupportedWithFallback);
544+
//Likely the exception is related permission, fall back context save mode to process
545+
autoSaveEnabled = false;
546+
AzureSession.Instance.ARMContextSaveMode = ContextSaveMode.Process;
547+
WriteInitializationWarnings(Resources.FallbackContextSaveModeDueCacheCheckError.FormatInvariant(ex.Message));
533548
}
534549

535550
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 `Connect-AzAccount -KeyVaultAccessToken` not working [#13127]
2223
* Fixed null reference and method case insensitive in `Invoke-AzRestMethod`
2324

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: 14 additions & 5 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)