| | 1 | | using System.Security.Claims; |
| | 2 | | using System.Text; |
| | 3 | | using Kestrun.Hosting; |
| | 4 | | using Kestrun.Languages; |
| | 5 | | using Kestrun.Logging; |
| | 6 | | using Kestrun.Models; |
| | 7 | | using Kestrun.SharedState; |
| | 8 | | using Microsoft.CodeAnalysis; |
| | 9 | | using Serilog.Events; |
| | 10 | | using System.Reflection; |
| | 11 | |
|
| | 12 | | internal static class DelegateBuilder |
| | 13 | | { |
| | 14 | | /// <summary> |
| | 15 | | /// Prepares the Kestrun context, response, and script globals for execution. |
| | 16 | | /// Encapsulates request parsing, shared state snapshot, arg injection, and logging. |
| | 17 | | /// </summary> |
| | 18 | | /// <param name="ctx">The current HTTP context.</param> |
| | 19 | | /// <param name="log">Logger for diagnostics.</param> |
| | 20 | | /// <param name="args">Optional variables to inject into the globals.</param> |
| | 21 | | /// <returns>Tuple containing the prepared CsGlobals, KestrunResponse, and KestrunContext.</returns> |
| | 22 | | internal static async Task<(CsGlobals Globals, KestrunResponse Response, KestrunContext Context)> PrepareExecutionAs |
| | 23 | | HttpContext ctx, |
| | 24 | | Serilog.ILogger log, |
| | 25 | | Dictionary<string, object?>? args) |
| | 26 | | { |
| 5 | 27 | | var krRequest = await KestrunRequest.NewRequest(ctx).ConfigureAwait(false); |
| 5 | 28 | | var krResponse = new KestrunResponse(krRequest); |
| 5 | 29 | | var Context = new KestrunContext(krRequest, krResponse, ctx); |
| 5 | 30 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 31 | | { |
| 3 | 32 | | log.DebugSanitized("Kestrun context created for {Path}", ctx.Request.Path); |
| | 33 | | } |
| | 34 | |
|
| | 35 | | // Create a shared state dictionary that will be used to store global variables |
| | 36 | | // This will be shared across all requests and can be used to store state |
| | 37 | | // that needs to persist across multiple requests |
| 5 | 38 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 39 | | { |
| 3 | 40 | | log.Debug("Creating shared state store for Kestrun context"); |
| | 41 | | } |
| | 42 | |
|
| 5 | 43 | | var glob = new Dictionary<string, object?>(SharedStateStore.Snapshot()); |
| 5 | 44 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 45 | | { |
| 3 | 46 | | log.Debug("Shared state store created with {Count} items", glob.Count); |
| | 47 | | } |
| | 48 | |
|
| | 49 | | // Inject the provided arguments into the globals so the script can access them |
| 5 | 50 | | if (args != null && args.Count > 0) |
| | 51 | | { |
| 1 | 52 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 53 | | { |
| 0 | 54 | | log.Debug("Setting variables from arguments: {Count}", args.Count); |
| | 55 | | } |
| | 56 | |
|
| 4 | 57 | | foreach (var kv in args) |
| | 58 | | { |
| 1 | 59 | | glob[kv.Key] = kv.Value; // add args to globals |
| | 60 | | } |
| | 61 | | } |
| | 62 | |
|
| | 63 | | // Create a new CsGlobals instance with the current context and shared state |
| 5 | 64 | | var globals = new CsGlobals(glob, Context); |
| 5 | 65 | | return (globals, krResponse, Context); |
| 5 | 66 | | } |
| | 67 | |
|
| | 68 | |
|
| | 69 | | /// <summary> |
| | 70 | | /// Decides the VB return type string that matches TResult. |
| | 71 | | /// </summary> |
| | 72 | | /// <param name="ctx">The current HTTP context.</param> |
| | 73 | | /// <param name="response">The Kestrun response to apply.</param> |
| | 74 | | /// <param name="log">The logger to use for logging.</param> |
| | 75 | | /// <returns>A task representing the asynchronous operation.</returns> |
| | 76 | | internal static async Task ApplyResponseAsync(HttpContext ctx, KestrunResponse response, Serilog.ILogger log) |
| | 77 | | { |
| 5 | 78 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 79 | | { |
| 3 | 80 | | log.DebugSanitized("Applying response to Kestrun context for {Path}", ctx.Request.Path); |
| | 81 | | } |
| | 82 | |
|
| 5 | 83 | | if (!string.IsNullOrEmpty(response.RedirectUrl)) |
| | 84 | | { |
| 2 | 85 | | ctx.Response.Redirect(response.RedirectUrl); |
| 2 | 86 | | return; |
| | 87 | | } |
| | 88 | |
|
| 3 | 89 | | await response.ApplyTo(ctx.Response).ConfigureAwait(false); |
| | 90 | |
|
| 3 | 91 | | if (log.IsEnabled(LogEventLevel.Debug)) |
| | 92 | | { |
| 2 | 93 | | log.DebugSanitized("Response applied to Kestrun context for {Path}", ctx.Request.Path); |
| | 94 | | } |
| 5 | 95 | | } |
| | 96 | |
|
| | 97 | | /// <summary> |
| | 98 | | /// Common baseline references shared across script compilations. |
| | 99 | | /// </summary> |
| | 100 | | /// <returns> MetadataReference[] </returns> |
| | 101 | | internal static MetadataReference[] BuildBaselineReferences() |
| | 102 | | { |
| | 103 | | // Collect unique assembly locations |
| 33 | 104 | | var locations = new HashSet<string>(StringComparer.OrdinalIgnoreCase); |
| | 105 | |
|
| | 106 | | void Add(Type t) |
| | 107 | | { |
| 495 | 108 | | var loc = t.Assembly.Location; |
| 495 | 109 | | if (!string.IsNullOrWhiteSpace(loc)) |
| | 110 | | { |
| 495 | 111 | | _ = locations.Add(loc); // capture return to satisfy analyzer |
| | 112 | | } |
| 495 | 113 | | } |
| | 114 | |
|
| | 115 | | // Seed core & always-required assemblies |
| 33 | 116 | | Add(typeof(object)); // System.Private.CoreLib |
| 33 | 117 | | Add(typeof(Enumerable)); // System.Linq |
| 33 | 118 | | Add(typeof(HttpContext)); // Microsoft.AspNetCore.Http |
| 33 | 119 | | Add(typeof(Console)); // System.Console |
| 33 | 120 | | Add(typeof(StringBuilder)); // System.Text |
| 33 | 121 | | Add(typeof(Serilog.Log)); // Serilog |
| 33 | 122 | | Add(typeof(ClaimsPrincipal)); // System.Security.Claims |
| 33 | 123 | | Add(typeof(ClaimsIdentity)); // System.Security.Claims |
| 33 | 124 | | Add(typeof(System.Security.Cryptography.X509Certificates.X509Certificate2)); // X509 Certificates |
| | 125 | |
|
| | 126 | | // Snapshot loaded assemblies once |
| 33 | 127 | | var loadedAssemblies = AppDomain.CurrentDomain |
| 33 | 128 | | .GetAssemblies() |
| 8668 | 129 | | .Where(a => !a.IsDynamic && !string.IsNullOrWhiteSpace(a.Location)) |
| 33 | 130 | | .ToArray(); |
| | 131 | |
|
| | 132 | | // Attempt to bind each namespace in PlatformImports to a loaded assembly |
| 2904 | 133 | | foreach (var ns in PlatformImports) |
| | 134 | | { |
| 672090 | 135 | | foreach (var asm in loadedAssemblies) |
| | 136 | | { |
| 334626 | 137 | | if (locations.Contains(asm.Location)) |
| | 138 | | { |
| | 139 | | continue; // already referenced |
| | 140 | | } |
| 196695 | 141 | | if (NamespaceExistsInAssembly(asm, ns)) |
| | 142 | | { |
| 5356 | 143 | | _ = locations.Add(asm.Location); // capture return to satisfy analyzer |
| | 144 | | } |
| | 145 | | } |
| | 146 | | } |
| | 147 | |
|
| | 148 | | // Explicitly ensure critical assemblies needed for dynamic auth / razor / encodings even if not yet scanned |
| 33 | 149 | | Add(typeof(Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults)); |
| 33 | 150 | | Add(typeof(Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults)); |
| 33 | 151 | | Add(typeof(Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectDefaults)); |
| 33 | 152 | | Add(typeof(Microsoft.AspNetCore.Authentication.Negotiate.NegotiateDefaults)); |
| 33 | 153 | | Add(typeof(Microsoft.AspNetCore.Mvc.Razor.RazorPageBase)); |
| 33 | 154 | | Add(typeof(System.Text.Encodings.Web.HtmlEncoder)); |
| | 155 | |
|
| 33 | 156 | | return [.. locations |
| 33 | 157 | | .Distinct(StringComparer.OrdinalIgnoreCase) |
| 5620 | 158 | | .Select(loc => MetadataReference.CreateFromFile(loc))]; |
| | 159 | | } |
| | 160 | |
|
| | 161 | | private static bool NamespaceExistsInAssembly(Assembly asm, string @namespace) |
| | 162 | | { |
| | 163 | | try |
| | 164 | | { |
| | 165 | | // Using DefinedTypes to avoid loading reflection-only contexts; guard against type load issues. |
| 45051186 | 166 | | foreach (var t in asm.DefinedTypes) |
| | 167 | | { |
| 22331576 | 168 | | var ns = t.Namespace; |
| 22331576 | 169 | | if (ns == null) |
| | 170 | | { |
| | 171 | | continue; |
| | 172 | | } |
| 21423343 | 173 | | if (ns.Equals(@namespace, StringComparison.Ordinal) || ns.StartsWith(@namespace + ".", StringComparison. |
| | 174 | | { |
| 5356 | 175 | | return true; |
| | 176 | | } |
| | 177 | | } |
| 191339 | 178 | | } |
| 0 | 179 | | catch (ReflectionTypeLoadException) |
| | 180 | | { |
| | 181 | | // Ignore partially loadable assemblies; namespace absence treated as false. |
| 0 | 182 | | } |
| 191339 | 183 | | return false; |
| 5356 | 184 | | } |
| | 185 | |
|
| | 186 | | // Ordered & de-duplicated platform / framework imports used for dynamic script compilation. |
| 1 | 187 | | internal static string[] PlatformImports = [ |
| 1 | 188 | | "Kestrun.Languages", |
| 1 | 189 | | "Microsoft.AspNetCore.Authentication", |
| 1 | 190 | | "Microsoft.AspNetCore.Authentication.Cookies", |
| 1 | 191 | | "Microsoft.AspNetCore.Authentication.JwtBearer", |
| 1 | 192 | | "Microsoft.AspNetCore.Authentication.Negotiate", |
| 1 | 193 | | "Microsoft.AspNetCore.Authentication.OpenIdConnect", |
| 1 | 194 | | "Microsoft.AspNetCore.Authorization", |
| 1 | 195 | | "Microsoft.AspNetCore.Http", |
| 1 | 196 | | "Microsoft.AspNetCore.Mvc", |
| 1 | 197 | | "Microsoft.AspNetCore.Mvc.RazorPages", |
| 1 | 198 | | // "Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation". |
| 1 | 199 | | "Microsoft.AspNetCore.Server.Kestrel.Core", |
| 1 | 200 | | "Microsoft.AspNetCore.SignalR", |
| 1 | 201 | | "Microsoft.CodeAnalysis", |
| 1 | 202 | | "Microsoft.CodeAnalysis.CSharp", |
| 1 | 203 | | "Microsoft.CodeAnalysis.CSharp.Scripting", |
| 1 | 204 | | "Microsoft.CodeAnalysis.Scripting", |
| 1 | 205 | | "Microsoft.Extensions.FileProviders", |
| 1 | 206 | | "Microsoft.Extensions.Logging", |
| 1 | 207 | | "Microsoft.Extensions.Options", |
| 1 | 208 | | "Microsoft.Extensions.Primitives", |
| 1 | 209 | | "Microsoft.IdentityModel.Tokens", |
| 1 | 210 | | "Microsoft.PowerShell", |
| 1 | 211 | | "Microsoft.VisualBasic", |
| 1 | 212 | | "Serilog", |
| 1 | 213 | | "Serilog.Events", |
| 1 | 214 | | "System", |
| 1 | 215 | | "System.Collections", |
| 1 | 216 | | "System.Collections.Generic", |
| 1 | 217 | | "System.Collections.Immutable", |
| 1 | 218 | | "System.IO", |
| 1 | 219 | | "System.Linq", |
| 1 | 220 | | "System.Management.Automation", |
| 1 | 221 | | "System.Management.Automation.Runspaces", |
| 1 | 222 | | "System.Net", |
| 1 | 223 | | "System.Net.Http.Headers", |
| 1 | 224 | | "System.Reflection", |
| 1 | 225 | | "System.Runtime.InteropServices", |
| 1 | 226 | | "System.Security.Claims", |
| 1 | 227 | | "System.Security.Cryptography.X509Certificates", |
| 1 | 228 | | "System.Text", |
| 1 | 229 | | "System.Text.Encodings.Web", |
| 1 | 230 | | "System.Text.RegularExpressions", |
| 1 | 231 | | "System.Threading.Tasks" |
| 1 | 232 | | ]; |
| | 233 | | } |