public void InitializerCreatesTokenCacheFile() { AzureSessionInitializer.InitializeAzureSession(); IAzureSession oldSession = null; try { oldSession = AzureSession.Instance; } catch { } try { var store = new MemoryDataStore(); var path = Path.Combine(AzureSession.Instance.ARMProfileDirectory, ContextAutosaveSettings.AutoSaveSettingsFile); var settings = new ContextAutosaveSettings { Mode = ContextSaveMode.CurrentUser }; var content = JsonConvert.SerializeObject(settings); store.VirtualStore[path] = content; AzureSessionInitializer.CreateOrReplaceSession(store); var session = AzureSession.Instance; var tokenCacheFile = Path.Combine(session.ProfileDirectory, session.TokenCacheFile); Assert.True(store.FileExists(tokenCacheFile)); } finally { AzureSession.Initialize(() => oldSession, true); } }
protected void DisableAutosave(IAzureSession session, bool writeAutoSaveFile, out ContextAutosaveSettings result) { var store = session.DataStore; string tokenPath = Path.Combine(session.TokenCacheDirectory, session.TokenCacheFile); result = new ContextAutosaveSettings { Mode = ContextSaveMode.Process }; 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 && diskCache.Count > 0) { memoryCache.Deserialize(diskCache.Serialize()); } session.TokenCache = memoryCache; } if (writeAutoSaveFile) { FileUtilities.EnsureDirectoryExists(session.ProfileDirectory); string autoSavePath = Path.Combine(session.ProfileDirectory, ContextAutosaveSettings.AutoSaveSettingsFile); session.DataStore.WriteFile(autoSavePath, JsonConvert.SerializeObject(result)); } }
/// <summary> /// Initialize the AzureSession, avoid contention at startup /// </summary> /// <param name="instance">The instance of AzureSession to use</param> /// <param name="overwrite">If true, always overwrite the current instance. Otherwise do not initialize</param> public static void Initialize(Func <IAzureSession> instanceCreator, bool overwrite) { try { sessionLock.EnterWriteLock(); try { if (overwrite || !_initialized) { _instance = instanceCreator(); _initialized = true; } } finally { sessionLock.ExitWriteLock(); } } catch (LockRecursionException lockException) { throw new InvalidOperationException(Abstractions.Properties.Resources.SessionLockWriteRecursion, lockException); } catch (ObjectDisposedException disposedException) { throw new InvalidOperationException(Abstractions.Properties.Resources.SessionLockWriteDisposed, disposedException); } }
void EnableAutosave(IAzureSession session, bool writeAutoSaveFile, out ContextAutosaveSettings result) { var store = session.DataStore; string contextPath = Path.Combine(session.ARMProfileDirectory, session.ARMProfileFile); string tokenPath = Path.Combine(session.TokenCacheDirectory, session.TokenCacheFile); if (!IsValidPath(contextPath)) { throw new PSInvalidOperationException(string.Format("'{0}' is not a valid path. You cannot enable context autosave without a valid context path", contextPath)); } if (!IsValidPath(tokenPath)) { throw new PSInvalidOperationException(string.Format("'{0}' is not a valid path. You cannot enable context autosave without a valid token cache path", tokenPath)); } result = new ContextAutosaveSettings { CacheDirectory = session.TokenCacheDirectory, CacheFile = session.TokenCacheFile, ContextDirectory = session.ARMProfileDirectory, ContextFile = session.ARMProfileFile, Mode = ContextSaveMode.CurrentUser }; FileUtilities.DataStore = session.DataStore; session.ARMContextSaveMode = ContextSaveMode.CurrentUser; AzureSession.Instance.TryGetComponent(nameof(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey), out PowerShellTokenCacheProvider originalCacheProvider); if (originalCacheProvider is InMemoryTokenCacheProvider inMemoryTokenCacheProvider) { var tokenData = inMemoryTokenCacheProvider.ReadTokenData(); //must use explicit interface type PowerShellTokenCacheProvider below instead of var, otherwise could not retrieve registered component PowerShellTokenCacheProvider newCacheProvider = new SharedTokenCacheProvider(); if (tokenData != null && tokenData.Length > 0) { newCacheProvider.UpdateTokenDataWithoutFlush(tokenData); newCacheProvider.FlushTokenData(); } AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => newCacheProvider, true); } if (writeAutoSaveFile) { try { FileUtilities.EnsureDirectoryExists(session.ProfileDirectory); string autoSavePath = Path.Combine(session.ProfileDirectory, ContextAutosaveSettings.AutoSaveSettingsFile); session.DataStore.WriteFile(autoSavePath, JsonConvert.SerializeObject(result)); } catch { // do not fail for file system errors in writing the autosave setting // it may impact automation environment and module import. } } }
public static void Apply(IAzureSession session) { session.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => { var userPassword = new UsernamePasswordAuthenticator(); userPassword.Next = new InteractiveUserAuthenticator(); var authenticator = new DesktopAuthenticatorBuilder(); authenticator.Authenticator = userPassword; return(authenticator as IAuthenticatorBuilder); }); }
private void EnableAutosave(IAzureSession session, bool writeAutoSaveFile, out ContextAutosaveSettings result) { var store = session.DataStore; string contextPath = Path.Combine(session.ARMProfileDirectory, session.ARMProfileFile); string tokenPath = Path.Combine(session.TokenCacheDirectory, session.TokenCacheFile); if (!IsValidPath(contextPath)) { throw new PSInvalidOperationException(string.Format("'{0}' is not a valid path. You cannot enable context autosave without a valid context path", contextPath)); } if (!IsValidPath(tokenPath)) { throw new PSInvalidOperationException(string.Format("'{0}' is not a valid path. You cannot enable context autosave without a valid token cache path", tokenPath)); } result = new ContextAutosaveSettings { CacheDirectory = session.TokenCacheDirectory, CacheFile = session.TokenCacheFile, ContextDirectory = session.ARMProfileDirectory, ContextFile = session.ARMProfileFile, Mode = ContextSaveMode.CurrentUser }; FileUtilities.DataStore = session.DataStore; session.ARMContextSaveMode = ContextSaveMode.CurrentUser; try { if (writeAutoSaveFile) { try { FileUtilities.EnsureDirectoryExists(session.ProfileDirectory); string autoSavePath = Path.Combine(session.ProfileDirectory, ContextAutosaveSettings.AutoSaveSettingsFile); session.DataStore.WriteFile(autoSavePath, JsonConvert.SerializeObject(result)); } catch { // do not fail for file system errors in writing the autosave setting } } } catch { // do not throw if there are file system error } }
private void DisableAutosave(IAzureSession session) { 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 && diskCache.Count > 0) { memoryCache.Deserialize(diskCache.Serialize()); } session.TokenCache = memoryCache; } }
public static void WritePSDataCollectionProfile(IAzureSession session, AzurePSDataCollectionProfile profile) { try { var store = session.DataStore; string dataPath = Path.Combine(session.ProfileDirectory, AzurePSDataCollectionProfile.DefaultFileName); if (!store.DirectoryExists(session.ProfileDirectory)) { store.CreateDirectory(session.ProfileDirectory); } string contents = JsonConvert.SerializeObject(profile); store.WriteFile(dataPath, contents); } catch { // do not throw for i/o or serialization errors } }
/// <summary> /// Get the context modification scope for the current user. This will be 'Process' if changes should /// only affect the current PowerShell session, or 'CurrentUser' if any changes should be global. /// </summary> /// <param name="writer">A writer to write debug messages</param> /// <returns>'Process' if all changes should only impact the current session, or 'CurrentUser' if /// changes should be global.</returns> public static ContextModificationScope GetContextModificationScopeForUser(IAzureSession session, DebugWriter writer) { ContextModificationScope scope = ContextModificationScope.Process; try { string autoSavePath = Path.Combine(session.ProfileDirectory, ContextAutosaveSettings.AutoSaveSettingsFile); var store = session.DataStore; if (store.FileExists(autoSavePath)) { var settings = JsonConvert.DeserializeObject <ContextAutosaveSettings>(store.ReadFileAsText(autoSavePath)); if (settings != null && !string.IsNullOrWhiteSpace(settings.Mode)) { scope = GetContextModificationScopeFromSaveMode(settings.Mode); writer(Resources.AutosaveSettingFromFile, autoSavePath, settings.Mode); } } var userAutoSaveSetting = Environment.GetEnvironmentVariable(AzureRmProfileConstants.ProfileAutoSaveVariable, EnvironmentVariableTarget.User); var machineAutoSaveSetting = Environment.GetEnvironmentVariable(AzureRmProfileConstants.ProfileAutoSaveVariable, EnvironmentVariableTarget.Machine); bool autoSaveEnabled = false; if (userAutoSaveSetting != null && bool.TryParse(userAutoSaveSetting, out autoSaveEnabled)) { scope = autoSaveEnabled ? ContextModificationScope.CurrentUser : ContextModificationScope.Process; writer(Resources.AutosaveSettingFromEnvironment, AzureRmProfileConstants.ProfileAutoSaveVariable, userAutoSaveSetting); } else if (machineAutoSaveSetting != null && bool.TryParse(machineAutoSaveSetting, out autoSaveEnabled)) { scope = autoSaveEnabled ? ContextModificationScope.CurrentUser : ContextModificationScope.Process; writer(Resources.AutosaveSettingFromEnvironment, AzureRmProfileConstants.ProfileAutoSaveVariable, machineAutoSaveSetting); } else { writer(Resources.CouldNotRetrieveAutosaveSetting, AzureRmProfileConstants.ProfileAutoSaveVariable); } } catch (Exception exception) { writer(Resources.ErrorRetrievingAutosaveSetting, AzureRmProfileConstants.ProfileAutoSaveVariable, exception); } return(scope); }
public static void MigrateAdalCache(IAzureSession session, Func <IAzureContextContainer> getContextContainer, Action <string> writeWarning) { try { 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; } 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) { new AdalTokenMigrator(adalData, getContextContainer).MigrateFromAdalToMsal(); } } catch (Exception e) { writeWarning(Resources.FailedToMigrateAdal2Msal.FormatInvariant(e.Message)); } }
static AzurePSDataCollectionProfile Initialize(IAzureSession session) { AzurePSDataCollectionProfile result = new AzurePSDataCollectionProfile(true); try { var environmentValue = Environment.GetEnvironmentVariable(AzurePSDataCollectionProfile.EnvironmentVariableName); bool enabled = true; if (!string.IsNullOrWhiteSpace(environmentValue) && bool.TryParse(environmentValue, out enabled)) { result.EnableAzureDataCollection = enabled; } else { var store = session.DataStore; string dataPath = Path.Combine(session.ProfileDirectory, AzurePSDataCollectionProfile.DefaultFileName); if (store.FileExists(dataPath)) { string contents = store.ReadFileAsText(dataPath); var localResult = JsonConvert.DeserializeObject <AzurePSDataCollectionProfile>(contents); if (localResult != null && localResult.EnableAzureDataCollection.HasValue) { result = localResult; } } else { WritePSDataCollectionProfile(session, new AzurePSDataCollectionProfile(true)); } } } catch { // do not throw for i/o or serialization errors } return(result); }
public void InitializerCreatesTokenCacheFile() { AzureSessionInitializer.InitializeAzureSession(); IAzureSession oldSession = null; try { oldSession = AzureSession.Instance; } catch { } try { var store = new MemoryDataStore(); AzureSessionInitializer.CreateOrReplaceSession(store); var session = AzureSession.Instance; var tokenCacheFile = Path.Combine(session.ProfileDirectory, session.TokenCacheFile); Assert.True(store.FileExists(tokenCacheFile)); } finally { AzureSession.Initialize(() => oldSession, true); } }
void DisableAutosave(IAzureSession session, bool writeAutoSaveFile, out ContextAutosaveSettings result) { string tokenPath = Path.Combine(session.TokenCacheDirectory, session.TokenCacheFile); result = new ContextAutosaveSettings { Mode = ContextSaveMode.Process }; FileUtilities.DataStore = session.DataStore; session.ARMContextSaveMode = ContextSaveMode.Process; if (AzureSession.Instance.TryGetComponent( PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, out PowerShellTokenCacheProvider originalTokenCacheProvider)) { if (originalTokenCacheProvider is SharedTokenCacheProvider) { var token = originalTokenCacheProvider.ReadTokenData(); //must explicitely use type PowerShellTokenCacheProvider PowerShellTokenCacheProvider cacheProvider = new InMemoryTokenCacheProvider(token); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => cacheProvider, true); } } if (AzureSession.Instance.TryGetComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, out IAuthenticatorBuilder builder)) { builder.Reset(); } if (writeAutoSaveFile) { FileUtilities.EnsureDirectoryExists(session.ProfileDirectory); string autoSavePath = Path.Combine(session.ProfileDirectory, ContextAutosaveSettings.AutoSaveSettingsFile); session.DataStore.WriteFile(autoSavePath, JsonConvert.SerializeObject(result)); } }
void DisableAutosave(IAzureSession session, bool writeAutoSaveFile, out ContextAutosaveSettings result) { string tokenPath = Path.Combine(session.TokenCacheDirectory, session.TokenCacheFile); result = new ContextAutosaveSettings { Mode = ContextSaveMode.Process }; FileUtilities.DataStore = session.DataStore; session.ARMContextSaveMode = ContextSaveMode.Process; PowerShellTokenCacheProvider cacheProvider; MemoryStream memoryStream = null; if (AzureSession.Instance.TryGetComponent( PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, out PowerShellTokenCacheProvider originalTokenCacheProvider)) { if (originalTokenCacheProvider is SharedTokenCacheProvider) { cacheProvider = new InMemoryTokenCacheProvider(); var token = originalTokenCacheProvider.ReadTokenData(); if (token != null && token.Length > 0) { memoryStream = new MemoryStream(token); } cacheProvider.UpdateTokenDataWithoutFlush(token); cacheProvider.FlushTokenData(); AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => cacheProvider, true); } else { cacheProvider = originalTokenCacheProvider; } } else { cacheProvider = new InMemoryTokenCacheProvider(); } PowerShellTokenCache newTokenCache = null; if (AzureSession.Instance.TryGetComponent(nameof(PowerShellTokenCache), out PowerShellTokenCache tokenCache)) { if (!tokenCache.IsPersistentCache) { newTokenCache = tokenCache; } else { newTokenCache = memoryStream == null ? null : PowerShellTokenCache.Deserialize(memoryStream); } } if (newTokenCache == null) { newTokenCache = cacheProvider.GetTokenCache(); } AzureSession.Instance.RegisterComponent(nameof(PowerShellTokenCache), () => newTokenCache, true); if (AzureSession.Instance.TryGetComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, out IAuthenticatorBuilder builder)) { builder.Reset(); } if (writeAutoSaveFile) { FileUtilities.EnsureDirectoryExists(session.ProfileDirectory); string autoSavePath = Path.Combine(session.ProfileDirectory, ContextAutosaveSettings.AutoSaveSettingsFile); session.DataStore.WriteFile(autoSavePath, JsonConvert.SerializeObject(result)); } }
public static DataCollectionController Create(IAzureSession session) { return(new MemoryDataCollectionController(Initialize(session))); }
public static void Apply(IAzureSession session) { session.RegisterComponent <IAuthenticatorBuilder>(AuthenticatorBuilderKey, () => AuthenticatorBuilder.Instance); }
static void InitializeDataCollection(IAzureSession session) { session.RegisterComponent(DataCollectionController.RegistryKey, () => DataCollectionController.Create(session)); }
void EnableAutosave(IAzureSession session, bool writeAutoSaveFile, out ContextAutosaveSettings result) { var store = session.DataStore; string contextPath = Path.Combine(session.ARMProfileDirectory, session.ARMProfileFile); string tokenPath = Path.Combine(session.TokenCacheDirectory, session.TokenCacheFile); if (!IsValidPath(contextPath)) { throw new PSInvalidOperationException(string.Format("'{0}' is not a valid path. You cannot enable context autosave without a valid context path")); } if (!IsValidPath(tokenPath)) { throw new PSInvalidOperationException(string.Format("'{0}' is not a valid path. You cannot enable context autosave without a valid token cache path")); } result = new ContextAutosaveSettings { CacheDirectory = session.TokenCacheDirectory, CacheFile = session.TokenCacheFile, ContextDirectory = session.ARMProfileDirectory, ContextFile = session.ARMProfileFile, Mode = ContextSaveMode.CurrentUser }; FileUtilities.DataStore = session.DataStore; session.ARMContextSaveMode = ContextSaveMode.CurrentUser; var diskCache = session.TokenCache as ProtectedFileTokenCache; try { if (diskCache == null) { var memoryCache = session.TokenCache as AuthenticationStoreTokenCache; try { FileUtilities.EnsureDirectoryExists(session.TokenCacheDirectory); diskCache = new ProtectedFileTokenCache(tokenPath, store); if (memoryCache != null && memoryCache.Count > 0) { diskCache.Deserialize(memoryCache.Serialize()); } session.TokenCache = diskCache; } catch { // leave the token cache alone if there are file system errors } } if (writeAutoSaveFile) { try { FileUtilities.EnsureDirectoryExists(session.ProfileDirectory); string autoSavePath = Path.Combine(session.ProfileDirectory, ContextAutosaveSettings.AutoSaveSettingsFile); session.DataStore.WriteFile(autoSavePath, JsonConvert.SerializeObject(result)); } catch { // do not fail for file system errors in writing the autosave setting } } } catch { // do not throw if there are file system erroer } }