|
| 1 | +// ------------------------------------------------------------------------------ |
| 2 | +// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. |
| 3 | +// ------------------------------------------------------------------------------ |
| 4 | + |
| 5 | +namespace Microsoft.Graph.Beta.PowerShell |
| 6 | +{ |
| 7 | + using Microsoft.Graph.Beta.PowerShell.Models; |
| 8 | + using Newtonsoft.Json; |
| 9 | + using System; |
| 10 | + using System.Collections.Generic; |
| 11 | + using System.IO; |
| 12 | + using System.Linq; |
| 13 | + using System.Net.Http; |
| 14 | + using System.Net.Http.Headers; |
| 15 | + using System.Text; |
| 16 | + using System.Text.RegularExpressions; |
| 17 | + using System.Threading.Tasks; |
| 18 | + using System.Xml.Linq; |
| 19 | + |
| 20 | + public static class HttpMessageLogFormatter |
| 21 | + { |
| 22 | + internal static async Task<HttpRequestMessage> CloneAsync(this HttpRequestMessage originalRequest) |
| 23 | + { |
| 24 | + var newRequest = new HttpRequestMessage(originalRequest.Method, originalRequest.RequestUri); |
| 25 | + |
| 26 | + // Copy requestClone headers. |
| 27 | + foreach (var header in originalRequest.Headers) |
| 28 | + newRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); |
| 29 | + |
| 30 | + // Copy requestClone properties. |
| 31 | + foreach (var property in originalRequest.Properties) |
| 32 | + newRequest.Properties.Add(property); |
| 33 | + |
| 34 | + // Set Content if previous requestClone had one. |
| 35 | + if (originalRequest.Content != null) |
| 36 | + { |
| 37 | + // Try cloning request content; otherwise, skip due to https://github.com/dotnet/corefx/pull/19082 in .NET 4.x. |
| 38 | + try |
| 39 | + { |
| 40 | + // HttpClient doesn't rewind streams and we have to explicitly do so. |
| 41 | + var ms = new MemoryStream(); |
| 42 | + await originalRequest.Content.CopyToAsync(ms).ConfigureAwait(false); |
| 43 | + ms.Position = 0; |
| 44 | + newRequest.Content = new StreamContent(ms); |
| 45 | + // Attempt to copy request content headers with a single retry. |
| 46 | + // HttpHeaders dictionary is not thread-safe when targeting anything below .NET 7. For more information, see https://github.com/dotnet/runtime/issues/61798. |
| 47 | + int retryCount = 0; |
| 48 | + int maxRetryCount = 2; |
| 49 | + while (retryCount < maxRetryCount) |
| 50 | + { |
| 51 | + try |
| 52 | + { |
| 53 | + originalRequest.Content?.Headers?.ToList().ForEach(header => newRequest.Content?.Headers.TryAddWithoutValidation(header.Key, header.Value)); |
| 54 | + retryCount = maxRetryCount; |
| 55 | + } |
| 56 | + catch (InvalidOperationException) |
| 57 | + { |
| 58 | + retryCount++; |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + catch |
| 63 | + { |
| 64 | + } |
| 65 | + } |
| 66 | + return newRequest; |
| 67 | + } |
| 68 | + |
| 69 | + public static async Task<string> GetHttpRequestLogAsync(HttpRequestMessage request) |
| 70 | + { |
| 71 | + if (request == null) return string.Empty; |
| 72 | + var requestClone = await request.CloneAsync().ConfigureAwait(false); |
| 73 | + string body = string.Empty; |
| 74 | + try |
| 75 | + { |
| 76 | + if (requestClone.Content != null) |
| 77 | + { |
| 78 | + body = FormatString(await requestClone.Content.ReadAsStringAsync()); |
| 79 | + } |
| 80 | + else if (requestClone.Content == null && request.Content != null) |
| 81 | + { |
| 82 | + body = "Skipped: Content body was disposed before the logger could access it."; |
| 83 | + } |
| 84 | + } |
| 85 | + catch { } |
| 86 | + |
| 87 | + StringBuilder stringBuilder = new StringBuilder(); |
| 88 | + stringBuilder.AppendLine($"============================ HTTP REQUEST ============================{Environment.NewLine}"); |
| 89 | + stringBuilder.AppendLine($"HTTP Method:{Environment.NewLine}{requestClone.Method}{Environment.NewLine}"); |
| 90 | + stringBuilder.AppendLine($"Absolute Uri:{Environment.NewLine}{requestClone.RequestUri}{Environment.NewLine}"); |
| 91 | + stringBuilder.AppendLine($"Headers:{Environment.NewLine}{HeadersToString(requestClone.Headers)}{Environment.NewLine}"); |
| 92 | + stringBuilder.AppendLine($"Body:{Environment.NewLine}{SanitizeBody(body)}{Environment.NewLine}"); |
| 93 | + return stringBuilder.ToString(); |
| 94 | + } |
| 95 | + |
| 96 | + public static async Task<string> GetHttpResponseLogAsync(HttpResponseMessage response) |
| 97 | + { |
| 98 | + if (response == null) return string.Empty; |
| 99 | + |
| 100 | + string body = string.Empty; |
| 101 | + try |
| 102 | + { |
| 103 | + body = (response.Content == null) ? string.Empty : FormatString(await response.Content.ReadAsStringAsync()); |
| 104 | + } |
| 105 | + catch { } |
| 106 | + |
| 107 | + StringBuilder stringBuilder = new StringBuilder(); |
| 108 | + stringBuilder.AppendLine($"============================ HTTP RESPONSE ============================{Environment.NewLine}"); |
| 109 | + stringBuilder.AppendLine($"Status Code:{Environment.NewLine}{response.StatusCode}{Environment.NewLine}"); |
| 110 | + stringBuilder.AppendLine($"Headers:{Environment.NewLine}{HeadersToString(response.Headers)}{Environment.NewLine}"); |
| 111 | + stringBuilder.AppendLine($"Body:{Environment.NewLine}{SanitizeBody(body)}{Environment.NewLine}"); |
| 112 | + return stringBuilder.ToString(); |
| 113 | + } |
| 114 | + |
| 115 | + public static async Task<string> GetErrorLogAsync(HttpResponseMessage response, IMicrosoftGraphODataErrorsMainError odataError) |
| 116 | + { |
| 117 | + if (response == null) return string.Empty; |
| 118 | + |
| 119 | + StringBuilder stringBuilder = new StringBuilder(); |
| 120 | + stringBuilder.AppendLine($"{odataError?.Message}{Environment.NewLine}"); |
| 121 | + stringBuilder.AppendLine($"Status: {((int)response.StatusCode)} ({response.StatusCode})"); |
| 122 | + stringBuilder.AppendLine($"ErrorCode: {odataError?.Code}"); |
| 123 | + stringBuilder.AppendLine($"Date: {odataError?.InnerError?.Date}{Environment.NewLine}"); |
| 124 | + stringBuilder.AppendLine($"Headers:{Environment.NewLine}{HeadersToString(response.Headers)}{Environment.NewLine}"); |
| 125 | + return stringBuilder.ToString(); |
| 126 | + } |
| 127 | + |
| 128 | + internal static string HeadersToString(HttpHeaders headers) |
| 129 | + { |
| 130 | + return HeadersToString(ConvertHttpHeadersToCollection(headers)); |
| 131 | + } |
| 132 | + |
| 133 | + private static readonly Regex regexPattern = new Regex("(\\s*\"access_token\"\\s*:\\s*)\"[^\"]+\"", RegexOptions.Compiled); |
| 134 | + private static object SanitizeBody(string body) |
| 135 | + { |
| 136 | + IList<Regex> regexList = new List<Regex>(); |
| 137 | + // Remove access_token:* instances in body. |
| 138 | + regexList.Add(regexPattern); |
| 139 | + |
| 140 | + foreach (Regex matcher in regexList) |
| 141 | + { |
| 142 | + body = matcher.Replace(body, "$1\"<redacted>\""); |
| 143 | + } |
| 144 | + |
| 145 | + return body; |
| 146 | + } |
| 147 | + |
| 148 | + private static IDictionary<string, IEnumerable<string>> ConvertHttpHeadersToCollection(HttpHeaders headers) |
| 149 | + { |
| 150 | + headers.Remove("Authorization"); |
| 151 | + return headers.ToDictionary(a => a.Key, a => a.Value); |
| 152 | + } |
| 153 | + |
| 154 | + private static string HeadersToString(IDictionary<string, IEnumerable<string>> headers) |
| 155 | + { |
| 156 | + StringBuilder stringBuilder = headers.Aggregate(new StringBuilder(), |
| 157 | + (sb, kvp) => sb.AppendLine(string.Format("{0,-30}: {1}", kvp.Key, String.Join(",", kvp.Value.ToArray())))); |
| 158 | + |
| 159 | + if (stringBuilder.Length > 0) |
| 160 | + stringBuilder.Remove(stringBuilder.Length - 2, 2); |
| 161 | + |
| 162 | + return stringBuilder.ToString(); |
| 163 | + } |
| 164 | + |
| 165 | + private static string FormatString(string content) |
| 166 | + { |
| 167 | + try |
| 168 | + { |
| 169 | + content = content.Trim(); |
| 170 | + if ((content.StartsWith("{") && content.EndsWith("}")) || // object |
| 171 | + (content.StartsWith("[") && content.EndsWith("]"))) // array |
| 172 | + { |
| 173 | + return JsonConvert.SerializeObject(JsonConvert.DeserializeObject(content), Formatting.Indented); |
| 174 | + } |
| 175 | + if (content.StartsWith("<")) |
| 176 | + { |
| 177 | + return XDocument.Parse(content).ToString(); |
| 178 | + } |
| 179 | + } |
| 180 | + catch |
| 181 | + { |
| 182 | + return content; |
| 183 | + } |
| 184 | + |
| 185 | + if (content.Length > Microsoft.Graph.PowerShell.Authentication.Constants.MaxContentLength) |
| 186 | + { |
| 187 | + return content.Substring(0, Microsoft.Graph.PowerShell.Authentication.Constants.MaxContentLength) + "\r\nDATA TRUNCATED DUE TO SIZE\r\n"; |
| 188 | + } |
| 189 | + |
| 190 | + return content; |
| 191 | + } |
| 192 | + } |
| 193 | +} |
0 commit comments