diff --git a/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs b/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs index 75a55d6f353..9c16aed41f4 100644 --- a/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs +++ b/src/Authentication/Authentication/Cmdlets/ConnectMgGraph.cs @@ -3,10 +3,6 @@ // ------------------------------------------------------------------------------ namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets { - using Microsoft.Graph.Auth; - using Microsoft.Graph.PowerShell.Authentication.Helpers; - using Microsoft.Graph.PowerShell.Authentication.Models; - using Microsoft.Identity.Client; using System; using System.Collections.Generic; using System.Linq; @@ -16,10 +12,20 @@ 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; + using System.Collections; using System.Security.Cryptography.X509Certificates; + using Identity.Client; + + using Microsoft.Graph.Auth; + using Microsoft.Graph.PowerShell.Authentication.Helpers; + using Microsoft.Graph.PowerShell.Authentication.Models; + + using Interfaces; + using Common; + + using static Helpers.AsyncHelpers; + [Cmdlet(VerbsCommunications.Connect, "MgGraph", DefaultParameterSetName = Constants.UserParameterSet)] [Alias("Connect-Graph")] public class ConnectMgGraph : PSCmdlet, IModuleAssemblyInitializer, IModuleAssemblyCleanup @@ -70,10 +76,12 @@ public class ConnectMgGraph : PSCmdlet, IModuleAssemblyInitializer, IModuleAssem [Alias("EnvironmentName", "NationalCloud")] public string Environment { get; set; } - [Parameter(ParameterSetName = Constants.AppParameterSet, Mandatory = false, HelpMessage = "An x509 Certificate supplied during invocation")] + [Parameter(Mandatory = false, + ParameterSetName = Constants.AppParameterSet, + HelpMessage = "An x509 Certificate supplied during invocation")] public X509Certificate2 Certificate { get; set; } - private CancellationTokenSource cancellationTokenSource; + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private IGraphEnvironment environment; @@ -104,66 +112,102 @@ protected override void EndProcessing() 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) + try { - case Constants.UserParameterSet: - { - // 2 mins timeout. 1 min < HTTP timeout. - TimeSpan authTimeout = new TimeSpan(0, 0, Constants.MaxDeviceCodeTimeOut); - cancellationTokenSource = new CancellationTokenSource(authTimeout); - authContext.AuthType = AuthenticationType.Delegated; - string[] processedScopes = ProcessScopes(Scopes); - authContext.Scopes = processedScopes.Length == 0 ? new string[] { "User.Read" } : processedScopes; - // Default to CurrentUser but allow the customer to change this via `ContextScope` param. - authContext.ContextScope = this.IsParameterBound(nameof(ContextScope)) ? ContextScope : ContextScope.CurrentUser; - } - break; - case Constants.AppParameterSet: + using (var asyncCommandRuntime = new CustomAsyncCommandRuntime(this, _cancellationTokenSource.Token)) + { + asyncCommandRuntime.Wait(ProcessRecordAsync(), _cancellationTokenSource.Token); + } + } + catch (AggregateException aggregateException) + { + // unroll the inner exceptions to get the root cause + foreach (var innerException in aggregateException.Flatten().InnerExceptions) + { + var errorRecords = innerException.Data; + if (errorRecords.Count < 1) { - authContext.AuthType = AuthenticationType.AppOnly; - authContext.ClientId = ClientId; - authContext.CertificateThumbprint = CertificateThumbprint; - authContext.CertificateName = CertificateName; - authContext.Certificate = Certificate; - // Default to Process but allow the customer to change this via `ContextScope` param. - authContext.ContextScope = this.IsParameterBound(nameof(ContextScope)) ? ContextScope : ContextScope.Process; + foreach (DictionaryEntry dictionaryEntry in errorRecords) + { + WriteError((ErrorRecord)dictionaryEntry.Value); + } } - break; - case Constants.AccessTokenParameterSet: + else { - authContext.AuthType = AuthenticationType.UserProvidedAccessToken; - authContext.ContextScope = ContextScope.Process; - // Store user provided access token to a session object. - GraphSession.Instance.UserProvidedToken = new NetworkCredential(string.Empty, AccessToken).SecurePassword; + WriteError(new ErrorRecord(innerException, string.Empty, ErrorCategory.NotSpecified, null)); } - break; + } } + catch (Exception exception) when (exception as PipelineStoppedException == null || + (exception as PipelineStoppedException).InnerException != null) + { + // Write exception out to error channel. + WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.NotSpecified, null)); + } + } - CancellationToken cancellationToken = cancellationTokenSource.Token; - - try + private async Task ProcessRecordAsync() + { + using (NoSynchronizationContext) { - // 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) + IAuthContext authContext = new AuthContext { TenantId = TenantId }; + // Set selected environment to the session object. + GraphSession.Instance.Environment = environment; + + switch (ParameterSetName) { - clientApplication = (authProvider as DeviceCodeProvider).ClientApplication; + case Constants.UserParameterSet: + { + // 2 mins timeout. 1 min < HTTP timeout. + TimeSpan authTimeout = new TimeSpan(0, 0, Constants.MaxDeviceCodeTimeOut); + // To avoid re-initializing the tokenSource, use CancelAfter + _cancellationTokenSource.CancelAfter(authTimeout); + authContext.AuthType = AuthenticationType.Delegated; + string[] processedScopes = ProcessScopes(Scopes); + authContext.Scopes = processedScopes.Length == 0 ? new string[] { "User.Read" } : processedScopes; + // Default to CurrentUser but allow the customer to change this via `ContextScope` param. + authContext.ContextScope = this.IsParameterBound(nameof(ContextScope)) ? ContextScope : ContextScope.CurrentUser; + } + break; + case Constants.AppParameterSet: + { + authContext.AuthType = AuthenticationType.AppOnly; + authContext.ClientId = ClientId; + authContext.CertificateThumbprint = CertificateThumbprint; + authContext.CertificateName = CertificateName; + authContext.Certificate = Certificate; + // Default to Process but allow the customer to change this via `ContextScope` param. + authContext.ContextScope = this.IsParameterBound(nameof(ContextScope)) ? ContextScope : ContextScope.Process; + } + break; + case Constants.AccessTokenParameterSet: + { + authContext.AuthType = AuthenticationType.UserProvidedAccessToken; + authContext.ContextScope = ContextScope.Process; + // Store user provided access token to a session object. + GraphSession.Instance.UserProvidedToken = new NetworkCredential(string.Empty, AccessToken).SecurePassword; + } + break; } - else if (ParameterSetName == Constants.AppParameterSet) + + try { - clientApplication = (authProvider as ClientCredentialProvider).ClientApplication; - } + // 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) + { + clientApplication = (authProvider as DeviceCodeProvider).ClientApplication; + } + else if (ParameterSetName == Constants.AppParameterSet) + { + clientApplication = (authProvider as ClientCredentialProvider).ClientApplication; + } - // Incremental scope consent without re-instantiating the auth provider. We will use a static instance. - GraphRequestContext graphRequestContext = new GraphRequestContext(); - graphRequestContext.CancellationToken = cancellationToken; - graphRequestContext.MiddlewareOptions = new Dictionary + // Incremental scope consent without re-instantiating the auth provider. We will use a static instance. + GraphRequestContext graphRequestContext = new GraphRequestContext(); + graphRequestContext.CancellationToken = _cancellationTokenSource.Token; + graphRequestContext.MiddlewareOptions = new Dictionary { { typeof(AuthenticationHandlerOption).ToString(), @@ -178,49 +222,50 @@ protected override void ProcessRecord() } }; - // Trigger consent. - HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me"); - httpRequestMessage.Properties.Add(typeof(GraphRequestContext).ToString(), graphRequestContext); - authProvider.AuthenticateRequestAsync(httpRequestMessage).GetAwaiter().GetResult(); + // Trigger consent. + HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me"); + httpRequestMessage.Properties.Add(typeof(GraphRequestContext).ToString(), graphRequestContext); + await authProvider.AuthenticateRequestAsync(httpRequestMessage); - IAccount account = null; - if (clientApplication != null) - { - // Only get accounts when we are using MSAL to get an access token. - IEnumerable accounts = clientApplication.GetAccountsAsync().GetAwaiter().GetResult(); - account = accounts.FirstOrDefault(); - } - DecodeJWT(httpRequestMessage.Headers.Authorization?.Parameter, account, ref authContext); + IAccount account = null; + if (clientApplication != null) + { + // Only get accounts when we are using MSAL to get an access token. + IEnumerable accounts = clientApplication.GetAccountsAsync().GetAwaiter().GetResult(); + account = accounts.FirstOrDefault(); + } + DecodeJWT(httpRequestMessage.Headers.Authorization?.Parameter, account, ref authContext); - // Save auth context to session state. - GraphSession.Instance.AuthContext = authContext; - } - catch (AuthenticationException authEx) - { - if ((authEx.InnerException is TaskCanceledException) && cancellationToken.IsCancellationRequested) + // Save auth context to session state. + GraphSession.Instance.AuthContext = authContext; + } + catch (AuthenticationException authEx) { - // DeviceCodeTimeout - throw new Exception(string.Format( - CultureInfo.CurrentCulture, - ErrorConstants.Message.DeviceCodeTimeout, - Constants.MaxDeviceCodeTimeOut)); + if ((authEx.InnerException is TaskCanceledException) && _cancellationTokenSource.Token.IsCancellationRequested) + { + // DeviceCodeTimeout + throw new Exception(string.Format( + CultureInfo.CurrentCulture, + ErrorConstants.Message.DeviceCodeTimeout, + Constants.MaxDeviceCodeTimeOut)); + } + else + { + throw authEx.InnerException ?? authEx; + } } - else + catch (Exception ex) { - throw authEx.InnerException ?? authEx; + throw ex.InnerException ?? ex; } - } - catch (Exception ex) - { - throw ex.InnerException ?? ex; - } - WriteObject("Welcome To Microsoft Graph!"); + WriteObject("Welcome To Microsoft Graph!"); + } } protected override void StopProcessing() { - cancellationTokenSource.Cancel(); + _cancellationTokenSource.Cancel(); base.StopProcessing(); } diff --git a/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs b/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs index a707ddc32de..3edca17967e 100644 --- a/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs +++ b/src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs @@ -1,6 +1,5 @@ using System; using System.Collections; -using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; @@ -10,13 +9,19 @@ using System.Security; using System.Text; using System.Threading; +using System.Threading.Tasks; + 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 static Microsoft.Graph.PowerShell.Authentication.Helpers.AsyncHelpers; + using DriveNotFoundException = System.Management.Automation.DriveNotFoundException; namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets @@ -25,14 +30,13 @@ namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets [Alias("Invoke-GraphRequest")] public class InvokeMgGraphRequest : PSCmdlet { - private readonly CancellationTokenSource _cancellationTokenSource; + private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private readonly InvokeGraphRequestUserAgent _graphRequestUserAgent; + private IGraphEnvironment _originalEnvironment; private string _originalFilePath; - private IGraphEnvironment _originalEnvironment = null; public InvokeMgGraphRequest() { - _cancellationTokenSource = new CancellationTokenSource(); _graphRequestUserAgent = new InvokeGraphRequestUserAgent(this); Authentication = GraphRequestAuthenticationType.Default; } @@ -216,81 +220,81 @@ public InvokeMgGraphRequest() internal string QualifiedOutFile => QualifyFilePath(OutputFilePath); internal bool ShouldSaveToOutFile => !string.IsNullOrEmpty(OutputFilePath); + /// - /// Only write to pipeline if outfile is not specified, inference is not specified but PassThru is set. + /// Only write to pipeline if outfile is not specified, inference is not specified but PassThru is set. /// - internal bool ShouldWriteToPipeline => (!ShouldSaveToOutFile && !InferOutputFileName) || PassThru; + internal bool ShouldWriteToPipeline => !ShouldSaveToOutFile && !InferOutputFileName || PassThru; internal bool ShouldCheckHttpStatus => !SkipHttpErrorCheck; - private static ErrorRecord GenerateHttpErrorRecord(HttpMessageFormatter httpResponseMessageFormatter, + private static async Task GenerateHttpErrorRecordAsync( + HttpMessageFormatter httpResponseMessageFormatter, HttpRequestMessage httpRequestMessage) { - // Load into buffer to avoid stream already consumed issues. - httpResponseMessageFormatter.LoadIntoBufferAsync() - .GetAwaiter() - .GetResult(); - var currentResponse = httpResponseMessageFormatter.HttpResponseMessage; - var errorMessage = - Resources.ResponseStatusCodeFailure.FormatCurrentCulture(currentResponse.StatusCode, - currentResponse.ReasonPhrase); - var httpException = new HttpResponseException(errorMessage, currentResponse); - var errorRecord = new ErrorRecord(httpException, Errors.InvokeGraphHttpResponseException, - ErrorCategory.InvalidOperation, httpRequestMessage); - var detailMsg = httpResponseMessageFormatter.ReadAsStringAsync() - .GetAwaiter() - .GetResult(); - if (!string.IsNullOrEmpty(detailMsg)) + using (NoSynchronizationContext) { - errorRecord.ErrorDetails = new ErrorDetails(detailMsg); - } + // Load into buffer to avoid stream already consumed issues. + await httpResponseMessageFormatter.LoadIntoBufferAsync(); + var currentResponse = httpResponseMessageFormatter.HttpResponseMessage; + var errorMessage = + Resources.ResponseStatusCodeFailure.FormatCurrentCulture(currentResponse.StatusCode, + currentResponse.ReasonPhrase); + var httpException = new HttpResponseException(errorMessage, currentResponse); + var errorRecord = new ErrorRecord(httpException, Errors.InvokeGraphHttpResponseException, + ErrorCategory.InvalidOperation, httpRequestMessage); + var detailMsg = await httpResponseMessageFormatter.ReadAsStringAsync(); + if (!string.IsNullOrEmpty(detailMsg)) + { + errorRecord.ErrorDetails = new ErrorDetails(detailMsg); + } - return errorRecord; + return errorRecord; + } } /// /// When -Verbose is specified, print out response status /// /// - private void ReportRequestStatus(HttpMessageFormatter requestMessageFormatter) + private async Task ReportRequestStatusAsync(HttpMessageFormatter requestMessageFormatter) { - requestMessageFormatter.LoadIntoBufferAsync() - .GetAwaiter() - .GetResult(); - var requestMessage = requestMessageFormatter.HttpRequestMessage; - var requestContentLength = requestMessage.Content?.Headers.ContentLength.Value ?? 0; - var reqVerboseMsg = Resources.InvokeGraphRequestVerboseMessage.FormatCurrentCulture(requestMessage.Method, - requestMessage.RequestUri, - requestContentLength); - // If Verbose is specified, will print out Uri and Content Length - WriteVerbose(reqVerboseMsg); - var requestString = requestMessageFormatter.ReadAsStringAsync() - .GetAwaiter() - .GetResult(); - // If Debug is Specified, will print out the Http Request as a string - WriteDebug(requestString); + using (NoSynchronizationContext) + { + await requestMessageFormatter.LoadIntoBufferAsync(); + var requestMessage = requestMessageFormatter.HttpRequestMessage; + var requestContentLength = requestMessage.Content?.Headers.ContentLength.Value ?? 0; + var reqVerboseMsg = Resources.InvokeGraphRequestVerboseMessage.FormatCurrentCulture( + requestMessage.Method, + requestMessage.RequestUri, + requestContentLength); + // If Verbose is specified, will print out Uri and Content Length + WriteVerbose(reqVerboseMsg); + var requestString = await requestMessageFormatter.ReadAsStringAsync(); + // If Debug is Specified, will print out the Http Request as a string + WriteDebug(requestString); + } } /// /// When -Verbose is specified, print out response status /// /// - private void ReportResponseStatus(HttpMessageFormatter responseMessageFormatter) + private async Task ReportResponseStatusASync(HttpMessageFormatter responseMessageFormatter) { - responseMessageFormatter.LoadIntoBufferAsync() - .GetAwaiter() - .GetResult(); - var contentType = responseMessageFormatter.HttpResponseMessage.GetContentType(); - var respVerboseMsg = Resources.InvokeGraphResponseVerboseMessage.FormatCurrentCulture( - responseMessageFormatter.HttpResponseMessage.Content.Headers.ContentLength, - contentType); - // If Verbose is specified, will print out Uri and Content Length - WriteVerbose(respVerboseMsg); - var responseString = responseMessageFormatter.ReadAsStringAsync() - .GetAwaiter() - .GetResult(); - // If Debug is Specified, will print out the Http Response as a string - WriteDebug(responseString); + using (NoSynchronizationContext) + { + await responseMessageFormatter.LoadIntoBufferAsync(); + var contentType = responseMessageFormatter.HttpResponseMessage.GetContentType(); + var respVerboseMsg = Resources.InvokeGraphResponseVerboseMessage.FormatCurrentCulture( + responseMessageFormatter.HttpResponseMessage.Content.Headers.ContentLength, + contentType); + // If Verbose is specified, will print out Uri and Content Length + WriteVerbose(respVerboseMsg); + var responseString = await responseMessageFormatter.ReadAsStringAsync(); + // If Debug is Specified, will print out the Http Response as a string + WriteDebug(responseString); + } } /// @@ -367,7 +371,8 @@ private Uri PrepareUri(HttpClient httpClient, Uri uri) { // before creating the web request, // preprocess Body if content is a dictionary and method is GET (set as query) - if (Method == GraphRequestMethod.GET && LanguagePrimitives.TryConvertTo(Body, out IDictionary bodyAsDictionary)) + if (Method == GraphRequestMethod.GET && + LanguagePrimitives.TryConvertTo(Body, out IDictionary bodyAsDictionary)) { UriBuilder uriBuilder; // For AbsoluteUri such as /beta/groups$count=true, Get the scheme and host from httpClient @@ -388,7 +393,8 @@ private Uri PrepareUri(HttpClient httpClient, Uri uri) } var bodyQueryParameters = bodyAsDictionary?.FormatDictionary(); - if (uriBuilder.Query != null && uriBuilder.Query.Length > 1 && !string.IsNullOrWhiteSpace(bodyQueryParameters)) + if (uriBuilder.Query != null && uriBuilder.Query.Length > 1 && + !string.IsNullOrWhiteSpace(bodyQueryParameters)) { uriBuilder.Query = uriBuilder.Query.Substring(1) + "&" + bodyQueryParameters; } @@ -504,17 +510,17 @@ private IAuthenticationProvider GetAuthProvider() { return new InvokeGraphRequestAuthProvider(GraphRequestSession); } + // Ensure that AuthContext is present in DefaultAuth mode, otherwise demand for Connect-Graph to be called. if (Authentication == GraphRequestAuthenticationType.Default && GraphSession.Instance.AuthContext != null) { return AuthenticationHelpers.GetAuthProvider(GraphSession.Instance.AuthContext); } - else - { - var error = new ArgumentNullException(Resources.MissingAuthenticationContext.FormatCurrentCulture(nameof(GraphSession.Instance.AuthContext)), - nameof(GraphSession.Instance.AuthContext)); - throw error; - } + + var error = new ArgumentNullException( + Resources.MissingAuthenticationContext.FormatCurrentCulture(nameof(GraphSession.Instance.AuthContext)), + nameof(GraphSession.Instance.AuthContext)); + throw error; } /// @@ -534,24 +540,24 @@ private HttpClient GetHttpClient() /// /// /// - private HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request) + private async Task GetResponseAsync(HttpClient client, HttpRequestMessage request) { - if (client == null) - { - throw new ArgumentNullException(nameof(client)); - } - - if (request == null) + using (NoSynchronizationContext) { - throw new ArgumentNullException(nameof(request)); - } + if (client == null) + { + throw new ArgumentNullException(nameof(client)); + } - var cancellationToken = _cancellationTokenSource.Token; - var response = client.SendAsync(request, cancellationToken) - .GetAwaiter() - .GetResult(); + if (request == null) + { + throw new ArgumentNullException(nameof(request)); + } - return response; + var cancellationToken = _cancellationTokenSource.Token; + var response = await client.SendAsync(request, cancellationToken); + return response; + } } /// @@ -574,6 +580,7 @@ private long SetRequestContent(HttpRequestMessage request, IDictionary content) { throw new ArgumentNullException(nameof(content)); } + // Covert all dictionaries to Json var body = JsonConvert.SerializeObject(content); return SetRequestContent(request, body); @@ -674,6 +681,7 @@ private void FillRequestStream(HttpRequestMessage request) { content = psBody.BaseObject; } + // Passing a dictionary to the body object should be translated to Json. // Almost everything on Microsoft Graph works converts dictionaries and arrays to JSON. if (content is IDictionary dictionary && request.Method != HttpMethod.Get) @@ -712,14 +720,14 @@ private void FillRequestStream(HttpRequestMessage request) // Add the content headers // Only Set Content Headers when its not a GET Request - if (request.Content == null && this.Method != GraphRequestMethod.GET) + if (request.Content == null && Method != GraphRequestMethod.GET) { request.Content = new StringContent(string.Empty); request.Content.Headers.Clear(); } foreach (var entry in GraphRequestSession.ContentHeaders.Where(header => - !string.IsNullOrWhiteSpace(header.Value))) + !string.IsNullOrWhiteSpace(header.Value))) { if (SkipHeaderValidation) { @@ -808,8 +816,8 @@ internal virtual void PrepareSession() 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,7 +865,7 @@ private void ValidateRequestUri(HttpClient httpClient) if (Uri == null) { var error = GetValidationError( - Resources.InvokeGraphRequestMissingUriErrorMessage.FormatCurrentCulture(nameof(Uri)), + Resources.InvokeGraphRequestMissingUriErrorMessage, Errors.InvokeGraphRequestInvalidHost, nameof(Uri)); ThrowTerminatingError(error); @@ -866,7 +874,7 @@ private void ValidateRequestUri(HttpClient httpClient) if (string.IsNullOrWhiteSpace(Uri.ToString())) { var error = GetValidationError( - Resources.InvokeGraphRequestInvalidUriErrorMessage.FormatCurrentCulture(nameof(Uri)), + Resources.InvokeGraphRequestInvalidUriErrorMessage, Errors.InvokeGraphRequestInvalidHost, nameof(Uri)); ThrowTerminatingError(error); @@ -887,38 +895,40 @@ private void ValidateParameters() } // When PATCH or POST is specified, ensure a body is present - if ((Method == GraphRequestMethod.PATCH || Method == GraphRequestMethod.POST) && (Body == null && string.IsNullOrWhiteSpace(InputFilePath))) + if ((Method == GraphRequestMethod.PATCH || Method == GraphRequestMethod.POST) && Body == null && + string.IsNullOrWhiteSpace(InputFilePath)) { var error = GetValidationError( - Resources.BodyMissingWhenMethodIsSpecified.FormatCurrentCulture(nameof(Body), Method), + Resources.BodyMissingWhenMethodIsSpecified, Errors.InvokeGraphRequestBodyMissingWhenMethodIsSpecified, - nameof(Body)); + nameof(Body), Method); ThrowTerminatingError(error); } if (PassThru && OutputFilePath == null) { var error = GetValidationError( - Resources.PassThruWithOutputFilePathMissing.FormatCurrentCulture(nameof(PassThru), - nameof(OutputFilePath)), + Resources.PassThruWithOutputFilePathMissing, Errors.InvokeGraphRequestOutFileMissingException, - nameof(PassThru)); + nameof(PassThru), nameof(OutputFilePath)); ThrowTerminatingError(error); } if (Authentication == GraphRequestAuthenticationType.Default && Token != null) { var error = GetValidationError( - Resources.AuthenticationTokenConflict.FormatCurrentCulture(Authentication, nameof(Token)), - Errors.InvokeGraphRequestAuthenticationTokenConflictException); + Resources.AuthenticationTokenConflict, + Errors.InvokeGraphRequestAuthenticationTokenConflictException, + Authentication, nameof(Token)); ThrowTerminatingError(error); } if (Authentication == GraphRequestAuthenticationType.Default && GraphSession.Instance.AuthContext == null) { var error = GetValidationError( - Resources.NotConnectedToGraphException.FormatCurrentCulture(Authentication, nameof(Token)), - Errors.InvokeGraphRequestAuthenticationTokenConflictException); + Resources.NotConnectedToGraphException, + Errors.InvokeGraphRequestAuthenticationTokenConflictException, + Authentication, nameof(Token)); ThrowTerminatingError(error); } @@ -926,8 +936,9 @@ private void ValidateParameters() if (Authentication == GraphRequestAuthenticationType.UserProvidedToken && Token == null) { var error = GetValidationError( - Resources.AuthenticationCredentialNotSupplied.FormatCurrentCulture(Authentication, nameof(Token)), - Errors.InvokeGraphRequestAuthenticationTokenConflictException); + Resources.AuthenticationCredentialNotSupplied, + Errors.InvokeGraphRequestAuthenticationTokenConflictException, + Authentication, nameof(Token)); ThrowTerminatingError(error); } @@ -935,18 +946,21 @@ private void ValidateParameters() if (Body != null && !string.IsNullOrWhiteSpace(InputFilePath)) { var error = GetValidationError( - Resources.BodyConflict.FormatCurrentCulture(nameof(Body), nameof(InputFilePath)), - Errors.InvokeGraphRequestBodyConflictException); + Resources.BodyConflict, + Errors.InvokeGraphRequestBodyConflictException, + nameof(Body), nameof(InputFilePath)); ThrowTerminatingError(error); } if (InferOutputFileName.IsPresent && !string.IsNullOrWhiteSpace(OutputFilePath)) { var error = GetValidationError( - Resources.InferFileNameOutFilePathConflict.FormatCurrentCulture(nameof(InferOutputFileName), nameof(OutputFilePath)), - Errors.InvokeGraphRequestBodyConflictException); + Resources.InferFileNameOutFilePathConflict, + Errors.InvokeGraphRequestBodyConflictException, + nameof(InferOutputFileName), nameof(OutputFilePath)); ThrowTerminatingError(error); } + // Ensure InputFilePath is an Existing Item if (InputFilePath != null) { @@ -959,21 +973,22 @@ private void ValidateParameters() if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { errorRecord = GetValidationError( - Resources.NotFileSystemPath.FormatCurrentCulture(InputFilePath), - Errors.InvokeGraphRequestFileNotFilesystemPathException, InputFilePath); + Resources.NotFileSystemPath, + Errors.InvokeGraphRequestFileNotFilesystemPathException, + InputFilePath); } else { if (providerPaths.Count > 1) { errorRecord = GetValidationError( - Resources.MultiplePathsResolved.FormatCurrentCulture(InputFilePath), + Resources.MultiplePathsResolved, Errors.InvokeGraphRequestInputFileMultiplePathsResolvedException, InputFilePath); } else if (providerPaths.Count == 0) { errorRecord = GetValidationError( - Resources.NoPathResolved.FormatCurrentCulture(InputFilePath), + Resources.NoPathResolved, Errors.InvokeGraphRequestInputFileNoPathResolvedException, InputFilePath); } else @@ -981,7 +996,7 @@ private void ValidateParameters() if (Directory.Exists(providerPaths[0])) { errorRecord = GetValidationError( - Resources.DirectoryPathSpecified.FormatCurrentCulture(providerPaths[0]), + Resources.DirectoryPathSpecified, Errors.InvokeGraphRequestInputFileNotFilePathException, InputFilePath); } @@ -1048,7 +1063,7 @@ private string QualifyFilePath(string path) } /// - /// Resets GraphSession environment back to its original state. + /// Resets GraphSession environment back to its original state. /// private void ResetGraphSessionEnvironment() { @@ -1068,65 +1083,105 @@ protected override void BeginProcessing() base.BeginProcessing(); } - protected override void ProcessRecord() + private async Task ProcessRecordAsync() { - base.ProcessRecord(); - try + using (NoSynchronizationContext) { - PrepareSession(); - using (var client = GetHttpClient()) + try { - ValidateRequestUri(client); - using (var httpRequestMessage = GetRequest(client, Uri)) + PrepareSession(); + using (var client = GetHttpClient()) { - using (var httpRequestMessageFormatter = new HttpMessageFormatter(httpRequestMessage)) + ValidateRequestUri(client); + using (var httpRequestMessage = GetRequest(client, Uri)) { - FillRequestStream(httpRequestMessage); - try + using (var httpRequestMessageFormatter = new HttpMessageFormatter(httpRequestMessage)) { - ReportRequestStatus(httpRequestMessageFormatter); - var httpResponseMessage = GetResponse(client, httpRequestMessage); - using (var httpResponseMessageFormatter = new HttpMessageFormatter(httpResponseMessage)) + FillRequestStream(httpRequestMessage); + try { - ReportResponseStatus(httpResponseMessageFormatter); - var isSuccess = httpResponseMessage.IsSuccessStatusCode; - if (ShouldCheckHttpStatus && !isSuccess) + await ReportRequestStatusAsync(httpRequestMessageFormatter); + var httpResponseMessage = await GetResponseAsync(client, httpRequestMessage); + using (var httpResponseMessageFormatter = new HttpMessageFormatter(httpResponseMessage)) { - var httpErrorRecord = - GenerateHttpErrorRecord(httpResponseMessageFormatter, httpRequestMessage); - ThrowTerminatingError(httpErrorRecord); + await ReportResponseStatusASync(httpResponseMessageFormatter); + var isSuccess = httpResponseMessage.IsSuccessStatusCode; + if (ShouldCheckHttpStatus && !isSuccess) + { + var httpErrorRecord = await GenerateHttpErrorRecordAsync(httpResponseMessageFormatter, httpRequestMessage); + ThrowTerminatingError(httpErrorRecord); + } + + ProcessResponse(httpResponseMessage); } - - ProcessResponse(httpResponseMessage); } - } - catch (HttpRequestException ex) - { - var er = new ErrorRecord(ex, Errors.InvokeGraphHttpResponseException, - ErrorCategory.InvalidOperation, - httpRequestMessage); - if (ex.InnerException != null) + catch (HttpRequestException ex) { - er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); - } + var er = new ErrorRecord(ex, Errors.InvokeGraphHttpResponseException, + ErrorCategory.InvalidOperation, + httpRequestMessage); + if (ex.InnerException != null) + { + er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); + } - ThrowTerminatingError(er); + ThrowTerminatingError(er); + } } } } } + catch (HttpRequestException httpRequestException) + { + var errorRecord = new ErrorRecord(httpRequestException, ErrorCategory.ConnectionError.ToString(), + ErrorCategory.InvalidResult, null); + httpRequestException.Data.Add(ErrorCategory.ConnectionError.ToString(), errorRecord); + throw; + } + catch (Exception exception) + { + var errorRecord = new ErrorRecord(exception, ErrorCategory.NotSpecified.ToString(), + ErrorCategory.InvalidOperation, null); + exception.Data.Add(ErrorCategory.NotSpecified.ToString(), errorRecord); + throw; + } + } + } + + protected override void ProcessRecord() + { + base.ProcessRecord(); + try + { + using (var asyncCommandRuntime = new CustomAsyncCommandRuntime(this, _cancellationTokenSource.Token)) + { + asyncCommandRuntime.Wait(ProcessRecordAsync(), _cancellationTokenSource.Token); + } } - catch (HttpRequestException httpRequestException) + catch (AggregateException aggregateException) { - WriteError(new ErrorRecord(httpRequestException, ErrorCategory.ConnectionError.ToString(), - ErrorCategory.InvalidResult, null)); - throw; + // unroll the inner exceptions to get the root cause + foreach (var innerException in aggregateException.Flatten().InnerExceptions) + { + var errorRecords = innerException.Data; + if (errorRecords.Count < 1) + { + foreach (DictionaryEntry dictionaryEntry in errorRecords) + { + WriteError((ErrorRecord)dictionaryEntry.Value); + } + } + else + { + WriteError(new ErrorRecord(innerException, string.Empty, ErrorCategory.NotSpecified, null)); + } + } } - catch (Exception exception) + catch (Exception exception) when (exception as PipelineStoppedException == null || + (exception as PipelineStoppedException).InnerException != null) { - WriteError(new ErrorRecord(exception, ErrorCategory.ConnectionError.ToString(), - ErrorCategory.InvalidOperation, null)); - throw; + // Write exception out to error channel. + WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.NotSpecified, null)); } } diff --git a/src/Authentication/Authentication/Helpers/AsyncHelpers.cs b/src/Authentication/Authentication/Helpers/AsyncHelpers.cs new file mode 100644 index 00000000000..cbfbbdabcfd --- /dev/null +++ b/src/Authentication/Authentication/Helpers/AsyncHelpers.cs @@ -0,0 +1,73 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using System; +using System.Threading; + +namespace Microsoft.Graph.PowerShell.Authentication.Helpers +{ + internal static class AsyncHelpers + { + /// + /// An instance of the Dummy IDisposable. + /// + /// + internal static IDisposable Dummy = new DummyDisposable(); + + /// + /// An IDisposable that does absolutely nothing. + /// + internal class DummyDisposable : IDisposable + { + public void Dispose() + { + } + } + + /// + /// An IDisposable that saves the SynchronizationContext,sets it to null and + /// restores it to the original upon Dispose(). + /// NOTE: This is designed to be less invasive than using .ConfigureAwait(false) + /// on every single await in library code (ie, places where we know we don't need + /// to continue in the same context as we went async) + /// + internal class NoSyncContext : IDisposable + { + private readonly SynchronizationContext _original = SynchronizationContext.Current; + + internal NoSyncContext() + { + SynchronizationContext.SetSynchronizationContext(null); + } + + public void Dispose() + { + SynchronizationContext.SetSynchronizationContext(_original); + } + } + + /// + /// Sets the Synchronization Context to null, and returns an IDisposable that when disposed, + /// will restore the synchronization context to the original value. + /// This is used a less-invasive means to ensure that code in the library that doesn't + /// need to be continued in the original context doesn't have to have ConfigureAwait(false) + /// on every single await + /// If the SynchronizationContext is null when this is used, the resulting IDisposable + /// will not do anything (this prevents excessive re-setting of the SynchronizationContext) + /// + /// Usage: + /// + /// using(NoSynchronizationContext) { + /// await SomeAsyncOperation(); + /// await SomeOtherOperation(); + /// } + /// + /// + /// + /// An IDisposable that will return the SynchronizationContext to original state + internal static IDisposable NoSynchronizationContext => + SynchronizationContext.Current == null ? Dummy : new NoSyncContext(); + } +} \ No newline at end of file diff --git a/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs b/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs index 096c0350aa6..93631d0a257 100644 --- a/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs +++ b/src/Authentication/Authentication/Helpers/AuthenticationHelpers.cs @@ -172,11 +172,11 @@ private static void ConfigureTokenCache(ITokenCache tokenCache, IAuthContext aut } /// - /// Gets unexpired certificate of the specified certificate subject name for the current user in My store.. + /// Gets unexpired certificate of the specified certificate thumbprint for the current user in My store. /// - /// Subject name of the certificate to get. + /// Subject name of the certificate to get. /// - private static X509Certificate2 GetCertificateByThumbprint(string CertificateThumbprint) + private static X509Certificate2 GetCertificateByThumbprint(string certificateThumbprint) { X509Certificate2 xCertificate = null; @@ -187,10 +187,10 @@ private static X509Certificate2 GetCertificateByThumbprint(string CertificateThu // Get unexpired certificates with the specified name. X509Certificate2Collection unexpiredCerts = xStore.Certificates .Find(X509FindType.FindByTimeValid, DateTime.Now, false) - .Find(X509FindType.FindByThumbprint, CertificateThumbprint, false); + .Find(X509FindType.FindByThumbprint, certificateThumbprint, false); if (unexpiredCerts.Count < 1) - throw new Exception($"{CertificateThumbprint} certificate was not found or has expired."); + throw new Exception($"{certificateThumbprint} certificate was not found or has expired."); // Only return current cert. xCertificate = unexpiredCerts @@ -202,11 +202,11 @@ private static X509Certificate2 GetCertificateByThumbprint(string CertificateThu } /// - /// Gets unexpired certificate of the specified certificate subject name for the current user in My store.. + /// Gets unexpired certificate of the specified certificate subject name for the current user in My store. /// - /// Subjec name of the certificate to get. + /// Subject name of the certificate to get. /// - private static X509Certificate2 GetCertificateByName(string CertificateName) + private static X509Certificate2 GetCertificateByName(string certificateName) { X509Certificate2 xCertificate = null; @@ -217,10 +217,10 @@ private static X509Certificate2 GetCertificateByName(string CertificateName) // Get unexpired certificates with the specified name. X509Certificate2Collection unexpiredCerts = xStore.Certificates .Find(X509FindType.FindByTimeValid, DateTime.Now, false) - .Find(X509FindType.FindBySubjectDistinguishedName, CertificateName, false); + .Find(X509FindType.FindBySubjectDistinguishedName, certificateName, false); if (unexpiredCerts.Count < 1) - throw new Exception($"{CertificateName} certificate was not found or has expired."); + throw new Exception($"{certificateName} certificate was not found or has expired."); // Only return current cert. xCertificate = unexpiredCerts diff --git a/src/Authentication/Authentication/Helpers/CustomAsyncCommandRuntime.cs b/src/Authentication/Authentication/Helpers/CustomAsyncCommandRuntime.cs new file mode 100644 index 00000000000..acf1cf6b1d8 --- /dev/null +++ b/src/Authentication/Authentication/Helpers/CustomAsyncCommandRuntime.cs @@ -0,0 +1,821 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +using System; +using System.Management.Automation; +using System.Management.Automation.Host; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.Graph.PowerShell.Authentication.Helpers +{ + internal class CustomAsyncCommandRuntime : ICommandRuntime2, IDisposable + { + private readonly ICommandRuntime2 _originalCommandRuntime; + private readonly Thread _originalThread; + + private PSCmdlet _cmdlet; + private ManualResetEventSlim _completed = new ManualResetEventSlim(false); + private ManualResetEventSlim _readyToRun = new ManualResetEventSlim(false); + + private Action _runOnMainThread; + private SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); + + public CancellationToken CancellationToken; + + internal CustomAsyncCommandRuntime(PSCmdlet cmdlet, CancellationToken cancellationToken) + { + _originalCommandRuntime = cmdlet.CommandRuntime as ICommandRuntime2; + _originalThread = Thread.CurrentThread; + CancellationToken = cancellationToken; + _cmdlet = cmdlet; + cmdlet.CommandRuntime = this; + } + + public bool AllowInteractive { get; set; } = false; + + public PSHost Host => _originalCommandRuntime.Host; + + public PSTransactionContext CurrentPSTransaction => _originalCommandRuntime.CurrentPSTransaction; + + public bool ShouldContinue(string query, string caption, bool hasSecurityImpact, ref bool yesToAll, + ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + return _originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yesToAll, + ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + var yta = yesToAll; + var nta = noToAll; + var result = false; + + // set the function to run + _runOnMainThread = () => + result = _originalCommandRuntime.ShouldContinue(query, caption, hasSecurityImpact, ref yta, + ref nta); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + return _originalCommandRuntime.ShouldContinue(query, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + var result = false; + + // set the function to run + _runOnMainThread = () => result = _originalCommandRuntime.ShouldContinue(query, caption); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + return _originalCommandRuntime.ShouldContinue(query, caption, ref yesToAll, ref noToAll); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + var yta = yesToAll; + var nta = noToAll; + var result = false; + + // set the function to run + _runOnMainThread = () => + result = _originalCommandRuntime.ShouldContinue(query, caption, ref yta, ref nta); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + yesToAll = yta; + noToAll = nta; + return result; + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + return _originalCommandRuntime.ShouldProcess(target); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + var result = false; + + // set the function to run + _runOnMainThread = () => result = _originalCommandRuntime.ShouldProcess(target); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string target, string action) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + return _originalCommandRuntime.ShouldProcess(target, action); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + var result = false; + + // set the function to run + _runOnMainThread = () => result = _originalCommandRuntime.ShouldProcess(target, action); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + return _originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + var result = false; + + // set the function to run + _runOnMainThread = () => + result = _originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, + out ShouldProcessReason shouldProcessReason) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + return _originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, + out shouldProcessReason); + } + + CheckForInteractive(); + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + var result = false; + var reason = ShouldProcessReason.None; + + // set the function to run + _runOnMainThread = () => + result = _originalCommandRuntime.ShouldProcess(verboseDescription, verboseWarning, caption, + out reason); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + shouldProcessReason = reason; + return result; + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void ThrowTerminatingError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + _originalCommandRuntime.ThrowTerminatingError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + _runOnMainThread = () => _originalCommandRuntime.ThrowTerminatingError(errorRecord); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public bool TransactionAvailable() + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + return _originalCommandRuntime.TransactionAvailable(); + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + var result = false; + + // set the function to run + _runOnMainThread = () => result = _originalCommandRuntime.TransactionAvailable(); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // set the output variables + return result; + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteCommandDetail(string text) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + _originalCommandRuntime.WriteCommandDetail(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + _runOnMainThread = () => _originalCommandRuntime.WriteCommandDetail(text); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteDebug(string text) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + _originalCommandRuntime.WriteDebug(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + _runOnMainThread = () => _originalCommandRuntime.WriteDebug(text); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteError(ErrorRecord errorRecord) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + _originalCommandRuntime.WriteError(errorRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + _runOnMainThread = () => _originalCommandRuntime.WriteError(errorRecord); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteInformation(InformationRecord informationRecord) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + _originalCommandRuntime.WriteInformation(informationRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + _runOnMainThread = () => _originalCommandRuntime.WriteInformation(informationRecord); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + _originalCommandRuntime.WriteObject(sendToPipeline); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + _runOnMainThread = () => _originalCommandRuntime.WriteObject(sendToPipeline); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteObject(object sendToPipeline, bool enumerateCollection) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + _originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + _runOnMainThread = () => _originalCommandRuntime.WriteObject(sendToPipeline, enumerateCollection); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + _originalCommandRuntime.WriteProgress(progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + _runOnMainThread = () => _originalCommandRuntime.WriteProgress(progressRecord); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteProgress(long sourceId, ProgressRecord progressRecord) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + _originalCommandRuntime.WriteProgress(sourceId, progressRecord); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + _runOnMainThread = () => _originalCommandRuntime.WriteProgress(sourceId, progressRecord); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteVerbose(string text) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + _originalCommandRuntime.WriteVerbose(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + _runOnMainThread = () => _originalCommandRuntime.WriteVerbose(text); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void WriteWarning(string text) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + _originalCommandRuntime.WriteWarning(text); + return; + } + + // otherwise, queue up the request and wait for the main thread to do the right thing. + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + + // set the function to run + _runOnMainThread = () => _originalCommandRuntime.WriteWarning(text); + + // tell the main thread to go ahead + _readyToRun.Set(); + + // wait for the result (or cancellation!) + WaitForCompletion(); + + // return + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + + public void Dispose() + { + if (_cmdlet != null) + { + _cmdlet.CommandRuntime = _originalCommandRuntime; + _cmdlet = null; + } + + _semaphore?.Dispose(); + _semaphore = null; + _readyToRun?.Dispose(); + _readyToRun = null; + _completed?.Dispose(); + _completed = null; + } + + private void CheckForInteractive() + { + // This is an interactive call -- if we are not on the original thread, this will only work if this was done at ACR creation time; + if (!AllowInteractive) + { + throw new Exception("AsyncCommandRuntime is not configured for interactive calls"); + } + } + + private void WaitOurTurn() + { + // wait for our turn to play + _semaphore?.Wait(CancellationToken); + + // ensure that completed is not set + _completed.Reset(); + } + + private void WaitForCompletion() + { + // wait for the result (or cancellation!) + WaitHandle.WaitAny(new[] {CancellationToken.WaitHandle, _completed?.WaitHandle}); + + // let go of the semaphore + _semaphore?.Release(); + } + + public void Wait(Task ProcessRecordAsyncTask, CancellationToken cancellationToken) + { + do + { + WaitHandle.WaitAny(new[] + {_readyToRun.WaitHandle, ((IAsyncResult) ProcessRecordAsyncTask).AsyncWaitHandle}); + if (_readyToRun.IsSet) + { + // reset the request for the next time + _readyToRun.Reset(); + + // run the delegate on this thread + _runOnMainThread(); + + // tell the originator everything is complete + _completed.Set(); + } + } while (!ProcessRecordAsyncTask.IsCompleted); + + if (ProcessRecordAsyncTask.IsFaulted) + { + // don't unwrap a Aggregate Exception -- we'll lose the stack trace of the actual exception. + // if( ProcessRecordAsyncTask.Exception is System.AggregateException aggregate ) { + // throw aggregate.InnerException; + // } + throw ProcessRecordAsyncTask.Exception; + } + } + + public T ExecuteSync(Func step) + { + // if we are on the original thread, just call straight thru. + if (_originalThread == Thread.CurrentThread) + { + return step(); + } + + var result = default(T); + try + { + // wait for our turn to talk to the main thread + WaitOurTurn(); + // set the function to run + _runOnMainThread = () => { result = step(); }; + // tell the main thread to go ahead + _readyToRun.Set(); + // wait for the result (or cancellation!) + WaitForCompletion(); + // return + return result; + } + catch (OperationCanceledException exception) + { + // maybe don't even worry? + throw exception; + } + } + } +} \ No newline at end of file diff --git a/src/Authentication/Authentication/Interfaces/IAuthContext.cs b/src/Authentication/Authentication/Interfaces/IAuthContext.cs index 98ce72b2b87..6e52994179d 100644 --- a/src/Authentication/Authentication/Interfaces/IAuthContext.cs +++ b/src/Authentication/Authentication/Interfaces/IAuthContext.cs @@ -2,10 +2,10 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ -using System.Security.Cryptography.X509Certificates; - namespace Microsoft.Graph.PowerShell.Authentication { + using System.Security.Cryptography.X509Certificates; + public enum AuthenticationType { Delegated, diff --git a/src/Authentication/Authentication/Models/AuthContext.cs b/src/Authentication/Authentication/Models/AuthContext.cs index 8a9545d5478..5a7205e3a57 100644 --- a/src/Authentication/Authentication/Models/AuthContext.cs +++ b/src/Authentication/Authentication/Models/AuthContext.cs @@ -2,10 +2,9 @@ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ -using System.Security.Cryptography.X509Certificates; - namespace Microsoft.Graph.PowerShell.Authentication { + using System.Security.Cryptography.X509Certificates; public class AuthContext: IAuthContext { private const string PowerShellClientId = "14d82eec-204b-4c2f-b7e8-296a70dab67e";