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