| | | 1 | | using System.Management.Automation; |
| | | 2 | | using Kestrun.Hosting; |
| | | 3 | | using Kestrun.Hosting.Options; |
| | | 4 | | using Kestrun.Languages; |
| | | 5 | | using Kestrun.Models; |
| | | 6 | | using Microsoft.AspNetCore.Diagnostics; |
| | | 7 | | namespace Kestrun.Middleware; |
| | | 8 | | |
| | | 9 | | /// <summary> |
| | | 10 | | /// Extension methods for adding status code pages middleware. |
| | | 11 | | /// </summary> |
| | | 12 | | public static class StatusCodePageExtensions |
| | | 13 | | { |
| | | 14 | | /// <summary> |
| | | 15 | | /// Applies the configured status code pages middleware to the specified application builder. |
| | | 16 | | /// </summary> |
| | | 17 | | /// <param name="app">The application builder.</param> |
| | | 18 | | /// <param name="options">The status code options.</param> |
| | | 19 | | /// <returns>The application builder.</returns> |
| | | 20 | | public static IApplicationBuilder UseStatusCodePages(this IApplicationBuilder app, StatusCodeOptions options) |
| | | 21 | | { |
| | 10 | 22 | | ArgumentNullException.ThrowIfNull(options); |
| | | 23 | | // 1) direct delegate options |
| | 9 | 24 | | if (TryUseDirectOptions(app, options) is { } direct) |
| | | 25 | | { |
| | 2 | 26 | | return direct; |
| | | 27 | | } |
| | | 28 | | |
| | | 29 | | // 2) redirects |
| | 7 | 30 | | if (TryUseRedirects(app, options) is { } redirects) |
| | | 31 | | { |
| | 2 | 32 | | return redirects; |
| | | 33 | | } |
| | | 34 | | |
| | | 35 | | // 3) re-execute |
| | 5 | 36 | | if (TryUseReExecute(app, options) is { } reexec) |
| | | 37 | | { |
| | 2 | 38 | | return reexec; |
| | | 39 | | } |
| | | 40 | | |
| | | 41 | | // 4) static body |
| | 3 | 42 | | if (TryUseStaticBody(app, options) is { } staticBody) |
| | | 43 | | { |
| | 1 | 44 | | return staticBody; |
| | | 45 | | } |
| | | 46 | | |
| | | 47 | | // 5) custom script handler |
| | 2 | 48 | | if (TryUseScriptHandler(app, options) is { } script) |
| | | 49 | | { |
| | 1 | 50 | | return script; |
| | | 51 | | } |
| | | 52 | | |
| | | 53 | | // default to built-in behavior |
| | 1 | 54 | | return app.UseStatusCodePages(); |
| | | 55 | | } |
| | | 56 | | |
| | | 57 | | private static IApplicationBuilder? TryUseDirectOptions(IApplicationBuilder app, StatusCodeOptions options) |
| | 9 | 58 | | => options.Options is not null ? app.UseStatusCodePages(options.Options) : null; |
| | | 59 | | |
| | | 60 | | private static IApplicationBuilder? TryUseRedirects(IApplicationBuilder app, StatusCodeOptions options) |
| | 7 | 61 | | => HasValue(options.LocationFormat) ? app.UseStatusCodePagesWithRedirects(options.LocationFormat!) : null; |
| | | 62 | | |
| | | 63 | | private static IApplicationBuilder? TryUseReExecute(IApplicationBuilder app, StatusCodeOptions options) |
| | | 64 | | { |
| | 5 | 65 | | if (!HasValue(options.PathFormat)) |
| | | 66 | | { |
| | 3 | 67 | | return null; |
| | | 68 | | } |
| | 2 | 69 | | var query = NormalizeQuery(options.QueryFormat); |
| | 2 | 70 | | return app.UseStatusCodePagesWithReExecute(options.PathFormat!, query); |
| | | 71 | | } |
| | | 72 | | |
| | | 73 | | private static IApplicationBuilder? TryUseStaticBody(IApplicationBuilder app, StatusCodeOptions options) |
| | | 74 | | { |
| | 3 | 75 | | if (!HasValue(options.ContentType) || !HasValue(options.BodyFormat)) |
| | | 76 | | { |
| | 2 | 77 | | return null; |
| | | 78 | | } |
| | 1 | 79 | | var safeBody = EscapeTemplate(options.BodyFormat!); |
| | 1 | 80 | | return app.UseStatusCodePages(options.ContentType!, safeBody); |
| | | 81 | | } |
| | | 82 | | |
| | | 83 | | private static IApplicationBuilder? TryUseScriptHandler(IApplicationBuilder app, StatusCodeOptions options) |
| | | 84 | | { |
| | 2 | 85 | | if (options.LanguageOptions is null) |
| | | 86 | | { |
| | 1 | 87 | | return null; |
| | | 88 | | } |
| | 1 | 89 | | var compiled = options.Host.CompileScript(options.LanguageOptions, options.Host.Logger); |
| | 1 | 90 | | var handler = BuildScriptHandler(options, compiled); |
| | 1 | 91 | | return app.UseStatusCodePages(handler); |
| | | 92 | | } |
| | 18 | 93 | | private static bool HasValue(string? s) => !string.IsNullOrWhiteSpace(s); |
| | | 94 | | |
| | | 95 | | private static string? NormalizeQuery(string? query) |
| | | 96 | | { |
| | 2 | 97 | | if (!HasValue(query)) |
| | | 98 | | { |
| | 1 | 99 | | return query; |
| | | 100 | | } |
| | 1 | 101 | | var q = query!.Trim(); |
| | 1 | 102 | | return q.StartsWith('?') ? q : "?" + q; |
| | | 103 | | } |
| | | 104 | | |
| | | 105 | | // Escape curly braces for String.Format safety, but preserve the {0} placeholder used for status code. |
| | | 106 | | // If the template already contains escaped braces ({{ or }}), assume it is pre-escaped and skip. |
| | | 107 | | private static string EscapeTemplate(string bodyFormat) |
| | | 108 | | { |
| | 1 | 109 | | if (bodyFormat.Contains("{{", StringComparison.Ordinal) || bodyFormat.Contains("}}", StringComparison.Ordinal)) |
| | | 110 | | { |
| | 0 | 111 | | return bodyFormat; // already escaped |
| | | 112 | | } |
| | | 113 | | |
| | 1 | 114 | | var escaped = bodyFormat.Replace("{", "{{").Replace("}", "}}"); |
| | | 115 | | // restore the status-code placeholder |
| | 1 | 116 | | escaped = escaped.Replace("{{0}}", "{0}"); |
| | 1 | 117 | | return escaped; |
| | | 118 | | } |
| | | 119 | | |
| | | 120 | | private static Func<StatusCodeContext, Task> BuildScriptHandler(StatusCodeOptions options, RequestDelegate compiled) |
| | | 121 | | { |
| | 1 | 122 | | return async context => |
| | 1 | 123 | | { |
| | 0 | 124 | | var httpContext = context.HttpContext; |
| | 1 | 125 | | |
| | 1 | 126 | | // If running a PowerShell script but the runspace middleware did not execute |
| | 1 | 127 | | // (e.g., no matched endpoint so UseWhen predicate failed), bootstrap a temporary |
| | 1 | 128 | | // runspace and KestrunContext so the compiled delegate can run safely. |
| | 0 | 129 | | var needsBootstrap = options.LanguageOptions!.Language == Scripting.ScriptLanguage.PowerShell && |
| | 0 | 130 | | !httpContext.Items.ContainsKey(PowerShellDelegateBuilder.PS_INSTANCE_KEY); |
| | 1 | 131 | | |
| | 0 | 132 | | if (!needsBootstrap) |
| | 1 | 133 | | { |
| | 0 | 134 | | await compiled(httpContext); |
| | 0 | 135 | | return; |
| | 1 | 136 | | } |
| | 1 | 137 | | |
| | 0 | 138 | | var pool = options.Host.RunspacePool; // throws if not initialized |
| | 0 | 139 | | var runspace = await pool.AcquireAsync(httpContext.RequestAborted); |
| | 0 | 140 | | using var ps = PowerShell.Create(); |
| | 0 | 141 | | ps.Runspace = runspace; |
| | 1 | 142 | | |
| | 1 | 143 | | // Build Kestrun abstractions and inject into context for PS delegate to use |
| | 0 | 144 | | var req = await KestrunRequest.NewRequest(httpContext); |
| | 0 | 145 | | var res = new KestrunResponse(req) |
| | 0 | 146 | | { |
| | 0 | 147 | | StatusCode = httpContext.Response.StatusCode |
| | 0 | 148 | | }; |
| | 0 | 149 | | var kr = new KestrunContext(pool.Host, req, res, httpContext); |
| | 1 | 150 | | |
| | 0 | 151 | | httpContext.Items[PowerShellDelegateBuilder.PS_INSTANCE_KEY] = ps; |
| | 0 | 152 | | httpContext.Items[PowerShellDelegateBuilder.KR_CONTEXT_KEY] = kr; |
| | 0 | 153 | | var ss = ps.Runspace.SessionStateProxy; |
| | 0 | 154 | | ss.SetVariable("Context", kr); |
| | 1 | 155 | | |
| | 1 | 156 | | try |
| | 1 | 157 | | { |
| | 0 | 158 | | await compiled(httpContext); |
| | 0 | 159 | | } |
| | 1 | 160 | | finally |
| | 1 | 161 | | { |
| | 0 | 162 | | pool.Release(ps.Runspace); |
| | 0 | 163 | | ps.Dispose(); |
| | 0 | 164 | | _ = httpContext.Items.Remove(PowerShellDelegateBuilder.PS_INSTANCE_KEY); |
| | 0 | 165 | | _ = httpContext.Items.Remove(PowerShellDelegateBuilder.KR_CONTEXT_KEY); |
| | 1 | 166 | | } |
| | 1 | 167 | | }; |
| | | 168 | | } |
| | | 169 | | } |