| | 1 | | using System.Management.Automation; |
| | 2 | | using Kestrun.Hosting; |
| | 3 | | using Kestrun.Logging; |
| | 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 | | { |
| 5 | 16 | | ArgumentNullException.ThrowIfNull(code); |
| 5 | 17 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 18 | | { |
| 4 | 19 | | log.Debug("Building PowerShell delegate, script length={Length}", code.Length); |
| | 20 | | } |
| | 21 | |
|
| 5 | 22 | | return async context => |
| 5 | 23 | | { |
| 5 | 24 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| 5 | 25 | | { |
| 4 | 26 | | log.DebugSanitized("PS delegate invoked for {Path}", context.Request.Path); |
| 5 | 27 | | } |
| 5 | 28 | |
|
| 5 | 29 | | var ps = GetPowerShellFromContext(context, log); |
| 5 | 30 | | // Ensure the runspace pool is open before executing the script |
| 5 | 31 | | try |
| 5 | 32 | | { |
| 4 | 33 | | SetArgumentsAsVariables(ps, arguments, log); |
| 5 | 34 | |
|
| 4 | 35 | | log.Verbose("Setting PowerShell variables for Request and Response in the runspace."); |
| 4 | 36 | | var krContext = GetKestrunContext(context); |
| 5 | 37 | |
|
| 4 | 38 | | AddScript(ps, code); |
| 4 | 39 | | var psResults = await InvokeScriptAsync(ps, log).ConfigureAwait(false); |
| 4 | 40 | | LogTopResults(log, psResults); |
| 5 | 41 | |
|
| 4 | 42 | | if (await HandleErrorsIfAnyAsync(context, ps).ConfigureAwait(false)) |
| 5 | 43 | | { |
| 1 | 44 | | return; |
| 5 | 45 | | } |
| 5 | 46 | |
|
| 3 | 47 | | LogSideChannelMessagesIfAny(log, ps); |
| 5 | 48 | |
|
| 3 | 49 | | if (HandleRedirectIfAny(context, krContext, log)) |
| 5 | 50 | | { |
| 1 | 51 | | return; |
| 5 | 52 | | } |
| 5 | 53 | |
|
| 2 | 54 | | log.Verbose("Applying response to HttpResponse..."); |
| 2 | 55 | | await ApplyResponseAsync(context, krContext).ConfigureAwait(false); |
| 2 | 56 | | } |
| 5 | 57 | | // optional: catch client cancellation to avoid noisy logs |
| 0 | 58 | | catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested) |
| 5 | 59 | | { |
| 5 | 60 | | // client disconnected – nothing to send |
| 0 | 61 | | } |
| 0 | 62 | | catch (Exception ex) |
| 5 | 63 | | { |
| 5 | 64 | | // Log the exception (optional) |
| 0 | 65 | | log.Error(ex, "PowerShell script failed - {Preview}", code[..Math.Min(40, code.Length)]); |
| 0 | 66 | | context.Response.StatusCode = 500; // Internal Server Error |
| 0 | 67 | | context.Response.ContentType = "text/plain; charset=utf-8"; |
| 0 | 68 | | await context.Response.WriteAsync("An error occurred while processing your request."); |
| 5 | 69 | | } |
| 5 | 70 | | finally |
| 5 | 71 | | { |
| 4 | 72 | | await CompleteResponseSafelyAsync(context, log).ConfigureAwait(false); |
| 5 | 73 | | } |
| 9 | 74 | | }; |
| | 75 | | } |
| | 76 | |
|
| | 77 | | private static PowerShell GetPowerShellFromContext(HttpContext context, Serilog.ILogger log) |
| | 78 | | { |
| 5 | 79 | | if (!context.Items.ContainsKey(PS_INSTANCE_KEY)) |
| | 80 | | { |
| 1 | 81 | | throw new InvalidOperationException("PowerShell runspace not found in context items. Ensure PowerShellRunspa |
| | 82 | | } |
| | 83 | |
|
| 4 | 84 | | log.Verbose("Retrieving PowerShell instance from context items."); |
| 4 | 85 | | var ps = context.Items[PS_INSTANCE_KEY] as PowerShell |
| 4 | 86 | | ?? throw new InvalidOperationException("PowerShell instance not found in context items."); |
| 4 | 87 | | return ps.Runspace == null |
| 4 | 88 | | ? throw new InvalidOperationException("PowerShell runspace is not set. Ensure PowerShellRunspaceMiddleware i |
| 4 | 89 | | : ps; |
| | 90 | | } |
| | 91 | |
|
| | 92 | | private static KestrunContext GetKestrunContext(HttpContext context) |
| 4 | 93 | | => context.Items[KR_CONTEXT_KEY] as KestrunContext |
| 4 | 94 | | ?? throw new InvalidOperationException($"{KR_CONTEXT_KEY} key not found in context items."); |
| | 95 | |
|
| | 96 | | private static void SetArgumentsAsVariables(PowerShell ps, Dictionary<string, object?>? arguments, Serilog.ILogger l |
| | 97 | | { |
| 4 | 98 | | if (arguments is null || arguments.Count == 0) |
| | 99 | | { |
| 4 | 100 | | return; |
| | 101 | | } |
| | 102 | |
|
| 0 | 103 | | log.Verbose("Setting PowerShell variables from arguments: {Count}", arguments.Count); |
| 0 | 104 | | var ss = ps.Runspace!.SessionStateProxy; |
| 0 | 105 | | foreach (var arg in arguments) |
| | 106 | | { |
| 0 | 107 | | ss.SetVariable(arg.Key, arg.Value); |
| | 108 | | } |
| 0 | 109 | | } |
| | 110 | |
|
| 4 | 111 | | private static void AddScript(PowerShell ps, string code) => _ = ps.AddScript(code); |
| | 112 | |
|
| | 113 | | private static async Task<PSDataCollection<PSObject>> InvokeScriptAsync(PowerShell ps, Serilog.ILogger log) |
| | 114 | | { |
| 4 | 115 | | log.Verbose("Executing PowerShell script..."); |
| 4 | 116 | | var results = await ps.InvokeAsync().ConfigureAwait(false); |
| 4 | 117 | | log.Verbose($"PowerShell script executed with {results.Count} results."); |
| 4 | 118 | | return results; |
| 4 | 119 | | } |
| | 120 | |
|
| | 121 | | private static void LogTopResults(Serilog.ILogger log, PSDataCollection<PSObject> psResults) |
| | 122 | | { |
| 4 | 123 | | if (!log.IsEnabled(LogEventLevel.Debug)) |
| | 124 | | { |
| 1 | 125 | | return; |
| | 126 | | } |
| | 127 | |
|
| 3 | 128 | | log.Debug("PowerShell script output:"); |
| 6 | 129 | | foreach (var r in psResults.Take(10)) |
| | 130 | | { |
| 0 | 131 | | log.Debug(" • {Result}", r); |
| | 132 | | } |
| 3 | 133 | | if (psResults.Count > 10) |
| | 134 | | { |
| 0 | 135 | | log.Debug(" … {Count} more", psResults.Count - 10); |
| | 136 | | } |
| 3 | 137 | | } |
| | 138 | |
|
| | 139 | | private static async Task<bool> HandleErrorsIfAnyAsync(HttpContext context, PowerShell ps) |
| | 140 | | { |
| 4 | 141 | | if (ps.HadErrors || ps.Streams.Error.Count != 0) |
| | 142 | | { |
| 1 | 143 | | await BuildError.ResponseAsync(context, ps).ConfigureAwait(false); |
| 1 | 144 | | return true; |
| | 145 | | } |
| 3 | 146 | | return false; |
| 4 | 147 | | } |
| | 148 | |
|
| | 149 | | private static void LogSideChannelMessagesIfAny(Serilog.ILogger log, PowerShell ps) |
| | 150 | | { |
| 3 | 151 | | if (ps.Streams.Verbose.Count > 0 || ps.Streams.Debug.Count > 0 || ps.Streams.Warning.Count > 0 || ps.Streams.Inf |
| | 152 | | { |
| 0 | 153 | | log.Verbose("PowerShell script completed with verbose/debug/warning/info messages."); |
| 0 | 154 | | log.Verbose(BuildError.Text(ps)); |
| | 155 | | } |
| 3 | 156 | | log.Verbose("PowerShell script completed successfully."); |
| 3 | 157 | | } |
| | 158 | |
|
| | 159 | | private static bool HandleRedirectIfAny(HttpContext context, KestrunContext krContext, Serilog.ILogger log) |
| | 160 | | { |
| 3 | 161 | | if (!string.IsNullOrEmpty(krContext.Response.RedirectUrl)) |
| | 162 | | { |
| 1 | 163 | | log.Verbose($"Redirecting to {krContext.Response.RedirectUrl}"); |
| 1 | 164 | | context.Response.Redirect(krContext.Response.RedirectUrl); |
| 1 | 165 | | return true; |
| | 166 | | } |
| 2 | 167 | | return false; |
| | 168 | | } |
| | 169 | |
|
| | 170 | | private static Task ApplyResponseAsync(HttpContext context, KestrunContext krContext) |
| 2 | 171 | | => krContext.Response.ApplyTo(context.Response); |
| | 172 | |
|
| | 173 | | private static async Task CompleteResponseSafelyAsync(HttpContext context, Serilog.ILogger log) |
| | 174 | | { |
| | 175 | | // CompleteAsync is idempotent – safe to call once more |
| | 176 | | try |
| | 177 | | { |
| 4 | 178 | | log.Verbose("Completing response for " + context.Request.Path); |
| 4 | 179 | | await context.Response.CompleteAsync().ConfigureAwait(false); |
| 4 | 180 | | } |
| 0 | 181 | | catch (ObjectDisposedException odex) |
| | 182 | | { |
| | 183 | | // This can happen if the response has already been completed |
| | 184 | | // or the client has disconnected |
| 0 | 185 | | log.DebugSanitized(odex, "Response already completed for {Path}", context.Request.Path); |
| 0 | 186 | | } |
| 0 | 187 | | catch (InvalidOperationException ioex) |
| | 188 | | { |
| | 189 | | // This can happen if the response has already been completed |
| 0 | 190 | | log.DebugSanitized(ioex, "Response already completed for {Path}", context.Request.Path); |
| | 191 | | // No action needed, as the response is already completed |
| 0 | 192 | | } |
| 4 | 193 | | } |
| | 194 | | } |