From 77972f79f968b226c41af052d3e5c44c13cfc320 Mon Sep 17 00:00:00 2001 From: Peter Ombwa Date: Tue, 6 Oct 2020 16:42:36 -0700 Subject: [PATCH 1/8] Add Graph environment. --- .../Authentication/Cmdlets/ConnectMgGraph.cs | 40 ++++++- .../Cmdlets/InvokeMgGraphRequest.cs | 1 + .../Common/GraphContextSettings.cs | 89 ++++++++++++++ .../Authentication/Common/GraphSession.cs | 5 + .../Authentication/Constants.cs | 4 +- .../Authentication/ErrorConstants.cs | 5 + .../GraphEnvironmentConstants.cs | 112 ++++++++++++++++++ .../Helpers/AuthenticationHelpers.cs | 17 +++ .../Authentication/Helpers/HttpHelpers.cs | 26 ++-- .../Helpers/NationalCloudHandler.cs | 58 +++++++++ .../Interfaces/IGraphEnvironment.cs | 14 +++ .../Authentication/Models/GraphEnvironment.cs | 55 +++++++++ .../TokenCache/WindowsTokenCache.cs | 10 +- 13 files changed, 410 insertions(+), 26 deletions(-) create mode 100644 src/Authentication/Authentication/Common/GraphContextSettings.cs create mode 100644 src/Authentication/Authentication/GraphEnvironmentConstants.cs create mode 100644 src/Authentication/Authentication/Helpers/NationalCloudHandler.cs create mode 100644 src/Authentication/Authentication/Interfaces/IGraphEnvironment.cs create mode 100644 src/Authentication/Authentication/Models/GraphEnvironment.cs diff --git a/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs b/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs index e8bb9ea125b..efd53d7c69e 100644 --- a/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs +++ b/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs @@ -61,12 +61,39 @@ public class ConnectMgGraph : PSCmdlet, IModuleAssemblyInitializer, IModuleAssem HelpMessage = "Determines the scope of authentication context. This accepts `Process` for the current process, or `CurrentUser` for all sessions started by user.")] public ContextScope ContextScope { get; set; } + [Parameter(Mandatory = false, + HelpMessage = "The name of the national cloud environment to connect to. By default, the SDK uses global cloud.")] + [Alias("EnvironmentName", "NationalCloud")] + [ValidateNotNullOrEmpty] + public string Environment { get; set; } + private CancellationTokenSource cancellationTokenSource; + private IGraphEnvironment environment; + protected override void BeginProcessing() { - ValidateParameters(); base.BeginProcessing(); + ValidateParameters(); + + if (GraphEnvironment.GraphEnvironments.ContainsKey(GraphEnvironmentConstants.EnvironmentName.Global)) + { + environment = GraphEnvironment.GraphEnvironments[GraphEnvironmentConstants.EnvironmentName.Global]; + } + else + { + WriteWarning($"Default environment {GraphEnvironmentConstants.EnvironmentName.Global} cannot be found from environment list."); + WriteWarning("You can get current list via [Microsoft.Graph.PowerShell.Authentication.GraphEnvironment]::GraphEnvironments"); + } + + if (MyInvocation.BoundParameters.ContainsKey(nameof(Environment))) + { + var settings = new GraphContextSettings(); + if (!settings.TryGetEnvironment(Environment, out environment)) + { + throw new PSInvalidOperationException(string.Format(ErrorConstants.Message.InvalidEnvironment, Environment)); + } + } } protected override void EndProcessing() @@ -79,6 +106,7 @@ protected override void ProcessRecord() base.ProcessRecord(); IAuthContext authContext = new AuthContext { TenantId = TenantId }; cancellationTokenSource = new CancellationTokenSource(); + GraphSession.Instance.Environment = environment; switch (ParameterSetName) { @@ -258,10 +286,18 @@ private void ValidateParameters() } private void ThrowParameterError(string parameterName) + { + ThrowError($"Must specify '{parameterName}'.", ErrorCategory.InvalidArgument); + } + + private void ThrowError(string message, ErrorCategory errorCategory) { ThrowTerminatingError( new ErrorRecord( - new ArgumentException($"Must specify {parameterName}"), Guid.NewGuid().ToString(), ErrorCategory.InvalidArgument, null) + new ArgumentException(message), + Guid.NewGuid().ToString(), + errorCategory, + null) ); } diff --git a/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs b/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs index 7f4d0b3c9dc..4889fe2d02a 100644 --- a/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs +++ b/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs @@ -45,6 +45,7 @@ public InvokeMgGraphRequest() HelpMessage = "Http Method")] public GraphRequestMethod Method { get; set; } = GraphRequestMethod.GET; + //TODO: Ensure invoke graph supports national cloud. /// /// Uri to call using the Graph HttpClient can be segments such as /beta/me /// or fully qualified url such as https://graph.microsoft.com/beta/me diff --git a/src/Authentication/Authentication/Common/GraphContextSettings.cs b/src/Authentication/Authentication/Common/GraphContextSettings.cs new file mode 100644 index 00000000000..068c552cb52 --- /dev/null +++ b/src/Authentication/Authentication/Common/GraphContextSettings.cs @@ -0,0 +1,89 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication +{ + using Newtonsoft.Json; + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.IO; + public class GraphContextSettings + { + public IDictionary EnvironmentTable { get; set; } = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); + + public GraphContextSettings() + { + EnvironmentTable = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); + Load(Constants.ContextSettingFilePath); + } + + private void Load(string path) + { + // Creates directory if it doesn't exists. + Directory.CreateDirectory(path); + + if (File.Exists(path)) + { + string contents = File.ReadAllText(path); + if (SafeDeserializeObject(contents, out GraphContextSettings contextSettings)) + { + Initialize(contextSettings); + } + } + else + { + Initialize(); + } + } + + private void Initialize(GraphContextSettings settings = null) + { + EnvironmentTable.Clear(); + // Add predefined environments. + foreach (var env in GraphEnvironment.GraphEnvironments) + { + EnvironmentTable[env.Key] = env.Value; + } + + if (settings != null) + { + foreach (var environment in settings.EnvironmentTable) + { + EnvironmentTable[environment.Key] = environment.Value; + } + } + } + + private bool SafeDeserializeObject(string serialization, out T result, JsonConverter converter = null) + { + result = default(T); + bool success = false; + try + { + result = converter == null ? JsonConvert.DeserializeObject(serialization) : JsonConvert.DeserializeObject(serialization, converter); + success = true; + } + catch (JsonException) + { + + } + + return success; + } + + internal bool TryGetEnvironment(string name, out IGraphEnvironment environment) + { + bool result = false; + environment = null; + if (EnvironmentTable.ContainsKey(name)) + { + environment = EnvironmentTable[name]; + result = true; + } + + return result; + } + } +} diff --git a/src/Authentication/Authentication/Common/GraphSession.cs b/src/Authentication/Authentication/Common/GraphSession.cs index ec653e2375d..2aa319338f1 100644 --- a/src/Authentication/Authentication/Common/GraphSession.cs +++ b/src/Authentication/Authentication/Common/GraphSession.cs @@ -48,6 +48,11 @@ public byte[] MSALToken /// public string SelectedProfile { get; set; } = Constants.DefaultProfile; + /// + /// The selected national cloud environment. + /// + public IGraphEnvironment Environment { get; set; } + /// /// Gets an instance of . /// diff --git a/src/Authentication/Authentication/Constants.cs b/src/Authentication/Authentication/Constants.cs index 0cc2f234d91..5b1f5e4a1f1 100644 --- a/src/Authentication/Authentication/Constants.cs +++ b/src/Authentication/Authentication/Constants.cs @@ -4,7 +4,6 @@ namespace Microsoft.Graph.PowerShell.Authentication { - using System; using System.IO; public static class Constants { @@ -14,7 +13,8 @@ public static class Constants internal const string AppParameterSet = "AppParameterSet"; internal const string AccessTokenParameterSet = "AccessTokenParameterSet"; internal const int MaxDeviceCodeTimeOut = 120; // 2 mins timeout. - internal static readonly string TokenCacheDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".graph"); + internal static readonly string GraphDirectoryPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile), ".graph"); + internal static readonly string ContextSettingFilePath = Path.Combine(GraphDirectoryPath, "GraphContext.json"); internal const string ProfileDescription = "A snapshot of the Microsoft Graph {0} API for {1} cloud."; internal const string TokenCacheServiceName = "com.microsoft.graph.powershell.sdkcache"; internal const string DefaultProfile = "v1.0"; diff --git a/src/Authentication/Authentication/ErrorConstants.cs b/src/Authentication/Authentication/ErrorConstants.cs index c467a86b6fd..e17ea143c4e 100644 --- a/src/Authentication/Authentication/ErrorConstants.cs +++ b/src/Authentication/Authentication/ErrorConstants.cs @@ -1,6 +1,8 @@ // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ +using System; + namespace Microsoft.Graph.PowerShell.Authentication { public static class ErrorConstants @@ -24,6 +26,9 @@ internal static class Message internal const string DeviceCodeTimeout = "Device code terminal timed-out after {0} seconds. Please try again."; internal const string InvalidUserProvidedToken = "The provided access token is invalid. Set a valid access token to `-{0}` parameter and try again."; internal const string ExpiredUserProvidedToken = "The provided access token has expired. Set a valid access token to `-{0}` parameter and try again."; + //TODO: Confirm final name of Get-MgEnvironment. + internal const string InvalidNationalCloud = "Parameter `{0}` has an invalid national cloud. Use Get-MgEnvironment to get a list of valid national clouds."; + internal const string InvalidEnvironment = "Unable to find environment with name '{0}'."; } } } diff --git a/src/Authentication/Authentication/GraphEnvironmentConstants.cs b/src/Authentication/Authentication/GraphEnvironmentConstants.cs new file mode 100644 index 00000000000..d4e14b0d006 --- /dev/null +++ b/src/Authentication/Authentication/GraphEnvironmentConstants.cs @@ -0,0 +1,112 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication +{ + using System.Collections.Generic; + internal static class GraphEnvironmentConstants + { + /// + /// The default AD Tenant value + /// + public const string CommonAdTenant = "common"; + + /// + /// Collection of predefined environment/cloud names for Microsoft Graph. + /// + public static class EnvironmentName + { + /// + /// The graph national cloud. + /// + public const string Global = "Global"; + + /// + /// The graph national cloud US Government. + /// + public const string USGov = "USGov"; + + /// + /// The graph national cloud for US Government DoD. + /// + public const string USGovDoD = "USGovDoD"; + + /// + /// The graph national cloud for Germany. + /// + public const string Germany = "Germany"; + + /// + /// The graph national cloud for China. + /// + public const string China = "China"; + } + + /// + /// Environment types. + /// + public static class EnvironmentType + { + public const string BuiltIn = "Built-in"; + public const string UserDefined = "User-defined"; + } + + /// + /// Known endpoint values for Microsoft Graph national clouds. + /// + internal static readonly IDictionary GraphEnvironmentEndpoints = new Dictionary + { + // Global national cloud endpoints. + { + EnvironmentName.Global, new GraphEnvironment + { + Name = EnvironmentName.Global, + Type = EnvironmentType.BuiltIn, + AzureADEndpoint = "https://login.microsoftonline.com", + GraphEndpoint = "https://graph.microsoft.com" + } + }, + // US Gov national cloud endpoints. + { + EnvironmentName.USGov, new GraphEnvironment + { + Name = EnvironmentName.USGov, + Type = EnvironmentType.BuiltIn, + AzureADEndpoint = "https://login.microsoftonline.us", + GraphEndpoint = "https://graph.microsoft.us" + } + }, + // US Gov DoD national cloud endpoints. + { + EnvironmentName.USGovDoD, new GraphEnvironment + { + Name = EnvironmentName.USGovDoD, + Type = EnvironmentType.BuiltIn, + AzureADEndpoint = "https://login.microsoftonline.us", + GraphEndpoint = "https://dod-graph.microsoft.us" + } + }, + // Germany national cloud endpoints. + { + EnvironmentName.Germany, new GraphEnvironment + { + Name = EnvironmentName.Germany, + Type = EnvironmentType.BuiltIn, + AzureADEndpoint = "https://login.microsoftonline.de", + GraphEndpoint = "https://graph.microsoft.de" + } + }, + // China national cloud endpoints. + { + EnvironmentName.China, new GraphEnvironment + { + Name = EnvironmentName.China, + Type = EnvironmentType.BuiltIn, + AzureADEndpoint = "https://login.chinacloudapi.cn", + GraphEndpoint = "https://microsoftgraph.chinacloudapi.cn" + } + } + }; + } +} diff --git a/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs b/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs index 26a47c9288c..9a40e14710a 100644 --- a/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs +++ b/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs @@ -27,6 +27,7 @@ internal static IAuthenticationProvider GetAuthProvider(IAuthContext authContext } IAuthenticationProvider authProvider = null; + string authorityUrl = GetAuthorityUrl(authContext); switch (authContext.AuthType) { case AuthenticationType.Delegated: @@ -34,6 +35,7 @@ internal static IAuthenticationProvider GetAuthProvider(IAuthContext authContext IPublicClientApplication publicClientApp = PublicClientApplicationBuilder .Create(authContext.ClientId) .WithTenantId(authContext.TenantId) + .WithAuthority(authorityUrl) .Build(); ConfigureTokenCache(publicClientApp.UserTokenCache, authContext); @@ -47,6 +49,7 @@ internal static IAuthenticationProvider GetAuthProvider(IAuthContext authContext IConfidentialClientApplication confidentialClientApp = ConfidentialClientApplicationBuilder .Create(authContext.ClientId) .WithTenantId(authContext.TenantId) + .WithAuthority(authorityUrl) .WithCertificate(string.IsNullOrEmpty(authContext.CertificateThumbprint) ? GetCertificateByName(authContext.CertificateName) : GetCertificateByThumbprint(authContext.CertificateThumbprint)) .Build(); @@ -67,6 +70,20 @@ internal static IAuthenticationProvider GetAuthProvider(IAuthContext authContext return authProvider; } + private static string GetAuthorityUrl(IAuthContext authContext) + { + string audience = authContext.TenantId ?? GraphEnvironmentConstants.CommonAdTenant; + string defaultInstance = GraphEnvironmentConstants.GraphEnvironmentEndpoints[GraphEnvironmentConstants.EnvironmentName.Global].AzureADEndpoint; + string authorityUrl = $"{defaultInstance}/{audience}"; + + if (GraphSession.Instance.Environment != null) + { + authorityUrl = $"{GraphSession.Instance.Environment.AzureADEndpoint}/{audience}"; + } + + return authorityUrl; + } + internal static void Logout(IAuthContext authConfig) { try diff --git a/src/Authentication/Authentication/Helpers/HttpHelpers.cs b/src/Authentication/Authentication/Helpers/HttpHelpers.cs index 3b29c5a4c2d..f33cd226bfe 100644 --- a/src/Authentication/Authentication/Helpers/HttpHelpers.cs +++ b/src/Authentication/Authentication/Helpers/HttpHelpers.cs @@ -41,17 +41,7 @@ public static HttpClient GetGraphHttpClient(IAuthContext authContext = null) } IAuthenticationProvider authProvider = AuthenticationHelpers.GetAuthProvider(authContext); - IList defaultHandlers = GraphClientFactory.CreateDefaultHandlers(authProvider); - - // Register ODataQueryOptionsHandler after AuthHandler. - defaultHandlers.Insert(1, (new ODataQueryOptionsHandler())); - - HttpClient httpClient = GraphClientFactory.Create(defaultHandlers); - - // Prepend new SDKVersionHeaders - PrependNewSDKVersionHeaders(httpClient); - - return httpClient; + return GetGraphHttpClient(authProvider); } /// @@ -69,16 +59,18 @@ private static void PrependNewSDKVersionHeaders(HttpClient httpClient) /// /// Creates a pre-configured Microsoft Graph . - /// with a custom authenticationProvider + /// with an /// - /// Custom AuthProvider + /// Custom AuthProvider /// - public static HttpClient GetGraphHttpClient(IAuthenticationProvider customAuthProvider) + public static HttpClient GetGraphHttpClient(IAuthenticationProvider authProvider) { - IList defaultHandlers = GraphClientFactory.CreateDefaultHandlers(customAuthProvider); + IList defaultHandlers = GraphClientFactory.CreateDefaultHandlers(authProvider); - // Register ODataQueryOptionsHandler after AuthHandler. - defaultHandlers.Insert(1, (new ODataQueryOptionsHandler())); + // Register NationalCloudHandler after AuthHandler. + defaultHandlers.Insert(1, new NationalCloudHandler()); + // Register ODataQueryOptionsHandler after NationalCloudHandler. + defaultHandlers.Insert(2, new ODataQueryOptionsHandler()); HttpClient httpClient = GraphClientFactory.Create(defaultHandlers); diff --git a/src/Authentication/Authentication/Helpers/NationalCloudHandler.cs b/src/Authentication/Authentication/Helpers/NationalCloudHandler.cs new file mode 100644 index 00000000000..937b18d36d5 --- /dev/null +++ b/src/Authentication/Authentication/Helpers/NationalCloudHandler.cs @@ -0,0 +1,58 @@ +namespace Microsoft.Graph.PowerShell.Authentication.Helpers +{ + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + + internal class NationalCloudHandler : DelegatingHandler + { + /// + /// Creates a new . + /// + public NationalCloudHandler() + { + + } + + /// + /// Creates a new . + /// + /// Optional to be called after . + public NationalCloudHandler(HttpMessageHandler innerHandler) + { + this.InnerHandler = innerHandler; + } + /// + /// Sends the . + /// + /// The request to send. + /// The for the request. + /// + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + request = SetNationalCloudEndpoint(request); + return base.SendAsync(request, cancellationToken); + } + + /// + /// Sets national cloud to the outgoing HttpRequestMessage. + /// + /// + /// + private HttpRequestMessage SetNationalCloudEndpoint(HttpRequestMessage request) + { + if (GraphSession.Instance.Environment != null) + { + Uri baseUri = new Uri(GraphSession.Instance.Environment.GraphEndpoint); + Uri requestUri = new Uri(baseUri, request.RequestUri.PathAndQuery); + + request.RequestUri = requestUri; + } + + return request; + } + } +} diff --git a/src/Authentication/Authentication/Interfaces/IGraphEnvironment.cs b/src/Authentication/Authentication/Interfaces/IGraphEnvironment.cs new file mode 100644 index 00000000000..57551a81ab1 --- /dev/null +++ b/src/Authentication/Authentication/Interfaces/IGraphEnvironment.cs @@ -0,0 +1,14 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication +{ + public interface IGraphEnvironment + { + string Name { get; set; } + string Type { get; set; } + string AzureADEndpoint { get; set; } + string GraphEndpoint { get; set; } + } +} diff --git a/src/Authentication/Authentication/Models/GraphEnvironment.cs b/src/Authentication/Authentication/Models/GraphEnvironment.cs new file mode 100644 index 00000000000..4d19d7fb0f8 --- /dev/null +++ b/src/Authentication/Authentication/Models/GraphEnvironment.cs @@ -0,0 +1,55 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + + internal class GraphEnvironment : IGraphEnvironment + { + /// + /// Predefined Microsoft Graph environments + /// + public static IDictionary GraphEnvironments { get; } = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); + + static GraphEnvironment() + { + InitializeEnvironment(); + } + + /// + /// Initializes environments with well known national cloud environments. + /// + public static void InitializeEnvironment() + { + GraphEnvironments.Clear(); + foreach (var env in GraphEnvironmentConstants.GraphEnvironmentEndpoints) + { + GraphEnvironments.Add(env.Key, env.Value); + } + } + + /// + /// The name of the environment. + /// + public string Name { get; set; } + + /// + /// The token audience needed to get access tokens for Microsoft Graph endpoint. + /// + public string AzureADEndpoint { get; set; } + + /// + /// The URI of Microsoft Graph endpoint. + /// + public string GraphEndpoint { get; set; } + + /// + /// Type of environment. + /// + public string Type { get; set; } + } +} diff --git a/src/Authentication/Authentication/TokenCache/WindowsTokenCache.cs b/src/Authentication/Authentication/TokenCache/WindowsTokenCache.cs index 2af75c12bc3..fa2612ab814 100644 --- a/src/Authentication/Authentication/TokenCache/WindowsTokenCache.cs +++ b/src/Authentication/Authentication/TokenCache/WindowsTokenCache.cs @@ -29,8 +29,8 @@ public static byte[] GetToken(string appId) } // Try to create directory if it doesn't exist. - Directory.CreateDirectory(Constants.TokenCacheDirectory); - string tokenCacheFilePath = Path.Combine(Constants.TokenCacheDirectory, $"{appId}cache.bin3"); + Directory.CreateDirectory(Constants.GraphDirectoryPath); + string tokenCacheFilePath = Path.Combine(Constants.GraphDirectoryPath, $"{appId}cache.bin3"); return File.Exists(tokenCacheFilePath) ? ProtectedData.Unprotect( @@ -60,8 +60,8 @@ public static void SetToken(string appId, byte[] plainContent) } // Try to create directory if it doesn't exist. - Directory.CreateDirectory(Constants.TokenCacheDirectory); - string tokenCacheFilePath = Path.Combine(Constants.TokenCacheDirectory, $"{appId}cache.bin3"); + Directory.CreateDirectory(Constants.GraphDirectoryPath); + string tokenCacheFilePath = Path.Combine(Constants.GraphDirectoryPath, $"{appId}cache.bin3"); File.WriteAllBytes(tokenCacheFilePath, ProtectedData.Protect( @@ -84,7 +84,7 @@ public static void DeleteToken(string appId) nameof(appId))); } - string tokenCacheFilePath = Path.Combine(Constants.TokenCacheDirectory, $"{appId}cache.bin3"); + string tokenCacheFilePath = Path.Combine(Constants.GraphDirectoryPath, $"{appId}cache.bin3"); if (File.Exists(tokenCacheFilePath)) { File.Delete(tokenCacheFilePath); From 8bb71cdb6508fe0463ea3184b74fc7465690724f Mon Sep 17 00:00:00 2001 From: Peter Ombwa Date: Thu, 8 Oct 2020 16:34:28 -0700 Subject: [PATCH 2/8] Add cmdlets to manage environment. --- .../Helpers/ODataQueryOptionsHandlerTests.cs | 2 +- .../Authentication/Cmdlets/ConnectMgGraph.cs | 31 +- .../Cmdlets/Environment/AddMgEnvironment.cs | 85 +++++ .../Cmdlets/Environment/GetMgEnvironment.cs | 34 ++ .../Environment/RemoveMgEnvironment.cs | 45 +++ .../Cmdlets/Environment/SetMgEnvironment.cs | 100 ++++++ .../Authentication/Common/DiskDataStore.cs | 228 +++++++++++++ .../Common/GraphContextSettings.cs | 89 ----- .../Authentication/Common/GraphSession.cs | 6 + .../Common/GraphSessionInitializer.cs | 8 +- .../Authentication/Common/GraphSettings.cs | 310 ++++++++++++++++++ .../Common/GraphSettingsConverter.cs | 49 +++ .../Common/ProtectedFileProvider.cs | 228 +++++++++++++ .../Authentication/ErrorConstants.cs | 4 +- .../Extensions/IGraphEnvironmentExtensions.cs | 38 +++ .../Extensions/PSCmdletExtensions.cs | 34 ++ .../Extensions/StringExtensions.cs | 12 +- .../GraphEnvironmentConstants.cs | 2 +- .../NationalCloudHandler.cs | 8 +- .../ODataQueryOptionsHandler.cs | 4 +- .../Helpers/AuthenticationHelpers.cs | 2 +- .../Authentication/Helpers/HttpHelpers.cs | 2 +- .../Authentication/Interfaces/IDataStore.cs | 162 +++++++++ .../Interfaces/IFileProvider.cs | 16 + .../Interfaces/IGraphSession.cs | 1 + .../Microsoft.Graph.Authentication.psd1 | 3 +- .../Authentication/Models/GraphEnvironment.cs | 36 +- 27 files changed, 1395 insertions(+), 144 deletions(-) create mode 100644 src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs create mode 100644 src/Authentication/Authentication/Cmdlets/Environment/GetMgEnvironment.cs create mode 100644 src/Authentication/Authentication/Cmdlets/Environment/RemoveMgEnvironment.cs create mode 100644 src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs create mode 100644 src/Authentication/Authentication/Common/DiskDataStore.cs delete mode 100644 src/Authentication/Authentication/Common/GraphContextSettings.cs create mode 100644 src/Authentication/Authentication/Common/GraphSettings.cs create mode 100644 src/Authentication/Authentication/Common/GraphSettingsConverter.cs create mode 100644 src/Authentication/Authentication/Common/ProtectedFileProvider.cs create mode 100644 src/Authentication/Authentication/Extensions/IGraphEnvironmentExtensions.cs rename src/Authentication/Authentication/{Helpers => Handlers}/NationalCloudHandler.cs (83%) rename src/Authentication/Authentication/{Helpers => Handlers}/ODataQueryOptionsHandler.cs (96%) create mode 100644 src/Authentication/Authentication/Interfaces/IDataStore.cs create mode 100644 src/Authentication/Authentication/Interfaces/IFileProvider.cs diff --git a/src/Authentication/Authentication.Test/Helpers/ODataQueryOptionsHandlerTests.cs b/src/Authentication/Authentication.Test/Helpers/ODataQueryOptionsHandlerTests.cs index 90f0cf1c438..febc3dc64e8 100644 --- a/src/Authentication/Authentication.Test/Helpers/ODataQueryOptionsHandlerTests.cs +++ b/src/Authentication/Authentication.Test/Helpers/ODataQueryOptionsHandlerTests.cs @@ -1,6 +1,6 @@ namespace Microsoft.Graph.Authentication.Test { - using Microsoft.Graph.PowerShell.Authentication.Helpers; + using Microsoft.Graph.PowerShell.Authentication.Handlers; using System; using System.Linq; using System.Net.Http; diff --git a/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs b/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs index efd53d7c69e..87f9a6c3e8d 100644 --- a/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs +++ b/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs @@ -16,6 +16,7 @@ namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets using System.Threading.Tasks; using System.Net; using System.Globalization; + using Microsoft.Graph.PowerShell.Authentication.Common; [Cmdlet(VerbsCommunications.Connect, "MgGraph", DefaultParameterSetName = Constants.UserParameterSet)] [Alias("Connect-Graph")] @@ -63,8 +64,8 @@ public class ConnectMgGraph : PSCmdlet, IModuleAssemblyInitializer, IModuleAssem [Parameter(Mandatory = false, HelpMessage = "The name of the national cloud environment to connect to. By default, the SDK uses global cloud.")] - [Alias("EnvironmentName", "NationalCloud")] [ValidateNotNullOrEmpty] + [Alias("EnvironmentName", "NationalCloud")] public string Environment { get; set; } private CancellationTokenSource cancellationTokenSource; @@ -88,7 +89,7 @@ protected override void BeginProcessing() if (MyInvocation.BoundParameters.ContainsKey(nameof(Environment))) { - var settings = new GraphContextSettings(); + GraphSettings settings = this.GetContextSettings(); if (!settings.TryGetEnvironment(Environment, out environment)) { throw new PSInvalidOperationException(string.Format(ErrorConstants.Message.InvalidEnvironment, Environment)); @@ -106,6 +107,7 @@ protected override void ProcessRecord() base.ProcessRecord(); IAuthContext authContext = new AuthContext { TenantId = TenantId }; cancellationTokenSource = new CancellationTokenSource(); + // Set selected environment to the session object. GraphSession.Instance.Environment = environment; switch (ParameterSetName) @@ -256,19 +258,19 @@ private void ValidateParameters() // Client Id if (string.IsNullOrEmpty(ClientId)) { - ThrowParameterError(nameof(ClientId)); + this.ThrowParameterError(nameof(ClientId)); } // Certificate Thumbprint or name if (string.IsNullOrEmpty(CertificateThumbprint) && string.IsNullOrEmpty(CertificateName)) { - ThrowParameterError($"{nameof(CertificateThumbprint)} or {nameof(CertificateName)}"); + this.ThrowParameterError($"{nameof(CertificateThumbprint)} or {nameof(CertificateName)}"); } // Tenant Id if (string.IsNullOrEmpty(TenantId)) { - ThrowParameterError(nameof(TenantId)); + this.ThrowParameterError(nameof(TenantId)); } } @@ -278,29 +280,13 @@ private void ValidateParameters() // AccessToken if (string.IsNullOrEmpty(AccessToken)) { - ThrowParameterError(nameof(AccessToken)); + this.ThrowParameterError(nameof(AccessToken)); } } break; } } - private void ThrowParameterError(string parameterName) - { - ThrowError($"Must specify '{parameterName}'.", ErrorCategory.InvalidArgument); - } - - private void ThrowError(string message, ErrorCategory errorCategory) - { - ThrowTerminatingError( - new ErrorRecord( - new ArgumentException(message), - Guid.NewGuid().ToString(), - errorCategory, - null) - ); - } - private void DecodeJWT(string token, IAccount account, ref IAuthContext authContext) { JwtPayload jwtPayload = JwtHelpers.DecodeToObject(token); @@ -336,6 +322,7 @@ private void DecodeJWT(string token, IAccount account, ref IAuthContext authCont public void OnImport() { GraphSessionInitializer.InitializeSession(); + GraphSession.Instance.DataStore = new DiskDataStore(); } /// diff --git a/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs new file mode 100644 index 00000000000..04c9e2a243a --- /dev/null +++ b/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs @@ -0,0 +1,85 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets +{ + using Microsoft.Graph.PowerShell.Authentication.Extensions; + using Microsoft.Graph.PowerShell.Authentication.Helpers; + using System; + using System.Globalization; + using System.Linq; + using System.Management.Automation; + + /// + /// Adds Microsoft Graph environment to the settings file. + /// + [Cmdlet(VerbsCommon.Add, "MgEnvironment", SupportsShouldProcess = true)] + [OutputType(typeof(GraphEnvironment))] + public class AddMgEnvironment : PSCmdlet + { + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The environment name.")] + [ValidateNotNullOrEmpty] + public string Name { get; set; } + + [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The base URL for Azure AD endpoint to get access tokens for Microsoft Graph endpoint.")] + [ValidateNotNullOrEmpty] + [Alias("AzureADUrl")] + public string AzureADEndpoint { get; set; } + + [Parameter(Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The service root endpoint for Microsoft Graph.")] + [ValidateNotNullOrEmpty] + [Alias("GraphUrl")] + public string GraphEndpoint { get; set; } + + protected override void BeginProcessing() + { + base.BeginProcessing(); + ValidateParameters(); + } + + protected override void ProcessRecord() + { + base.ProcessRecord(); + if (ShouldProcess("adding environment", Name)) + { + if (GraphEnvironment.GraphEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase))) + { + throw new InvalidOperationException( + ErrorConstants.Message.CannotModifyBuiltInEnvironment.FormatCurrentCulture("add", Name)); + } + + GraphSettings settings = this.GetContextSettings(); + if (!settings.TryGetEnvironment(Name, out IGraphEnvironment newEnvironment)) + { + newEnvironment = new GraphEnvironment { Name = Name }; + } + + newEnvironment.AzureADEndpoint = AzureADEndpoint.GetBaseUrl(); + newEnvironment.GraphEndpoint = GraphEndpoint.GetBaseUrl(); + newEnvironment.Type = GraphEnvironmentConstants.EnvironmentType.UserDefined; + settings.TrySetEnvironment(newEnvironment, out IGraphEnvironment mergedEnvironment); + + WriteObject(mergedEnvironment); + } + } + + private void ValidateParameters() + { + if (string.IsNullOrWhiteSpace(Name)) + { + this.ThrowParameterError(nameof(Name)); + } + + if (string.IsNullOrWhiteSpace(AzureADEndpoint) || !Uri.IsWellFormedUriString(AzureADEndpoint, UriKind.Absolute)) + { + this.ThrowParameterError(ErrorConstants.Message.InvalidUrlParameter, nameof(AzureADEndpoint)); + } + + if (string.IsNullOrWhiteSpace(GraphEndpoint) || !Uri.IsWellFormedUriString(GraphEndpoint, UriKind.Absolute)) + { + this.ThrowParameterError(ErrorConstants.Message.InvalidUrlParameter, nameof(GraphEndpoint)); + } + } + } +} diff --git a/src/Authentication/Authentication/Cmdlets/Environment/GetMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/GetMgEnvironment.cs new file mode 100644 index 00000000000..aff04b65ce3 --- /dev/null +++ b/src/Authentication/Authentication/Cmdlets/Environment/GetMgEnvironment.cs @@ -0,0 +1,34 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets +{ + using System.Management.Automation; + + /// + /// Gets or lists available Microsoft Graph environments to the settings file.. + /// + [Cmdlet(VerbsCommon.Get, "MgEnvironment")] + [OutputType(typeof(GraphEnvironment))] + public class GetMgEnvironment : PSCmdlet + { + [Parameter(Position = 0, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The environment name.")] + [ValidateNotNullOrEmpty] + public string Name { get; set; } + + protected override void BeginProcessing() + { + base.BeginProcessing(); + } + + protected override void ProcessRecord() + { + base.ProcessRecord(); + + GraphSettings settings = this.GetContextSettings(); + var environments = settings.ListEnvironments(Name); + WriteObject(environments, enumerateCollection: true); + } + } +} diff --git a/src/Authentication/Authentication/Cmdlets/Environment/RemoveMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/RemoveMgEnvironment.cs new file mode 100644 index 00000000000..8f67f9e7eb9 --- /dev/null +++ b/src/Authentication/Authentication/Cmdlets/Environment/RemoveMgEnvironment.cs @@ -0,0 +1,45 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets +{ + using Microsoft.Graph.PowerShell.Authentication.Helpers; + using System; + using System.Globalization; + using System.Linq; + using System.Management.Automation; + + /// + /// Removes Microsoft Graph environment to the settings file.. + /// + [Cmdlet(VerbsCommon.Remove, "MgEnvironment", SupportsShouldProcess = true)] + [OutputType(typeof(GraphEnvironment))] + public class RemoveMgEnvironment : PSCmdlet + { + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The environment name.")] + public string Name { get; set; } + + protected override void BeginProcessing() + { + base.BeginProcessing(); + } + + protected override void ProcessRecord() + { + base.ProcessRecord(); + + if (ShouldProcess("removing environment", Name)) + { + if (GraphEnvironment.GraphEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase))) + { + throw new InvalidOperationException( + ErrorConstants.Message.CannotModifyBuiltInEnvironment.FormatCurrentCulture("remove", Name)); + } + + GraphSettings settings = this.GetContextSettings(); + WriteObject(settings.RemoveEnvironment(Name)); + } + } + } +} diff --git a/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs new file mode 100644 index 00000000000..bdb1567dae8 --- /dev/null +++ b/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs @@ -0,0 +1,100 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets +{ + using Microsoft.Graph.PowerShell.Authentication.Extensions; + using System; + using System.Globalization; + using System.Linq; + using System.Management.Automation; + + /// + /// Sets a Microsoft Graph environment to the settings file.. + /// + [Cmdlet(VerbsCommon.Set, "MgEnvironment", SupportsShouldProcess = true)] + [OutputType(typeof(GraphEnvironment))] + public class SetMgEnvironment : PSCmdlet + { + [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The environment name.")] + [ValidateNotNullOrEmpty] + public string Name { get; set; } + + [Parameter(Position = 1, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The base URL for Azure AD endpoint to get access tokens for Microsoft Graph endpoint.")] + [ValidateNotNullOrEmpty] + [Alias("AzureADUrl")] + public string AzureADEndpoint { get; set; } + + [Parameter(Position = 2, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The service root endpoint for Microsoft Graph.")] + [ValidateNotNullOrEmpty] + [Alias("GraphUrl")] + public string GraphEndpoint { get; set; } + + protected override void BeginProcessing() + { + base.BeginProcessing(); + ValidateParameters(); + } + + protected override void ProcessRecord() + { + base.ProcessRecord(); + + if (ShouldProcess("updating environment", Name)) + { + if (GraphEnvironment.GraphEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase))) + { + throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, + "Cannot change built-in environment {0}.", Name)); + } + + GraphSettings settings = this.GetContextSettings(); + if (!settings.TryGetEnvironment(Name, out IGraphEnvironment newEnvironment)) + { + // Create default environment if it doesn't exist. + newEnvironment = new GraphEnvironment { + Name = Name, + AzureADEndpoint = settings.EnvironmentTable[GraphEnvironmentConstants.EnvironmentName.Global].AzureADEndpoint, + GraphEndpoint = settings.EnvironmentTable[GraphEnvironmentConstants.EnvironmentName.Global].GraphEndpoint + }; + } + + if (MyInvocation.BoundParameters.ContainsKey(nameof(AzureADEndpoint))) + { + newEnvironment.AzureADEndpoint = AzureADEndpoint.GetBaseUrl(); + } + + if (MyInvocation.BoundParameters.ContainsKey(nameof(GraphEndpoint))) + { + newEnvironment.GraphEndpoint = GraphEndpoint.GetBaseUrl(); + } + + newEnvironment.Type = GraphEnvironmentConstants.EnvironmentType.UserDefined; + settings.TrySetEnvironment(newEnvironment, out IGraphEnvironment mergedEnvironment); + + WriteObject(mergedEnvironment); + } + } + + private void ValidateParameters() + { + if (string.IsNullOrWhiteSpace(Name)) + { + this.ThrowParameterError(nameof(Name)); + } + + if (MyInvocation.BoundParameters.ContainsKey(nameof(AzureADEndpoint)) + && (string.IsNullOrWhiteSpace(AzureADEndpoint) || !Uri.IsWellFormedUriString(AzureADEndpoint, UriKind.Absolute))) + { + this.ThrowParameterError(ErrorConstants.Message.InvalidUrlParameter, nameof(AzureADEndpoint)); + } + + if (MyInvocation.BoundParameters.ContainsKey(nameof(GraphEndpoint)) + && (string.IsNullOrWhiteSpace(GraphEndpoint) || !Uri.IsWellFormedUriString(GraphEndpoint, UriKind.Absolute))) + { + this.ThrowParameterError(ErrorConstants.Message.InvalidUrlParameter, nameof(GraphEndpoint)); + } + } + } +} diff --git a/src/Authentication/Authentication/Common/DiskDataStore.cs b/src/Authentication/Authentication/Common/DiskDataStore.cs new file mode 100644 index 00000000000..96fae179225 --- /dev/null +++ b/src/Authentication/Authentication/Common/DiskDataStore.cs @@ -0,0 +1,228 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication +{ + using System.IO; + using System.Text; + + /// + /// Disk data store based on Windows file management APIs (System.IO). + /// + internal class DiskDataStore : IDataStore + { + /// + /// Writes the given contents to the specified file. + /// + /// The file path. + /// The file contents. + public void WriteFile(string path, string contents) + { + File.WriteAllText(path, contents); + } + + /// + /// Writes the given contents to the specified file, using the specified encoding. + /// + /// The file path. + /// The file contents. + /// The encoding to use. + public void WriteFile(string path, string contents, Encoding encoding) + { + File.WriteAllText(path, contents, encoding); + } + + /// + /// Writes the given binary contents to the specified file. + /// + /// The file path. + /// The binary contents. + public void WriteFile(string path, byte[] contents) + { + File.WriteAllBytes(path, contents); + } + + /// + /// Returns the contents of the given file as a text string. + /// + /// The file path + /// The contents of the given file as a string. Throws an exception if the file is not found. + public string ReadFileAsText(string path) + { + return File.ReadAllText(path); + } + + /// + /// Returns the contents of the given file as a byte array. + /// + /// The file path. + /// The contents of the given file as a byte array. Throws an exception if the file is not found. + public byte[] ReadFileAsBytes(string path) + { + return File.ReadAllBytes(path); + } + + /// + /// Returns the contents of the given file as a stream. + /// + /// The file path. + /// The contents of the given file as a stream. Throws an exception if the file is not found. + public Stream ReadFileAsStream(string path) + { + return File.Open(path, FileMode.Open, FileAccess.Read); + } + + /// + /// Moves the file to the specified location. Overwrites the file if it exists. + /// + /// Source file path. + /// Target file path. + public void RenameFile(string oldPath, string newPath) + { + File.Move(oldPath, newPath); + } + + /// + /// Copies the given file to the target path. Overwrites the file if it exists. + /// + /// Source file path. + /// Target file path. + public void CopyFile(string oldPath, string newPath) + { + File.Copy(oldPath, newPath, true); + } + + /// + /// Checks if the given file exists. + /// + /// The file path to check. + /// True if the file exists, false otherwise. + public bool FileExists(string path) + { + return File.Exists(path); + } + + /// + /// Removes the given file. + /// + /// The path of the file to delete. + public void DeleteFile(string path) + { + File.Delete(path); + } + + /// + /// Removes the given directory. + /// + /// The directory path. + public void DeleteDirectory(string dir) + { + Directory.Delete(dir, true); + } + + /// + /// Removes all files from the given directory. + /// + /// The directory to empty. + public void EmptyDirectory(string dirPath) + { + foreach (var filePath in Directory.GetFiles(dirPath)) + { + File.Delete(filePath); + } + } + + /// + /// Gets the files in the given directory. + /// + /// The directory path to check. + /// The list of file paths in the given directory. + public string[] GetFiles(string sourceDirName) + { + return Directory.GetFiles(sourceDirName); + } + + /// + /// Gets files at the given path matching the given pattern and search options. + /// + /// The directory to list file contents. + /// The pattern of file names to include. + /// File search options. + /// The path to all contained files. + public string[] GetFiles(string startDirectory, string filePattern, SearchOption options) + { + return Directory.GetFiles(startDirectory, filePattern, options); + } + + /// + /// Gets the file system attributes for the given file. + /// + /// The file path. + /// The file system attributes associated with the file + public FileAttributes GetFileAttributes(string path) + { + return File.GetAttributes(path); + } + + /// + /// Checks for existence of the given directory. + /// + /// The directory path to check. + /// True if the directory exists, otherwise false. + public bool DirectoryExists(string path) + { + return Directory.Exists(path); + } + + /// + /// Creates a directory at the given path. + /// + /// The directory path. + public void CreateDirectory(string path) + { + Directory.CreateDirectory(path); + } + + /// + /// Gets the set of directories inside the given directory path. + /// + /// The directory to list directory contents. + public string[] GetDirectories(string sourceDirName) + { + return Directory.GetDirectories(sourceDirName); + } + + /// + /// Gets directories at the given path matching the given pattern and search options. + /// + /// The directory to list directory contents of. + /// The pattern of directory names to include. + /// Directory search options. + /// The path to all contained directories. + public string[] GetDirectories(string startDirectory, string filePattern, SearchOption options) + { + return Directory.GetDirectories(startDirectory, filePattern, options); + } + + /// + /// Opens a with shared read. + /// + /// Path to the file to open. + /// A to the specified path with shared read. + public Stream OpenForSharedRead(string path) + { + return File.Open(path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.Read); + } + + /// + /// Opens a with exclusive write. + /// + /// Path to the file to open. + /// A to the specified path with exclusive write. + public Stream OpenForExclusiveWrite(string path) + { + return File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); + } + } +} diff --git a/src/Authentication/Authentication/Common/GraphContextSettings.cs b/src/Authentication/Authentication/Common/GraphContextSettings.cs deleted file mode 100644 index 068c552cb52..00000000000 --- a/src/Authentication/Authentication/Common/GraphContextSettings.cs +++ /dev/null @@ -1,89 +0,0 @@ -// ------------------------------------------------------------------------------ -// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. -// ------------------------------------------------------------------------------ - -namespace Microsoft.Graph.PowerShell.Authentication -{ - using Newtonsoft.Json; - using System; - using System.Collections.Concurrent; - using System.Collections.Generic; - using System.IO; - public class GraphContextSettings - { - public IDictionary EnvironmentTable { get; set; } = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); - - public GraphContextSettings() - { - EnvironmentTable = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); - Load(Constants.ContextSettingFilePath); - } - - private void Load(string path) - { - // Creates directory if it doesn't exists. - Directory.CreateDirectory(path); - - if (File.Exists(path)) - { - string contents = File.ReadAllText(path); - if (SafeDeserializeObject(contents, out GraphContextSettings contextSettings)) - { - Initialize(contextSettings); - } - } - else - { - Initialize(); - } - } - - private void Initialize(GraphContextSettings settings = null) - { - EnvironmentTable.Clear(); - // Add predefined environments. - foreach (var env in GraphEnvironment.GraphEnvironments) - { - EnvironmentTable[env.Key] = env.Value; - } - - if (settings != null) - { - foreach (var environment in settings.EnvironmentTable) - { - EnvironmentTable[environment.Key] = environment.Value; - } - } - } - - private bool SafeDeserializeObject(string serialization, out T result, JsonConverter converter = null) - { - result = default(T); - bool success = false; - try - { - result = converter == null ? JsonConvert.DeserializeObject(serialization) : JsonConvert.DeserializeObject(serialization, converter); - success = true; - } - catch (JsonException) - { - - } - - return success; - } - - internal bool TryGetEnvironment(string name, out IGraphEnvironment environment) - { - bool result = false; - environment = null; - if (EnvironmentTable.ContainsKey(name)) - { - environment = EnvironmentTable[name]; - result = true; - } - - return result; - } - } -} diff --git a/src/Authentication/Authentication/Common/GraphSession.cs b/src/Authentication/Authentication/Common/GraphSession.cs index 2aa319338f1..be6799d4058 100644 --- a/src/Authentication/Authentication/Common/GraphSession.cs +++ b/src/Authentication/Authentication/Common/GraphSession.cs @@ -7,6 +7,7 @@ namespace Microsoft.Graph.PowerShell.Authentication using System; using System.Security; using System.Threading; + /// /// Contains methods to create, modify or obtain a thread safe static instance of . /// @@ -25,6 +26,11 @@ public class GraphSession : IGraphSession /// public IAuthContext AuthContext { get; set; } + /// + /// Gets or sets . + /// + public IDataStore DataStore { get; set; } + private byte[] msalToken; /// diff --git a/src/Authentication/Authentication/Common/GraphSessionInitializer.cs b/src/Authentication/Authentication/Common/GraphSessionInitializer.cs index 72fa61c51fd..e8ec9c3a8ce 100644 --- a/src/Authentication/Authentication/Common/GraphSessionInitializer.cs +++ b/src/Authentication/Authentication/Common/GraphSessionInitializer.cs @@ -18,10 +18,12 @@ public static void InitializeSession() /// Creates a new instance of a . /// /// - internal static GraphSession CreateInstance() + internal static GraphSession CreateInstance(IDataStore dataStore = null) { - // This can be used to initialize GraphSession from a file in the future. - return new GraphSession(); + return new GraphSession + { + DataStore = dataStore ?? new DiskDataStore() + }; } } } diff --git a/src/Authentication/Authentication/Common/GraphSettings.cs b/src/Authentication/Authentication/Common/GraphSettings.cs new file mode 100644 index 00000000000..500768a955d --- /dev/null +++ b/src/Authentication/Authentication/Common/GraphSettings.cs @@ -0,0 +1,310 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication +{ + using Microsoft.Graph.PowerShell.Authentication.Common; + using Microsoft.Graph.PowerShell.Authentication.Extensions; + using Microsoft.Graph.PowerShell.Authentication.Helpers; + using Newtonsoft.Json; + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using System.Xml.Serialization; + + /// + /// Represents a Microsoft Graph settings structure with environments. + /// + [Serializable] + internal class GraphSettings + { + public IDictionary EnvironmentTable { get; set; } = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); + + [JsonIgnore] + [XmlIgnore] + public IEnumerable Environments + { + get + { + return EnvironmentTable.Values.ToList(); + } + } + + /// + /// Creates a new instance of . + /// + public GraphSettings() + { + EnvironmentTable = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); + + foreach (var env in GraphEnvironment.GraphEnvironments) + { + EnvironmentTable[env.Key] = env.Value; + } + } + + /// + /// Creates a new instance of using . + /// + /// The file provider that allows access to settings contents. + public GraphSettings(IFileProvider fileProvider) + { + Load(fileProvider); + } + + /// + /// Reads settings from disk using the specified . + /// + /// The file provider that allows access to settings contents. + private void Load(IFileProvider fileProvider) + { + using (fileProvider) + { + string contents = fileProvider.CreateReader().ReadToEnd(); + if (TryDeserializeObject(contents, out GraphSettings contextSettings, new GraphSettingsConverter())) + { + Initialize(contextSettings); + } + else + { + Initialize(); + } + } + } + + /// + /// Initializes from an existing settings if any. + /// + /// An optional . + private void Initialize(GraphSettings settings = null) + { + EnvironmentTable.Clear(); + // Add built-in environments. + foreach (var env in GraphEnvironment.GraphEnvironments) + { + EnvironmentTable[env.Key] = env.Value; + } + + if (settings != null) + { + foreach (var environment in settings.EnvironmentTable) + { + EnvironmentTable[environment.Key] = environment.Value; + } + } + } + + /// + /// Writes settings to the disk. + /// + public void Save() + { + Save(Constants.ContextSettingFilePath); + } + + /// + /// Writes settings to the specified file path. + /// + /// A file path on disk to save settings to. + public void Save(string path) + { + if (!string.IsNullOrEmpty(path)) + { + using (var provider = ProtectedFileProvider.CreateFileProvider(path, FileProtection.ExclusiveWrite)) + { + Save(provider); + } + } + } + + public void Save(IFileProvider provider) + { + // Remove built-in environments. + foreach (string env in GraphEnvironment.GraphEnvironments.Keys) + { + EnvironmentTable.Remove(env); + } + + try + { + string contents = ToString(); + string diskContents = string.Empty; + diskContents = provider.CreateReader().ReadToEnd(); + + if (diskContents != contents) + { + var writer = provider.CreateWriter(); + writer.Write(contents); + writer.Flush(); + + // When writing to a stream, ensure that the file is truncated + // so that previous data is overwritten + provider.Stream.SetLength(provider.Stream.Position); + } + } + finally + { + // Add back built-in environments. + foreach (GraphEnvironment env in GraphEnvironment.GraphEnvironments.Values) + { + EnvironmentTable[env.Name] = env; + } + } + } + + /// + /// Safely deserializes JSON string to an object. + /// + /// + /// A string to deserialize. + /// An object with deserialized content. + /// A to use to deserialize JSON content. + /// True is successful, otherwise false. + private bool TryDeserializeObject(string serialization, out T result, JsonConverter converter = null) + { + result = default(T); + bool success = false; + try + { + result = converter == null ? JsonConvert.DeserializeObject(serialization) : JsonConvert.DeserializeObject(serialization, converter); + success = true; + } + catch (JsonException) + { + } + + return success; + } + + /// + /// Gets a list of . + /// + /// The name of the environment to remove. + /// A list of + public List ListEnvironments(string name) + { + var result = new List(); + IGraphEnvironment environment; + if (string.IsNullOrWhiteSpace(name)) + { + result.AddRange(Environments); + } + else if (TryGetEnvironment(name, out environment)) + { + result.Add(environment); + } + + result.Sort((e1, e2) => { + return e1.Type.CompareTo(e2.Type); + }); + + return result; + } + + /// + /// Removes a Microsoft Graph environment to the settings file. + /// + /// The name of the environment to remove. + /// The removed object. + public IGraphEnvironment RemoveEnvironment(string name) + { + if (string.IsNullOrEmpty(name)) + { + throw new ArgumentNullException(nameof(name), "Environment name deeds to be specified."); + } + if (GraphEnvironment.GraphEnvironments.ContainsKey(name)) + { + throw new ArgumentException( + ErrorConstants.Message.CannotModifyBuiltInEnvironment.FormatCurrentCulture("remove", name), + nameof(name)); + } + + IGraphEnvironment environment; + if (TryRemoveEnvironment(name, out environment)) + { + return environment; + } + else + { + throw new ArgumentException(string.Format("Environment {0} not found.", name), nameof(name)); + } + } + + /// + /// Sets a Microsoft Graph environment to the settings file. + /// + /// An object to set. + /// An updated object with merged changes. + /// True is successful, otherwise false. + public bool TrySetEnvironment(IGraphEnvironment environment, out IGraphEnvironment mergedEnvironment) + { + bool result = false; + mergedEnvironment = environment; + if (environment != null && !GraphEnvironment.GraphEnvironments.ContainsKey(environment.Name)) + { + if (EnvironmentTable.ContainsKey(environment.Name)) + { + mergedEnvironment = mergedEnvironment.Merge(EnvironmentTable[environment.Name]); + } + + EnvironmentTable[environment.Name] = mergedEnvironment; + result = true; + + // Persist changes to disk. + Save(); + } + + return result; + } + + /// + /// Gets a Microsoft Graph environment to the settings file. + /// + /// The name of the environment to get. + /// The retrieved object. + /// True is successful, otherwise false. + public bool TryGetEnvironment(string name, out IGraphEnvironment environment) + { + bool result = false; + environment = null; + if (EnvironmentTable.ContainsKey(name)) + { + environment = EnvironmentTable[name]; + result = true; + } + + return result; + } + + /// + /// Removes a Microsoft Graph environment to the settings file. + /// + /// The name of the environment to remove. + /// The removed object. + /// True is successful, otherwise false. + public bool TryRemoveEnvironment(string name, out IGraphEnvironment environment) + { + bool result = false; + if (TryGetEnvironment(name, out environment)) + { + result = EnvironmentTable.Remove(name); + // Persist changes to disk. + Save(); + } + + return result; + } + + /// + /// Serializes to JSON. + /// + /// A JSON string. + public override string ToString() + { + return JsonConvert.SerializeObject(this, Formatting.Indented, new GraphSettingsConverter()); + } + + } +} diff --git a/src/Authentication/Authentication/Common/GraphSettingsConverter.cs b/src/Authentication/Authentication/Common/GraphSettingsConverter.cs new file mode 100644 index 00000000000..bc8a3e55c07 --- /dev/null +++ b/src/Authentication/Authentication/Common/GraphSettingsConverter.cs @@ -0,0 +1,49 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication.Common +{ + using Newtonsoft.Json; + using System; + using System.Collections.Generic; + + /// + /// A for . + /// + internal class GraphSettingsConverter: JsonConverter + { + public override bool CanWrite => true; + public override bool CanRead => true; + public override bool CanConvert(Type objectType) + { + return objectType == typeof(IGraphEnvironment); + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (objectType == typeof(IGraphEnvironment)) + { + return serializer.Deserialize(reader); + } + else if (objectType == typeof(Dictionary)) + { + var tempResult = serializer.Deserialize>(reader); + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var key in tempResult.Keys) + { + result[key] = tempResult[key]; + } + + return result; + } + + return serializer.Deserialize(reader); + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + serializer.Serialize(writer, value); + } + } +} diff --git a/src/Authentication/Authentication/Common/ProtectedFileProvider.cs b/src/Authentication/Authentication/Common/ProtectedFileProvider.cs new file mode 100644 index 00000000000..f7c7c7000fa --- /dev/null +++ b/src/Authentication/Authentication/Common/ProtectedFileProvider.cs @@ -0,0 +1,228 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication.Common +{ + using Microsoft.Graph.PowerShell.Authentication.Helpers; + using System; + using System.IO; + using System.Text; + using System.Threading; + + public enum FileProtection + { + SharedRead, + ExclusiveWrite + } + + /// + /// Provides a protected access a shared file. + /// The file can be accessed in ReadOnly or ReadWrite mode. + /// This class MUST be disposed by the caller. + /// + internal abstract class ProtectedFileProvider : IFileProvider, IDisposable + { + protected Stream _stream; + public const int MaxTries = 30; + static readonly TimeSpan RetryInterval = TimeSpan.FromMilliseconds(500); + public string FilePath { get; set; } + protected IDataStore DataStore { get; set; } + + /// + /// Use a named Mutex to prevent cross-process file I/O. + /// + /// + private static readonly Mutex _initializationLock = new Mutex(false, @"Local\GraphPowerShellProtectedFileProviderInit"); + + /// + /// A stream for the file provider. + /// + public Stream Stream + { + get + { + if (_stream == null) + { + InitializeStream(); + } + + return _stream; + } + } + + /// + /// Initializes a stream for the file provider. + /// + protected virtual void InitializeStream() + { + _initializationLock.WaitOne(); + try + { + if (_stream == null) + { + Stream stream; + if (!TryGetStreamLock(AcquireLock, FilePath, out stream)) + { + throw new UnauthorizedAccessException(ErrorConstants.Message.CannotAccessFile.FormatCurrentCulture("acquire access to", FilePath)); + } + _stream = stream; + } + } + finally + { + _initializationLock.ReleaseMutex(); + } + } + + protected abstract Stream AcquireLock(string filePath); + + /// + /// Creates a reader for the stream associated with the file provider. + /// + /// A . + public StreamReader CreateReader() + { + if (Stream == null || !Stream.CanRead || !Stream.CanSeek) + { + throw new IOException(ErrorConstants.Message.CannotAccessFile.FormatCurrentCulture("read", FilePath)); + } + + Stream.Seek(0, SeekOrigin.Begin); + return new StreamReader(Stream, Encoding.UTF8); + } + + /// + /// Creates a writer for the stream associated with the file provider. + /// + /// + public StreamWriter CreateWriter() + { + if (Stream == null || !Stream.CanWrite || !Stream.CanSeek) + { + throw new IOException(ErrorConstants.Message.CannotAccessFile.FormatCurrentCulture("write to", FilePath)); + } + + Stream.Seek(0, SeekOrigin.Begin); + return new StreamWriter(Stream, Encoding.UTF8); + } + + private bool TryGetStreamLock(Func acquireLock, string filePath, out Stream stream) + { + stream = null; + int tries = 0; + do + { + try + { + stream = acquireLock(filePath); + } + catch (IOException) + { + tries++; + Thread.Sleep(RetryInterval); + } + } + while (tries <= MaxTries && stream == null); + return stream != null; + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + var stream = Interlocked.Exchange(ref _stream, null); + if (stream != null) + { + FileStream file = stream as FileStream; + if (file != null) + { + file.Flush(true); + } + else + { + stream.Flush(); + } + + stream.Close(); + } + } + } + + /// + /// Disposes the file and file lock. The caller MUST dispose. + /// + public void Dispose() + { + this.Dispose(true); + } + + /// + /// Create a with protected access using the given protection level. + /// + /// The path to the file. + /// The level for the file. + /// The to access. + /// A with specified access to the file. + public static ProtectedFileProvider CreateFileProvider(string filePath, FileProtection protectionLevel, IDataStore dataStore) + { + if (null == dataStore) + { + throw new ArgumentNullException(nameof(dataStore), "IDataStore cannot be null."); + } + + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentOutOfRangeException(nameof(filePath), "A valid file path must be provided."); + } + + ProtectedFileProvider provider; + switch (protectionLevel) + { + case FileProtection.ExclusiveWrite: + provider = new ExclusiveWriteFileProvider(); + break; + default: + provider = new SharedReadOnlyFileProvider(); + break; + } + + provider.DataStore = dataStore; + provider.FilePath = filePath; + return provider; + } + + /// + /// Create a with protected access using the given protection level. + /// + /// The path to the file. + /// The level for the file. + /// A with specified access to the file. + public static ProtectedFileProvider CreateFileProvider(string filePath, FileProtection protectionLevel = FileProtection.SharedRead) + { + return CreateFileProvider(filePath, protectionLevel, GraphSession.Instance.DataStore); + } + + /// + /// A with shared read only access to the file. + /// + private class SharedReadOnlyFileProvider : ProtectedFileProvider + { + protected override Stream AcquireLock(string filePath) + { + return DataStore.OpenForSharedRead(filePath); + } + } + + /// + /// A with exclusive write access to the file. + /// + private class ExclusiveWriteFileProvider : ProtectedFileProvider + { + protected override Stream AcquireLock(string filePath) + { + return DataStore.OpenForExclusiveWrite(filePath); + } + } + } +} diff --git a/src/Authentication/Authentication/ErrorConstants.cs b/src/Authentication/Authentication/ErrorConstants.cs index e17ea143c4e..33c7df8a925 100644 --- a/src/Authentication/Authentication/ErrorConstants.cs +++ b/src/Authentication/Authentication/ErrorConstants.cs @@ -26,9 +26,11 @@ internal static class Message internal const string DeviceCodeTimeout = "Device code terminal timed-out after {0} seconds. Please try again."; internal const string InvalidUserProvidedToken = "The provided access token is invalid. Set a valid access token to `-{0}` parameter and try again."; internal const string ExpiredUserProvidedToken = "The provided access token has expired. Set a valid access token to `-{0}` parameter and try again."; - //TODO: Confirm final name of Get-MgEnvironment. + internal const string InvalidUrlParameter = "Parameter '{0}' has an invalid endpoint URL. Please use a valid URL with a network protocol i.e. [protocol]://[resource-name]."; internal const string InvalidNationalCloud = "Parameter `{0}` has an invalid national cloud. Use Get-MgEnvironment to get a list of valid national clouds."; internal const string InvalidEnvironment = "Unable to find environment with name '{0}'."; + internal const string CannotAccessFile = "Could not {0} file at '{1}'. Please ensure you have access to this file and try again in a few minutes.."; + internal const string CannotModifyBuiltInEnvironment = "Cannot {0} built-in environment {1}."; } } } diff --git a/src/Authentication/Authentication/Extensions/IGraphEnvironmentExtensions.cs b/src/Authentication/Authentication/Extensions/IGraphEnvironmentExtensions.cs new file mode 100644 index 00000000000..23737d8df10 --- /dev/null +++ b/src/Authentication/Authentication/Extensions/IGraphEnvironmentExtensions.cs @@ -0,0 +1,38 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication.Extensions +{ + using System; + public static class IGraphEnvironmentExtensions + { + /// + /// Merges two into one. + /// + /// The environment to merge into. + /// The environment to merge. + /// A merged . + public static IGraphEnvironment Merge(this IGraphEnvironment environment1, IGraphEnvironment environment2) + { + if (environment1 == null || environment2 == null) + { + throw new ArgumentNullException(nameof(environment1)); + } + if (!string.Equals(environment1.Name, environment2.Name, StringComparison.InvariantCultureIgnoreCase)) + { + throw new ArgumentException("Environment names do not match."); + } + + GraphEnvironment mergedEnvironment = new GraphEnvironment + { + Name = environment1.Name, + Type = environment1.Type, + AzureADEndpoint = environment1.AzureADEndpoint ?? environment2.AzureADEndpoint, + GraphEndpoint = environment1.GraphEndpoint ?? environment2.GraphEndpoint + }; + + return mergedEnvironment; + } + } +} diff --git a/src/Authentication/Authentication/Extensions/PSCmdletExtensions.cs b/src/Authentication/Authentication/Extensions/PSCmdletExtensions.cs index 3ea3118a7ea..c2608f66e7e 100644 --- a/src/Authentication/Authentication/Extensions/PSCmdletExtensions.cs +++ b/src/Authentication/Authentication/Extensions/PSCmdletExtensions.cs @@ -3,7 +3,10 @@ // ------------------------------------------------------------------------------ namespace Microsoft.Graph.PowerShell { + using Microsoft.Graph.PowerShell.Authentication; + using Microsoft.Graph.PowerShell.Authentication.Common; using Microsoft.Graph.PowerShell.Authentication.Extensions; + using Microsoft.Graph.PowerShell.Authentication.Helpers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -85,5 +88,36 @@ internal static bool IsParameterBound(this TPSCmdlet cmdlet, E var propName = ((MemberExpression)propertySelector.Body).Member.Name; return cmdlet.IsParameterBound(propName); } + + internal static void ThrowParameterError(this PSCmdlet cmdlet, string message, params object[] parameters) + { + cmdlet.ThrowError(message.FormatCurrentCulture(parameters), ErrorCategory.InvalidArgument); + } + + internal static void ThrowParameterError(this PSCmdlet cmdlet, string parameterName) + { + cmdlet.ThrowError($"Must specify '{parameterName}'.", ErrorCategory.InvalidArgument); + } + + internal static void ThrowError(this PSCmdlet cmdlet, string message, ErrorCategory errorCategory) + { + cmdlet.ThrowTerminatingError( + new ErrorRecord( + new ArgumentException(message), + Guid.NewGuid().ToString(), + errorCategory, + null) + ); + } + + /// + /// Creates a with shared read access to the data store. + /// + /// The calling cmdlet. + /// A new instance of . + internal static GraphSettings GetContextSettings(this PSCmdlet cmdlet) + { + return new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.ContextSettingFilePath, FileProtection.SharedRead)); + } } } diff --git a/src/Authentication/Authentication/Extensions/StringExtensions.cs b/src/Authentication/Authentication/Extensions/StringExtensions.cs index d3474d4d3e4..9a2b0ae0d22 100644 --- a/src/Authentication/Authentication/Extensions/StringExtensions.cs +++ b/src/Authentication/Authentication/Extensions/StringExtensions.cs @@ -5,7 +5,7 @@ namespace Microsoft.Graph.PowerShell.Authentication.Extensions { using System; - public static class StringExtensions + internal static class StringExtensions { /// /// Indicates whether a specified string is null, empty, consists only of white-space, or has the specified search value. @@ -36,5 +36,15 @@ public static bool ContainsValue(this string target, string searchValue, StringC return target.Contains(searchValue); } + + /// + /// Gets the base URL of a URL string. + /// + /// A URL string to get its base URL (Authority). + public static string GetBaseUrl(this string url) + { + Uri uri = new Uri(url); + return uri.GetLeftPart(UriPartial.Authority); + } } } diff --git a/src/Authentication/Authentication/GraphEnvironmentConstants.cs b/src/Authentication/Authentication/GraphEnvironmentConstants.cs index d4e14b0d006..a31735404ba 100644 --- a/src/Authentication/Authentication/GraphEnvironmentConstants.cs +++ b/src/Authentication/Authentication/GraphEnvironmentConstants.cs @@ -55,7 +55,7 @@ public static class EnvironmentType /// /// Known endpoint values for Microsoft Graph national clouds. /// - internal static readonly IDictionary GraphEnvironmentEndpoints = new Dictionary + internal static readonly IDictionary BuiltInEnvironments = new Dictionary { // Global national cloud endpoints. { diff --git a/src/Authentication/Authentication/Helpers/NationalCloudHandler.cs b/src/Authentication/Authentication/Handlers/NationalCloudHandler.cs similarity index 83% rename from src/Authentication/Authentication/Helpers/NationalCloudHandler.cs rename to src/Authentication/Authentication/Handlers/NationalCloudHandler.cs index 937b18d36d5..3a5baffd465 100644 --- a/src/Authentication/Authentication/Helpers/NationalCloudHandler.cs +++ b/src/Authentication/Authentication/Handlers/NationalCloudHandler.cs @@ -1,9 +1,11 @@ -namespace Microsoft.Graph.PowerShell.Authentication.Helpers +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication.Handlers { using System; - using System.Collections.Generic; using System.Net.Http; - using System.Text; using System.Threading; using System.Threading.Tasks; diff --git a/src/Authentication/Authentication/Helpers/ODataQueryOptionsHandler.cs b/src/Authentication/Authentication/Handlers/ODataQueryOptionsHandler.cs similarity index 96% rename from src/Authentication/Authentication/Helpers/ODataQueryOptionsHandler.cs rename to src/Authentication/Authentication/Handlers/ODataQueryOptionsHandler.cs index ef7a13eac1d..22f69236d35 100644 --- a/src/Authentication/Authentication/Helpers/ODataQueryOptionsHandler.cs +++ b/src/Authentication/Authentication/Handlers/ODataQueryOptionsHandler.cs @@ -2,7 +2,7 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ -namespace Microsoft.Graph.PowerShell.Authentication.Helpers +namespace Microsoft.Graph.PowerShell.Authentication.Handlers { using System; using System.Collections.Generic; @@ -14,7 +14,7 @@ namespace Microsoft.Graph.PowerShell.Authentication.Helpers /// /// A implementation that is used to properly format OData query parameters. /// - public class ODataQueryOptionsHandler : DelegatingHandler + internal class ODataQueryOptionsHandler : DelegatingHandler { private List _standardODataQueryOptions = new List { diff --git a/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs b/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs index 9a40e14710a..c433ad4701a 100644 --- a/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs +++ b/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs @@ -73,7 +73,7 @@ internal static IAuthenticationProvider GetAuthProvider(IAuthContext authContext private static string GetAuthorityUrl(IAuthContext authContext) { string audience = authContext.TenantId ?? GraphEnvironmentConstants.CommonAdTenant; - string defaultInstance = GraphEnvironmentConstants.GraphEnvironmentEndpoints[GraphEnvironmentConstants.EnvironmentName.Global].AzureADEndpoint; + string defaultInstance = GraphEnvironmentConstants.BuiltInEnvironments[GraphEnvironmentConstants.EnvironmentName.Global].AzureADEndpoint; string authorityUrl = $"{defaultInstance}/{audience}"; if (GraphSession.Instance.Environment != null) diff --git a/src/Authentication/Authentication/Helpers/HttpHelpers.cs b/src/Authentication/Authentication/Helpers/HttpHelpers.cs index f33cd226bfe..7ce62d006c5 100644 --- a/src/Authentication/Authentication/Helpers/HttpHelpers.cs +++ b/src/Authentication/Authentication/Helpers/HttpHelpers.cs @@ -3,13 +3,13 @@ // ------------------------------------------------------------------------------ namespace Microsoft.Graph.PowerShell.Authentication.Helpers { - using System; using Microsoft.Graph.PowerShell.Authentication.Cmdlets; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Reflection; using System.Security.Authentication; + using Microsoft.Graph.PowerShell.Authentication.Handlers; /// /// A HTTP helper class. diff --git a/src/Authentication/Authentication/Interfaces/IDataStore.cs b/src/Authentication/Authentication/Interfaces/IDataStore.cs new file mode 100644 index 00000000000..e215bf5e473 --- /dev/null +++ b/src/Authentication/Authentication/Interfaces/IDataStore.cs @@ -0,0 +1,162 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication +{ + using System.IO; + using System.Text; + + /// + /// An interface for a file system. + /// + public interface IDataStore + { + /// + /// Writes the given contents to the specified file. + /// + /// The file path. + /// The file contents. + void WriteFile(string path, string contents); + + /// + /// Writes the given contents to the specified file, using the specified encoding. + /// + /// The file path. + /// The file contents. + /// The encoding to use. + void WriteFile(string path, string content, Encoding encoding); + + /// + /// Writes the given binary contents to the specified file. + /// + /// The file path. + /// The binary contents. + void WriteFile(string path, byte[] contents); + + /// + /// Returns the contents of the given file as a text string. + /// + /// The file path + /// The contents of the given file as a string. Throws an exception if the file is not found. + string ReadFileAsText(string path); + + /// + /// Returns the contents of the given file as a byte array. + /// + /// The file path. + /// The contents of the given file as a byte array. Throws an exception if the file is not found. + byte[] ReadFileAsBytes(string path); + + /// + /// Returns the contents of the given file as a stream. + /// + /// The file path. + /// The contents of the given file as a stream. Throws an exception if the file is not found. + Stream ReadFileAsStream(string path); + + /// + /// Moves the file to the specified location. Overwrites the file if it exists. + /// + /// Source file path. + /// Target file path. + void RenameFile(string oldPath, string newPath); + + /// + /// Copies the given file to the target path. Overwrites the file if it exists. + /// + /// Source file path. + /// Target file path. + void CopyFile(string oldPath, string newPath); + + /// + /// Checks if the given file exists. + /// + /// The file path to check. + /// True if the file exists, false otherwise. + bool FileExists(string path); + + /// + /// Removes the given file. + /// + /// The path of the file to delete. + void DeleteFile(string path); + + /// + /// Removes the given directory. + /// + /// The directory path. + void DeleteDirectory(string dir); + + /// + /// Removes all files from the given directory. + /// + /// The directory to empty. + void EmptyDirectory(string dirPath); + + /// + /// Checks for existence of the given directory. + /// + /// The directory path to check. + /// True if the directory exists, otherwise false. + bool DirectoryExists(string path); + + /// + /// Creates a directory at the given path. + /// + /// The directory path. + void CreateDirectory(string path); + + /// + /// Gets the set of directories inside the given directory path. + /// + /// The directory to list directory contents. + string[] GetDirectories(string sourceDirName); + + /// + /// Gets directories at the given path matching the given pattern and search options. + /// + /// The directory to list directory contents of. + /// The pattern of directory names to include. + /// Directory search options. + /// The path to all contained directories. + string[] GetDirectories(string startDirectory, string filePattern, SearchOption options); + + /// + /// Gets the files in the given directory. + /// + /// The directory path to check. + /// The list of file paths in the given directory. + string[] GetFiles(string sourceDirName); + + /// + /// Gets files at the given path matching the given pattern and search options. + /// + /// The directory to list file contents. + /// The pattern of file names to include. + /// File search options. + /// The path to all contained files. + string[] GetFiles(string startDirectory, string filePattern, SearchOption options); + + /// + /// Gets the file system attributes for the given file. + /// + /// The file path. + /// The file system attributes associated with the file + FileAttributes GetFileAttributes(string path); + + /// + /// Opens a with shared read. + /// + /// Path to the file to open. + /// A to the specified path with shared read. + Stream OpenForSharedRead(string path); + + /// + /// Opens a with exclusive write. + /// + /// Path to the file to open. + /// A to the specified path with exclusive write. + Stream OpenForExclusiveWrite(string path); + } +} diff --git a/src/Authentication/Authentication/Interfaces/IFileProvider.cs b/src/Authentication/Authentication/Interfaces/IFileProvider.cs new file mode 100644 index 00000000000..f02f30b5ace --- /dev/null +++ b/src/Authentication/Authentication/Interfaces/IFileProvider.cs @@ -0,0 +1,16 @@ +// ------------------------------------------------------------------------------ +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. +// ------------------------------------------------------------------------------ + +namespace Microsoft.Graph.PowerShell.Authentication +{ + using System; + using System.IO; + public interface IFileProvider : IDisposable + { + string FilePath { get; } + Stream Stream { get; } + StreamReader CreateReader(); + StreamWriter CreateWriter(); + } +} diff --git a/src/Authentication/Authentication/Interfaces/IGraphSession.cs b/src/Authentication/Authentication/Interfaces/IGraphSession.cs index 2623b77e85d..e41cc745df5 100644 --- a/src/Authentication/Authentication/Interfaces/IGraphSession.cs +++ b/src/Authentication/Authentication/Interfaces/IGraphSession.cs @@ -7,5 +7,6 @@ namespace Microsoft.Graph.PowerShell.Authentication public interface IGraphSession { IAuthContext AuthContext { get; set; } + IDataStore DataStore { get; set; } } } \ No newline at end of file diff --git a/src/Authentication/Authentication/Microsoft.Graph.Authentication.psd1 b/src/Authentication/Authentication/Microsoft.Graph.Authentication.psd1 index d10001395e6..b7abced8764 100644 --- a/src/Authentication/Authentication/Microsoft.Graph.Authentication.psd1 +++ b/src/Authentication/Authentication/Microsoft.Graph.Authentication.psd1 @@ -73,7 +73,8 @@ FunctionsToExport = @() # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = 'Connect-MgGraph', 'Disconnect-MgGraph', 'Get-MgContext', 'Get-MgProfile', - 'Select-MgProfile', 'Invoke-MgGraphRequest' + 'Select-MgProfile', 'Invoke-MgGraphRequest', 'Add-MgEnvironment', 'Get-MgEnvironment', + 'Remove-MgEnvironment', 'Set-MgEnvironment' # Variables to export from this module # VariablesToExport = @() diff --git a/src/Authentication/Authentication/Models/GraphEnvironment.cs b/src/Authentication/Authentication/Models/GraphEnvironment.cs index 4d19d7fb0f8..6c195688e6b 100644 --- a/src/Authentication/Authentication/Models/GraphEnvironment.cs +++ b/src/Authentication/Authentication/Models/GraphEnvironment.cs @@ -15,30 +15,13 @@ internal class GraphEnvironment : IGraphEnvironment /// public static IDictionary GraphEnvironments { get; } = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); - static GraphEnvironment() - { - InitializeEnvironment(); - } - - /// - /// Initializes environments with well known national cloud environments. - /// - public static void InitializeEnvironment() - { - GraphEnvironments.Clear(); - foreach (var env in GraphEnvironmentConstants.GraphEnvironmentEndpoints) - { - GraphEnvironments.Add(env.Key, env.Value); - } - } - /// /// The name of the environment. /// public string Name { get; set; } /// - /// The token audience needed to get access tokens for Microsoft Graph endpoint. + /// The Azure AD endpoint to get access tokens for Microsoft Graph endpoint. /// public string AzureADEndpoint { get; set; } @@ -51,5 +34,22 @@ public static void InitializeEnvironment() /// Type of environment. /// public string Type { get; set; } + + static GraphEnvironment() + { + InitializeEnvironment(); + } + + /// + /// Initializes environments with well known national cloud environments. + /// + public static void InitializeEnvironment() + { + GraphEnvironments.Clear(); + foreach (var env in GraphEnvironmentConstants.BuiltInEnvironments) + { + GraphEnvironments.Add(env.Key, env.Value); + } + } } } From ac22dd408ac5f6df10b80bdb5ef511cf1f856e66 Mon Sep 17 00:00:00 2001 From: Peter Ombwa Date: Fri, 9 Oct 2020 17:26:02 -0700 Subject: [PATCH 3/8] Add unit tests. --- .../Common/GraphSettingsTests.cs | 167 ++++++++ .../Handlers/NationalCloudHandlerTests.cs | 120 ++++++ .../ODataQueryOptionsHandlerTests.cs | 11 +- .../FakeSuccessHandler.cs | 5 +- .../Mocks/MockDataStore.cs | 357 ++++++++++++++++++ .../Authentication/Cmdlets/ConnectMgGraph.cs | 6 +- .../Cmdlets/Environment/AddMgEnvironment.cs | 3 +- .../Environment/RemoveMgEnvironment.cs | 2 +- .../Cmdlets/Environment/SetMgEnvironment.cs | 2 +- .../Authentication/Common/GraphSettings.cs | 20 +- .../Authentication/Constants.cs | 2 +- .../Extensions/PSCmdletExtensions.cs | 2 +- .../Helpers/AuthenticationHelpers.cs | 5 +- .../Authentication/Helpers/HttpHelpers.cs | 6 +- .../Authentication/Models/GraphEnvironment.cs | 6 +- .../Properties/launchSettings.json | 2 +- 16 files changed, 684 insertions(+), 32 deletions(-) create mode 100644 src/Authentication/Authentication.Test/Common/GraphSettingsTests.cs create mode 100644 src/Authentication/Authentication.Test/Handlers/NationalCloudHandlerTests.cs rename src/Authentication/Authentication.Test/{Helpers => Handlers}/ODataQueryOptionsHandlerTests.cs (95%) rename src/Authentication/Authentication.Test/{TestUtils => Mocks}/FakeSuccessHandler.cs (86%) create mode 100644 src/Authentication/Authentication.Test/Mocks/MockDataStore.cs diff --git a/src/Authentication/Authentication.Test/Common/GraphSettingsTests.cs b/src/Authentication/Authentication.Test/Common/GraphSettingsTests.cs new file mode 100644 index 00000000000..b9565a7ecbb --- /dev/null +++ b/src/Authentication/Authentication.Test/Common/GraphSettingsTests.cs @@ -0,0 +1,167 @@ +namespace Microsoft.Graph.Authentication.Test.Common +{ + using Microsoft.Graph.Authentication.Test.Mocks; + using Microsoft.Graph.PowerShell.Authentication; + using Microsoft.Graph.PowerShell.Authentication.Common; + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Runtime.Serialization.Formatters.Binary; + using System.Text; + using Xunit; + + public class GraphSettingsTests + { + [Fact] + public void ShouldSerializeAndDeserializeSettings() + { + GraphSession.Initialize(() => new GraphSession()); + + // Arrange + GraphSession.Instance.DataStore = new MockDataStore(); + GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead)); + + GraphEnvironment userDefinedEnv = new GraphEnvironment + { + Name = "TestCloud", + Type = GraphEnvironmentConstants.EnvironmentType.UserDefined, + AzureADEndpoint = "https://tester.com", + GraphEndpoint = "https://tester.com" + }; + + settings.EnvironmentTable[userDefinedEnv.Name] = userDefinedEnv; + + // Act + string serializedSettings = settings.ToString(); + settings.TryDeserializeObject(serializedSettings, out GraphSettings deserializedSettings, new GraphSettingsConverter()); + deserializedSettings.TryGetEnvironment(userDefinedEnv.Name, out IGraphEnvironment deserializedEnv); + + // Assert + Assert.NotNull(deserializedSettings); + Assert.NotNull(deserializedEnv); + Assert.Equal(serializedSettings, deserializedSettings.ToString()); + Assert.Equal(userDefinedEnv.GraphEndpoint, deserializedEnv.GraphEndpoint); + + GraphSession.Reset(); + } + + [Fact] + public void ShouldSaveSettingsToConfiguredDataStore() + { + GraphSession.Initialize(() => new GraphSession()); + + // Arrange + GraphSession.Instance.DataStore = new MockDataStore(); + GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead)); + + GraphEnvironment userDefinedEnv = new GraphEnvironment + { + Name = "TestCloud", + Type = GraphEnvironmentConstants.EnvironmentType.UserDefined, + AzureADEndpoint = "https://tester.com", + GraphEndpoint = "https://tester.com" + }; + string expectedSettingsContent = @"{ + ""EnvironmentTable"": { + ""TestCloud"": { + ""Name"": ""TestCloud"", + ""AzureADEndpoint"": ""https://tester.com"", + ""GraphEndpoint"": ""https://tester.com"", + ""Type"": ""User-defined"" + } + } +}"; + + // Act + // Saves settings to disk store. + settings.TrySetEnvironment(userDefinedEnv, out IGraphEnvironment savedEnvironment); + string settingsContent = GraphSession.Instance.DataStore.ReadFileAsText(Constants.SettingFilePath).Substring(1).TrimEnd(new[] { '\0' }); + + // Assert + Assert.NotEmpty(settingsContent); + Assert.Equal(expectedSettingsContent, settingsContent); + + GraphSession.Reset(); + } + + [Fact] + public void ShouldLoadSettingsFromConfiguredDataStore() + { + GraphSession.Initialize(() => new GraphSession()); + + // Arrange + GraphSession.Instance.DataStore = new MockDataStore(); + string settingsContent = @"{ + ""EnvironmentTable"": { + ""MyNewCloud"": { + ""Name"": ""MyNewCloud"", + ""AzureADEndpoint"": ""https://login.MyNewCloud.com"", + ""GraphEndpoint"": ""https://graph.MyNewCloud.com"", + ""Type"": ""User-defined"" + }, + ""TrialCloud"": { + ""Name"": ""MyNewCloud"", + ""AzureADEndpoint"": ""https://login.TrialCloud.com"", + ""GraphEndpoint"": ""https://graph.TrialCloud.com"", + ""Type"": ""User-defined"" + } + } +}"; + GraphSession.Instance.DataStore.WriteFile(Constants.SettingFilePath, settingsContent); + + // Act + // Loads settings from disk store. + GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead)); + + settings.TryGetEnvironment("MyNewCloud", out IGraphEnvironment loadedEnvironment); + + // Assert + Assert.NotNull(loadedEnvironment); + // 5 built-in + 2 user-defined + Assert.Equal(7, settings.Environments.Count()); + Assert.Equal("https://login.MyNewCloud.com", loadedEnvironment.AzureADEndpoint); + Assert.Equal("https://graph.MyNewCloud.com", loadedEnvironment.GraphEndpoint); + Assert.Equal(GraphEnvironmentConstants.EnvironmentType.UserDefined, loadedEnvironment.Type); + + GraphSession.Reset(); + } + + [Fact] + public void ShouldRemoveSettingsFromConfiguredDataStore() + { + GraphSession.Initialize(() => new GraphSession()); + + // Arrange + GraphSession.Instance.DataStore = new MockDataStore(); + GraphSettings settings = new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead)); + GraphEnvironment myNewCloudEnv = new GraphEnvironment + { + Name = "MyNewCloud", + Type = GraphEnvironmentConstants.EnvironmentType.UserDefined, + AzureADEndpoint = "https://login.MyNewCloud.com", + GraphEndpoint = "https://graph.MyNewCloud.com" + }; + GraphEnvironment trialCloudEnv = new GraphEnvironment + { + Name = "TrialCloud", + Type = GraphEnvironmentConstants.EnvironmentType.UserDefined, + AzureADEndpoint = "https://login.TrialCloud.com", + GraphEndpoint = "https://graph.TrialCloud.com" + }; + settings.TrySetEnvironment(myNewCloudEnv, out IGraphEnvironment mergedMyNewCloudEnv); + settings.TrySetEnvironment(trialCloudEnv, out IGraphEnvironment mergedTrialCloudEnv); + + // Act + settings.RemoveEnvironment(trialCloudEnv.Name); + string settingsContent = GraphSession.Instance.DataStore.ReadFileAsText(Constants.SettingFilePath); + + // Assert + Assert.NotEmpty(settingsContent); + // 5 built-in + 1 user-defined + Assert.Equal(6, settings.Environments.Count()); + + GraphSession.Reset(); + } + } +} diff --git a/src/Authentication/Authentication.Test/Handlers/NationalCloudHandlerTests.cs b/src/Authentication/Authentication.Test/Handlers/NationalCloudHandlerTests.cs new file mode 100644 index 00000000000..9d5efc407b4 --- /dev/null +++ b/src/Authentication/Authentication.Test/Handlers/NationalCloudHandlerTests.cs @@ -0,0 +1,120 @@ +namespace Microsoft.Graph.Authentication.Test +{ + using Microsoft.Graph.PowerShell.Authentication; + using Microsoft.Graph.PowerShell.Authentication.Handlers; + using System; + using System.Linq; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Xunit; + public class NationalCloudHandlerTests : IDisposable + { + private HttpMessageInvoker _invoker; + private FakeSuccessHandler _fakeSuccessHandler; + private NationalCloudHandler _nationalCloudHandler; + private string topParam = "$top=5"; + private string selectParam = "Select=DisplayName%2CId%2CMail%2CUserType"; + + public NationalCloudHandlerTests() + { + this._fakeSuccessHandler = new FakeSuccessHandler(); + this._nationalCloudHandler = new NationalCloudHandler(new ODataQueryOptionsHandler(_fakeSuccessHandler)); + this._invoker = new HttpMessageInvoker(_nationalCloudHandler); + } + + public void Dispose() + { + Dispose(true); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this._invoker.Dispose(); + } + } + + + [Fact] + public async Task ShouldUseGlobalCloudWhenEnvironmentIsNotSet() + { + GraphSession.Initialize(() => new GraphSession()); + + // Arrange + GraphSession.Instance.Environment = null; + string initialRequestUrl = $"https://graph.microsoft.com/v1.0/users?{topParam}&{selectParam}"; + Uri requestUrl = new Uri(initialRequestUrl); + var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUrl); + + // Act + var response = await this._invoker.SendAsync(httpRequestMessage, new CancellationToken()); + var sentRequestQuery = response.RequestMessage.RequestUri.Query; + + // Assert + Assert.Equal(requestUrl.Scheme, response.RequestMessage.RequestUri.Scheme); + Assert.Equal(requestUrl.Host, response.RequestMessage.RequestUri.Host); + Assert.Contains(topParam, sentRequestQuery); + Assert.Contains($"${selectParam}", sentRequestQuery); + Assert.Equal(2, sentRequestQuery.Split('&').Length); + + GraphSession.Reset(); + } + + [Fact] + public async Task ShouldUseGermanyCloudWhenEnvironmentIsSetToGermany() + { + GraphSession.Initialize(() => new GraphSession()); + + // Arrange + GraphEnvironment germanyEnvironment = GraphEnvironment.BuiltInEnvironments[GraphEnvironmentConstants.EnvironmentName.Germany]; + GraphSession.Instance.Environment = germanyEnvironment; + Uri requestUrl = new Uri($"https://graph.microsoft.com/beta/users?{topParam}&{selectParam}"); + var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUrl); + + // Act + var response = await this._invoker.SendAsync(httpRequestMessage, new CancellationToken()); + var sentRequestQuery = response.RequestMessage.RequestUri.Query; + + // Assert + Assert.Equal(requestUrl.Scheme, response.RequestMessage.RequestUri.Scheme); + Assert.Equal("graph.microsoft.de", response.RequestMessage.RequestUri.Host); + Assert.Contains(topParam, sentRequestQuery); + Assert.Contains(selectParam, sentRequestQuery); + Assert.Equal(2, sentRequestQuery.Split('&').Length); + + GraphSession.Reset(); + } + + [Fact] + public async Task ShouldUseUserDefinedCloudWhenEnvironmentIsSetToAUserDefinedCloud() + { + GraphSession.Initialize(() => new GraphSession()); + + // Arrange + GraphEnvironment userDefinedEnvironment = new GraphEnvironment + { + Name = "Canary", + AzureADEndpoint = "https://login.microsoftonline.com", + GraphEndpoint = "https://canary.graph.microsoft.com" + }; + GraphSession.Instance.Environment = userDefinedEnvironment; + Uri requestUrl = new Uri($"https://graph.microsoft.com/v1.0/users?{topParam}&{selectParam}"); + var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, requestUrl); + + // Act + var response = await this._invoker.SendAsync(httpRequestMessage, new CancellationToken()); + var sentRequestQuery = response.RequestMessage.RequestUri.Query; + + // Assert + Assert.Equal(requestUrl.Scheme, response.RequestMessage.RequestUri.Scheme); + Assert.Equal("canary.graph.microsoft.com", response.RequestMessage.RequestUri.Host); + Assert.Contains(topParam, sentRequestQuery); + Assert.Contains($"${selectParam}", sentRequestQuery); + Assert.Equal(2, sentRequestQuery.Split('&').Length); + + GraphSession.Reset(); + } + } +} diff --git a/src/Authentication/Authentication.Test/Helpers/ODataQueryOptionsHandlerTests.cs b/src/Authentication/Authentication.Test/Handlers/ODataQueryOptionsHandlerTests.cs similarity index 95% rename from src/Authentication/Authentication.Test/Helpers/ODataQueryOptionsHandlerTests.cs rename to src/Authentication/Authentication.Test/Handlers/ODataQueryOptionsHandlerTests.cs index febc3dc64e8..70bbc296c35 100644 --- a/src/Authentication/Authentication.Test/Helpers/ODataQueryOptionsHandlerTests.cs +++ b/src/Authentication/Authentication.Test/Handlers/ODataQueryOptionsHandlerTests.cs @@ -24,9 +24,18 @@ public ODataQueryOptionsHandlerTests() public void Dispose() { - this._invoker.Dispose(); + Dispose(true); } + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this._invoker.Dispose(); + } + } + + [Fact] public async Task ShouldAddDollarSignToStandardODataQueryOptionsToV1Endpoint() { diff --git a/src/Authentication/Authentication.Test/TestUtils/FakeSuccessHandler.cs b/src/Authentication/Authentication.Test/Mocks/FakeSuccessHandler.cs similarity index 86% rename from src/Authentication/Authentication.Test/TestUtils/FakeSuccessHandler.cs rename to src/Authentication/Authentication.Test/Mocks/FakeSuccessHandler.cs index 91b84e3b3e2..5207953cc86 100644 --- a/src/Authentication/Authentication.Test/TestUtils/FakeSuccessHandler.cs +++ b/src/Authentication/Authentication.Test/Mocks/FakeSuccessHandler.cs @@ -1,8 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Net; +using System.Net; using System.Net.Http; -using System.Text; using System.Threading; using System.Threading.Tasks; diff --git a/src/Authentication/Authentication.Test/Mocks/MockDataStore.cs b/src/Authentication/Authentication.Test/Mocks/MockDataStore.cs new file mode 100644 index 00000000000..7d777b810b1 --- /dev/null +++ b/src/Authentication/Authentication.Test/Mocks/MockDataStore.cs @@ -0,0 +1,357 @@ +namespace Microsoft.Graph.Authentication.Test.Mocks +{ + using Microsoft.Graph.PowerShell.Authentication; + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + + public class MockDataStore : IDataStore + { + private const string FolderName = "Folder"; + private Dictionary writeLocks = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + private Dictionary readLocks = new Dictionary(StringComparer.InvariantCultureIgnoreCase); + + public IDictionary VirtualStore = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); + + public void CopyFile(string oldPath, string newPath) + { + if (VirtualStore.ContainsKey(oldPath)) + { + VirtualStore[newPath] = VirtualStore[oldPath]; + } + else + { + throw new IOException("File not found: " + oldPath); + } + } + + public void CreateDirectory(string path) + { + VirtualStore[path] = FolderName; + } + + public void DeleteDirectory(string dir) + { + foreach (var key in VirtualStore.Keys.ToArray()) + { + if (key.StartsWith(dir)) + { + VirtualStore.Remove(key); + } + } + } + + public void DeleteFile(string path) + { + if (VirtualStore.ContainsKey(path)) + { + VirtualStore.Remove(path); + } + else + { + throw new IOException("File not found: " + path); + } + } + + public bool DirectoryExists(string path) + { + foreach (var key in VirtualStore.Keys.ToArray()) + { + if (key.StartsWith(path)) + { + return true; + } + } + return false; + } + + public void EmptyDirectory(string dirPath) + { + foreach (var key in VirtualStore.Keys.ToArray()) + { + if (key.StartsWith(dirPath)) + { + VirtualStore.Remove(key); + } + } + } + + public bool FileExists(string path) + { + return VirtualStore.ContainsKey(path); + } + + public string[] GetDirectories(string sourceDirName) + { + HashSet dirs = new HashSet(); + foreach (var key in VirtualStore.Keys.ToArray()) + { + if (key.StartsWith(sourceDirName)) + { + var directoryName = Path.GetDirectoryName(key); + if (!dirs.Contains(directoryName)) + { + dirs.Add(directoryName); + } + } + } + return dirs.ToArray(); + } + + public string[] GetDirectories(string startDirectory, string filePattern, SearchOption options) + { + HashSet dirs = new HashSet(); + foreach (var key in VirtualStore.Keys.ToArray()) + { + if (key.StartsWith(startDirectory) && Regex.IsMatch(key, WildcardToRegex(filePattern), RegexOptions.IgnoreCase)) + { + var directoryName = Path.GetDirectoryName(key); + if (!dirs.Contains(directoryName)) + { + dirs.Add(directoryName); + } + } + } + return dirs.ToArray(); + } + + public FileAttributes GetFileAttributes(string path) + { + if (VirtualStore[path] == FolderName) + { + return FileAttributes.Directory; + } + if (VirtualStore.ContainsKey(path)) + { + return FileAttributes.Normal; + } + else + { + foreach (var key in VirtualStore.Keys.ToArray()) + { + if (key.StartsWith(path)) + { + return FileAttributes.Directory; + } + } + throw new IOException("File not found: " + path); + } + } + + public string[] GetFiles(string sourceDirName) + { + HashSet files = new HashSet(); + foreach (var key in VirtualStore.Keys.ToArray()) + { + if (key.StartsWith(sourceDirName) && VirtualStore[key] != FolderName) + { + if (!files.Contains(key)) + { + files.Add(key); + } + } + } + return files.ToArray(); + } + + public string[] GetFiles(string startDirectory, string filePattern, SearchOption options) + { + HashSet files = new HashSet(); + foreach (var key in VirtualStore.Keys.ToArray()) + { + if (key.StartsWith(startDirectory) && VirtualStore[key] != FolderName && Regex.IsMatch(key, WildcardToRegex(filePattern), RegexOptions.IgnoreCase)) + { + if (!files.Contains(key)) + { + files.Add(key); + } + } + } + return files.ToArray(); + } + + public Stream OpenForExclusiveWrite(string path) + { + if (string.IsNullOrWhiteSpace(path)) + { + throw new ArgumentNullException(nameof(path)); + } + + if (writeLocks.ContainsKey(path) && writeLocks[path]) + { + throw new IOException($"File {path} is open for writing"); + } + else if (readLocks.ContainsKey(path) && readLocks[path] > 0) + { + throw new IOException($"File {path} is open for reading"); + } + else + { + writeLocks[path] = true; + } + + if (!FileExists(path)) + { + VirtualStore[path] = string.Empty; + } + byte[] buffer = new byte[16384]; + var copyBytes = Encoding.UTF8.GetBytes(VirtualStore[path]); + for (int i = 0; i < copyBytes.Length && i < buffer.Length; ++i) buffer[i] = copyBytes[i]; + return new LockingMemoryStream(buffer, true, + () => + { + writeLocks[path] = false; + VirtualStore[path] = Encoding.UTF8.GetString(buffer); + } + ); + } + + public Stream OpenForSharedRead(string path) + { + if (string.IsNullOrWhiteSpace(path)) + { + throw new ArgumentNullException(nameof(path)); + } + + if (writeLocks.ContainsKey(path) && writeLocks[path]) + { + throw new IOException($"File {path} is open for writing"); + } + else if (readLocks.ContainsKey(path)) + { + readLocks[path]++; + } + else + { + readLocks[path] = 1; + } + + if (!FileExists(path)) + { + VirtualStore[path] = string.Empty; + } + + return new LockingMemoryStream(Encoding.UTF8.GetBytes(VirtualStore[path]), false, () => readLocks[path]--); + } + + public byte[] ReadFileAsBytes(string path) + { + if (VirtualStore.ContainsKey(path)) + { + return Encoding.Default.GetBytes(VirtualStore[path]); + } + else + { + throw new IOException("File not found: " + path); + } + } + + public Stream ReadFileAsStream(string path) + { + if (VirtualStore.ContainsKey(path)) + { + MemoryStream stream = new MemoryStream(); + StreamWriter writer = new StreamWriter(stream); + writer.Write(VirtualStore[path]); + writer.Flush(); + stream.Position = 0; + return stream; + } + else + { + throw new IOException("File not found: " + path); + } + } + + public string ReadFileAsText(string path) + { + if (VirtualStore.ContainsKey(path)) + { + return VirtualStore[path]; + } + else + { + throw new IOException("File not found: " + path); + } + } + + public void RenameFile(string oldPath, string newPath) + { + if (VirtualStore.ContainsKey(oldPath)) + { + VirtualStore[newPath] = VirtualStore[oldPath]; + VirtualStore.Remove(oldPath); + } + else + { + throw new IOException("File not found: " + oldPath); + } + } + + public void WriteFile(string path, string contents) + { + VirtualStore[path] = contents; + } + + public void WriteFile(string path, string contents, Encoding encoding) + { + WriteFile(path, contents); + } + + public void WriteFile(string path, byte[] contents) + { + VirtualStore[path] = Encoding.Default.GetString(contents); + } + + /// + /// Converts unix asterisk based file pattern to regex. + /// + /// Asterisk based pattern. + /// Regular expression of null is empt.y + private static string WildcardToRegex(string wildcard) + { + if (wildcard == null || wildcard == "") return wildcard; + + StringBuilder sb = new StringBuilder(); + + char[] chars = wildcard.ToCharArray(); + for (int i = 0; i < chars.Length; ++i) + { + if (chars[i] == '*') + sb.Append(".*"); + else if (chars[i] == '?') + sb.Append("."); + else if ("+()^$.{}|\\".IndexOf(chars[i]) != -1) + sb.Append('\\').Append(chars[i]); // prefix all meta-characters with backslash. + else + sb.Append(chars[i]); + } + return sb.ToString().ToLowerInvariant(); + } + + private class LockingMemoryStream : MemoryStream + { + Action _unlock; + int _closed = 0; + public LockingMemoryStream(byte[] data, bool writable, Action unlockAction) : base(data, writable) + { + _unlock = unlockAction; + } + + public override void Close() + { + if (Interlocked.Exchange(ref _closed, 1) == 0) + { + _unlock(); + } + + base.Close(); + } + } + } +} diff --git a/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs b/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs index 87f9a6c3e8d..5e0e53db471 100644 --- a/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs +++ b/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs @@ -77,9 +77,9 @@ protected override void BeginProcessing() base.BeginProcessing(); ValidateParameters(); - if (GraphEnvironment.GraphEnvironments.ContainsKey(GraphEnvironmentConstants.EnvironmentName.Global)) + if (GraphEnvironment.BuiltInEnvironments.ContainsKey(GraphEnvironmentConstants.EnvironmentName.Global)) { - environment = GraphEnvironment.GraphEnvironments[GraphEnvironmentConstants.EnvironmentName.Global]; + environment = GraphEnvironment.BuiltInEnvironments[GraphEnvironmentConstants.EnvironmentName.Global]; } else { @@ -148,7 +148,7 @@ protected override void ProcessRecord() try { - // Gets a static instance of IAuthenticationProvider when the client app hasn't changed. + // Gets a static instance of IAuthenticationProvider when the client app hasn't changed. IAuthenticationProvider authProvider = AuthenticationHelpers.GetAuthProvider(authContext); IClientApplicationBase clientApplication = null; if (ParameterSetName == Constants.UserParameterSet) diff --git a/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs index 04c9e2a243a..2359fb56dda 100644 --- a/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs +++ b/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs @@ -7,7 +7,6 @@ namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets using Microsoft.Graph.PowerShell.Authentication.Extensions; using Microsoft.Graph.PowerShell.Authentication.Helpers; using System; - using System.Globalization; using System.Linq; using System.Management.Automation; @@ -43,7 +42,7 @@ protected override void ProcessRecord() base.ProcessRecord(); if (ShouldProcess("adding environment", Name)) { - if (GraphEnvironment.GraphEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase))) + if (GraphEnvironment.BuiltInEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase))) { throw new InvalidOperationException( ErrorConstants.Message.CannotModifyBuiltInEnvironment.FormatCurrentCulture("add", Name)); diff --git a/src/Authentication/Authentication/Cmdlets/Environment/RemoveMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/RemoveMgEnvironment.cs index 8f67f9e7eb9..118ea1a9e99 100644 --- a/src/Authentication/Authentication/Cmdlets/Environment/RemoveMgEnvironment.cs +++ b/src/Authentication/Authentication/Cmdlets/Environment/RemoveMgEnvironment.cs @@ -31,7 +31,7 @@ protected override void ProcessRecord() if (ShouldProcess("removing environment", Name)) { - if (GraphEnvironment.GraphEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase))) + if (GraphEnvironment.BuiltInEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase))) { throw new InvalidOperationException( ErrorConstants.Message.CannotModifyBuiltInEnvironment.FormatCurrentCulture("remove", Name)); diff --git a/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs index bdb1567dae8..fe57bd7baa2 100644 --- a/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs +++ b/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs @@ -43,7 +43,7 @@ protected override void ProcessRecord() if (ShouldProcess("updating environment", Name)) { - if (GraphEnvironment.GraphEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase))) + if (GraphEnvironment.BuiltInEnvironments.Keys.Any((k) => string.Equals(k, Name, StringComparison.CurrentCultureIgnoreCase))) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Cannot change built-in environment {0}.", Name)); diff --git a/src/Authentication/Authentication/Common/GraphSettings.cs b/src/Authentication/Authentication/Common/GraphSettings.cs index 500768a955d..9127bd40b39 100644 --- a/src/Authentication/Authentication/Common/GraphSettings.cs +++ b/src/Authentication/Authentication/Common/GraphSettings.cs @@ -39,7 +39,7 @@ public GraphSettings() { EnvironmentTable = new ConcurrentDictionary(StringComparer.CurrentCultureIgnoreCase); - foreach (var env in GraphEnvironment.GraphEnvironments) + foreach (var env in GraphEnvironment.BuiltInEnvironments) { EnvironmentTable[env.Key] = env.Value; } @@ -82,7 +82,7 @@ private void Initialize(GraphSettings settings = null) { EnvironmentTable.Clear(); // Add built-in environments. - foreach (var env in GraphEnvironment.GraphEnvironments) + foreach (var env in GraphEnvironment.BuiltInEnvironments) { EnvironmentTable[env.Key] = env.Value; } @@ -101,7 +101,7 @@ private void Initialize(GraphSettings settings = null) /// public void Save() { - Save(Constants.ContextSettingFilePath); + Save(Constants.SettingFilePath); } /// @@ -122,7 +122,7 @@ public void Save(string path) public void Save(IFileProvider provider) { // Remove built-in environments. - foreach (string env in GraphEnvironment.GraphEnvironments.Keys) + foreach (string env in GraphEnvironment.BuiltInEnvironments.Keys) { EnvironmentTable.Remove(env); } @@ -147,7 +147,7 @@ public void Save(IFileProvider provider) finally { // Add back built-in environments. - foreach (GraphEnvironment env in GraphEnvironment.GraphEnvironments.Values) + foreach (GraphEnvironment env in GraphEnvironment.BuiltInEnvironments.Values) { EnvironmentTable[env.Name] = env; } @@ -162,7 +162,7 @@ public void Save(IFileProvider provider) /// An object with deserialized content. /// A to use to deserialize JSON content. /// True is successful, otherwise false. - private bool TryDeserializeObject(string serialization, out T result, JsonConverter converter = null) + internal bool TryDeserializeObject(string serialization, out T result, JsonConverter converter = null) { result = default(T); bool success = false; @@ -214,7 +214,7 @@ public IGraphEnvironment RemoveEnvironment(string name) { throw new ArgumentNullException(nameof(name), "Environment name deeds to be specified."); } - if (GraphEnvironment.GraphEnvironments.ContainsKey(name)) + if (GraphEnvironment.BuiltInEnvironments.ContainsKey(name)) { throw new ArgumentException( ErrorConstants.Message.CannotModifyBuiltInEnvironment.FormatCurrentCulture("remove", name), @@ -234,6 +234,7 @@ public IGraphEnvironment RemoveEnvironment(string name) /// /// Sets a Microsoft Graph environment to the settings file. + /// This saves the environment to disk. /// /// An object to set. /// An updated object with merged changes. @@ -242,7 +243,7 @@ public bool TrySetEnvironment(IGraphEnvironment environment, out IGraphEnvironme { bool result = false; mergedEnvironment = environment; - if (environment != null && !GraphEnvironment.GraphEnvironments.ContainsKey(environment.Name)) + if (environment != null && !GraphEnvironment.BuiltInEnvironments.ContainsKey(environment.Name)) { if (EnvironmentTable.ContainsKey(environment.Name)) { @@ -250,10 +251,11 @@ public bool TrySetEnvironment(IGraphEnvironment environment, out IGraphEnvironme } EnvironmentTable[environment.Name] = mergedEnvironment; - result = true; // Persist changes to disk. Save(); + + result = true; } return result; diff --git a/src/Authentication/Authentication/Constants.cs b/src/Authentication/Authentication/Constants.cs index 5b1f5e4a1f1..8a4cac07642 100644 --- a/src/Authentication/Authentication/Constants.cs +++ b/src/Authentication/Authentication/Constants.cs @@ -14,7 +14,7 @@ public static class Constants internal const string AccessTokenParameterSet = "AccessTokenParameterSet"; internal const int MaxDeviceCodeTimeOut = 120; // 2 mins timeout. internal static readonly string GraphDirectoryPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile), ".graph"); - internal static readonly string ContextSettingFilePath = Path.Combine(GraphDirectoryPath, "GraphContext.json"); + internal static readonly string SettingFilePath = Path.Combine(GraphDirectoryPath, "GraphContext.json"); internal const string ProfileDescription = "A snapshot of the Microsoft Graph {0} API for {1} cloud."; internal const string TokenCacheServiceName = "com.microsoft.graph.powershell.sdkcache"; internal const string DefaultProfile = "v1.0"; diff --git a/src/Authentication/Authentication/Extensions/PSCmdletExtensions.cs b/src/Authentication/Authentication/Extensions/PSCmdletExtensions.cs index c2608f66e7e..9a90f9277ed 100644 --- a/src/Authentication/Authentication/Extensions/PSCmdletExtensions.cs +++ b/src/Authentication/Authentication/Extensions/PSCmdletExtensions.cs @@ -117,7 +117,7 @@ internal static void ThrowError(this PSCmdlet cmdlet, string message, ErrorCateg /// A new instance of . internal static GraphSettings GetContextSettings(this PSCmdlet cmdlet) { - return new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.ContextSettingFilePath, FileProtection.SharedRead)); + return new GraphSettings(ProtectedFileProvider.CreateFileProvider(Constants.SettingFilePath, FileProtection.SharedRead)); } } } diff --git a/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs b/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs index c433ad4701a..a39ea2563f5 100644 --- a/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs +++ b/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs @@ -54,7 +54,8 @@ internal static IAuthenticationProvider GetAuthProvider(IAuthContext authContext .Build(); ConfigureTokenCache(confidentialClientApp.AppTokenCache, authContext); - authProvider = new ClientCredentialProvider(confidentialClientApp); + string graphBaseUrl = GraphSession.Instance.Environment?.GraphEndpoint ?? "https://graph.microsoft.com"; + authProvider = new ClientCredentialProvider(confidentialClientApp, $"{graphBaseUrl}/.default"); break; } case AuthenticationType.UserProvidedAccessToken: @@ -73,7 +74,7 @@ internal static IAuthenticationProvider GetAuthProvider(IAuthContext authContext private static string GetAuthorityUrl(IAuthContext authContext) { string audience = authContext.TenantId ?? GraphEnvironmentConstants.CommonAdTenant; - string defaultInstance = GraphEnvironmentConstants.BuiltInEnvironments[GraphEnvironmentConstants.EnvironmentName.Global].AzureADEndpoint; + string defaultInstance = GraphEnvironment.BuiltInEnvironments[GraphEnvironmentConstants.EnvironmentName.Global].AzureADEndpoint; string authorityUrl = $"{defaultInstance}/{audience}"; if (GraphSession.Instance.Environment != null) diff --git a/src/Authentication/Authentication/Helpers/HttpHelpers.cs b/src/Authentication/Authentication/Helpers/HttpHelpers.cs index 7ce62d006c5..7732252c06f 100644 --- a/src/Authentication/Authentication/Helpers/HttpHelpers.cs +++ b/src/Authentication/Authentication/Helpers/HttpHelpers.cs @@ -50,10 +50,10 @@ public static HttpClient GetGraphHttpClient(IAuthContext authContext = null) /// private static void PrependNewSDKVersionHeaders(HttpClient httpClient) { - IEnumerable previousSDKHeaders = - httpClient.DefaultRequestHeaders.GetValues(CoreConstants.Headers.SdkVersionHeaderName); + IEnumerable previousSDKHeaders = httpClient.DefaultRequestHeaders.GetValues(CoreConstants.Headers.SdkVersionHeaderName); httpClient.DefaultRequestHeaders.Remove(CoreConstants.Headers.SdkVersionHeaderName); - httpClient.DefaultRequestHeaders.Add(CoreConstants.Headers.SdkVersionHeaderName, + httpClient.DefaultRequestHeaders.Add( + CoreConstants.Headers.SdkVersionHeaderName, previousSDKHeaders.Prepend(AuthModuleVersionHeaderValue)); } diff --git a/src/Authentication/Authentication/Models/GraphEnvironment.cs b/src/Authentication/Authentication/Models/GraphEnvironment.cs index 6c195688e6b..5f4a53bdc38 100644 --- a/src/Authentication/Authentication/Models/GraphEnvironment.cs +++ b/src/Authentication/Authentication/Models/GraphEnvironment.cs @@ -13,7 +13,7 @@ internal class GraphEnvironment : IGraphEnvironment /// /// Predefined Microsoft Graph environments /// - public static IDictionary GraphEnvironments { get; } = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); + public static IDictionary BuiltInEnvironments { get; } = new ConcurrentDictionary(StringComparer.InvariantCultureIgnoreCase); /// /// The name of the environment. @@ -45,10 +45,10 @@ static GraphEnvironment() /// public static void InitializeEnvironment() { - GraphEnvironments.Clear(); + BuiltInEnvironments.Clear(); foreach (var env in GraphEnvironmentConstants.BuiltInEnvironments) { - GraphEnvironments.Add(env.Key, env.Value); + BuiltInEnvironments.Add(env.Key, env.Value); } } } diff --git a/src/Authentication/Authentication/Properties/launchSettings.json b/src/Authentication/Authentication/Properties/launchSettings.json index 4153aac9d29..26a5601995e 100644 --- a/src/Authentication/Authentication/Properties/launchSettings.json +++ b/src/Authentication/Authentication/Properties/launchSettings.json @@ -3,7 +3,7 @@ "Graph.Authentication": { "commandName": "Executable", "executablePath": "C:\\Program Files\\PowerShell\\7\\pwsh.exe", - "commandLineArgs": "-NoProfile -NoExit" + "commandLineArgs": "-NoExit" } } } \ No newline at end of file From e409f787b4f83d7536ee273245402e0b5ea53744 Mon Sep 17 00:00:00 2001 From: Peter Ombwa Date: Fri, 9 Oct 2020 18:34:31 -0700 Subject: [PATCH 4/8] Add soverign cloud support to Invoke-GraphRequest. --- .../Cmdlets/InvokeMgGraphRequest.cs | 38 +++++++++++++------ .../Extensions/StringExtensions.cs | 9 +++++ 2 files changed, 36 insertions(+), 11 deletions(-) diff --git a/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs b/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs index 4889fe2d02a..3b02b4bb7be 100644 --- a/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs +++ b/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs @@ -10,7 +10,7 @@ using System.Security; using System.Text; using System.Threading; - +using Microsoft.Graph.PowerShell.Authentication.Extensions; using Microsoft.Graph.PowerShell.Authentication.Helpers; using Microsoft.Graph.PowerShell.Authentication.Models; using Microsoft.Graph.PowerShell.Authentication.Properties; @@ -29,6 +29,7 @@ public class InvokeMgGraphRequest : PSCmdlet private readonly CancellationTokenSource _cancellationTokenSource; private readonly InvokeGraphRequestUserAgent _graphRequestUserAgent; private string _originalFilePath; + private IGraphEnvironment _originalEnvironment = null; public InvokeMgGraphRequest() { @@ -45,7 +46,6 @@ public InvokeMgGraphRequest() HelpMessage = "Http Method")] public GraphRequestMethod Method { get; set; } = GraphRequestMethod.GET; - //TODO: Ensure invoke graph supports national cloud. /// /// Uri to call using the Graph HttpClient can be segments such as /beta/me /// or fully qualified url such as https://graph.microsoft.com/beta/me @@ -796,6 +796,21 @@ private static HttpMethod GetHttpMethod(GraphRequestMethod graphRequestMethod) /// internal virtual void PrepareSession() { + // Swap current GraphSession environment with a temporary environment for this request. + // This only occurs when a customer has provided an absolute url and an access token. + if (MyInvocation.BoundParameters.ContainsKey(nameof(Uri)) + && MyInvocation.BoundParameters.ContainsKey(nameof(Token)) + && Uri.IsAbsoluteUri) + { + _originalEnvironment = GraphSession.Instance.Environment; + GraphSession.Instance.Environment = new GraphEnvironment + { + Name = "MSGraphInvokeGraphRequest", + GraphEndpoint = Uri.GetBaseUrl() + // No need to set AAD endpoint since a token is provided. + }; + + } // Create a new GraphRequestSession object to work with if one is not supplied GraphRequestSession = GraphRequestSession ?? new GraphRequestSession(); if (SessionVariable != null) @@ -857,15 +872,6 @@ private void ValidateRequestUri(HttpClient httpClient) nameof(Uri)); ThrowTerminatingError(error); } - // Ensure that the Passed in Uri has the same Host as the HttpClient. - if (Uri.IsAbsoluteUri && httpClient.BaseAddress.Host != Uri.Host) - { - var error = GetValidationError( - Resources.InvokeGraphRequestInvalidHostErrorMessage.FormatCurrentCulture(Uri.Host), - Errors.InvokeGraphRequestInvalidHost, - nameof(Uri)); - ThrowTerminatingError(error); - } } /// @@ -1042,6 +1048,14 @@ private string QualifyFilePath(string path) return resolvedFilePath; } + /// + /// Resets GraphSession environment back to its original state. + /// + private void ResetGraphSessionEnvironment() + { + GraphSession.Instance.Environment = _originalEnvironment; + } + #region CmdLet LifeCycle protected override void BeginProcessing() @@ -1119,11 +1133,13 @@ protected override void ProcessRecord() protected override void EndProcessing() { + ResetGraphSessionEnvironment(); base.EndProcessing(); } protected override void StopProcessing() { + ResetGraphSessionEnvironment(); _cancellationTokenSource.Cancel(); base.StopProcessing(); } diff --git a/src/Authentication/Authentication/Extensions/StringExtensions.cs b/src/Authentication/Authentication/Extensions/StringExtensions.cs index 9a2b0ae0d22..19fd0b577f9 100644 --- a/src/Authentication/Authentication/Extensions/StringExtensions.cs +++ b/src/Authentication/Authentication/Extensions/StringExtensions.cs @@ -44,6 +44,15 @@ public static bool ContainsValue(this string target, string searchValue, StringC public static string GetBaseUrl(this string url) { Uri uri = new Uri(url); + return uri.GetBaseUrl(); + } + + /// + /// Gets the base URL of URI. + /// + /// A URI to get its base URL (Authority). + public static string GetBaseUrl(this Uri uri) + { return uri.GetLeftPart(UriPartial.Authority); } } From 917a8e4ae7ebe5c15c0074fa9508227330071ea1 Mon Sep 17 00:00:00 2001 From: Peter Ombwa Date: Mon, 12 Oct 2020 09:32:43 -0700 Subject: [PATCH 5/8] Update environment session object after updates. --- .../Cmdlets/Environment/AddMgEnvironment.cs | 8 +++++++- .../Cmdlets/Environment/SetMgEnvironment.cs | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs index 2359fb56dda..bc1ed1861d4 100644 --- a/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs +++ b/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs @@ -57,7 +57,13 @@ protected override void ProcessRecord() newEnvironment.AzureADEndpoint = AzureADEndpoint.GetBaseUrl(); newEnvironment.GraphEndpoint = GraphEndpoint.GetBaseUrl(); newEnvironment.Type = GraphEnvironmentConstants.EnvironmentType.UserDefined; - settings.TrySetEnvironment(newEnvironment, out IGraphEnvironment mergedEnvironment); + bool isSuccess = settings.TrySetEnvironment(newEnvironment, out IGraphEnvironment mergedEnvironment); + + // Update environment session object. + if (isSuccess && GraphSession.Instance.Environment?.Name == mergedEnvironment?.Name) + { + GraphSession.Instance.Environment = mergedEnvironment; + } WriteObject(mergedEnvironment); } diff --git a/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs index fe57bd7baa2..41068866129 100644 --- a/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs +++ b/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs @@ -71,7 +71,13 @@ protected override void ProcessRecord() } newEnvironment.Type = GraphEnvironmentConstants.EnvironmentType.UserDefined; - settings.TrySetEnvironment(newEnvironment, out IGraphEnvironment mergedEnvironment); + bool isSuccess = settings.TrySetEnvironment(newEnvironment, out IGraphEnvironment mergedEnvironment); + + // Update environment session object. + if (isSuccess && GraphSession.Instance.Environment?.Name == mergedEnvironment?.Name) + { + GraphSession.Instance.Environment = mergedEnvironment; + } WriteObject(mergedEnvironment); } From 28e649d3931e78461e082d7e0469247ee19fc70f Mon Sep 17 00:00:00 2001 From: Peter Ombwa Date: Mon, 12 Oct 2020 11:11:14 -0700 Subject: [PATCH 6/8] Log updated request url with -Debug. --- src/Authentication/Authentication/ErrorConstants.cs | 2 +- .../Authentication/Helpers/HttpMessageFormatter.cs | 2 ++ tools/Custom/HttpMessageFormatter.cs | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Authentication/Authentication/ErrorConstants.cs b/src/Authentication/Authentication/ErrorConstants.cs index 33c7df8a925..e0212b8aa2b 100644 --- a/src/Authentication/Authentication/ErrorConstants.cs +++ b/src/Authentication/Authentication/ErrorConstants.cs @@ -28,7 +28,7 @@ internal static class Message internal const string ExpiredUserProvidedToken = "The provided access token has expired. Set a valid access token to `-{0}` parameter and try again."; internal const string InvalidUrlParameter = "Parameter '{0}' has an invalid endpoint URL. Please use a valid URL with a network protocol i.e. [protocol]://[resource-name]."; internal const string InvalidNationalCloud = "Parameter `{0}` has an invalid national cloud. Use Get-MgEnvironment to get a list of valid national clouds."; - internal const string InvalidEnvironment = "Unable to find environment with name '{0}'."; + internal const string InvalidEnvironment = "Unable to find environment with name '{0}'. Use Get-MgEnvironment to list available environments."; internal const string CannotAccessFile = "Could not {0} file at '{1}'. Please ensure you have access to this file and try again in a few minutes.."; internal const string CannotModifyBuiltInEnvironment = "Cannot {0} built-in environment {1}."; } diff --git a/src/Authentication/Authentication/Helpers/HttpMessageFormatter.cs b/src/Authentication/Authentication/Helpers/HttpMessageFormatter.cs index 652f4b90917..07d926c5a5a 100644 --- a/src/Authentication/Authentication/Helpers/HttpMessageFormatter.cs +++ b/src/Authentication/Authentication/Helpers/HttpMessageFormatter.cs @@ -245,6 +245,8 @@ private static void SerializeRequestLine(StringBuilder message, HttpRequestMessa private static void SerializeStatusLine(StringBuilder message, HttpResponseMessage httpResponse) { Contract.Assert(message != null, "message cannot be null"); + message.Append(httpResponse.RequestMessage?.Method + SP); + message.Append(httpResponse.RequestMessage?.RequestUri.AbsoluteUri + CRLF); message.Append($"HTTP/{(httpResponse.Version != null ? httpResponse.Version.ToString(2) : "1.1")}{SP}"); message.Append((int) httpResponse.StatusCode + SP); message.Append(httpResponse.ReasonPhrase + CRLF); diff --git a/tools/Custom/HttpMessageFormatter.cs b/tools/Custom/HttpMessageFormatter.cs index 25cd7731ef6..e749d1a41aa 100644 --- a/tools/Custom/HttpMessageFormatter.cs +++ b/tools/Custom/HttpMessageFormatter.cs @@ -265,6 +265,8 @@ private static void SerializeRequestLine(StringBuilder message, HttpRequestMessa private static void SerializeStatusLine(StringBuilder message, HttpResponseMessage httpResponse) { Contract.Assert(message != null, "message cannot be null"); + message.Append(httpResponse.RequestMessage?.Method + SP); + message.Append(httpResponse.RequestMessage?.RequestUri.AbsoluteUri + CRLF); message.Append($"HTTP/{(httpResponse.Version != null ? httpResponse.Version.ToString(2) : "1.1")}{SP}"); message.Append((int)httpResponse.StatusCode + SP); message.Append(httpResponse.ReasonPhrase + CRLF); From 7465e7179170c63ab7aa0985cf93cde9250f8723 Mon Sep 17 00:00:00 2001 From: Peter Ombwa Date: Mon, 12 Oct 2020 14:45:23 -0700 Subject: [PATCH 7/8] Apply suggestions from code review Co-authored-by: DeVere Dyett --- src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs | 2 +- src/Authentication/Authentication/Interfaces/IDataStore.cs | 2 +- src/Authentication/Authentication/Interfaces/IFileProvider.cs | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs b/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs index 5e0e53db471..a92b2f29cb5 100644 --- a/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs +++ b/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs @@ -63,7 +63,7 @@ public class ConnectMgGraph : PSCmdlet, IModuleAssemblyInitializer, IModuleAssem public ContextScope ContextScope { get; set; } [Parameter(Mandatory = false, - HelpMessage = "The name of the national cloud environment to connect to. By default, the SDK uses global cloud.")] + HelpMessage = "The name of the national cloud environment to connect to. By default global cloud is used.")] [ValidateNotNullOrEmpty] [Alias("EnvironmentName", "NationalCloud")] public string Environment { get; set; } diff --git a/src/Authentication/Authentication/Interfaces/IDataStore.cs b/src/Authentication/Authentication/Interfaces/IDataStore.cs index e215bf5e473..06b29f86e78 100644 --- a/src/Authentication/Authentication/Interfaces/IDataStore.cs +++ b/src/Authentication/Authentication/Interfaces/IDataStore.cs @@ -95,7 +95,7 @@ public interface IDataStore void EmptyDirectory(string dirPath); /// - /// Checks for existence of the given directory. + /// Checks for the existence of the given directory. /// /// The directory path to check. /// True if the directory exists, otherwise false. diff --git a/src/Authentication/Authentication/Interfaces/IFileProvider.cs b/src/Authentication/Authentication/Interfaces/IFileProvider.cs index f02f30b5ace..b8cf067799b 100644 --- a/src/Authentication/Authentication/Interfaces/IFileProvider.cs +++ b/src/Authentication/Authentication/Interfaces/IFileProvider.cs @@ -6,6 +6,7 @@ namespace Microsoft.Graph.PowerShell.Authentication { using System; using System.IO; + public interface IFileProvider : IDisposable { string FilePath { get; } From bd0b988b57b6dee8c93695051947f809d419289c Mon Sep 17 00:00:00 2001 From: Peter Ombwa Date: Mon, 12 Oct 2020 16:39:43 -0700 Subject: [PATCH 8/8] Resolve namespaces. --- .../Common/GraphSettingsTests.cs | 7 ++---- .../Handlers/NationalCloudHandlerTests.cs | 3 ++- .../Mocks/MockDataStore.cs | 2 +- .../ProcessTokenCacheStorageTests.cs | 1 + .../Authentication/Cmdlets/ConnectMgGraph.cs | 15 ++++-------- .../Cmdlets/Environment/AddMgEnvironment.cs | 3 +++ .../Cmdlets/Environment/GetMgEnvironment.cs | 2 ++ .../Environment/RemoveMgEnvironment.cs | 2 ++ .../Cmdlets/Environment/SetMgEnvironment.cs | 24 ++++++++++++++----- .../Cmdlets/InvokeMgGraphRequest.cs | 3 +-- .../Authentication/Common/DiskDataStore.cs | 5 ++-- .../Authentication/Common/GraphSession.cs | 1 + .../Common/GraphSessionInitializer.cs | 4 +++- .../Authentication/Common/GraphSettings.cs | 22 ++++++++--------- .../Common/GraphSettingsConverter.cs | 2 ++ .../Common/ProtectedFileProvider.cs | 3 ++- .../Extensions/IGraphEnvironmentExtensions.cs | 3 +++ .../GraphEnvironmentConstants.cs | 2 ++ .../Handlers/NationalCloudHandler.cs | 3 +++ .../Helpers/AuthenticationHelpers.cs | 1 + .../Authentication/Interfaces/IDataStore.cs | 2 +- .../Interfaces/IFileProvider.cs | 2 +- .../Interfaces/IGraphEnvironment.cs | 2 +- .../Interfaces/IGraphSession.cs | 2 +- .../Authentication/Models/GraphEnvironment.cs | 3 ++- 25 files changed, 74 insertions(+), 45 deletions(-) diff --git a/src/Authentication/Authentication.Test/Common/GraphSettingsTests.cs b/src/Authentication/Authentication.Test/Common/GraphSettingsTests.cs index b9565a7ecbb..3d52bf1dc8f 100644 --- a/src/Authentication/Authentication.Test/Common/GraphSettingsTests.cs +++ b/src/Authentication/Authentication.Test/Common/GraphSettingsTests.cs @@ -3,12 +3,9 @@ using Microsoft.Graph.Authentication.Test.Mocks; using Microsoft.Graph.PowerShell.Authentication; using Microsoft.Graph.PowerShell.Authentication.Common; - using System; - using System.Collections.Generic; - using System.IO; + using Microsoft.Graph.PowerShell.Authentication.Interfaces; + using Microsoft.Graph.PowerShell.Authentication.Models; using System.Linq; - using System.Runtime.Serialization.Formatters.Binary; - using System.Text; using Xunit; public class GraphSettingsTests diff --git a/src/Authentication/Authentication.Test/Handlers/NationalCloudHandlerTests.cs b/src/Authentication/Authentication.Test/Handlers/NationalCloudHandlerTests.cs index 9d5efc407b4..7c6bbf1d5d2 100644 --- a/src/Authentication/Authentication.Test/Handlers/NationalCloudHandlerTests.cs +++ b/src/Authentication/Authentication.Test/Handlers/NationalCloudHandlerTests.cs @@ -2,12 +2,13 @@ namespace Microsoft.Graph.Authentication.Test { using Microsoft.Graph.PowerShell.Authentication; using Microsoft.Graph.PowerShell.Authentication.Handlers; + using Microsoft.Graph.PowerShell.Authentication.Models; using System; - using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Xunit; + public class NationalCloudHandlerTests : IDisposable { private HttpMessageInvoker _invoker; diff --git a/src/Authentication/Authentication.Test/Mocks/MockDataStore.cs b/src/Authentication/Authentication.Test/Mocks/MockDataStore.cs index 7d777b810b1..718ab63307d 100644 --- a/src/Authentication/Authentication.Test/Mocks/MockDataStore.cs +++ b/src/Authentication/Authentication.Test/Mocks/MockDataStore.cs @@ -1,6 +1,6 @@ namespace Microsoft.Graph.Authentication.Test.Mocks { - using Microsoft.Graph.PowerShell.Authentication; + using Microsoft.Graph.PowerShell.Authentication.Interfaces; using System; using System.Collections.Concurrent; using System.Collections.Generic; diff --git a/src/Authentication/Authentication.Test/TokenCache/ProcessTokenCacheStorageTests.cs b/src/Authentication/Authentication.Test/TokenCache/ProcessTokenCacheStorageTests.cs index 62193843a18..a9d0582c157 100644 --- a/src/Authentication/Authentication.Test/TokenCache/ProcessTokenCacheStorageTests.cs +++ b/src/Authentication/Authentication.Test/TokenCache/ProcessTokenCacheStorageTests.cs @@ -1,6 +1,7 @@ namespace Microsoft.Graph.Authentication.Test.TokenCache { using Microsoft.Graph.PowerShell.Authentication; + using Microsoft.Graph.PowerShell.Authentication.Common; using Microsoft.Graph.PowerShell.Authentication.TokenCache; using System; using System.Text; diff --git a/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs b/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs index a92b2f29cb5..04c83aabfde 100644 --- a/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs +++ b/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs @@ -16,6 +16,7 @@ namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets using System.Threading.Tasks; using System.Net; using System.Globalization; + using Microsoft.Graph.PowerShell.Authentication.Interfaces; using Microsoft.Graph.PowerShell.Authentication.Common; [Cmdlet(VerbsCommunications.Connect, "MgGraph", DefaultParameterSetName = Constants.UserParameterSet)] @@ -77,16 +78,6 @@ protected override void BeginProcessing() base.BeginProcessing(); ValidateParameters(); - if (GraphEnvironment.BuiltInEnvironments.ContainsKey(GraphEnvironmentConstants.EnvironmentName.Global)) - { - environment = GraphEnvironment.BuiltInEnvironments[GraphEnvironmentConstants.EnvironmentName.Global]; - } - else - { - WriteWarning($"Default environment {GraphEnvironmentConstants.EnvironmentName.Global} cannot be found from environment list."); - WriteWarning("You can get current list via [Microsoft.Graph.PowerShell.Authentication.GraphEnvironment]::GraphEnvironments"); - } - if (MyInvocation.BoundParameters.ContainsKey(nameof(Environment))) { GraphSettings settings = this.GetContextSettings(); @@ -95,6 +86,10 @@ protected override void BeginProcessing() throw new PSInvalidOperationException(string.Format(ErrorConstants.Message.InvalidEnvironment, Environment)); } } + else + { + environment = GraphEnvironment.BuiltInEnvironments[GraphEnvironmentConstants.EnvironmentName.Global]; + } } protected override void EndProcessing() diff --git a/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs index bc1ed1861d4..56ff1f2cfdf 100644 --- a/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs +++ b/src/Authentication/Authentication/Cmdlets/Environment/AddMgEnvironment.cs @@ -4,8 +4,11 @@ namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets { + using Microsoft.Graph.PowerShell.Authentication.Common; using Microsoft.Graph.PowerShell.Authentication.Extensions; using Microsoft.Graph.PowerShell.Authentication.Helpers; + using Microsoft.Graph.PowerShell.Authentication.Interfaces; + using Microsoft.Graph.PowerShell.Authentication.Models; using System; using System.Linq; using System.Management.Automation; diff --git a/src/Authentication/Authentication/Cmdlets/Environment/GetMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/GetMgEnvironment.cs index aff04b65ce3..5d84d5f4fac 100644 --- a/src/Authentication/Authentication/Cmdlets/Environment/GetMgEnvironment.cs +++ b/src/Authentication/Authentication/Cmdlets/Environment/GetMgEnvironment.cs @@ -4,6 +4,8 @@ namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets { + using Microsoft.Graph.PowerShell.Authentication.Common; + using Microsoft.Graph.PowerShell.Authentication.Models; using System.Management.Automation; /// diff --git a/src/Authentication/Authentication/Cmdlets/Environment/RemoveMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/RemoveMgEnvironment.cs index 118ea1a9e99..c491923dac2 100644 --- a/src/Authentication/Authentication/Cmdlets/Environment/RemoveMgEnvironment.cs +++ b/src/Authentication/Authentication/Cmdlets/Environment/RemoveMgEnvironment.cs @@ -4,7 +4,9 @@ namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets { + using Microsoft.Graph.PowerShell.Authentication.Common; using Microsoft.Graph.PowerShell.Authentication.Helpers; + using Microsoft.Graph.PowerShell.Authentication.Models; using System; using System.Globalization; using System.Linq; diff --git a/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs b/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs index 41068866129..ad9631d4f86 100644 --- a/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs +++ b/src/Authentication/Authentication/Cmdlets/Environment/SetMgEnvironment.cs @@ -4,7 +4,10 @@ namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets { + using Microsoft.Graph.PowerShell.Authentication.Common; using Microsoft.Graph.PowerShell.Authentication.Extensions; + using Microsoft.Graph.PowerShell.Authentication.Interfaces; + using Microsoft.Graph.PowerShell.Authentication.Models; using System; using System.Globalization; using System.Linq; @@ -52,12 +55,7 @@ protected override void ProcessRecord() GraphSettings settings = this.GetContextSettings(); if (!settings.TryGetEnvironment(Name, out IGraphEnvironment newEnvironment)) { - // Create default environment if it doesn't exist. - newEnvironment = new GraphEnvironment { - Name = Name, - AzureADEndpoint = settings.EnvironmentTable[GraphEnvironmentConstants.EnvironmentName.Global].AzureADEndpoint, - GraphEndpoint = settings.EnvironmentTable[GraphEnvironmentConstants.EnvironmentName.Global].GraphEndpoint - }; + newEnvironment = new GraphEnvironment { Name = Name }; } if (MyInvocation.BoundParameters.ContainsKey(nameof(AzureADEndpoint))) @@ -70,6 +68,7 @@ protected override void ProcessRecord() newEnvironment.GraphEndpoint = GraphEndpoint.GetBaseUrl(); } + ValidateEnvironment(newEnvironment); newEnvironment.Type = GraphEnvironmentConstants.EnvironmentType.UserDefined; bool isSuccess = settings.TrySetEnvironment(newEnvironment, out IGraphEnvironment mergedEnvironment); @@ -83,6 +82,19 @@ protected override void ProcessRecord() } } + /// + /// Ensures all required properties are set to object. + /// + /// The new object. + private void ValidateEnvironment(IGraphEnvironment newEnvironment) + { + if (string.IsNullOrWhiteSpace(newEnvironment.AzureADEndpoint) + || string.IsNullOrWhiteSpace(newEnvironment.GraphEndpoint)) + { + this.ThrowParameterError(ErrorConstants.Message.InvalidUrlParameter, $"{nameof(GraphEndpoint)} or {nameof(AzureADEndpoint)}"); + } + } + private void ValidateParameters() { if (string.IsNullOrWhiteSpace(Name)) diff --git a/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs b/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs index 3b02b4bb7be..a707ddc32de 100644 --- a/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs +++ b/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs @@ -12,12 +12,11 @@ using System.Threading; using Microsoft.Graph.PowerShell.Authentication.Extensions; using Microsoft.Graph.PowerShell.Authentication.Helpers; +using Microsoft.Graph.PowerShell.Authentication.Interfaces; using Microsoft.Graph.PowerShell.Authentication.Models; using Microsoft.Graph.PowerShell.Authentication.Properties; using Microsoft.PowerShell.Commands; - using Newtonsoft.Json; - using DriveNotFoundException = System.Management.Automation.DriveNotFoundException; namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets diff --git a/src/Authentication/Authentication/Common/DiskDataStore.cs b/src/Authentication/Authentication/Common/DiskDataStore.cs index 96fae179225..667791297e4 100644 --- a/src/Authentication/Authentication/Common/DiskDataStore.cs +++ b/src/Authentication/Authentication/Common/DiskDataStore.cs @@ -2,13 +2,14 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ -namespace Microsoft.Graph.PowerShell.Authentication +namespace Microsoft.Graph.PowerShell.Authentication.Common { + using Microsoft.Graph.PowerShell.Authentication.Interfaces; using System.IO; using System.Text; /// - /// Disk data store based on Windows file management APIs (System.IO). + /// Disk data store based on System.IO APIs. /// internal class DiskDataStore : IDataStore { diff --git a/src/Authentication/Authentication/Common/GraphSession.cs b/src/Authentication/Authentication/Common/GraphSession.cs index be6799d4058..275b4a190b0 100644 --- a/src/Authentication/Authentication/Common/GraphSession.cs +++ b/src/Authentication/Authentication/Common/GraphSession.cs @@ -4,6 +4,7 @@ namespace Microsoft.Graph.PowerShell.Authentication { + using Microsoft.Graph.PowerShell.Authentication.Interfaces; using System; using System.Security; using System.Threading; diff --git a/src/Authentication/Authentication/Common/GraphSessionInitializer.cs b/src/Authentication/Authentication/Common/GraphSessionInitializer.cs index e8ec9c3a8ce..393ea82d12a 100644 --- a/src/Authentication/Authentication/Common/GraphSessionInitializer.cs +++ b/src/Authentication/Authentication/Common/GraphSessionInitializer.cs @@ -2,8 +2,10 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ -namespace Microsoft.Graph.PowerShell.Authentication +namespace Microsoft.Graph.PowerShell.Authentication.Common { + using Microsoft.Graph.PowerShell.Authentication.Interfaces; + public static class GraphSessionInitializer { /// diff --git a/src/Authentication/Authentication/Common/GraphSettings.cs b/src/Authentication/Authentication/Common/GraphSettings.cs index 9127bd40b39..b41a40282f5 100644 --- a/src/Authentication/Authentication/Common/GraphSettings.cs +++ b/src/Authentication/Authentication/Common/GraphSettings.cs @@ -2,11 +2,13 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ -namespace Microsoft.Graph.PowerShell.Authentication +namespace Microsoft.Graph.PowerShell.Authentication.Common { using Microsoft.Graph.PowerShell.Authentication.Common; using Microsoft.Graph.PowerShell.Authentication.Extensions; using Microsoft.Graph.PowerShell.Authentication.Helpers; + using Microsoft.Graph.PowerShell.Authentication.Interfaces; + using Microsoft.Graph.PowerShell.Authentication.Models; using Newtonsoft.Json; using System; using System.Collections.Concurrent; @@ -181,25 +183,23 @@ internal bool TryDeserializeObject(string serialization, out T result, JsonCo /// /// Gets a list of . /// - /// The name of the environment to remove. - /// A list of - public List ListEnvironments(string name) + /// The name of the environment to get. This is optional. + /// A list of . + public List ListEnvironments(string name = null) { var result = new List(); - IGraphEnvironment environment; if (string.IsNullOrWhiteSpace(name)) { result.AddRange(Environments); + result.Sort((e1, e2) => { + return e1.Type.CompareTo(e2.Type); + }); } - else if (TryGetEnvironment(name, out environment)) + else if (TryGetEnvironment(name, out IGraphEnvironment environment)) { result.Add(environment); } - result.Sort((e1, e2) => { - return e1.Type.CompareTo(e2.Type); - }); - return result; } @@ -212,7 +212,7 @@ public IGraphEnvironment RemoveEnvironment(string name) { if (string.IsNullOrEmpty(name)) { - throw new ArgumentNullException(nameof(name), "Environment name deeds to be specified."); + throw new ArgumentNullException(nameof(name), "Environment name needs to be specified."); } if (GraphEnvironment.BuiltInEnvironments.ContainsKey(name)) { diff --git a/src/Authentication/Authentication/Common/GraphSettingsConverter.cs b/src/Authentication/Authentication/Common/GraphSettingsConverter.cs index bc8a3e55c07..bb2bbbd706d 100644 --- a/src/Authentication/Authentication/Common/GraphSettingsConverter.cs +++ b/src/Authentication/Authentication/Common/GraphSettingsConverter.cs @@ -4,6 +4,8 @@ namespace Microsoft.Graph.PowerShell.Authentication.Common { + using Microsoft.Graph.PowerShell.Authentication.Interfaces; + using Microsoft.Graph.PowerShell.Authentication.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; diff --git a/src/Authentication/Authentication/Common/ProtectedFileProvider.cs b/src/Authentication/Authentication/Common/ProtectedFileProvider.cs index f7c7c7000fa..4bf2514e263 100644 --- a/src/Authentication/Authentication/Common/ProtectedFileProvider.cs +++ b/src/Authentication/Authentication/Common/ProtectedFileProvider.cs @@ -5,6 +5,7 @@ namespace Microsoft.Graph.PowerShell.Authentication.Common { using Microsoft.Graph.PowerShell.Authentication.Helpers; + using Microsoft.Graph.PowerShell.Authentication.Interfaces; using System; using System.IO; using System.Text; @@ -17,7 +18,7 @@ public enum FileProtection } /// - /// Provides a protected access a shared file. + /// Provides protected access to a shared file. /// The file can be accessed in ReadOnly or ReadWrite mode. /// This class MUST be disposed by the caller. /// diff --git a/src/Authentication/Authentication/Extensions/IGraphEnvironmentExtensions.cs b/src/Authentication/Authentication/Extensions/IGraphEnvironmentExtensions.cs index 23737d8df10..46bdbab31b2 100644 --- a/src/Authentication/Authentication/Extensions/IGraphEnvironmentExtensions.cs +++ b/src/Authentication/Authentication/Extensions/IGraphEnvironmentExtensions.cs @@ -4,7 +4,10 @@ namespace Microsoft.Graph.PowerShell.Authentication.Extensions { + using Microsoft.Graph.PowerShell.Authentication.Interfaces; + using Microsoft.Graph.PowerShell.Authentication.Models; using System; + public static class IGraphEnvironmentExtensions { /// diff --git a/src/Authentication/Authentication/GraphEnvironmentConstants.cs b/src/Authentication/Authentication/GraphEnvironmentConstants.cs index a31735404ba..56c7025f063 100644 --- a/src/Authentication/Authentication/GraphEnvironmentConstants.cs +++ b/src/Authentication/Authentication/GraphEnvironmentConstants.cs @@ -4,7 +4,9 @@ namespace Microsoft.Graph.PowerShell.Authentication { + using Microsoft.Graph.PowerShell.Authentication.Models; using System.Collections.Generic; + internal static class GraphEnvironmentConstants { /// diff --git a/src/Authentication/Authentication/Handlers/NationalCloudHandler.cs b/src/Authentication/Authentication/Handlers/NationalCloudHandler.cs index 3a5baffd465..4604584ba3c 100644 --- a/src/Authentication/Authentication/Handlers/NationalCloudHandler.cs +++ b/src/Authentication/Authentication/Handlers/NationalCloudHandler.cs @@ -9,6 +9,9 @@ namespace Microsoft.Graph.PowerShell.Authentication.Handlers using System.Threading; using System.Threading.Tasks; + /// + /// A implementation that switches the base URL of a request based on the specified environment\cloud. + /// internal class NationalCloudHandler : DelegatingHandler { /// diff --git a/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs b/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs index a39ea2563f5..afef14b889e 100644 --- a/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs +++ b/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs @@ -4,6 +4,7 @@ namespace Microsoft.Graph.PowerShell.Authentication.Helpers { using Microsoft.Graph.Auth; + using Microsoft.Graph.PowerShell.Authentication.Models; using Microsoft.Graph.PowerShell.Authentication.TokenCache; using Microsoft.Identity.Client; using System; diff --git a/src/Authentication/Authentication/Interfaces/IDataStore.cs b/src/Authentication/Authentication/Interfaces/IDataStore.cs index 06b29f86e78..7629b4a4268 100644 --- a/src/Authentication/Authentication/Interfaces/IDataStore.cs +++ b/src/Authentication/Authentication/Interfaces/IDataStore.cs @@ -2,7 +2,7 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ -namespace Microsoft.Graph.PowerShell.Authentication +namespace Microsoft.Graph.PowerShell.Authentication.Interfaces { using System.IO; using System.Text; diff --git a/src/Authentication/Authentication/Interfaces/IFileProvider.cs b/src/Authentication/Authentication/Interfaces/IFileProvider.cs index b8cf067799b..13127bbc4f8 100644 --- a/src/Authentication/Authentication/Interfaces/IFileProvider.cs +++ b/src/Authentication/Authentication/Interfaces/IFileProvider.cs @@ -2,7 +2,7 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ -namespace Microsoft.Graph.PowerShell.Authentication +namespace Microsoft.Graph.PowerShell.Authentication.Interfaces { using System; using System.IO; diff --git a/src/Authentication/Authentication/Interfaces/IGraphEnvironment.cs b/src/Authentication/Authentication/Interfaces/IGraphEnvironment.cs index 57551a81ab1..db83407195e 100644 --- a/src/Authentication/Authentication/Interfaces/IGraphEnvironment.cs +++ b/src/Authentication/Authentication/Interfaces/IGraphEnvironment.cs @@ -2,7 +2,7 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ -namespace Microsoft.Graph.PowerShell.Authentication +namespace Microsoft.Graph.PowerShell.Authentication.Interfaces { public interface IGraphEnvironment { diff --git a/src/Authentication/Authentication/Interfaces/IGraphSession.cs b/src/Authentication/Authentication/Interfaces/IGraphSession.cs index e41cc745df5..699d32d1d13 100644 --- a/src/Authentication/Authentication/Interfaces/IGraphSession.cs +++ b/src/Authentication/Authentication/Interfaces/IGraphSession.cs @@ -2,7 +2,7 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ -namespace Microsoft.Graph.PowerShell.Authentication +namespace Microsoft.Graph.PowerShell.Authentication.Interfaces { public interface IGraphSession { diff --git a/src/Authentication/Authentication/Models/GraphEnvironment.cs b/src/Authentication/Authentication/Models/GraphEnvironment.cs index 5f4a53bdc38..fe6c02d9f7c 100644 --- a/src/Authentication/Authentication/Models/GraphEnvironment.cs +++ b/src/Authentication/Authentication/Models/GraphEnvironment.cs @@ -2,8 +2,9 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ -namespace Microsoft.Graph.PowerShell.Authentication +namespace Microsoft.Graph.PowerShell.Authentication.Models { + using Microsoft.Graph.PowerShell.Authentication.Interfaces; using System; using System.Collections.Concurrent; using System.Collections.Generic;