| | | 1 | | using System.Management.Automation; |
| | | 2 | | using System.Diagnostics.CodeAnalysis; |
| | | 3 | | using Kestrun.Languages; |
| | | 4 | | using Kestrun.Models; |
| | | 5 | | using Kestrun.Runtime; |
| | | 6 | | using Microsoft.AspNetCore.Diagnostics; |
| | | 7 | | |
| | | 8 | | namespace Kestrun.Hosting.Options; |
| | | 9 | | /// <summary> |
| | | 10 | | /// Options for configuring Kestrun-style exception handling middleware. |
| | | 11 | | /// </summary> |
| | | 12 | | public sealed class ExceptionOptions : ExceptionHandlerOptions |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// Optional scripting options (e.g., PowerShell). If present, a script-based handler is used. |
| | | 16 | | /// </summary> |
| | | 17 | | private LanguageOptions? _languageOptions; |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Initializes a new instance of the <see cref="ExceptionOptions"/> class. |
| | | 21 | | /// </summary> |
| | | 22 | | /// <param name="host">The KestrunHost instance associated with these options.</param> |
| | | 23 | | /// <param name="developerExceptionPage">If true, enables the Developer Exception Page middleware with default optio |
| | | 24 | | [SetsRequiredMembers] |
| | 5 | 25 | | public ExceptionOptions(KestrunHost host, bool developerExceptionPage = false) |
| | | 26 | | { |
| | 5 | 27 | | ArgumentNullException.ThrowIfNull(host); |
| | 5 | 28 | | Host = host; |
| | 5 | 29 | | if (developerExceptionPage) |
| | | 30 | | { |
| | 1 | 31 | | DeveloperExceptionPageOptions = new DeveloperExceptionPageOptions(); |
| | | 32 | | } |
| | 5 | 33 | | } |
| | | 34 | | |
| | | 35 | | /// <summary> |
| | | 36 | | /// Optional Developer Exception Page options. If present, the Developer Exception Page middleware is used. |
| | | 37 | | /// </summary> |
| | 7 | 38 | | public DeveloperExceptionPageOptions? DeveloperExceptionPageOptions { get; set; } |
| | | 39 | | |
| | | 40 | | /// <summary> |
| | | 41 | | /// Optional scripting options (e.g., PowerShell). If present, a script-based handler is used. |
| | | 42 | | /// </summary> |
| | | 43 | | public LanguageOptions? LanguageOptions |
| | | 44 | | { |
| | 2 | 45 | | get => _languageOptions; |
| | | 46 | | set |
| | | 47 | | { |
| | 2 | 48 | | _languageOptions = value; |
| | 2 | 49 | | if (value is not null && ExceptionHandler is null) |
| | | 50 | | { |
| | 2 | 51 | | if (value.Language == Scripting.ScriptLanguage.PowerShell) |
| | | 52 | | { |
| | 0 | 53 | | throw new NotSupportedException("PowerShell is not supported for ExceptionOptions scripting at this |
| | | 54 | | } |
| | 2 | 55 | | var compiled = Host.CompileScript(value, Host.Logger); |
| | | 56 | | |
| | 2 | 57 | | ExceptionHandler = BuildScriptExceptionHandler(this, compiled); |
| | | 58 | | } |
| | 2 | 59 | | } |
| | | 60 | | } |
| | | 61 | | |
| | | 62 | | /// <summary>Host is needed for runspace/bootstrap if using PowerShell.</summary> |
| | 10 | 63 | | public required KestrunHost Host { get; init; } |
| | | 64 | | |
| | | 65 | | // .NET 8 compatibility: ExceptionHandlerOptions in .NET 8 does not expose StatusCodeSelector. |
| | | 66 | | // Provide our own selector for net8.0; on net9.0+ prefer the base property. |
| | | 67 | | #if !NET9_0_OR_GREATER |
| | | 68 | | /// <summary> |
| | | 69 | | /// .NET 8: Optional custom status code selector for JSON/script fallback. |
| | | 70 | | /// Lets you map exception types to status codes. |
| | | 71 | | /// </summary> |
| | | 72 | | public Func<Exception, int>? LegacyStatusCodeSelector { get; set; } |
| | | 73 | | #endif |
| | | 74 | | |
| | | 75 | | |
| | | 76 | | |
| | | 77 | | private RequestDelegate BuildScriptExceptionHandler(ExceptionOptions o, RequestDelegate compiled) |
| | | 78 | | { |
| | 2 | 79 | | return async httpContext => |
| | 2 | 80 | | { |
| | 2 | 81 | | // Ensure a PS runspace exists if we're executing a PowerShell-based handler outside the normal PS middlewar |
| | 2 | 82 | | var needsBootstrap = o.LanguageOptions!.Language == Scripting.ScriptLanguage.PowerShell && |
| | 2 | 83 | | !httpContext.Items.ContainsKey(PowerShellDelegateBuilder.PS_INSTANCE_KEY); |
| | 2 | 84 | | |
| | 2 | 85 | | if (!needsBootstrap) |
| | 2 | 86 | | { |
| | 2 | 87 | | await compiled(httpContext); |
| | 2 | 88 | | return; |
| | 2 | 89 | | } |
| | 2 | 90 | | |
| | 0 | 91 | | var pool = o.Host.RunspacePool; // throws if not initialized |
| | 0 | 92 | | var runspace = await pool.AcquireAsync(httpContext.RequestAborted); |
| | 0 | 93 | | using var ps = PowerShell.Create(); |
| | 0 | 94 | | ps.Runspace = runspace; |
| | 2 | 95 | | |
| | 2 | 96 | | // Build Kestrun abstractions and inject for the script to consume |
| | 0 | 97 | | var req = await KestrunRequest.NewRequest(httpContext); |
| | 0 | 98 | | var res = new KestrunResponse(req) { StatusCode = httpContext.Response.StatusCode }; |
| | 0 | 99 | | var kr = new KestrunContext(Host, req, res, httpContext); |
| | 2 | 100 | | |
| | 0 | 101 | | httpContext.Items[PowerShellDelegateBuilder.PS_INSTANCE_KEY] = ps; |
| | 0 | 102 | | httpContext.Items[PowerShellDelegateBuilder.KR_CONTEXT_KEY] = kr; |
| | 0 | 103 | | ps.Runspace.SessionStateProxy.SetVariable("Context", kr); |
| | 2 | 104 | | |
| | 2 | 105 | | try |
| | 2 | 106 | | { |
| | 0 | 107 | | await compiled(httpContext); |
| | 0 | 108 | | } |
| | 2 | 109 | | finally |
| | 2 | 110 | | { |
| | 0 | 111 | | o.Host.RunspacePool.Release(ps.Runspace); |
| | 0 | 112 | | ps.Dispose(); |
| | 0 | 113 | | _ = httpContext.Items.Remove(PowerShellDelegateBuilder.PS_INSTANCE_KEY); |
| | 0 | 114 | | _ = httpContext.Items.Remove(PowerShellDelegateBuilder.KR_CONTEXT_KEY); |
| | 2 | 115 | | } |
| | 4 | 116 | | }; |
| | | 117 | | } |
| | | 118 | | |
| | | 119 | | /// <summary> |
| | | 120 | | /// Builds a JSON fallback handler that can be used if no script/inline handler is provided. |
| | | 121 | | /// </summary> |
| | | 122 | | /// <param name="useProblemDetails">Whether to use RFC 7807 ProblemDetails in the JSON fallback.</param> |
| | | 123 | | /// <param name="includeDetailsInDevelopment">Whether to include exception details in development.</param> |
| | | 124 | | /// <param name="compress">Whether to compress the JSON response.</param> |
| | | 125 | | /// <returns></returns> |
| | | 126 | | public void UseJsonExceptionHandler(bool useProblemDetails, bool includeDetailsInDevelopment, bool compress = false) |
| | | 127 | | { |
| | 1 | 128 | | ExceptionHandler = async httpContext => |
| | 1 | 129 | | { |
| | 1 | 130 | | // If the response already started, let the server bubble up |
| | 1 | 131 | | if (httpContext.Response.HasStarted) |
| | 1 | 132 | | { |
| | 1 | 133 | | // optional: log here |
| | 0 | 134 | | return; |
| | 1 | 135 | | } |
| | 1 | 136 | | |
| | 1 | 137 | | var env = httpContext.RequestServices.GetService(typeof(IHostEnvironment)) as IHostEnvironment; |
| | 1 | 138 | | var feature = httpContext.Features.Get<IExceptionHandlerFeature>(); |
| | 1 | 139 | | var ex = feature?.Error; |
| | 1 | 140 | | |
| | 1 | 141 | | #if NET9_0_OR_GREATER |
| | 1 | 142 | | var status = StatusCodeSelector?.Invoke(ex ?? new Exception("Unhandled exception")) |
| | 1 | 143 | | ?? StatusCodes.Status500InternalServerError; |
| | 1 | 144 | | #else |
| | 1 | 145 | | var status = LegacyStatusCodeSelector?.Invoke(ex ?? new Exception("Unhandled exception")) |
| | 1 | 146 | | ?? StatusCodes.Status500InternalServerError; |
| | 1 | 147 | | #endif |
| | 1 | 148 | | |
| | 1 | 149 | | var kestrunContext = new KestrunContext(Host, httpContext); |
| | 1 | 150 | | |
| | 1 | 151 | | // Always set the HTTP status first |
| | 1 | 152 | | kestrunContext.Response.StatusCode = status; |
| | 1 | 153 | | |
| | 1 | 154 | | // Choose the right media type |
| | 1 | 155 | | var contentType = useProblemDetails |
| | 1 | 156 | | ? "application/problem+json; charset=utf-8" |
| | 1 | 157 | | : "application/json; charset=utf-8"; |
| | 1 | 158 | | |
| | 1 | 159 | | // No-cache for error payloads |
| | 1 | 160 | | httpContext.Response.Headers.CacheControl = "no-store, no-cache, must-revalidate"; |
| | 1 | 161 | | httpContext.Response.Headers.Pragma = "no-cache"; |
| | 1 | 162 | | httpContext.Response.Headers.Expires = "0"; |
| | 1 | 163 | | |
| | 1 | 164 | | // Build body |
| | 1 | 165 | | var body = new Dictionary<string, object?> |
| | 1 | 166 | | { |
| | 1 | 167 | | ["status"] = status, |
| | 1 | 168 | | ["traceId"] = System.Diagnostics.Activity.Current?.Id ?? httpContext.TraceIdentifier, |
| | 1 | 169 | | ["instance"] = httpContext.Request.Path.HasValue ? httpContext.Request.Path.Value : "/" |
| | 1 | 170 | | }; |
| | 1 | 171 | | |
| | 1 | 172 | | if (useProblemDetails) |
| | 1 | 173 | | { |
| | 1 | 174 | | body["type"] = "about:blank"; // you can swap for a doc URL later |
| | 1 | 175 | | body["title"] = status switch |
| | 1 | 176 | | { |
| | 0 | 177 | | 400 => "Bad Request", |
| | 0 | 178 | | 401 => "Unauthorized", |
| | 0 | 179 | | 403 => "Forbidden", |
| | 0 | 180 | | 404 => "Not Found", |
| | 1 | 181 | | _ => "Internal Server Error" |
| | 1 | 182 | | }; |
| | 1 | 183 | | body["detail"] = includeDetailsInDevelopment && EnvironmentHelper.IsDevelopment() |
| | 1 | 184 | | ? ex?.ToString() |
| | 1 | 185 | | : ex?.Message; |
| | 1 | 186 | | } |
| | 1 | 187 | | else |
| | 1 | 188 | | { |
| | 0 | 189 | | body["error"] = true; |
| | 0 | 190 | | body["message"] = (includeDetailsInDevelopment && EnvironmentHelper.IsDevelopment()) |
| | 0 | 191 | | ? ex?.ToString() |
| | 0 | 192 | | : ex?.Message; |
| | 1 | 193 | | } |
| | 1 | 194 | | |
| | 1 | 195 | | // Note: `compress` means "compact JSON". Pretty-print when not compressing. |
| | 1 | 196 | | // Adjust the `5` (maxDepth) if your WriteJsonResponseAsync uses it that way. |
| | 1 | 197 | | await kestrunContext.Response.WriteJsonResponseAsync( |
| | 1 | 198 | | body, |
| | 1 | 199 | | 5, |
| | 1 | 200 | | compress, // compact when true |
| | 1 | 201 | | status, |
| | 1 | 202 | | contentType |
| | 1 | 203 | | ); |
| | 1 | 204 | | |
| | 1 | 205 | | await kestrunContext.Response.ApplyTo(httpContext.Response); |
| | 2 | 206 | | }; |
| | 1 | 207 | | } |
| | | 208 | | } |