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