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