From 79e15706cfd648ce70d8183e82dd7453e8dd46fb Mon Sep 17 00:00:00 2001 From: Nate McMaster Date: Thu, 6 Sep 2018 08:24:30 -0700 Subject: [PATCH] UserSecrets: Add fallbacks when HOME or APPDATA env vars are unset (#873) --- src/Config.UserSecrets/PathHelper.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/Config.UserSecrets/PathHelper.cs b/src/Config.UserSecrets/PathHelper.cs index 7026bf9..679ca0d 100644 --- a/src/Config.UserSecrets/PathHelper.cs +++ b/src/Config.UserSecrets/PathHelper.cs @@ -40,8 +40,19 @@ namespace Microsoft.Extensions.Configuration.UserSecrets badCharIndex)); } - var root = Environment.GetEnvironmentVariable("APPDATA") ?? // On Windows it goes to %APPDATA%\Microsoft\UserSecrets\ - Environment.GetEnvironmentVariable("HOME"); // On Mac/Linux it goes to ~/.microsoft/usersecrets/ + const string userSecretsFallbackDir = "DOTNET_USER_SECRETS_FALLBACK_DIR"; + + // For backwards compat, this checks env vars first before using Env.GetFolderPath + var root = Environment.GetEnvironmentVariable("APPDATA") // On Windows it goes to %APPDATA%\Microsoft\UserSecrets\ + ?? Environment.GetEnvironmentVariable("HOME") // On Mac/Linux it goes to ~/.microsoft/usersecrets/ + ?? Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + ?? Environment.GetEnvironmentVariable(userSecretsFallbackDir); // this fallback is an escape hatch if everything else fails + + if (string.IsNullOrEmpty(root)) + { + throw new InvalidOperationException("Could not determine an appropriate location for storing user secrets. Set the " + userSecretsFallbackDir + " environment variable to a folder where user secrets should be stored."); + } if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPDATA"))) {