| | | 1 | | using System.Management.Automation; |
| | | 2 | | using System.Net.Http.Headers; |
| | | 3 | | using Kestrun.Hosting; |
| | | 4 | | using Kestrun.KrException; |
| | | 5 | | using Kestrun.Logging; |
| | | 6 | | using Kestrun.Models; |
| | | 7 | | using Kestrun.Utilities; |
| | | 8 | | using Serilog.Events; |
| | | 9 | | |
| | | 10 | | namespace Kestrun.Languages; |
| | | 11 | | |
| | | 12 | | internal static class PowerShellDelegateBuilder |
| | | 13 | | { |
| | | 14 | | public const string PS_INSTANCE_KEY = "PS_INSTANCE"; |
| | | 15 | | public const string KR_CONTEXT_KEY = "KR_CONTEXT"; |
| | | 16 | | internal static RequestDelegate Build(KestrunHost host, string code, Dictionary<string, object?>? arguments) |
| | | 17 | | { |
| | 8 | 18 | | var log = host.Logger; |
| | 8 | 19 | | ArgumentNullException.ThrowIfNull(code); |
| | 8 | 20 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 21 | | { |
| | 6 | 22 | | log.Debug("Building PowerShell delegate, script length={Length}", code.Length); |
| | | 23 | | } |
| | | 24 | | |
| | 15 | 25 | | return context => ExecutePowerShellRequestAsync(context, log, code, arguments); |
| | | 26 | | } |
| | | 27 | | |
| | | 28 | | /// <summary> |
| | | 29 | | /// Executes the PowerShell request pipeline and applies the resulting response. |
| | | 30 | | /// </summary> |
| | | 31 | | /// <param name="context">Current HTTP context.</param> |
| | | 32 | | /// <param name="log">Logger instance.</param> |
| | | 33 | | /// <param name="code">PowerShell script code.</param> |
| | | 34 | | /// <param name="arguments">Arguments to inject as variables into the script.</param> |
| | | 35 | | private static async Task ExecutePowerShellRequestAsync( |
| | | 36 | | HttpContext context, |
| | | 37 | | Serilog.ILogger log, |
| | | 38 | | string code, |
| | | 39 | | Dictionary<string, object?>? arguments) |
| | | 40 | | { |
| | 7 | 41 | | var isLogVerbose = log.IsEnabled(LogEventLevel.Verbose); |
| | | 42 | | // Log invocation |
| | 7 | 43 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 44 | | { |
| | 5 | 45 | | log.DebugSanitized("PS delegate invoked for {Path}", context.Request.Path); |
| | | 46 | | } |
| | | 47 | | |
| | | 48 | | // Prepare for execution |
| | 7 | 49 | | KestrunContext? krContext = null; |
| | | 50 | | // Get the PowerShell instance from the context (set by middleware) |
| | 7 | 51 | | var ps = GetPowerShellFromContext(context, log); |
| | | 52 | | |
| | | 53 | | // Ensure the runspace pool is open before executing the script |
| | | 54 | | try |
| | | 55 | | { |
| | 6 | 56 | | PowerShellExecutionHelpers.SetVariables(ps, arguments, log); |
| | 6 | 57 | | if (isLogVerbose) |
| | | 58 | | { |
| | 0 | 59 | | log.Verbose("Setting PowerShell variables for Request and Response in the runspace."); |
| | | 60 | | } |
| | 6 | 61 | | krContext = GetKestrunContext(context); |
| | | 62 | | |
| | 6 | 63 | | var allowed = krContext.MapRouteOptions.AllowedRequestContentTypes; |
| | | 64 | | |
| | 6 | 65 | | if (allowed is { Count: > 0 }) |
| | | 66 | | { |
| | | 67 | | // Reliable body detection |
| | 0 | 68 | | var hasBody = |
| | 0 | 69 | | (context.Request.ContentLength.HasValue && context.Request.ContentLength.Value > 0) || |
| | 0 | 70 | | context.Request.Headers.TransferEncoding.Count > 0; |
| | | 71 | | |
| | 0 | 72 | | if (string.IsNullOrWhiteSpace(context.Request.ContentType)) |
| | | 73 | | { |
| | 0 | 74 | | if (hasBody) |
| | | 75 | | { |
| | 0 | 76 | | var message = |
| | 0 | 77 | | "Content-Type header is required. Supported types: " + string.Join(", ", allowed); |
| | | 78 | | |
| | 0 | 79 | | log.Warning( |
| | 0 | 80 | | "Request with missing Content-Type header is not allowed. {Message}", |
| | 0 | 81 | | message); |
| | | 82 | | |
| | 0 | 83 | | await WriteErrorResponseWithCustomHandlerAsync( |
| | 0 | 84 | | context, |
| | 0 | 85 | | krContext, |
| | 0 | 86 | | ps, |
| | 0 | 87 | | log, |
| | 0 | 88 | | message, |
| | 0 | 89 | | StatusCodes.Status415UnsupportedMediaType).ConfigureAwait(false); |
| | 0 | 90 | | return; |
| | | 91 | | } |
| | | 92 | | } |
| | | 93 | | else |
| | | 94 | | { |
| | 0 | 95 | | if (!MediaTypeHeaderValue.TryParse(context.Request.ContentType, out var mediaType)) |
| | | 96 | | { |
| | | 97 | | // Malformed Content-Type → 400 (syntax error, not support issue) |
| | 0 | 98 | | var message = $"Invalid Content-Type header value '{context.Request.ContentType}'."; |
| | | 99 | | |
| | 0 | 100 | | log.WarningSanitized( |
| | 0 | 101 | | "Malformed Content-Type header '{ContentType}'.", |
| | 0 | 102 | | context.Request.ContentType); |
| | | 103 | | |
| | 0 | 104 | | await WriteErrorResponseWithCustomHandlerAsync( |
| | 0 | 105 | | context, |
| | 0 | 106 | | krContext, |
| | 0 | 107 | | ps, |
| | 0 | 108 | | log, |
| | 0 | 109 | | message, |
| | 0 | 110 | | StatusCodes.Status400BadRequest).ConfigureAwait(false); |
| | 0 | 111 | | return; |
| | | 112 | | } |
| | | 113 | | // Canonicalize the request content type and check against allowed list |
| | 0 | 114 | | var requestContentTypeRaw = mediaType.MediaType ?? string.Empty; |
| | | 115 | | // Canonicalize the request content type and check against allowed list |
| | 0 | 116 | | var requestContentTypeCanonical = MediaTypeHelper.Canonicalize(requestContentTypeRaw); |
| | | 117 | | // Check both raw and canonical forms against the allowed list to allow for flexible matching |
| | 0 | 118 | | var rawAllowed = allowed.Contains(requestContentTypeRaw, StringComparer.OrdinalIgnoreCase); |
| | | 119 | | // Canonicalize the request content type and check against allowed list |
| | 0 | 120 | | var canonicalAllowed = allowed |
| | 0 | 121 | | .Select(MediaTypeHelper.Canonicalize) |
| | 0 | 122 | | .Contains(requestContentTypeCanonical, StringComparer.OrdinalIgnoreCase); |
| | | 123 | | // If neither the raw nor canonical content type is allowed, return 415 Unsupported Media Type |
| | 0 | 124 | | if (!rawAllowed && !canonicalAllowed) |
| | | 125 | | { |
| | 0 | 126 | | var message = |
| | 0 | 127 | | $"Request content type '{requestContentTypeRaw}' is not allowed. Supported types: {string.Jo |
| | | 128 | | |
| | 0 | 129 | | log.Warning( |
| | 0 | 130 | | "Request content type '{ContentType}' (canonical '{Canonical}') is not allowed for this rout |
| | 0 | 131 | | requestContentTypeRaw, |
| | 0 | 132 | | requestContentTypeCanonical); |
| | | 133 | | |
| | 0 | 134 | | await WriteErrorResponseWithCustomHandlerAsync( |
| | 0 | 135 | | context, |
| | 0 | 136 | | krContext, |
| | 0 | 137 | | ps, |
| | 0 | 138 | | log, |
| | 0 | 139 | | message, |
| | 0 | 140 | | StatusCodes.Status415UnsupportedMediaType).ConfigureAwait(false); |
| | 0 | 141 | | return; |
| | | 142 | | } |
| | | 143 | | } |
| | | 144 | | } |
| | | 145 | | |
| | 6 | 146 | | if (krContext.HasRequestCulture) |
| | | 147 | | { |
| | 0 | 148 | | PowerShellExecutionHelpers.AddCulturePrelude(ps, krContext.Culture, log); |
| | | 149 | | } |
| | 6 | 150 | | PowerShellExecutionHelpers.AddScript(ps, code); |
| | | 151 | | |
| | | 152 | | // Extract and add parameters for injection |
| | 6 | 153 | | ParameterForInjectionInfo.InjectParameters(krContext, ps); |
| | | 154 | | |
| | | 155 | | // Execute the script |
| | 6 | 156 | | if (isLogVerbose) |
| | | 157 | | { |
| | 0 | 158 | | log.Verbose("Invoking PowerShell script..."); |
| | | 159 | | } |
| | 6 | 160 | | var psResults = await ps.InvokeAsync(log, context.RequestAborted).ConfigureAwait(false); |
| | 4 | 161 | | LogTopResults(log, psResults); |
| | | 162 | | |
| | 4 | 163 | | if (await HandleErrorsIfAnyAsync(context, krContext, ps, log).ConfigureAwait(false)) |
| | | 164 | | { |
| | 1 | 165 | | return; |
| | | 166 | | } |
| | | 167 | | |
| | 3 | 168 | | LogSideChannelMessagesIfAny(log, ps); |
| | | 169 | | |
| | 3 | 170 | | if (HandleRedirectIfAny(context, krContext, log)) |
| | | 171 | | { |
| | 1 | 172 | | return; |
| | | 173 | | } |
| | | 174 | | |
| | | 175 | | // Some endpoints (e.g., SSE streaming) write directly to the HttpResponse and |
| | | 176 | | // intentionally start the response early. In that case, applying KestrunResponse |
| | | 177 | | // would attempt to set headers/status again and throw. |
| | 2 | 178 | | if (context.Response.HasStarted) |
| | | 179 | | { |
| | 0 | 180 | | if (isLogVerbose) |
| | | 181 | | { |
| | 0 | 182 | | log.Verbose("HttpResponse has already started; skipping KestrunResponse.ApplyTo()."); |
| | | 183 | | } |
| | 0 | 184 | | return; |
| | | 185 | | } |
| | 2 | 186 | | if (isLogVerbose) |
| | | 187 | | { |
| | 0 | 188 | | log.Verbose("No redirect detected; applying response to HttpResponse..."); |
| | | 189 | | } |
| | | 190 | | |
| | 2 | 191 | | var postponed = krContext.Response.PostPonedWriteObject; |
| | 2 | 192 | | if (postponed.Error is int postponedError && postponedError != 0) |
| | | 193 | | { |
| | 0 | 194 | | log.Error("Postponed response contains error code {ErrorCode}; throwing before response write.", postpon |
| | 0 | 195 | | throw new InvalidOperationException($"Postponed response error detected: {postponedError}"); |
| | | 196 | | } |
| | | 197 | | |
| | 2 | 198 | | if (krContext.Response.HasPostPonedWriteObject) |
| | | 199 | | { |
| | 0 | 200 | | if (isLogVerbose) |
| | | 201 | | { |
| | 0 | 202 | | log.Verbose("Postponed Write-KrResponse detected; applying response with Write-KrResponse."); |
| | | 203 | | } |
| | 0 | 204 | | await krContext.Response.WriteResponseAsync(postponed).ConfigureAwait(false); |
| | | 205 | | } |
| | 2 | 206 | | } |
| | | 207 | | // optional: catch client cancellation to avoid noisy logs |
| | 0 | 208 | | catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) |
| | | 209 | | { |
| | | 210 | | // client disconnected – nothing to send |
| | 0 | 211 | | } |
| | 0 | 212 | | catch (ParameterForInjectionException pfiiex) |
| | | 213 | | { |
| | | 214 | | // Log parameter resolution errors with preview of code |
| | | 215 | | // log.Error("Parameter resolution error ({Message}) - {Preview}", |
| | | 216 | | // pfiiex.Message, code[..Math.Min(40, code.Length)]); |
| | 0 | 217 | | if (krContext is not null) |
| | | 218 | | { |
| | | 219 | | // Return 400 Bad Request for parameter resolution errors |
| | 0 | 220 | | await WriteErrorResponseWithCustomHandlerAsync( |
| | 0 | 221 | | context, |
| | 0 | 222 | | krContext, |
| | 0 | 223 | | ps, |
| | 0 | 224 | | log, |
| | 0 | 225 | | "Invalid request parameters: " + pfiiex.Message, |
| | 0 | 226 | | pfiiex.StatusCode, |
| | 0 | 227 | | pfiiex).ConfigureAwait(false); |
| | | 228 | | } |
| | | 229 | | else |
| | | 230 | | { |
| | 0 | 231 | | throw; |
| | | 232 | | } |
| | 0 | 233 | | } |
| | 0 | 234 | | catch (ParameterBindingException pbaex) |
| | | 235 | | { |
| | 0 | 236 | | var fqid = pbaex.ErrorRecord?.FullyQualifiedErrorId; |
| | 0 | 237 | | var cat = pbaex.ErrorRecord?.CategoryInfo?.Category; |
| | 0 | 238 | | if (krContext is not null) |
| | | 239 | | { |
| | | 240 | | // Return 400 Bad Request for parameter binding errors |
| | 0 | 241 | | await WriteErrorResponseWithCustomHandlerAsync( |
| | 0 | 242 | | context, |
| | 0 | 243 | | krContext, |
| | 0 | 244 | | ps, |
| | 0 | 245 | | log, |
| | 0 | 246 | | "Invalid request parameters: " + pbaex.Message, |
| | 0 | 247 | | StatusCodes.Status400BadRequest, |
| | 0 | 248 | | pbaex).ConfigureAwait(false); |
| | | 249 | | } |
| | | 250 | | else |
| | | 251 | | { |
| | 0 | 252 | | throw; |
| | | 253 | | } |
| | 0 | 254 | | } |
| | 0 | 255 | | catch (Forms.KrFormException kfex) |
| | | 256 | | { |
| | | 257 | | // Log form parsing errors with preview of code |
| | 0 | 258 | | log.Error("Form parsing error ({Message}) - {Preview}", |
| | 0 | 259 | | kfex.Message, code[..Math.Min(40, code.Length)]); |
| | 0 | 260 | | if (krContext is not null) |
| | | 261 | | { |
| | | 262 | | // Return 400 Bad Request for form parsing errors |
| | 0 | 263 | | await WriteErrorResponseWithCustomHandlerAsync( |
| | 0 | 264 | | context, |
| | 0 | 265 | | krContext, |
| | 0 | 266 | | ps, |
| | 0 | 267 | | log, |
| | 0 | 268 | | "Invalid form data: " + kfex.Message, |
| | 0 | 269 | | kfex.StatusCode, |
| | 0 | 270 | | kfex).ConfigureAwait(false); |
| | | 271 | | } |
| | 0 | 272 | | else { throw; } |
| | 0 | 273 | | } |
| | 0 | 274 | | catch (InvalidOperationException ioex) when (ioex.Message.StartsWith("Postponed response error detected:", Strin |
| | | 275 | | { |
| | 0 | 276 | | log.Error(ioex, "Postponed response error detected while applying Write-KrResponse result."); |
| | 0 | 277 | | if (krContext is not null) |
| | | 278 | | { |
| | 0 | 279 | | await WriteErrorResponseWithCustomHandlerAsync( |
| | 0 | 280 | | context, |
| | 0 | 281 | | krContext, |
| | 0 | 282 | | ps, |
| | 0 | 283 | | log, |
| | 0 | 284 | | "An internal server error occurred.", |
| | 0 | 285 | | StatusCodes.Status500InternalServerError, |
| | 0 | 286 | | ioex).ConfigureAwait(false); |
| | | 287 | | } |
| | | 288 | | else |
| | | 289 | | { |
| | 0 | 290 | | throw; |
| | | 291 | | } |
| | 0 | 292 | | } |
| | 2 | 293 | | catch (Exception ex) |
| | | 294 | | { |
| | | 295 | | // If we have exception options, set a 500 status code and generic message. |
| | | 296 | | // Otherwise rethrow to let higher-level middleware handle it (e.g., Developer Exception Page |
| | 2 | 297 | | if (krContext?.Host?.ExceptionOptions is null) |
| | | 298 | | { // Log and handle script errors |
| | 2 | 299 | | log.Error(ex, "PowerShell script failed - {Preview}", code[..Math.Min(40, code.Length)]); |
| | 2 | 300 | | if (krContext is not null) |
| | | 301 | | { |
| | 2 | 302 | | await WriteErrorResponseWithCustomHandlerAsync( |
| | 2 | 303 | | context, |
| | 2 | 304 | | krContext, |
| | 2 | 305 | | ps, |
| | 2 | 306 | | log, |
| | 2 | 307 | | "An internal server error occurred.", |
| | 2 | 308 | | StatusCodes.Status500InternalServerError, |
| | 2 | 309 | | ex).ConfigureAwait(false); |
| | | 310 | | } |
| | | 311 | | else |
| | | 312 | | { |
| | 0 | 313 | | context.Response.StatusCode = 500; // Internal Server Error |
| | 0 | 314 | | context.Response.ContentType = "text/plain; charset=utf-8"; |
| | 0 | 315 | | await context.Response.WriteAsync("An error occurred while processing your request."); |
| | | 316 | | } |
| | | 317 | | } |
| | | 318 | | else |
| | | 319 | | { |
| | | 320 | | // re-throw to let higher-level middleware handle it (e.g., Developer Exception Page) |
| | 0 | 321 | | throw; |
| | | 322 | | } |
| | | 323 | | } |
| | | 324 | | finally |
| | | 325 | | { |
| | 6 | 326 | | if (krContext is not null) |
| | | 327 | | { |
| | 6 | 328 | | await ApplyResponseAsync(context, krContext).ConfigureAwait(false); |
| | | 329 | | } |
| | | 330 | | // Do not call Response.CompleteAsync here; leaving the response open allows |
| | | 331 | | // downstream middleware like StatusCodePages to generate a body for status-only responses. |
| | | 332 | | } |
| | 6 | 333 | | } |
| | | 334 | | |
| | | 335 | | /// <summary> |
| | | 336 | | /// Writes an error response using a custom PowerShell handler when configured; otherwise falls back to the built-in |
| | | 337 | | /// </summary> |
| | | 338 | | /// <param name="context">Current HTTP context.</param> |
| | | 339 | | /// <param name="krContext">Current Kestrun context.</param> |
| | | 340 | | /// <param name="ps">PowerShell instance bound to the request runspace.</param> |
| | | 341 | | /// <param name="log">Logger instance.</param> |
| | | 342 | | /// <param name="message">Error message to expose to the handler/fallback writer.</param> |
| | | 343 | | /// <param name="statusCode">HTTP status code for the error.</param> |
| | | 344 | | /// <param name="exception">Optional exception that triggered the error flow.</param> |
| | | 345 | | private static async Task WriteErrorResponseWithCustomHandlerAsync( |
| | | 346 | | HttpContext context, |
| | | 347 | | KestrunContext krContext, |
| | | 348 | | PowerShell ps, |
| | | 349 | | Serilog.ILogger log, |
| | | 350 | | string message, |
| | | 351 | | int statusCode, |
| | | 352 | | Exception? exception = null) |
| | | 353 | | { |
| | 2 | 354 | | if (!await TryExecuteCustomErrorResponseScriptAsync(context, krContext, ps, log, message, statusCode, exception) |
| | | 355 | | { |
| | 1 | 356 | | await krContext.Response.WriteErrorResponseAsync(message, statusCode).ConfigureAwait(false); |
| | | 357 | | } |
| | 2 | 358 | | } |
| | | 359 | | |
| | | 360 | | /// <summary> |
| | | 361 | | /// Attempts to execute a configured custom PowerShell error response script for the current request. |
| | | 362 | | /// </summary> |
| | | 363 | | /// <param name="context">Current HTTP context.</param> |
| | | 364 | | /// <param name="krContext">Current Kestrun context.</param> |
| | | 365 | | /// <param name="ps">PowerShell instance bound to the request runspace.</param> |
| | | 366 | | /// <param name="log">Logger instance.</param> |
| | | 367 | | /// <param name="message">Error message to expose to the script.</param> |
| | | 368 | | /// <param name="statusCode">HTTP status code to expose to the script.</param> |
| | | 369 | | /// <param name="exception">Optional exception to expose to the script.</param> |
| | | 370 | | /// <returns>True when a custom script executed successfully; otherwise false.</returns> |
| | | 371 | | private static async Task<bool> TryExecuteCustomErrorResponseScriptAsync( |
| | | 372 | | HttpContext context, |
| | | 373 | | KestrunContext krContext, |
| | | 374 | | PowerShell ps, |
| | | 375 | | Serilog.ILogger log, |
| | | 376 | | string message, |
| | | 377 | | int statusCode, |
| | | 378 | | Exception? exception) |
| | | 379 | | { |
| | 2 | 380 | | var script = krContext.Host.PowerShellErrorResponseScript; |
| | 2 | 381 | | if (string.IsNullOrWhiteSpace(script) || ps.Runspace is null || context.Response.HasStarted) |
| | | 382 | | { |
| | 0 | 383 | | return false; |
| | | 384 | | } |
| | | 385 | | |
| | | 386 | | try |
| | | 387 | | { |
| | 2 | 388 | | using var customErrorPs = PowerShell.Create(); |
| | 2 | 389 | | customErrorPs.Runspace = ps.Runspace; |
| | | 390 | | |
| | 2 | 391 | | var sessionState = customErrorPs.Runspace.SessionStateProxy; |
| | 2 | 392 | | sessionState.SetVariable("Context", krContext); |
| | 2 | 393 | | sessionState.SetVariable("KrContext", krContext); |
| | 2 | 394 | | sessionState.SetVariable("StatusCode", statusCode); |
| | 2 | 395 | | sessionState.SetVariable("ErrorMessage", message); |
| | 2 | 396 | | sessionState.SetVariable("Exception", exception); |
| | | 397 | | |
| | 2 | 398 | | if (krContext.HasRequestCulture) |
| | | 399 | | { |
| | 0 | 400 | | PowerShellExecutionHelpers.AddCulturePrelude(customErrorPs, krContext.Culture, log); |
| | | 401 | | } |
| | | 402 | | |
| | 2 | 403 | | PowerShellExecutionHelpers.AddScript(customErrorPs, script); |
| | 2 | 404 | | _ = await customErrorPs.InvokeAsync(log, context.RequestAborted).ConfigureAwait(false); |
| | | 405 | | |
| | 1 | 406 | | if (customErrorPs.Streams.Error.Count > 0) |
| | | 407 | | { |
| | 0 | 408 | | log.Warning("Custom PowerShell error response script reported errors; falling back to default error resp |
| | 0 | 409 | | return false; |
| | | 410 | | } |
| | | 411 | | |
| | 1 | 412 | | return true; |
| | | 413 | | } |
| | 1 | 414 | | catch (Exception ex) |
| | | 415 | | { |
| | 1 | 416 | | log.Error(ex, "Custom PowerShell error response script failed; falling back to default error response."); |
| | 1 | 417 | | return false; |
| | | 418 | | } |
| | 2 | 419 | | } |
| | | 420 | | |
| | | 421 | | /// <summary> |
| | | 422 | | /// Retrieves the PowerShell instance from the HttpContext items. |
| | | 423 | | /// </summary> |
| | | 424 | | /// <param name="context">The HttpContext from which to retrieve the PowerShell instance.</param> |
| | | 425 | | /// <param name="log">The logger to use for logging.</param> |
| | | 426 | | /// <returns>The PowerShell instance associated with the current request.</returns> |
| | | 427 | | /// <exception cref="InvalidOperationException">Thrown if the PowerShell instance is not found in the context items. |
| | | 428 | | private static PowerShell GetPowerShellFromContext(HttpContext context, Serilog.ILogger log) |
| | | 429 | | { |
| | 7 | 430 | | if (!context.Items.ContainsKey(PS_INSTANCE_KEY)) |
| | | 431 | | { |
| | 1 | 432 | | throw new InvalidOperationException("PowerShell runspace not found in context items. Ensure PowerShellRunspa |
| | | 433 | | } |
| | | 434 | | |
| | 6 | 435 | | log.Verbose("Retrieving PowerShell instance from context items."); |
| | 6 | 436 | | var ps = context.Items[PS_INSTANCE_KEY] as PowerShell |
| | 6 | 437 | | ?? throw new InvalidOperationException("PowerShell instance not found in context items."); |
| | 6 | 438 | | return ps.Runspace == null |
| | 6 | 439 | | ? throw new InvalidOperationException("PowerShell runspace is not set. Ensure PowerShellRunspaceMiddleware i |
| | 6 | 440 | | : ps; |
| | | 441 | | } |
| | | 442 | | |
| | | 443 | | /// <summary> |
| | | 444 | | /// Retrieves the KestrunContext from the HttpContext items. |
| | | 445 | | /// </summary> |
| | | 446 | | /// <param name="context">The HttpContext from which to retrieve the KestrunContext.</param> |
| | | 447 | | /// <returns>The KestrunContext associated with the current request.</returns> |
| | | 448 | | /// <exception cref="InvalidOperationException">Thrown if the KestrunContext is not found in the context items.</exc |
| | | 449 | | private static KestrunContext GetKestrunContext(HttpContext context) |
| | 6 | 450 | | => context.Items[KR_CONTEXT_KEY] as KestrunContext |
| | 6 | 451 | | ?? throw new InvalidOperationException($"{KR_CONTEXT_KEY} key not found in context items."); |
| | | 452 | | |
| | | 453 | | ///<summary> |
| | | 454 | | /// Logs the top results from the PowerShell script output for debugging purposes. |
| | | 455 | | /// Only logs if the log level is set to Debug. |
| | | 456 | | /// </summary> |
| | | 457 | | /// <param name="log">The logger to use for logging.</param> |
| | | 458 | | /// <param name="psResults">The collection of PSObject results from the PowerShell script.</param> |
| | | 459 | | private static void LogTopResults(Serilog.ILogger log, PSDataCollection<PSObject> psResults) |
| | | 460 | | { |
| | 4 | 461 | | if (!log.IsEnabled(LogEventLevel.Debug)) |
| | | 462 | | { |
| | 2 | 463 | | return; |
| | | 464 | | } |
| | | 465 | | |
| | 2 | 466 | | log.Debug("PowerShell script output:"); |
| | 4 | 467 | | foreach (var r in psResults.Take(10)) |
| | | 468 | | { |
| | 0 | 469 | | log.Debug(" • {Result}", r); |
| | | 470 | | } |
| | 2 | 471 | | if (psResults.Count > 10) |
| | | 472 | | { |
| | 0 | 473 | | log.Debug(" … {Count} more", psResults.Count - 10); |
| | | 474 | | } |
| | 2 | 475 | | } |
| | | 476 | | |
| | | 477 | | /// <summary> |
| | | 478 | | /// Handles any errors that occurred during the PowerShell script execution. |
| | | 479 | | /// </summary> |
| | | 480 | | /// <param name="context">The HttpContext for the current request.</param> |
| | | 481 | | /// <param name="krContext">The Kestrun context for the current request.</param> |
| | | 482 | | /// <param name="ps">The PowerShell instance used for script execution.</param> |
| | | 483 | | /// <param name="log">The logger used for diagnostic messages.</param> |
| | | 484 | | /// <returns>True if errors were handled, false otherwise.</returns> |
| | | 485 | | private static async Task<bool> HandleErrorsIfAnyAsync(HttpContext context, KestrunContext krContext, PowerShell ps, |
| | | 486 | | { |
| | 4 | 487 | | if (ps.HadErrors || ps.Streams.Error.Count != 0) |
| | | 488 | | { |
| | 1 | 489 | | if (context.Response.HasStarted || krContext.Response.StatusCode >= StatusCodes.Status400BadRequest) |
| | | 490 | | { |
| | 0 | 491 | | log.Debug( |
| | 0 | 492 | | "PowerShell error stream contains records but response is already set (StatusCode={StatusCode}); ski |
| | 0 | 493 | | krContext.Response.StatusCode); |
| | 0 | 494 | | return false; |
| | | 495 | | } |
| | | 496 | | |
| | 1 | 497 | | await BuildError.ResponseAsync(context, ps).ConfigureAwait(false); |
| | 1 | 498 | | return true; |
| | | 499 | | } |
| | 3 | 500 | | return false; |
| | 4 | 501 | | } |
| | | 502 | | |
| | | 503 | | /// <summary> |
| | | 504 | | /// Logs any side-channel messages (Verbose, Debug, Warning, Information) produced by the PowerShell script. |
| | | 505 | | /// </summary> |
| | | 506 | | /// <param name="log">The logger to use for logging.</param> |
| | | 507 | | /// <param name="ps">The PowerShell instance used to invoke the script.</param> |
| | | 508 | | private static void LogSideChannelMessagesIfAny(Serilog.ILogger log, PowerShell ps) |
| | | 509 | | { |
| | 3 | 510 | | if (ps.Streams.Verbose.Count > 0 || ps.Streams.Debug.Count > 0 || ps.Streams.Warning.Count > 0 || ps.Streams.Inf |
| | | 511 | | { |
| | 0 | 512 | | log.Verbose("PowerShell script completed with verbose/debug/warning/info messages."); |
| | 0 | 513 | | log.Verbose(BuildError.Text(ps)); |
| | | 514 | | } |
| | 3 | 515 | | log.Verbose("PowerShell script completed successfully."); |
| | 3 | 516 | | } |
| | | 517 | | |
| | | 518 | | private static bool HandleRedirectIfAny(HttpContext context, KestrunContext krContext, Serilog.ILogger log) |
| | | 519 | | { |
| | 3 | 520 | | if (!string.IsNullOrEmpty(krContext.Response.RedirectUrl)) |
| | | 521 | | { |
| | 1 | 522 | | log.Verbose($"Redirecting to {krContext.Response.RedirectUrl}"); |
| | 1 | 523 | | context.Response.Redirect(krContext.Response.RedirectUrl); |
| | 1 | 524 | | return true; |
| | | 525 | | } |
| | 2 | 526 | | return false; |
| | | 527 | | } |
| | | 528 | | |
| | | 529 | | private static Task ApplyResponseAsync(HttpContext context, KestrunContext krContext) |
| | 6 | 530 | | => krContext.Response.ApplyTo(context.Response); |
| | | 531 | | |
| | | 532 | | // Removed explicit Response.CompleteAsync to allow StatusCodePages to run after endpoints when appropriate. |
| | | 533 | | } |