| | | 1 | | using System.Management.Automation; |
| | | 2 | | using Kestrun.Hosting; |
| | | 3 | | using Kestrun.Logging; |
| | | 4 | | using Kestrun.Models; |
| | | 5 | | using Kestrun.Utilities; |
| | | 6 | | using Serilog.Events; |
| | | 7 | | |
| | | 8 | | namespace Kestrun.Languages; |
| | | 9 | | |
| | | 10 | | internal static class PowerShellDelegateBuilder |
| | | 11 | | { |
| | | 12 | | public const string PS_INSTANCE_KEY = "PS_INSTANCE"; |
| | | 13 | | public const string KR_CONTEXT_KEY = "KR_CONTEXT"; |
| | | 14 | | |
| | | 15 | | internal static RequestDelegate Build(KestrunHost host, string code, Dictionary<string, object?>? arguments) |
| | | 16 | | { |
| | 6 | 17 | | var log = host.Logger; |
| | 6 | 18 | | ArgumentNullException.ThrowIfNull(code); |
| | 6 | 19 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | | 20 | | { |
| | 4 | 21 | | log.Debug("Building PowerShell delegate, script length={Length}", code.Length); |
| | | 22 | | } |
| | | 23 | | |
| | 6 | 24 | | return async context => |
| | 6 | 25 | | { |
| | 6 | 26 | | // Log invocation |
| | 5 | 27 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 6 | 28 | | { |
| | 3 | 29 | | log.DebugSanitized("PS delegate invoked for {Path}", context.Request.Path); |
| | 6 | 30 | | } |
| | 6 | 31 | | // Prepare for execution |
| | 5 | 32 | | KestrunContext? krContext = null; |
| | 6 | 33 | | // Get the PowerShell instance from the context (set by middleware) |
| | 5 | 34 | | var ps = GetPowerShellFromContext(context, log); |
| | 6 | 35 | | |
| | 6 | 36 | | // Ensure the runspace pool is open before executing the script |
| | 6 | 37 | | try |
| | 6 | 38 | | { |
| | 4 | 39 | | PowerShellExecutionHelpers.SetVariables(ps, arguments, log); |
| | 4 | 40 | | if (log.IsEnabled(LogEventLevel.Verbose)) |
| | 6 | 41 | | { |
| | 0 | 42 | | log.Verbose("Setting PowerShell variables for Request and Response in the runspace."); |
| | 6 | 43 | | } |
| | 4 | 44 | | krContext = GetKestrunContext(context); |
| | 6 | 45 | | |
| | 4 | 46 | | PowerShellExecutionHelpers.AddScript(ps, code); |
| | 6 | 47 | | |
| | 6 | 48 | | // Extract and add parameters for injection |
| | 4 | 49 | | ParameterForInjectionInfo.InjectParameters(krContext, ps); |
| | 6 | 50 | | |
| | 6 | 51 | | // Execute the script |
| | 4 | 52 | | if (log.IsEnabled(LogEventLevel.Verbose)) |
| | 6 | 53 | | { |
| | 0 | 54 | | log.Verbose("Invoking PowerShell script..."); |
| | 6 | 55 | | } |
| | 4 | 56 | | var psResults = await ps.InvokeAsync(log, context.RequestAborted).ConfigureAwait(false); |
| | 4 | 57 | | LogTopResults(log, psResults); |
| | 6 | 58 | | |
| | 4 | 59 | | if (await HandleErrorsIfAnyAsync(context, ps).ConfigureAwait(false)) |
| | 6 | 60 | | { |
| | 1 | 61 | | return; |
| | 6 | 62 | | } |
| | 6 | 63 | | |
| | 3 | 64 | | LogSideChannelMessagesIfAny(log, ps); |
| | 6 | 65 | | |
| | 3 | 66 | | if (HandleRedirectIfAny(context, krContext, log)) |
| | 6 | 67 | | { |
| | 1 | 68 | | return; |
| | 6 | 69 | | } |
| | 2 | 70 | | if (log.IsEnabled(LogEventLevel.Verbose)) |
| | 6 | 71 | | { |
| | 0 | 72 | | log.Verbose("No redirect detected; applying response to HttpResponse..."); |
| | 6 | 73 | | } |
| | 2 | 74 | | await ApplyResponseAsync(context, krContext).ConfigureAwait(false); |
| | 2 | 75 | | } |
| | 6 | 76 | | // optional: catch client cancellation to avoid noisy logs |
| | 0 | 77 | | catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) |
| | 6 | 78 | | { |
| | 6 | 79 | | // client disconnected – nothing to send |
| | 0 | 80 | | } |
| | 0 | 81 | | catch (Exception ex) |
| | 6 | 82 | | { |
| | 6 | 83 | | // If we have exception options, set a 500 status code and generic message. |
| | 6 | 84 | | // Otherwise rethrow to let higher-level middleware handle it (e.g., Developer Exception Page |
| | 0 | 85 | | if (krContext?.Host?.ExceptionOptions is null) |
| | 6 | 86 | | { // Log and handle script errors |
| | 0 | 87 | | log.Error(ex, "PowerShell script failed - {Preview}", code[..Math.Min(40, code.Length)]); |
| | 0 | 88 | | context.Response.StatusCode = 500; // Internal Server Error |
| | 0 | 89 | | context.Response.ContentType = "text/plain; charset=utf-8"; |
| | 0 | 90 | | await context.Response.WriteAsync("An error occurred while processing your request."); |
| | 6 | 91 | | } |
| | 6 | 92 | | else |
| | 6 | 93 | | { |
| | 6 | 94 | | // re-throw to let higher-level middleware handle it (e.g., Developer Exception Page) |
| | 0 | 95 | | throw; |
| | 6 | 96 | | } |
| | 6 | 97 | | } |
| | 6 | 98 | | finally |
| | 6 | 99 | | { |
| | 6 | 100 | | // Do not call Response.CompleteAsync here; leaving the response open allows |
| | 6 | 101 | | // downstream middleware like StatusCodePages to generate a body for status-only responses. |
| | 6 | 102 | | } |
| | 6 | 103 | | }; |
| | 4 | 104 | | } |
| | | 105 | | |
| | | 106 | | /// <summary> |
| | | 107 | | /// Retrieves the PowerShell instance from the HttpContext items. |
| | | 108 | | /// </summary> |
| | | 109 | | /// <param name="context">The HttpContext from which to retrieve the PowerShell instance.</param> |
| | | 110 | | /// <param name="log">The logger to use for logging.</param> |
| | | 111 | | /// <returns>The PowerShell instance associated with the current request.</returns> |
| | | 112 | | /// <exception cref="InvalidOperationException">Thrown if the PowerShell instance is not found in the context items. |
| | | 113 | | private static PowerShell GetPowerShellFromContext(HttpContext context, Serilog.ILogger log) |
| | | 114 | | { |
| | 5 | 115 | | if (!context.Items.ContainsKey(PS_INSTANCE_KEY)) |
| | | 116 | | { |
| | 1 | 117 | | throw new InvalidOperationException("PowerShell runspace not found in context items. Ensure PowerShellRunspa |
| | | 118 | | } |
| | | 119 | | |
| | 4 | 120 | | log.Verbose("Retrieving PowerShell instance from context items."); |
| | 4 | 121 | | var ps = context.Items[PS_INSTANCE_KEY] as PowerShell |
| | 4 | 122 | | ?? throw new InvalidOperationException("PowerShell instance not found in context items."); |
| | 4 | 123 | | return ps.Runspace == null |
| | 4 | 124 | | ? throw new InvalidOperationException("PowerShell runspace is not set. Ensure PowerShellRunspaceMiddleware i |
| | 4 | 125 | | : ps; |
| | | 126 | | } |
| | | 127 | | |
| | | 128 | | /// <summary> |
| | | 129 | | /// Retrieves the KestrunContext from the HttpContext items. |
| | | 130 | | /// </summary> |
| | | 131 | | /// <param name="context">The HttpContext from which to retrieve the KestrunContext.</param> |
| | | 132 | | /// <returns>The KestrunContext associated with the current request.</returns> |
| | | 133 | | /// <exception cref="InvalidOperationException">Thrown if the KestrunContext is not found in the context items.</exc |
| | | 134 | | private static KestrunContext GetKestrunContext(HttpContext context) |
| | 4 | 135 | | => context.Items[KR_CONTEXT_KEY] as KestrunContext |
| | 4 | 136 | | ?? throw new InvalidOperationException($"{KR_CONTEXT_KEY} key not found in context items."); |
| | | 137 | | |
| | | 138 | | ///<summary> |
| | | 139 | | /// Logs the top results from the PowerShell script output for debugging purposes. |
| | | 140 | | /// Only logs if the log level is set to Debug. |
| | | 141 | | /// </summary> |
| | | 142 | | /// <param name="log">The logger to use for logging.</param> |
| | | 143 | | /// <param name="psResults">The collection of PSObject results from the PowerShell script.</param> |
| | | 144 | | private static void LogTopResults(Serilog.ILogger log, PSDataCollection<PSObject> psResults) |
| | | 145 | | { |
| | 4 | 146 | | if (!log.IsEnabled(LogEventLevel.Debug)) |
| | | 147 | | { |
| | 2 | 148 | | return; |
| | | 149 | | } |
| | | 150 | | |
| | 2 | 151 | | log.Debug("PowerShell script output:"); |
| | 4 | 152 | | foreach (var r in psResults.Take(10)) |
| | | 153 | | { |
| | 0 | 154 | | log.Debug(" • {Result}", r); |
| | | 155 | | } |
| | 2 | 156 | | if (psResults.Count > 10) |
| | | 157 | | { |
| | 0 | 158 | | log.Debug(" … {Count} more", psResults.Count - 10); |
| | | 159 | | } |
| | 2 | 160 | | } |
| | | 161 | | |
| | | 162 | | /// <summary> |
| | | 163 | | /// Handles any errors that occurred during the PowerShell script execution. |
| | | 164 | | /// </summary> |
| | | 165 | | /// <param name="context">The HttpContext for the current request.</param> |
| | | 166 | | /// <param name="ps">The PowerShell instance used for script execution.</param> |
| | | 167 | | /// <returns>True if errors were handled, false otherwise.</returns> |
| | | 168 | | private static async Task<bool> HandleErrorsIfAnyAsync(HttpContext context, PowerShell ps) |
| | | 169 | | { |
| | 4 | 170 | | if (ps.HadErrors || ps.Streams.Error.Count != 0) |
| | | 171 | | { |
| | 1 | 172 | | await BuildError.ResponseAsync(context, ps).ConfigureAwait(false); |
| | 1 | 173 | | return true; |
| | | 174 | | } |
| | 3 | 175 | | return false; |
| | 4 | 176 | | } |
| | | 177 | | |
| | | 178 | | /// <summary> |
| | | 179 | | /// Logs any side-channel messages (Verbose, Debug, Warning, Information) produced by the PowerShell script. |
| | | 180 | | /// </summary> |
| | | 181 | | /// <param name="log">The logger to use for logging.</param> |
| | | 182 | | /// <param name="ps">The PowerShell instance used to invoke the script.</param> |
| | | 183 | | private static void LogSideChannelMessagesIfAny(Serilog.ILogger log, PowerShell ps) |
| | | 184 | | { |
| | 3 | 185 | | if (ps.Streams.Verbose.Count > 0 || ps.Streams.Debug.Count > 0 || ps.Streams.Warning.Count > 0 || ps.Streams.Inf |
| | | 186 | | { |
| | 0 | 187 | | log.Verbose("PowerShell script completed with verbose/debug/warning/info messages."); |
| | 0 | 188 | | log.Verbose(BuildError.Text(ps)); |
| | | 189 | | } |
| | 3 | 190 | | log.Verbose("PowerShell script completed successfully."); |
| | 3 | 191 | | } |
| | | 192 | | |
| | | 193 | | private static bool HandleRedirectIfAny(HttpContext context, KestrunContext krContext, Serilog.ILogger log) |
| | | 194 | | { |
| | 3 | 195 | | if (!string.IsNullOrEmpty(krContext.Response.RedirectUrl)) |
| | | 196 | | { |
| | 1 | 197 | | log.Verbose($"Redirecting to {krContext.Response.RedirectUrl}"); |
| | 1 | 198 | | context.Response.Redirect(krContext.Response.RedirectUrl); |
| | 1 | 199 | | return true; |
| | | 200 | | } |
| | 2 | 201 | | return false; |
| | | 202 | | } |
| | | 203 | | |
| | | 204 | | private static Task ApplyResponseAsync(HttpContext context, KestrunContext krContext) |
| | 2 | 205 | | => krContext.Response.ApplyTo(context.Response); |
| | | 206 | | |
| | | 207 | | // Removed explicit Response.CompleteAsync to allow StatusCodePages to run after endpoints when appropriate. |
| | | 208 | | } |