| | | 1 | | using System.Net; |
| | | 2 | | using System.Text.RegularExpressions; |
| | | 3 | | using Kestrun.Hosting.Options; |
| | | 4 | | using Kestrun.Languages; |
| | | 5 | | using Kestrun.Models; |
| | | 6 | | using Kestrun.OpenApi; |
| | | 7 | | using Kestrun.Runtime; |
| | | 8 | | using Kestrun.Scripting; |
| | | 9 | | using Kestrun.TBuilder; |
| | | 10 | | using Kestrun.Utilities; |
| | | 11 | | using Microsoft.AspNetCore.Antiforgery; |
| | | 12 | | using Microsoft.AspNetCore.Authorization; |
| | | 13 | | using Microsoft.Extensions.Options; |
| | | 14 | | using Microsoft.OpenApi; |
| | | 15 | | using Serilog.Events; |
| | | 16 | | |
| | | 17 | | namespace Kestrun.Hosting; |
| | | 18 | | |
| | | 19 | | /// <summary> |
| | | 20 | | /// Provides extension methods for mapping routes and handlers to the KestrunHost. |
| | | 21 | | /// </summary> |
| | | 22 | | public static partial class KestrunHostMapExtensions |
| | | 23 | | { |
| | | 24 | | /// <summary> |
| | | 25 | | /// Public utility facade for endpoint specification parsing. This provides a stable API surface |
| | | 26 | | /// over the internal helper logic used by host route constraint processing. |
| | | 27 | | /// </summary> |
| | | 28 | | public static class EndpointSpecParser |
| | | 29 | | { |
| | | 30 | | /// <summary> |
| | | 31 | | /// Parses an endpoint specification into host, port and optional HTTPS flag. |
| | | 32 | | /// </summary> |
| | | 33 | | /// <param name="spec">Specification string. See <see cref="TryParseEndpointSpec"/> for accepted formats.</param |
| | | 34 | | /// <param name="host">Resolved host when successful, otherwise empty string.</param> |
| | | 35 | | /// <param name="port">Resolved port when successful, otherwise 0.</param> |
| | | 36 | | /// <param name="https">True for https, false for http, null when unspecified (host:port form).</param> |
| | | 37 | | /// <returns><c>true</c> if parsing succeeds; otherwise <c>false</c>.</returns> |
| | | 38 | | public static bool TryParse(string spec, out string host, out int port, out bool? https) |
| | 16 | 39 | | => TryParseEndpointSpec(spec, out host, out port, out https); |
| | | 40 | | } |
| | | 41 | | /// <summary> |
| | | 42 | | /// Represents a delegate that handles a Kestrun request with the provided context. |
| | | 43 | | /// </summary> |
| | | 44 | | /// <param name="Context">The context for the Kestrun request.</param> |
| | | 45 | | /// <returns>A task representing the asynchronous operation.</returns> |
| | | 46 | | public delegate Task KestrunHandler(KestrunContext Context); |
| | | 47 | | |
| | | 48 | | /// <summary> |
| | | 49 | | /// Adds a native route to the KestrunHost for the specified pattern and HTTP verb. |
| | | 50 | | /// </summary> |
| | | 51 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 52 | | /// <param name="pattern">The route pattern.</param> |
| | | 53 | | /// <param name="httpVerb">The HTTP verb for the route.</param> |
| | | 54 | | /// <param name="handler">The handler to execute for the route.</param> |
| | | 55 | | /// <param name="requireSchemes">Optional array of authorization schemes required for the route.</param> |
| | | 56 | | /// <param name="map">The endpoint convention builder for further configuration.</param> |
| | | 57 | | /// <returns>The KestrunHost instance for chaining.</returns> |
| | | 58 | | public static KestrunHost AddMapRoute(this KestrunHost host, string pattern, HttpVerb httpVerb, KestrunHandler handl |
| | 2 | 59 | | host.AddMapRoute(pattern: pattern, httpVerbs: [httpVerb], handler: handler, out map, requireSchemes: requireSchemes) |
| | | 60 | | |
| | | 61 | | /// <summary> |
| | | 62 | | /// Adds a native route to the KestrunHost for the specified pattern and HTTP verbs. |
| | | 63 | | /// </summary> |
| | | 64 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 65 | | /// <param name="pattern">The route pattern.</param> |
| | | 66 | | /// <param name="httpVerbs">The HTTP verbs for the route.</param> |
| | | 67 | | /// <param name="handler">The handler to execute for the route.</param> |
| | | 68 | | /// <param name="requireSchemes">Optional array of authorization schemes required for the route.</param> |
| | | 69 | | /// <param name="map">The endpoint convention builder for further configuration.</param> |
| | | 70 | | /// <returns>The KestrunHost instance for chaining.</returns> |
| | | 71 | | public static KestrunHost AddMapRoute(this KestrunHost host, string pattern, IEnumerable<HttpVerb> httpVerbs, Kestru |
| | | 72 | | out IEndpointConventionBuilder? map, List<string>? requireSchemes = null) |
| | | 73 | | { |
| | 2 | 74 | | return host.AddMapRoute(new MapRouteOptions |
| | 2 | 75 | | { |
| | 2 | 76 | | Pattern = pattern, |
| | 2 | 77 | | HttpVerbs = [.. httpVerbs], |
| | 2 | 78 | | ScriptCode = new LanguageOptions |
| | 2 | 79 | | { |
| | 2 | 80 | | Language = ScriptLanguage.Native, |
| | 2 | 81 | | }, |
| | 2 | 82 | | RequireSchemes = requireSchemes ?? [] // No authorization by default |
| | 2 | 83 | | }, handler, out map); |
| | | 84 | | } |
| | | 85 | | |
| | | 86 | | /// <summary> |
| | | 87 | | /// Adds a native route to the KestrunHost using the specified MapRouteOptions and handler. |
| | | 88 | | /// </summary> |
| | | 89 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 90 | | /// <param name="options">The MapRouteOptions containing route configuration.</param> |
| | | 91 | | /// <param name="handler">The handler to execute for the route.</param> |
| | | 92 | | /// <param name="map">The endpoint convention builder for further configuration.</param> |
| | | 93 | | /// <returns>The KestrunHost instance for chaining.</returns> |
| | | 94 | | public static KestrunHost AddMapRoute(this KestrunHost host, MapRouteOptions options, KestrunHandler handler, out IE |
| | | 95 | | { |
| | 2 | 96 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 97 | | { |
| | 1 | 98 | | host.Logger.Debug("AddMapRoute called with options={Options}", options); |
| | | 99 | | } |
| | | 100 | | // Ensure the WebApplication is initialized |
| | 2 | 101 | | if (host.App is null) |
| | | 102 | | { |
| | 0 | 103 | | throw new InvalidOperationException("WebApplication is not initialized. Call EnableConfiguration first."); |
| | | 104 | | } |
| | | 105 | | |
| | | 106 | | // Validate options |
| | 1 | 107 | | if (string.IsNullOrWhiteSpace(options.Pattern)) |
| | | 108 | | { |
| | 0 | 109 | | throw new ArgumentException("Pattern cannot be null or empty.", nameof(options.Pattern)); |
| | | 110 | | } |
| | | 111 | | |
| | 2 | 112 | | string[] methods = [.. options.HttpVerbs.Select(v => v.ToMethodString())]; |
| | 1 | 113 | | map = host.App.MapMethods(options.Pattern, methods, async context => |
| | 1 | 114 | | { |
| | 1 | 115 | | // 🔒 CSRF validation only for the current request when that verb is unsafe (unless disabled) |
| | 0 | 116 | | if (ShouldValidateCsrf(options, context)) |
| | 1 | 117 | | { |
| | 0 | 118 | | if (!await TryValidateAntiforgeryAsync(context)) |
| | 1 | 119 | | { |
| | 0 | 120 | | return; // already responded 400 |
| | 1 | 121 | | } |
| | 1 | 122 | | } |
| | 0 | 123 | | var req = await KestrunRequest.NewRequest(context); |
| | 0 | 124 | | var res = new KestrunResponse(req); |
| | 0 | 125 | | KestrunContext kestrunContext = new(host, req, res, context); |
| | 0 | 126 | | await handler(kestrunContext); |
| | 0 | 127 | | await res.ApplyTo(context.Response); |
| | 1 | 128 | | }); |
| | | 129 | | |
| | 1 | 130 | | host.AddMapOptions(map, options); |
| | | 131 | | |
| | 1 | 132 | | host.Logger.Information("Added native route: {Pattern} with methods: {Methods}", options.Pattern, string.Join(", |
| | | 133 | | // Add to the feature queue for later processing |
| | 1 | 134 | | host.FeatureQueue.Add(host => host.AddMapRoute(options)); |
| | 1 | 135 | | return host; |
| | | 136 | | } |
| | | 137 | | |
| | | 138 | | /// <summary> |
| | | 139 | | /// Adds a route to the KestrunHost that serves OpenAPI documents based on the provided options. |
| | | 140 | | /// </summary> |
| | | 141 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 142 | | /// <param name="options">The OpenApiMapRouteOptions instance.</param> |
| | | 143 | | /// <returns>The KestrunHost instance for chaining.</returns> |
| | | 144 | | public static KestrunHost AddOpenApiMapRoute(this KestrunHost host, OpenApiMapRouteOptions options) |
| | | 145 | | { |
| | 0 | 146 | | ArgumentNullException.ThrowIfNull(options); |
| | 0 | 147 | | ArgumentNullException.ThrowIfNull(host); |
| | | 148 | | |
| | | 149 | | // Validate options |
| | 0 | 150 | | return host.AddMapRoute(options.MapOptions, async context => |
| | 0 | 151 | | { |
| | 0 | 152 | | // Extract parameters |
| | 0 | 153 | | var refresh = false; |
| | 0 | 154 | | var docId = options.DocId; |
| | 0 | 155 | | OpenApiSpecVersion specVersion; |
| | 0 | 156 | | // Try to get version and format from route values |
| | 0 | 157 | | var version = context.Request.RouteValues[options.VersionVarName]?.ToString() ?? options.DefaultVersion; |
| | 0 | 158 | | var format = context.Request.RouteValues[options.FormatVarName]?.ToString() ?? options.DefaultFormat; |
| | 0 | 159 | | if (context.Request.Query.TryGetValue(options.RefreshVarName, out var value)) |
| | 0 | 160 | | { |
| | 0 | 161 | | _ = bool.TryParse(value, out refresh); |
| | 0 | 162 | | } |
| | 0 | 163 | | // Try to get version and format from route values |
| | 0 | 164 | | try |
| | 0 | 165 | | { |
| | 0 | 166 | | specVersion = OpenApiSpecVersionExtensions.ParseOpenApiSpecVersion(version); |
| | 0 | 167 | | if (format is not "json" and not "yaml") |
| | 0 | 168 | | { |
| | 0 | 169 | | throw new InvalidOperationException($"Unsupported OpenAPI format requested: {format}"); |
| | 0 | 170 | | } |
| | 0 | 171 | | } |
| | 0 | 172 | | catch |
| | 0 | 173 | | { |
| | 0 | 174 | | host.Logger.Warning("Invalid OpenAPI version or format requested: {Version}, {Format}", version, format) |
| | 0 | 175 | | context.Response.StatusCode = 404; // Not Found |
| | 0 | 176 | | return; |
| | 0 | 177 | | } |
| | 0 | 178 | | // Refresh the document if requested |
| | 0 | 179 | | if (refresh) |
| | 0 | 180 | | { |
| | 0 | 181 | | host.Logger.Information("Refreshing OpenAPI document cache as requested."); |
| | 0 | 182 | | var doc = host.OpenApiDocumentDescriptor[docId]; |
| | 0 | 183 | | doc.GenerateDoc(); |
| | 0 | 184 | | } |
| | 0 | 185 | | // Serve the document in the requested format |
| | 0 | 186 | | if (format == "json") |
| | 0 | 187 | | { |
| | 0 | 188 | | var json = host.OpenApiDocumentDescriptor[docId].ToJson(specVersion); |
| | 0 | 189 | | await context.Response.WriteTextResponseAsync(json, 200, "application/json"); |
| | 0 | 190 | | } |
| | 0 | 191 | | else |
| | 0 | 192 | | { |
| | 0 | 193 | | var yml = host.OpenApiDocumentDescriptor[docId].ToYaml(specVersion); |
| | 0 | 194 | | await context.Response.WriteTextResponseAsync(yml, 200, "application/yaml"); |
| | 0 | 195 | | } |
| | 0 | 196 | | }, out _); |
| | | 197 | | } |
| | | 198 | | |
| | | 199 | | /// <summary> |
| | | 200 | | /// Adds a route to the KestrunHost that executes a script block for the specified HTTP verb and pattern. |
| | | 201 | | /// </summary> |
| | | 202 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 203 | | /// <param name="pattern">The route pattern.</param> |
| | | 204 | | /// <param name="httpVerbs">The HTTP verb for the route.</param> |
| | | 205 | | /// <param name="scriptBlock">The script block to execute.</param> |
| | | 206 | | /// <param name="language">The scripting language to use (default is PowerShell).</param> |
| | | 207 | | /// <param name="requireSchemes">Optional array of authorization schemes required for the route.</param> |
| | | 208 | | /// <param name="arguments">Optional dictionary of arguments to pass to the script.</param> |
| | | 209 | | /// <returns>The KestrunHost instance for chaining.</returns> |
| | | 210 | | public static KestrunHost AddMapRoute(this KestrunHost host, string pattern, HttpVerb httpVerbs, string scriptBlock, |
| | | 211 | | List<string>? requireSchemes = null, |
| | | 212 | | Dictionary<string, object?>? arguments = null) |
| | | 213 | | { |
| | 11 | 214 | | arguments ??= []; |
| | 11 | 215 | | return host.AddMapRoute(new MapRouteOptions |
| | 11 | 216 | | { |
| | 11 | 217 | | Pattern = pattern, |
| | 11 | 218 | | HttpVerbs = [httpVerbs], |
| | 11 | 219 | | ScriptCode = new LanguageOptions |
| | 11 | 220 | | { |
| | 11 | 221 | | Code = scriptBlock, |
| | 11 | 222 | | Language = language, |
| | 11 | 223 | | Arguments = arguments ?? [] // No additional arguments by default |
| | 11 | 224 | | }, |
| | 11 | 225 | | RequireSchemes = requireSchemes ?? [], // No authorization by default |
| | 11 | 226 | | }); |
| | | 227 | | } |
| | | 228 | | |
| | | 229 | | /// <summary> |
| | | 230 | | /// Adds a route to the KestrunHost that executes a script block for the specified HTTP verbs and pattern. |
| | | 231 | | /// </summary> |
| | | 232 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 233 | | /// <param name="pattern">The route pattern.</param> |
| | | 234 | | /// <param name="httpVerbs">The HTTP verbs for the route.</param> |
| | | 235 | | /// <param name="scriptBlock">The script block to execute.</param> |
| | | 236 | | /// <param name="language">The scripting language to use (default is PowerShell).</param> |
| | | 237 | | /// <param name="requireSchemes">Optional array of authorization schemes required for the route.</param> |
| | | 238 | | /// <param name="arguments">Optional dictionary of arguments to pass to the script.</param> |
| | | 239 | | /// <returns>The KestrunHost instance for chaining.</returns> |
| | | 240 | | public static KestrunHost AddMapRoute(this KestrunHost host, string pattern, |
| | | 241 | | IEnumerable<HttpVerb> httpVerbs, |
| | | 242 | | string scriptBlock, |
| | | 243 | | ScriptLanguage language = ScriptLanguage.PowerShell, |
| | | 244 | | List<string>? requireSchemes = null, |
| | | 245 | | Dictionary<string, object?>? arguments = null) |
| | | 246 | | { |
| | 1 | 247 | | return host.AddMapRoute(new MapRouteOptions |
| | 1 | 248 | | { |
| | 1 | 249 | | Pattern = pattern, |
| | 1 | 250 | | HttpVerbs = [.. httpVerbs], |
| | 1 | 251 | | ScriptCode = new LanguageOptions |
| | 1 | 252 | | { |
| | 1 | 253 | | Code = scriptBlock, |
| | 1 | 254 | | Language = language, |
| | 1 | 255 | | Arguments = arguments ?? [] // No additional arguments by default |
| | 1 | 256 | | }, |
| | 1 | 257 | | RequireSchemes = requireSchemes ?? [], // No authorization by default |
| | 1 | 258 | | }); |
| | | 259 | | } |
| | | 260 | | |
| | | 261 | | /// <summary> |
| | | 262 | | /// Adds a route to the KestrunHost using the specified MapRouteOptions. |
| | | 263 | | /// </summary> |
| | | 264 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 265 | | /// <param name="options">The MapRouteOptions containing route configuration.</param> |
| | | 266 | | /// <returns>The KestrunHost instance for chaining.</returns> |
| | | 267 | | public static KestrunHost AddMapRoute(this KestrunHost host, MapRouteOptions options) |
| | | 268 | | { |
| | 31 | 269 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 270 | | { |
| | 22 | 271 | | host.Logger.Debug("AddMapRoute called with pattern={Pattern}, language={Language}, method={Methods}", option |
| | | 272 | | } |
| | 31 | 273 | | if (host.IsConfigured) |
| | | 274 | | { |
| | 30 | 275 | | _ = CreateMapRoute(host, options); |
| | | 276 | | } |
| | | 277 | | else |
| | | 278 | | { |
| | 1 | 279 | | _ = host.Use(app => |
| | 1 | 280 | | { |
| | 1 | 281 | | _ = CreateMapRoute(host, options); |
| | 2 | 282 | | }); |
| | | 283 | | } |
| | 25 | 284 | | return host; // for chaining |
| | | 285 | | } |
| | | 286 | | |
| | | 287 | | /// <summary> |
| | | 288 | | /// Adds a route to the KestrunHost using the specified MapRouteOptions. |
| | | 289 | | /// </summary> |
| | | 290 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 291 | | /// <param name="options">The MapRouteOptions containing route configuration.</param> |
| | | 292 | | /// <returns>The IEndpointConventionBuilder for the created route.</returns> |
| | | 293 | | private static IEndpointConventionBuilder CreateMapRoute(KestrunHost host, MapRouteOptions options) |
| | | 294 | | { |
| | 31 | 295 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 296 | | { |
| | 22 | 297 | | host.Logger.Debug("AddMapRoute called with pattern={Pattern}, language={Language}, method={Methods}", option |
| | | 298 | | } |
| | | 299 | | |
| | | 300 | | try |
| | | 301 | | { |
| | | 302 | | // Validate options and get normalized route options |
| | 31 | 303 | | if (!ValidateRouteOptions(host, options, out var routeOptions)) |
| | | 304 | | { |
| | 0 | 305 | | return null!; // Route already exists and should be skipped |
| | | 306 | | } |
| | | 307 | | |
| | 30 | 308 | | var logger = host.Logger.ForContext("Route", routeOptions.Pattern); |
| | | 309 | | |
| | | 310 | | // Compile the script once – return a RequestDelegate |
| | 30 | 311 | | var compiled = CompileScript(host, options.ScriptCode); |
| | | 312 | | |
| | | 313 | | // Create and register the route |
| | 30 | 314 | | return CreateAndRegisterRoute(host, routeOptions, compiled); |
| | | 315 | | } |
| | 0 | 316 | | catch (CompilationErrorException ex) |
| | | 317 | | { |
| | | 318 | | // Log the detailed compilation errors |
| | 0 | 319 | | host.Logger.Error($"Failed to add route '{options.Pattern}' due to compilation errors:"); |
| | 0 | 320 | | host.Logger.Error(ex.GetDetailedErrorMessage()); |
| | | 321 | | |
| | | 322 | | // Re-throw with additional context |
| | 0 | 323 | | throw new InvalidOperationException( |
| | 0 | 324 | | $"Failed to compile {options.ScriptCode.Language} script for route '{options.Pattern}'. {ex.GetErrors(). |
| | 0 | 325 | | ex); |
| | | 326 | | } |
| | 6 | 327 | | catch (Exception ex) |
| | | 328 | | { |
| | 6 | 329 | | throw new InvalidOperationException( |
| | 6 | 330 | | $"Failed to add route '{options.Pattern}' with method '{string.Join(", ", options.HttpVerbs)}' using {op |
| | 6 | 331 | | ex); |
| | | 332 | | } |
| | 25 | 333 | | } |
| | | 334 | | |
| | | 335 | | /// <summary> |
| | | 336 | | /// Validates the host and options for adding a map route. |
| | | 337 | | /// </summary> |
| | | 338 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 339 | | /// <param name="options">The MapRouteOptions to validate.</param> |
| | | 340 | | /// <param name="routeOptions">The validated route options with defaults applied.</param> |
| | | 341 | | /// <returns>True if validation passes and route should be added; false if duplicate route should be skipped.</retur |
| | | 342 | | /// <exception cref="InvalidOperationException">Thrown when WebApplication is not initialized or route already exist |
| | | 343 | | /// <exception cref="ArgumentException">Thrown when required options are invalid.</exception> |
| | | 344 | | internal static bool ValidateRouteOptions(KestrunHost host, MapRouteOptions options, out MapRouteOptions routeOption |
| | | 345 | | { |
| | | 346 | | // Ensure the WebApplication is initialized |
| | 40 | 347 | | if (host.App is null) |
| | | 348 | | { |
| | 0 | 349 | | throw new InvalidOperationException("WebApplication is not initialized. Call EnableConfiguration first."); |
| | | 350 | | } |
| | | 351 | | |
| | | 352 | | // Validate options |
| | 39 | 353 | | if (string.IsNullOrWhiteSpace(options.Pattern)) |
| | | 354 | | { |
| | 2 | 355 | | throw new ArgumentException("Pattern cannot be null or empty.", nameof(options.Pattern)); |
| | | 356 | | } |
| | | 357 | | |
| | | 358 | | // Validate code |
| | 37 | 359 | | if (string.IsNullOrWhiteSpace(options.ScriptCode.Code)) |
| | | 360 | | { |
| | 2 | 361 | | throw new ArgumentException("ScriptBlock cannot be null or empty.", nameof(options.ScriptCode.Code)); |
| | | 362 | | } |
| | | 363 | | |
| | 35 | 364 | | routeOptions = options; |
| | 35 | 365 | | if (options.HttpVerbs.Count == 0) |
| | | 366 | | { |
| | | 367 | | // If no HTTP verbs were specified, default to GET. |
| | 2 | 368 | | routeOptions.HttpVerbs = [HttpVerb.Get]; |
| | | 369 | | } |
| | | 370 | | |
| | 35 | 371 | | if (MapExists(host, routeOptions.Pattern, routeOptions.HttpVerbs)) |
| | | 372 | | { |
| | 3 | 373 | | var msg = $"Route '{routeOptions.Pattern}' with method(s) {string.Join(", ", routeOptions.HttpVerbs)} alread |
| | 3 | 374 | | if (options.ThrowOnDuplicate) |
| | | 375 | | { |
| | 2 | 376 | | throw new InvalidOperationException(msg); |
| | | 377 | | } |
| | | 378 | | |
| | 1 | 379 | | host.Logger.Warning(msg); |
| | 1 | 380 | | return false; // Skip this route |
| | | 381 | | } |
| | | 382 | | |
| | 32 | 383 | | return true; // Continue with route creation |
| | | 384 | | } |
| | | 385 | | |
| | | 386 | | /// <summary> |
| | | 387 | | /// Compiles the script code for the specified language. |
| | | 388 | | /// </summary> |
| | | 389 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 390 | | /// <param name="options">The language options containing the script code and language.</param> |
| | | 391 | | /// <returns>A compiled RequestDelegate that can handle HTTP requests.</returns> |
| | | 392 | | /// <exception cref="NotSupportedException">Thrown when the script language is not supported.</exception> |
| | | 393 | | internal static RequestDelegate CompileScript(this KestrunHost host, LanguageOptions options) |
| | | 394 | | { |
| | 37 | 395 | | return options.Language switch |
| | 37 | 396 | | { |
| | 1 | 397 | | ScriptLanguage.PowerShell => PowerShellDelegateBuilder.Build(host, options.Code!, options.Arguments), |
| | 33 | 398 | | ScriptLanguage.CSharp => CSharpDelegateBuilder.Build(host, options.Code!, options.Arguments, options.ExtraIm |
| | 2 | 399 | | ScriptLanguage.VBNet => VBNetDelegateBuilder.Build(host, options.Code!, options.Arguments, options.ExtraImpo |
| | 0 | 400 | | ScriptLanguage.FSharp => FSharpDelegateBuilder.Build(host, options.Code!), // F# scripting not implemented |
| | 0 | 401 | | ScriptLanguage.Python => PyDelegateBuilder.Build(host, options.Code!), |
| | 0 | 402 | | ScriptLanguage.JavaScript => JScriptDelegateBuilder.Build(host, options.Code!), |
| | 1 | 403 | | _ => throw new NotSupportedException(options.Language.ToString()) |
| | 37 | 404 | | }; |
| | | 405 | | } |
| | | 406 | | |
| | | 407 | | /// <summary> |
| | | 408 | | /// Creates and registers a route with the specified options and compiled handler. |
| | | 409 | | /// </summary> |
| | | 410 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 411 | | /// <param name="routeOptions">The validated route options.</param> |
| | | 412 | | /// <param name="compiled">The compiled script delegate.</param> |
| | | 413 | | /// <returns>An IEndpointConventionBuilder for further configuration.</returns> |
| | | 414 | | internal static IEndpointConventionBuilder CreateAndRegisterRoute(KestrunHost host, MapRouteOptions routeOptions, Re |
| | | 415 | | { |
| | | 416 | | // Wrap with CSRF validation |
| | | 417 | | async Task handler(HttpContext ctx) |
| | | 418 | | { |
| | 11 | 419 | | if (ShouldValidateCsrf(routeOptions, ctx)) |
| | | 420 | | { |
| | 0 | 421 | | if (!await TryValidateAntiforgeryAsync(ctx)) |
| | | 422 | | { |
| | 0 | 423 | | return; // already responded 400 |
| | | 424 | | } |
| | | 425 | | } |
| | 11 | 426 | | await compiled(ctx); |
| | 6 | 427 | | } |
| | | 428 | | |
| | 67 | 429 | | string[] methods = [.. routeOptions.HttpVerbs.Select(v => v.ToMethodString())]; |
| | 32 | 430 | | var map = host.App!.MapMethods(routeOptions.Pattern!, methods, handler).WithLanguage(routeOptions.ScriptCode.Lan |
| | | 431 | | |
| | 32 | 432 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 433 | | { |
| | 23 | 434 | | host.Logger.Debug("Mapped route: {Pattern} with methods: {Methods}", routeOptions.Pattern, string.Join(", ", |
| | | 435 | | } |
| | | 436 | | |
| | 32 | 437 | | host.AddMapOptions(map, routeOptions); |
| | | 438 | | |
| | | 439 | | // Register OpenAPI metadata for each verb |
| | 114 | 440 | | foreach (var method in routeOptions.HttpVerbs) |
| | | 441 | | { |
| | 30 | 442 | | if (routeOptions.OpenAPI.TryGetValue(method, out var value)) |
| | | 443 | | { |
| | 0 | 444 | | ApplyOpenApiMetadata(host, map, value); |
| | | 445 | | } |
| | | 446 | | // Register the route to prevent duplicates |
| | 30 | 447 | | host._registeredRoutes[(routeOptions.Pattern!, method)] = routeOptions; |
| | | 448 | | } |
| | | 449 | | |
| | 27 | 450 | | host.Logger.Information("Added route: {Pattern} with methods: {Methods}", routeOptions.Pattern, string.Join(", " |
| | 27 | 451 | | return map; |
| | | 452 | | } |
| | | 453 | | |
| | | 454 | | /// <summary> |
| | | 455 | | /// Adds additional mapping options to the route. |
| | | 456 | | /// </summary> |
| | | 457 | | /// <param name="host">The Kestrun host.</param> |
| | | 458 | | /// <param name="map">The endpoint convention builder.</param> |
| | | 459 | | /// <param name="options">The mapping options.</param> |
| | | 460 | | internal static void AddMapOptions(this KestrunHost host, IEndpointConventionBuilder map, MapRouteOptions options) |
| | | 461 | | { |
| | 35 | 462 | | ApplyShortCircuit(host, map, options); |
| | 35 | 463 | | ApplyAnonymous(host, map, options); |
| | 35 | 464 | | DisableAntiforgery(host, map, options); |
| | 35 | 465 | | DisableResponseCompression(host, map, options); |
| | 35 | 466 | | ApplyRateLimiting(host, map, options); |
| | 35 | 467 | | ApplyAuthSchemes(host, map, options); |
| | 34 | 468 | | ApplyPolicies(host, map, options); |
| | 33 | 469 | | ApplyCors(host, map, options); |
| | 33 | 470 | | ApplyRequiredHost(host, map, options); |
| | 30 | 471 | | AddMetadata(host, map, options); |
| | 30 | 472 | | } |
| | | 473 | | |
| | | 474 | | /// <summary> |
| | | 475 | | /// Tries to parse an endpoint specification string into its components: host, port, and HTTPS flag. |
| | | 476 | | /// </summary> |
| | | 477 | | /// <param name="spec">The endpoint specification string.</param> |
| | | 478 | | /// <param name="host">The host component.</param> |
| | | 479 | | /// <param name="port">The port component.</param> |
| | | 480 | | /// <param name="https"> |
| | | 481 | | /// Indicates HTTPS (<c>true</c>) or HTTP (<c>false</c>) when the scheme is explicitly specified via a full URL. |
| | | 482 | | /// For host:port forms where no scheme information is available the value is <c>null</c>. |
| | | 483 | | /// </param> |
| | | 484 | | /// <returns> |
| | | 485 | | /// <c>true</c> if parsing succeeds; otherwise <c>false</c> and <paramref name="host"/> will be <c>string.Empty</c> |
| | | 486 | | /// </returns> |
| | | 487 | | /// <remarks> |
| | | 488 | | /// Accepted formats (in priority order): |
| | | 489 | | /// <list type="bullet"> |
| | | 490 | | /// <item><description>Full URL: <c>https://host:port</c>, <c>http://host:port</c>, IPv6 literal allowed in brackets |
| | | 491 | | /// <item><description>Bracketed IPv6 host & port: <c>[::1]:5000</c>, <c>[2001:db8::1]:8080</c>.</description></ |
| | | 492 | | /// <item><description>Host or IPv4 with port: <c>localhost:5000</c>, <c>127.0.0.1:8080</c>, <c>example.com:443</c>. |
| | | 493 | | /// </list> |
| | | 494 | | /// Unsupported / rejected examples: non http(s) schemes (e.g. <c>ftp://</c>), missing port in host:port form, empty |
| | | 495 | | /// </remarks> |
| | | 496 | | public static bool TryParseEndpointSpec(string spec, out string host, out int port, out bool? https) |
| | | 497 | | { |
| | 171 | 498 | | host = ""; port = 0; https = null; |
| | | 499 | | |
| | 57 | 500 | | if (string.IsNullOrWhiteSpace(spec)) |
| | | 501 | | { |
| | 5 | 502 | | return false; |
| | | 503 | | } |
| | | 504 | | |
| | | 505 | | // 1. Try full URL form first |
| | 52 | 506 | | if (TryParseUrlSpec(spec, out host, out port, out https)) |
| | | 507 | | { |
| | 16 | 508 | | return true; |
| | | 509 | | } |
| | | 510 | | |
| | | 511 | | // 2. Bracketed IPv6 literal with port: [::1]:5000 |
| | 36 | 512 | | if (TryParseBracketedIpv6Spec(spec, out host, out port)) |
| | | 513 | | { |
| | 4 | 514 | | return true; // https stays null (not specified) |
| | | 515 | | } |
| | | 516 | | |
| | | 517 | | // 3. Regular host:port (hostname, IPv4, or raw IPv6 w/out brackets not supported here) |
| | 32 | 518 | | if (TryParseHostPortSpec(spec, out host, out port)) |
| | | 519 | | { |
| | 12 | 520 | | return true; // https stays null (not specified) |
| | | 521 | | } |
| | | 522 | | |
| | | 523 | | // No match |
| | 60 | 524 | | host = ""; port = 0; https = null; |
| | 20 | 525 | | return false; |
| | | 526 | | } |
| | | 527 | | |
| | | 528 | | /// <summary> |
| | | 529 | | /// Tries to parse a full URL endpoint specification. |
| | | 530 | | /// </summary> |
| | | 531 | | /// <param name="spec">The endpoint specification string.</param> |
| | | 532 | | /// <param name="host">The parsed host component.</param> |
| | | 533 | | /// <param name="port">The parsed port component.</param> |
| | | 534 | | /// <param name="https">The parsed HTTPS flag.</param> |
| | | 535 | | /// <returns><c>true</c> if parsing succeeded; otherwise <c>false</c>.</returns> |
| | | 536 | | private static bool TryParseUrlSpec(string spec, out string host, out int port, out bool? https) |
| | | 537 | | { |
| | 156 | 538 | | host = ""; port = 0; https = null; |
| | | 539 | | // Fast rejection for an explicitly empty port (e.g. "https://localhost:" or "http://[::1]:") |
| | | 540 | | // Uri.TryCreate will happily parse these and supply the default scheme port (80/443), |
| | | 541 | | // which would make us treat an intentionally empty port as a valid implicit port. |
| | | 542 | | // The accepted formats require either no colon at all (implicit default) OR a colon followed by digits. |
| | | 543 | | // Therefore pattern: scheme:// host-part : end-of-string (no digits after colon) should be rejected. |
| | 52 | 544 | | if (EmptyPortDetectionRegex().IsMatch(spec)) |
| | | 545 | | { |
| | 2 | 546 | | return false; |
| | | 547 | | } |
| | 50 | 548 | | if (!Uri.TryCreate(spec, UriKind.Absolute, out var uri)) |
| | | 549 | | { |
| | 22 | 550 | | return false; |
| | | 551 | | } |
| | 28 | 552 | | if (!(uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) || |
| | 28 | 553 | | uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase))) |
| | | 554 | | { |
| | 12 | 555 | | return false; // Not http/https → let other parsers try |
| | | 556 | | } |
| | 16 | 557 | | if (uri.Authority.EndsWith(':')) |
| | | 558 | | { |
| | 0 | 559 | | return false; // reject empty port like https://localhost: |
| | | 560 | | } |
| | 16 | 561 | | host = uri.Host; |
| | 16 | 562 | | port = uri.Port; |
| | 16 | 563 | | https = uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase) |
| | 16 | 564 | | ? true |
| | 16 | 565 | | : uri.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase) |
| | 16 | 566 | | ? false |
| | 16 | 567 | | : null; |
| | 16 | 568 | | return !string.IsNullOrWhiteSpace(host) && IsValidPort(port); |
| | | 569 | | } |
| | | 570 | | |
| | | 571 | | /// <summary> |
| | | 572 | | /// Tries to parse a bracketed IPv6 endpoint specification. |
| | | 573 | | /// </summary> |
| | | 574 | | /// <param name="spec">The endpoint specification string.</param> |
| | | 575 | | /// <param name="host">The parsed host component.</param> |
| | | 576 | | /// <param name="port">The parsed port component.</param> |
| | | 577 | | /// <returns><c>true</c> if parsing succeeded; otherwise <c>false</c>.</returns> |
| | | 578 | | private static bool TryParseBracketedIpv6Spec(string spec, out string host, out int port) |
| | | 579 | | { |
| | 72 | 580 | | host = ""; port = 0; |
| | 36 | 581 | | var m = BracketedIpv6SpecMatcher().Match(spec); |
| | 36 | 582 | | if (!m.Success) |
| | | 583 | | { |
| | 32 | 584 | | return false; |
| | | 585 | | } |
| | 4 | 586 | | host = m.Groups[1].Value; |
| | 4 | 587 | | if (!int.TryParse(m.Groups[2].Value, out port) || !IsValidPort(port)) |
| | | 588 | | { |
| | 0 | 589 | | host = ""; port = 0; return false; |
| | | 590 | | } |
| | 4 | 591 | | return !string.IsNullOrWhiteSpace(host); |
| | | 592 | | } |
| | | 593 | | |
| | | 594 | | /// <summary> |
| | | 595 | | /// Tries to parse a host:port endpoint specification. |
| | | 596 | | /// </summary> |
| | | 597 | | /// <param name="spec">The endpoint specification string.</param> |
| | | 598 | | /// <param name="host">The parsed host component.</param> |
| | | 599 | | /// <param name="port">The parsed port component.</param> |
| | | 600 | | /// <returns><c>true</c> if parsing succeeded; otherwise <c>false</c>.</returns> |
| | | 601 | | private static bool TryParseHostPortSpec(string spec, out string host, out int port) |
| | | 602 | | { |
| | 64 | 603 | | host = ""; port = 0; |
| | 32 | 604 | | var m = HostPortSpecMatcher().Match(spec); |
| | 32 | 605 | | if (!m.Success) |
| | | 606 | | { |
| | 17 | 607 | | return false; |
| | | 608 | | } |
| | 15 | 609 | | host = m.Groups[1].Value; |
| | 15 | 610 | | if (!int.TryParse(m.Groups[2].Value, out port) || !IsValidPort(port)) |
| | | 611 | | { |
| | 9 | 612 | | host = ""; port = 0; return false; |
| | | 613 | | } |
| | 12 | 614 | | return !string.IsNullOrWhiteSpace(host); |
| | | 615 | | } |
| | | 616 | | private const int MIN_PORT = 1; |
| | | 617 | | private const int MAX_PORT = 65535; |
| | | 618 | | |
| | | 619 | | /// <summary> |
| | | 620 | | /// Validates that the port number is within the acceptable range (1-65535). |
| | | 621 | | /// </summary> |
| | | 622 | | /// <param name="port">The port number to validate.</param> |
| | | 623 | | /// <returns><c>true</c> if the port number is valid; otherwise, <c>false</c>.</returns> |
| | 35 | 624 | | private static bool IsValidPort(int port) => port is >= MIN_PORT and <= MAX_PORT; |
| | | 625 | | |
| | | 626 | | /// <summary> |
| | | 627 | | /// Formats the host and port for use in RequireHost, adding brackets for IPv6 literals. |
| | | 628 | | /// </summary> |
| | | 629 | | /// <param name="host">The host component.</param> |
| | | 630 | | /// <param name="port">The port component.</param> |
| | | 631 | | /// <returns>The formatted host and port string.</returns> |
| | | 632 | | internal static string ToRequireHost(string host, int port) => |
| | 18 | 633 | | IsIPv6Address(host) ? $"[{host}]:{port}" : $"{host}:{port}"; // IPv6 literals must be bracketed in RequireHost |
| | | 634 | | |
| | | 635 | | /// <summary> |
| | | 636 | | /// Determines if the given host string is an IPv6 address. |
| | | 637 | | /// </summary> |
| | | 638 | | /// <param name="host">The host string to check.</param> |
| | | 639 | | /// <returns>True if the host is an IPv6 address; otherwise, false.</returns> |
| | 18 | 640 | | private static bool IsIPv6Address(string host) => IPAddress.TryParse(host, out var ip) && ip.AddressFamily == System |
| | | 641 | | |
| | | 642 | | /// <summary> |
| | | 643 | | /// Applies required hosts to the route based on the specified endpoints in the options. |
| | | 644 | | /// </summary> |
| | | 645 | | /// <param name="host">The Kestrun host.</param> |
| | | 646 | | /// <param name="map">The endpoint convention builder.</param> |
| | | 647 | | /// <param name="options">The mapping options.</param> |
| | | 648 | | /// <exception cref="ArgumentException">Thrown when the specified endpoints are invalid.</exception> |
| | | 649 | | internal static void ApplyRequiredHost(this KestrunHost host, IEndpointConventionBuilder map, MapRouteOptions option |
| | | 650 | | { |
| | 33 | 651 | | if (options.Endpoints is not { Length: > 0 }) |
| | | 652 | | { |
| | 25 | 653 | | return; |
| | | 654 | | } |
| | | 655 | | |
| | 8 | 656 | | var listeners = host.Options.Listeners; |
| | 8 | 657 | | var require = new List<string>(); |
| | 8 | 658 | | var errs = new List<string>(); |
| | | 659 | | |
| | 38 | 660 | | foreach (var spec in options.Endpoints) |
| | | 661 | | { |
| | 11 | 662 | | if (!TryParseEndpointSpec(spec, out var eh, out var ep, out var eHttps)) |
| | | 663 | | { |
| | 2 | 664 | | errs.Add($"'{spec}' must be 'host:port' or 'http(s)://host:port'."); |
| | 2 | 665 | | continue; |
| | | 666 | | } |
| | | 667 | | |
| | | 668 | | // Is the host a numeric IP? |
| | 9 | 669 | | var isNumericHost = IPAddress.TryParse(eh, out var endpointIp); |
| | | 670 | | |
| | | 671 | | // Find a compatible listener: same port, scheme (if specified), and IP match if numeric host. |
| | 9 | 672 | | var match = listeners.FirstOrDefault(l => |
| | 19 | 673 | | l.Port == ep && |
| | 19 | 674 | | (eHttps is null || l.UseHttps == eHttps.Value) && |
| | 19 | 675 | | (!isNumericHost || |
| | 19 | 676 | | l.IPAddress.Equals(endpointIp) || |
| | 19 | 677 | | l.IPAddress.Equals(IPAddress.Any) || |
| | 19 | 678 | | l.IPAddress.Equals(IPAddress.IPv6Any))); |
| | | 679 | | |
| | 9 | 680 | | if (match is null) |
| | | 681 | | { |
| | 2 | 682 | | errs.Add($"'{spec}' doesn't match any configured listener. " + |
| | 4 | 683 | | $"Known: {string.Join(", ", listeners.Select(l => l.ToString()))}"); |
| | 2 | 684 | | continue; |
| | | 685 | | } |
| | | 686 | | |
| | 7 | 687 | | require.Add(ToRequireHost(eh, ep)); |
| | | 688 | | } |
| | | 689 | | |
| | 8 | 690 | | if (errs.Count > 0) |
| | | 691 | | { |
| | 3 | 692 | | throw new InvalidOperationException("Invalid Endpoints:" + Environment.NewLine + " - " + string.Join(Enviro |
| | | 693 | | } |
| | 5 | 694 | | if (require.Count > 0) |
| | | 695 | | { |
| | 5 | 696 | | host.Logger.Verbose("Applying required hosts: {RequiredHosts} to route: {Pattern}", |
| | 5 | 697 | | string.Join(", ", require), options.Pattern); |
| | 5 | 698 | | _ = map.RequireHost([.. require]); |
| | | 699 | | } |
| | 5 | 700 | | } |
| | | 701 | | |
| | | 702 | | /// <summary> |
| | | 703 | | /// Applies the same route conventions used by the AddMapRoute helpers to an arbitrary endpoint. |
| | | 704 | | /// </summary> |
| | | 705 | | /// <param name="host">The Kestrun host used for validation (auth schemes/policies).</param> |
| | | 706 | | /// <param name="builder">The endpoint convention builder to decorate.</param> |
| | | 707 | | /// <param name="configure">Delegate to configure a fresh <see cref="MapRouteOptions"/> instance. Only applicable pr |
| | | 708 | | /// <remarks> |
| | | 709 | | /// This is useful when you map endpoints manually via <c>app.MapGet</c>/<c>MapPost</c> and still want consistent be |
| | | 710 | | /// (auth, CORS, rate limiting, antiforgery disable, OpenAPI metadata, short-circuiting) without re-implementing log |
| | | 711 | | /// Validation notes: |
| | | 712 | | /// - Pattern, Code are ignored if not relevant. |
| | | 713 | | /// - Authentication schemes and policies are validated against the host registry. |
| | | 714 | | /// - OpenAPI metadata is applied only when non-empty. |
| | | 715 | | /// </remarks> |
| | | 716 | | /// <returns>The original <paramref name="builder"/> for fluent chaining.</returns> |
| | | 717 | | public static IEndpointConventionBuilder ApplyKestrunConventions(this KestrunHost host, IEndpointConventionBuilder b |
| | | 718 | | { |
| | 1 | 719 | | ArgumentNullException.ThrowIfNull(host); |
| | 1 | 720 | | ArgumentNullException.ThrowIfNull(builder); |
| | 1 | 721 | | ArgumentNullException.ThrowIfNull(configure); |
| | | 722 | | |
| | | 723 | | // Start with an empty options record (only convention-related fields will matter) |
| | 1 | 724 | | var options = new MapRouteOptions |
| | 1 | 725 | | { |
| | 1 | 726 | | Pattern = string.Empty, |
| | 1 | 727 | | HttpVerbs = [], |
| | 1 | 728 | | ScriptCode = new LanguageOptions |
| | 1 | 729 | | { |
| | 1 | 730 | | Language = ScriptLanguage.Native, |
| | 1 | 731 | | Code = string.Empty |
| | 1 | 732 | | } |
| | 1 | 733 | | }; |
| | 1 | 734 | | configure(options); |
| | | 735 | | |
| | | 736 | | // Reuse internal helper (kept internal to avoid accidental misuse) for actual application |
| | 1 | 737 | | host.AddMapOptions(builder, options); |
| | 1 | 738 | | return builder; |
| | | 739 | | } |
| | | 740 | | /// <summary> |
| | | 741 | | /// Adds metadata to the route from the script parameters. |
| | | 742 | | /// </summary> |
| | | 743 | | /// <param name="host">The Kestrun host.</param> |
| | | 744 | | /// <param name="map">The endpoint convention builder.</param> |
| | | 745 | | /// <param name="options">The mapping options.</param> |
| | | 746 | | private static void AddMetadata(KestrunHost host, IEndpointConventionBuilder map, MapRouteOptions options) |
| | | 747 | | { |
| | 30 | 748 | | if (options.ScriptCode is null || options.ScriptCode.Parameters is null || options.ScriptCode.Parameters.Count = |
| | | 749 | | { |
| | 30 | 750 | | return; |
| | | 751 | | } |
| | | 752 | | |
| | 0 | 753 | | host.Logger.Verbose("Adding metadata to route: {Pattern}", options.Pattern); |
| | 0 | 754 | | _ = map.WithMetadata(options.ScriptCode.Parameters); |
| | 0 | 755 | | _ = map.WithMetadata(new DefaultResponseContentType(options.DefaultResponseContentType)); |
| | 0 | 756 | | } |
| | | 757 | | /// <summary> |
| | | 758 | | /// Applies short-circuiting behavior to the route. |
| | | 759 | | /// </summary> |
| | | 760 | | /// <param name="host">The Kestrun host.</param> |
| | | 761 | | /// <param name="map">The endpoint convention builder.</param> |
| | | 762 | | /// <param name="options">The mapping options.</param> |
| | | 763 | | private static void ApplyShortCircuit(KestrunHost host, IEndpointConventionBuilder map, MapRouteOptions options) |
| | | 764 | | { |
| | 35 | 765 | | if (!options.ShortCircuit) |
| | | 766 | | { |
| | 35 | 767 | | return; |
| | | 768 | | } |
| | | 769 | | |
| | 0 | 770 | | host.Logger.Verbose("Short-circuiting route: {Pattern} with status code: {StatusCode}", options.Pattern, options |
| | 0 | 771 | | if (options.ShortCircuitStatusCode is null) |
| | | 772 | | { |
| | 0 | 773 | | throw new ArgumentException("ShortCircuitStatusCode must be set if ShortCircuit is true.", nameof(options.Sh |
| | | 774 | | } |
| | | 775 | | |
| | 0 | 776 | | _ = map.ShortCircuit(options.ShortCircuitStatusCode); |
| | 0 | 777 | | } |
| | | 778 | | |
| | | 779 | | /// <summary> |
| | | 780 | | /// Applies anonymous access behavior to the route. |
| | | 781 | | /// </summary> |
| | | 782 | | /// <param name="host">The Kestrun host.</param> |
| | | 783 | | /// <param name="map">The endpoint convention builder.</param> |
| | | 784 | | /// <param name="options">The mapping options.</param> |
| | | 785 | | private static void ApplyAnonymous(KestrunHost host, IEndpointConventionBuilder map, MapRouteOptions options) |
| | | 786 | | { |
| | 35 | 787 | | if (options.AllowAnonymous) |
| | | 788 | | { |
| | 0 | 789 | | host.Logger.Verbose("Allowing anonymous access for route: {Pattern}", options.Pattern); |
| | 0 | 790 | | _ = map.AllowAnonymous(); |
| | | 791 | | } |
| | | 792 | | else |
| | | 793 | | { |
| | 35 | 794 | | host.Logger.Debug("No anonymous access allowed for route: {Pattern}", options.Pattern); |
| | | 795 | | } |
| | 35 | 796 | | } |
| | | 797 | | |
| | | 798 | | /// <summary> |
| | | 799 | | /// Disables anti-forgery behavior to the route. |
| | | 800 | | /// </summary> |
| | | 801 | | /// <param name="host">The Kestrun host.</param> |
| | | 802 | | /// <param name="map">The endpoint convention builder.</param> |
| | | 803 | | /// <param name="options">The mapping options.</param> |
| | | 804 | | private static void DisableAntiforgery(KestrunHost host, IEndpointConventionBuilder map, MapRouteOptions options) |
| | | 805 | | { |
| | 35 | 806 | | if (!options.DisableAntiforgery) |
| | | 807 | | { |
| | 35 | 808 | | return; |
| | | 809 | | } |
| | | 810 | | |
| | 0 | 811 | | _ = map.DisableAntiforgery(); |
| | 0 | 812 | | host.Logger.Verbose("CSRF protection disabled for route: {Pattern}", options.Pattern); |
| | 0 | 813 | | } |
| | | 814 | | |
| | | 815 | | /// <summary> |
| | | 816 | | /// Disables response compression for the route. |
| | | 817 | | /// </summary> |
| | | 818 | | /// <param name="host">The Kestrun host.</param> |
| | | 819 | | /// <param name="map">The endpoint convention builder.</param> |
| | | 820 | | /// <param name="options">The mapping options.</param> |
| | | 821 | | private static void DisableResponseCompression(KestrunHost host, IEndpointConventionBuilder map, MapRouteOptions opt |
| | | 822 | | { |
| | 35 | 823 | | if (!options.DisableResponseCompression) |
| | | 824 | | { |
| | 34 | 825 | | return; |
| | | 826 | | } |
| | | 827 | | |
| | 1 | 828 | | _ = map.DisableResponseCompression(); |
| | 1 | 829 | | host.Logger.Verbose("Response compression disabled for route: {Pattern}", options.Pattern); |
| | 1 | 830 | | } |
| | | 831 | | /// <summary> |
| | | 832 | | /// Applies rate limiting behavior to the route. |
| | | 833 | | /// </summary> |
| | | 834 | | /// <param name="host">The Kestrun host.</param> |
| | | 835 | | /// <param name="map">The endpoint convention builder.</param> |
| | | 836 | | /// <param name="options">The mapping options.</param> |
| | | 837 | | private static void ApplyRateLimiting(KestrunHost host, IEndpointConventionBuilder map, MapRouteOptions options) |
| | | 838 | | { |
| | 35 | 839 | | if (string.IsNullOrWhiteSpace(options.RateLimitPolicyName)) |
| | | 840 | | { |
| | 35 | 841 | | return; |
| | | 842 | | } |
| | | 843 | | |
| | 0 | 844 | | host.Logger.Verbose("Applying rate limit policy: {RateLimitPolicyName} to route: {Pattern}", options.RateLimitPo |
| | 0 | 845 | | _ = map.RequireRateLimiting(options.RateLimitPolicyName); |
| | 0 | 846 | | } |
| | | 847 | | |
| | | 848 | | /// <summary> |
| | | 849 | | /// Applies authentication schemes to the route. |
| | | 850 | | /// </summary> |
| | | 851 | | /// <param name="host">The Kestrun host.</param> |
| | | 852 | | /// <param name="map">The endpoint convention builder.</param> |
| | | 853 | | /// <param name="options">The mapping options.</param> |
| | | 854 | | private static void ApplyAuthSchemes(KestrunHost host, IEndpointConventionBuilder map, MapRouteOptions options) |
| | | 855 | | { |
| | 35 | 856 | | if (options.RequireSchemes is not null && options.RequireSchemes.Count != 0) |
| | | 857 | | { |
| | 7 | 858 | | foreach (var schema in options.RequireSchemes) |
| | | 859 | | { |
| | 2 | 860 | | if (!host.HasAuthScheme(schema)) |
| | | 861 | | { |
| | 1 | 862 | | throw new ArgumentException($"Authentication scheme '{schema}' is not registered.", nameof(options.R |
| | | 863 | | } |
| | | 864 | | } |
| | 1 | 865 | | host.Logger.Verbose("Requiring authorization for route: {Pattern} with policies: {Policies}", options.Patter |
| | 1 | 866 | | _ = map.RequireAuthorization(new AuthorizeAttribute |
| | 1 | 867 | | { |
| | 1 | 868 | | AuthenticationSchemes = string.Join(',', options.RequireSchemes) |
| | 1 | 869 | | }); |
| | | 870 | | } |
| | | 871 | | else |
| | | 872 | | { |
| | 33 | 873 | | host.Logger.Debug("No authorization required for route: {Pattern}", options.Pattern); |
| | | 874 | | } |
| | 33 | 875 | | } |
| | | 876 | | |
| | | 877 | | /// <summary> |
| | | 878 | | /// Applies authorization policies to the route. |
| | | 879 | | /// </summary> |
| | | 880 | | /// <param name="host">The Kestrun host.</param> |
| | | 881 | | /// <param name="map">The endpoint convention builder.</param> |
| | | 882 | | /// <param name="options">The mapping options.</param> |
| | | 883 | | private static void ApplyPolicies(KestrunHost host, IEndpointConventionBuilder map, MapRouteOptions options) |
| | | 884 | | { |
| | 34 | 885 | | if (options.RequirePolicies is not null && options.RequirePolicies.Count != 0) |
| | | 886 | | { |
| | 7 | 887 | | foreach (var policy in options.RequirePolicies) |
| | | 888 | | { |
| | 2 | 889 | | if (!host.HasAuthPolicy(policy)) |
| | | 890 | | { |
| | 1 | 891 | | throw new ArgumentException($"Authorization policy '{policy}' is not registered.", nameof(options.Re |
| | | 892 | | } |
| | | 893 | | } |
| | 1 | 894 | | _ = map.RequireAuthorization(options.RequirePolicies.ToArray()); |
| | | 895 | | } |
| | | 896 | | else |
| | | 897 | | { |
| | 32 | 898 | | host.Logger.Debug("No authorization policies required for route: {Pattern}", options.Pattern); |
| | | 899 | | } |
| | 32 | 900 | | } |
| | | 901 | | /// <summary> |
| | | 902 | | /// Applies CORS behavior to the route. |
| | | 903 | | /// </summary> |
| | | 904 | | /// <param name="host">The Kestrun host.</param> |
| | | 905 | | /// <param name="map">The endpoint convention builder.</param> |
| | | 906 | | /// <param name="options">The mapping options.</param> |
| | | 907 | | private static void ApplyCors(KestrunHost host, IEndpointConventionBuilder map, MapRouteOptions options) |
| | | 908 | | { |
| | 33 | 909 | | if (!string.IsNullOrWhiteSpace(options.CorsPolicy)) |
| | | 910 | | { |
| | 0 | 911 | | if (!host.DefinedCorsPolicyNames.Contains(options.CorsPolicy)) |
| | | 912 | | { |
| | 0 | 913 | | throw new ArgumentException($"CORS policy '{options.CorsPolicy}' is not registered."); |
| | | 914 | | } |
| | 0 | 915 | | host.Logger.Verbose("Applying CORS policy: {CorsPolicy} to route: {Pattern}", options.CorsPolicy, options.Pa |
| | 0 | 916 | | _ = map.RequireCors(options.CorsPolicy); |
| | 0 | 917 | | return; |
| | | 918 | | } |
| | | 919 | | // No per-route policy requested. |
| | 33 | 920 | | if (host.CorsPolicyDefined) |
| | | 921 | | { |
| | 0 | 922 | | host.Logger.Verbose("No per-route CORS policy set for route: {Pattern}; default CORS policy will apply.", op |
| | | 923 | | } |
| | | 924 | | else |
| | | 925 | | { |
| | 33 | 926 | | host.Logger.Debug("No CORS policy configured for route: {Pattern}", options.Pattern); |
| | | 927 | | } |
| | 33 | 928 | | } |
| | | 929 | | |
| | | 930 | | /// <summary> |
| | | 931 | | /// Applies OpenAPI metadata to the route. |
| | | 932 | | /// </summary> |
| | | 933 | | /// <param name="host">The Kestrun host.</param> |
| | | 934 | | /// <param name="map">The endpoint convention builder.</param> |
| | | 935 | | /// <param name="openAPI">The OpenAPI metadata.</param> |
| | | 936 | | private static void ApplyOpenApiMetadata(KestrunHost host, IEndpointConventionBuilder map, OpenAPIMetadata openAPI) |
| | | 937 | | { |
| | 0 | 938 | | if (!string.IsNullOrEmpty(openAPI.OperationId)) |
| | | 939 | | { |
| | 0 | 940 | | host.Logger.Verbose("Adding OpenAPI metadata for route: {Pattern} with OperationId: {OperationId}", openAPI. |
| | 0 | 941 | | _ = map.WithName(openAPI.OperationId); |
| | | 942 | | } |
| | | 943 | | |
| | 0 | 944 | | if (!string.IsNullOrWhiteSpace(openAPI.Summary)) |
| | | 945 | | { |
| | 0 | 946 | | host.Logger.Verbose("Adding OpenAPI summary for route: {Pattern} with Summary: {Summary}", openAPI.Pattern, |
| | 0 | 947 | | _ = map.WithSummary(openAPI.Summary); |
| | | 948 | | } |
| | | 949 | | |
| | 0 | 950 | | if (!string.IsNullOrWhiteSpace(openAPI.Description)) |
| | | 951 | | { |
| | 0 | 952 | | host.Logger.Verbose("Adding OpenAPI description for route: {Pattern} with Description: {Description}", openA |
| | 0 | 953 | | _ = map.WithDescription(openAPI.Description); |
| | | 954 | | } |
| | | 955 | | |
| | 0 | 956 | | if (openAPI.Tags.Count > 0) |
| | | 957 | | { |
| | 0 | 958 | | host.Logger.Verbose("Adding OpenAPI tags for route: {Pattern} with Tags: {Tags}", openAPI.Pattern, string.Jo |
| | 0 | 959 | | _ = map.WithTags([.. openAPI.Tags]); |
| | | 960 | | } |
| | 0 | 961 | | } |
| | | 962 | | |
| | | 963 | | /// <summary> |
| | | 964 | | /// Adds an HTML template route to the KestrunHost for the specified pattern and HTML file path. |
| | | 965 | | /// </summary> |
| | | 966 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 967 | | /// <param name="pattern">The route pattern.</param> |
| | | 968 | | /// <param name="htmlFilePath">The path to the HTML template file.</param> |
| | | 969 | | /// <param name="requireSchemes">Optional array of authorization schemes required for the route.</param> |
| | | 970 | | /// <returns>An IEndpointConventionBuilder for further configuration.</returns> |
| | | 971 | | public static IEndpointConventionBuilder AddHtmlTemplateRoute(this KestrunHost host, string pattern, string htmlFile |
| | | 972 | | { |
| | 0 | 973 | | return host.AddHtmlTemplateRoute(new MapRouteOptions |
| | 0 | 974 | | { |
| | 0 | 975 | | Pattern = pattern, |
| | 0 | 976 | | HttpVerbs = [HttpVerb.Get], |
| | 0 | 977 | | RequireSchemes = requireSchemes ?? [] // No authorization by default |
| | 0 | 978 | | }, htmlFilePath); |
| | | 979 | | } |
| | | 980 | | |
| | | 981 | | /// <summary> |
| | | 982 | | /// Adds an HTML template route to the KestrunHost using the specified MapRouteOptions and HTML file path. |
| | | 983 | | /// </summary> |
| | | 984 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 985 | | /// <param name="options">The MapRouteOptions containing route configuration.</param> |
| | | 986 | | /// <param name="htmlFilePath">The path to the HTML template file.</param> |
| | | 987 | | /// <returns>An IEndpointConventionBuilder for further configuration.</returns> |
| | | 988 | | public static IEndpointConventionBuilder AddHtmlTemplateRoute(this KestrunHost host, MapRouteOptions options, string |
| | | 989 | | { |
| | 3 | 990 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 991 | | { |
| | 2 | 992 | | host.Logger.Debug("Adding HTML template route: {Pattern}", options.Pattern); |
| | | 993 | | } |
| | | 994 | | |
| | 3 | 995 | | if (options.HttpVerbs.Count != 0 && |
| | 3 | 996 | | (options.HttpVerbs.Count > 1 || options.HttpVerbs.First() != HttpVerb.Get)) |
| | | 997 | | { |
| | 1 | 998 | | host.Logger.Error("HTML template routes only support GET requests. Provided HTTP verbs: {HttpVerbs}", string |
| | 1 | 999 | | throw new ArgumentException("HTML template routes only support GET requests.", nameof(options.HttpVerbs)); |
| | | 1000 | | } |
| | 2 | 1001 | | if (string.IsNullOrWhiteSpace(htmlFilePath) || !File.Exists(htmlFilePath)) |
| | | 1002 | | { |
| | 1 | 1003 | | host.Logger.Error("HTML file path is null, empty, or does not exist: {HtmlFilePath}", htmlFilePath); |
| | 1 | 1004 | | throw new FileNotFoundException("HTML file not found.", htmlFilePath); |
| | | 1005 | | } |
| | | 1006 | | |
| | 1 | 1007 | | if (string.IsNullOrWhiteSpace(options.Pattern)) |
| | | 1008 | | { |
| | 0 | 1009 | | host.Logger.Error("Pattern cannot be null or empty."); |
| | 0 | 1010 | | throw new ArgumentException("Pattern cannot be null or empty.", nameof(options.Pattern)); |
| | | 1011 | | } |
| | | 1012 | | |
| | 1 | 1013 | | _ = host.AddMapRoute(options.Pattern, HttpVerb.Get, async (ctx) => |
| | 1 | 1014 | | { |
| | 1 | 1015 | | // ② Build your variables map |
| | 0 | 1016 | | var vars = new Dictionary<string, object?>(); |
| | 0 | 1017 | | _ = VariablesMap.GetVariablesMap(ctx, ref vars); |
| | 1 | 1018 | | |
| | 0 | 1019 | | await ctx.Response.WriteHtmlResponseFromFileAsync(htmlFilePath, vars, ctx.Response.StatusCode); |
| | 1 | 1020 | | }, out var map); |
| | 1 | 1021 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1022 | | { |
| | 1 | 1023 | | host.Logger.Debug("Mapped HTML template route: {Pattern} to file: {HtmlFilePath}", options.Pattern, htmlFile |
| | | 1024 | | } |
| | 1 | 1025 | | if (map is null) |
| | | 1026 | | { |
| | 0 | 1027 | | throw new InvalidOperationException("Failed to create HTML template route."); |
| | | 1028 | | } |
| | 1 | 1029 | | AddMapOptions(host, map, options); |
| | 1 | 1030 | | return map; |
| | | 1031 | | } |
| | | 1032 | | |
| | | 1033 | | /// <summary> |
| | | 1034 | | /// Adds a Swagger UI route to the KestrunHost for the specified pattern and OpenAPI endpoint. |
| | | 1035 | | /// </summary> |
| | | 1036 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 1037 | | /// <param name="options">The MapRouteOptions containing route configuration.</param> |
| | | 1038 | | /// <param name="openApiEndpoint">The URI of the OpenAPI endpoint.</param> |
| | | 1039 | | /// <returns>An IEndpointConventionBuilder for further configuration.</returns> |
| | | 1040 | | /// <exception cref="ArgumentException">Thrown when the provided options are invalid.</exception> |
| | | 1041 | | /// <exception cref="InvalidOperationException">Thrown when the Swagger UI route cannot be created.</exception> |
| | | 1042 | | public static IEndpointConventionBuilder AddSwaggerUiRoute( |
| | | 1043 | | this KestrunHost host, |
| | | 1044 | | MapRouteOptions options, |
| | | 1045 | | Uri openApiEndpoint) |
| | | 1046 | | { |
| | 0 | 1047 | | return AddOpenApiUiRoute( |
| | 0 | 1048 | | host, |
| | 0 | 1049 | | options, |
| | 0 | 1050 | | openApiEndpoint, |
| | 0 | 1051 | | uiName: "Swagger", |
| | 0 | 1052 | | defaultPattern: "/docs/swagger", |
| | 0 | 1053 | | resourceName: "Kestrun.Assets.swagger-ui.html"); |
| | | 1054 | | } |
| | | 1055 | | |
| | | 1056 | | /// <summary> |
| | | 1057 | | /// Adds a Redoc UI route to the KestrunHost for the specified pattern and OpenAPI endpoint. |
| | | 1058 | | /// </summary> |
| | | 1059 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 1060 | | /// <param name="options">The route mapping options.</param> |
| | | 1061 | | /// <param name="openApiEndpoint">The OpenAPI endpoint URI.</param> |
| | | 1062 | | /// <returns>An IEndpointConventionBuilder for the mapped route.</returns> |
| | | 1063 | | /// <exception cref="ArgumentException">Thrown when the provided options are invalid.</exception> |
| | | 1064 | | /// <exception cref="InvalidOperationException">Thrown when the Redoc UI route cannot be created.</exception> |
| | | 1065 | | public static IEndpointConventionBuilder AddRedocUiRoute( |
| | | 1066 | | this KestrunHost host, |
| | | 1067 | | MapRouteOptions options, |
| | | 1068 | | Uri openApiEndpoint) |
| | | 1069 | | { |
| | 0 | 1070 | | return AddOpenApiUiRoute( |
| | 0 | 1071 | | host, |
| | 0 | 1072 | | options, |
| | 0 | 1073 | | openApiEndpoint, |
| | 0 | 1074 | | uiName: "Redoc", |
| | 0 | 1075 | | defaultPattern: "/docs/redoc", |
| | 0 | 1076 | | resourceName: "Kestrun.Assets.redoc-ui.html"); |
| | | 1077 | | } |
| | | 1078 | | |
| | | 1079 | | /// <summary> |
| | | 1080 | | /// Adds a Scalar UI route to the KestrunHost for the specified pattern and OpenAPI endpoint. |
| | | 1081 | | /// </summary> |
| | | 1082 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 1083 | | /// <param name="options">The route mapping options.</param> |
| | | 1084 | | /// <param name="openApiEndpoint">The OpenAPI endpoint URI.</param> |
| | | 1085 | | /// <returns>An IEndpointConventionBuilder for the mapped route.</returns> |
| | | 1086 | | /// <exception cref="ArgumentException">Thrown when the provided options are invalid.</exception> |
| | | 1087 | | /// <exception cref="InvalidOperationException">Thrown when the Scalar UI route cannot be created.</exception> |
| | | 1088 | | public static IEndpointConventionBuilder AddScalarUiRoute( |
| | | 1089 | | this KestrunHost host, |
| | | 1090 | | MapRouteOptions options, |
| | | 1091 | | Uri openApiEndpoint) |
| | | 1092 | | { |
| | 0 | 1093 | | return AddOpenApiUiRoute( |
| | 0 | 1094 | | host, |
| | 0 | 1095 | | options, |
| | 0 | 1096 | | openApiEndpoint, |
| | 0 | 1097 | | uiName: "Scalar", |
| | 0 | 1098 | | defaultPattern: "/docs/scalar", |
| | 0 | 1099 | | resourceName: "Kestrun.Assets.scalar.html"); |
| | | 1100 | | } |
| | | 1101 | | |
| | | 1102 | | /// <summary> |
| | | 1103 | | /// Adds a RapiDoc UI route to the KestrunHost for the specified pattern and OpenAPI endpoint. |
| | | 1104 | | /// </summary> |
| | | 1105 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 1106 | | /// <param name="options">The route mapping options.</param> |
| | | 1107 | | /// <param name="openApiEndpoint">The OpenAPI endpoint URI.</param> |
| | | 1108 | | /// <returns>An IEndpointConventionBuilder for the mapped route.</returns> |
| | | 1109 | | public static IEndpointConventionBuilder AddRapiDocUiRoute( |
| | | 1110 | | this KestrunHost host, |
| | | 1111 | | MapRouteOptions options, |
| | | 1112 | | Uri openApiEndpoint) |
| | | 1113 | | { |
| | 0 | 1114 | | return AddOpenApiUiRoute( |
| | 0 | 1115 | | host, |
| | 0 | 1116 | | options, |
| | 0 | 1117 | | openApiEndpoint, |
| | 0 | 1118 | | uiName: "RapiDoc", |
| | 0 | 1119 | | defaultPattern: "/docs/rapidoc", |
| | 0 | 1120 | | resourceName: "Kestrun.Assets.rapidoc.html"); |
| | | 1121 | | } |
| | | 1122 | | |
| | | 1123 | | /// <summary> |
| | | 1124 | | /// Adds an Elements UI route to the KestrunHost for the specified pattern and OpenAPI endpoint. |
| | | 1125 | | /// </summary> |
| | | 1126 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 1127 | | /// <param name="options">The route mapping options.</param> |
| | | 1128 | | /// <param name="openApiEndpoint">The OpenAPI endpoint URI.</param> |
| | | 1129 | | /// <returns>An IEndpointConventionBuilder for the mapped route.</returns> |
| | | 1130 | | public static IEndpointConventionBuilder AddElementsUiRoute( |
| | | 1131 | | this KestrunHost host, |
| | | 1132 | | MapRouteOptions options, |
| | | 1133 | | Uri openApiEndpoint) |
| | | 1134 | | { |
| | 0 | 1135 | | return AddOpenApiUiRoute( |
| | 0 | 1136 | | host, |
| | 0 | 1137 | | options, |
| | 0 | 1138 | | openApiEndpoint, |
| | 0 | 1139 | | uiName: "Elements", |
| | 0 | 1140 | | defaultPattern: "/docs/elements", |
| | 0 | 1141 | | resourceName: "Kestrun.Assets.elements.html"); |
| | | 1142 | | } |
| | | 1143 | | |
| | | 1144 | | /// <summary> |
| | | 1145 | | /// Adds an OpenAPI UI route to the KestrunHost for the specified pattern and OpenAPI endpoint. |
| | | 1146 | | /// </summary> |
| | | 1147 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 1148 | | /// <param name="options">The route mapping options.</param> |
| | | 1149 | | /// <param name="openApiEndpoint">The OpenAPI endpoint URI.</param> |
| | | 1150 | | /// <param name="uiName">The name of the UI.</param> |
| | | 1151 | | /// <param name="defaultPattern">The default route pattern.</param> |
| | | 1152 | | /// <param name="resourceName">The embedded resource name.</param> |
| | | 1153 | | /// <returns>The endpoint convention builder for the mapped route.</returns> |
| | | 1154 | | /// <exception cref="ArgumentException">Thrown when the provided options are invalid.</exception> |
| | | 1155 | | /// <exception cref="InvalidOperationException">Thrown when the OpenAPI UI route cannot be created.</exception> |
| | | 1156 | | private static IEndpointConventionBuilder AddOpenApiUiRoute( |
| | | 1157 | | KestrunHost host, |
| | | 1158 | | MapRouteOptions options, |
| | | 1159 | | Uri openApiEndpoint, |
| | | 1160 | | string uiName, |
| | | 1161 | | string defaultPattern, |
| | | 1162 | | string resourceName) |
| | | 1163 | | { |
| | 0 | 1164 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1165 | | { |
| | 0 | 1166 | | host.Logger.Debug( |
| | 0 | 1167 | | "Adding {UiName} UI route: {Pattern} for OpenAPI endpoint: {OpenApiEndpoint}", |
| | 0 | 1168 | | uiName, |
| | 0 | 1169 | | options.Pattern, |
| | 0 | 1170 | | openApiEndpoint); |
| | | 1171 | | } |
| | | 1172 | | |
| | 0 | 1173 | | if (options.HttpVerbs.Count != 0 && |
| | 0 | 1174 | | (options.HttpVerbs.Count > 1 || options.HttpVerbs.First() != HttpVerb.Get)) |
| | | 1175 | | { |
| | 0 | 1176 | | host.Logger.Error( |
| | 0 | 1177 | | "{UiName} UI routes only support GET requests. Provided HTTP verbs: {HttpVerbs}", |
| | 0 | 1178 | | uiName, |
| | 0 | 1179 | | string.Join(", ", options.HttpVerbs)); |
| | | 1180 | | |
| | 0 | 1181 | | throw new ArgumentException( |
| | 0 | 1182 | | $"{uiName} UI routes only support GET requests.", |
| | 0 | 1183 | | nameof(options.HttpVerbs)); |
| | | 1184 | | } |
| | | 1185 | | |
| | | 1186 | | // Set default pattern if not provided |
| | 0 | 1187 | | if (string.IsNullOrWhiteSpace(options.Pattern)) |
| | | 1188 | | { |
| | 0 | 1189 | | options.Pattern = defaultPattern; |
| | | 1190 | | } |
| | | 1191 | | |
| | | 1192 | | // Load embedded UI HTML |
| | 0 | 1193 | | var map = AddHtmlRouteFromEmbeddedResource(host, options.Pattern, openApiEndpoint, resourceName); |
| | | 1194 | | |
| | 0 | 1195 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 1196 | | { |
| | 0 | 1197 | | host.Logger.Debug( |
| | 0 | 1198 | | "Mapped {UiName} UI route: {Pattern} for OpenAPI endpoint: {OpenApiEndpoint}", |
| | 0 | 1199 | | uiName, |
| | 0 | 1200 | | options.Pattern, |
| | 0 | 1201 | | openApiEndpoint); |
| | | 1202 | | } |
| | | 1203 | | |
| | 0 | 1204 | | if (map is null) |
| | | 1205 | | { |
| | 0 | 1206 | | throw new InvalidOperationException($"Failed to create {uiName} UI route."); |
| | | 1207 | | } |
| | | 1208 | | |
| | 0 | 1209 | | AddMapOptions(host, map, options); |
| | 0 | 1210 | | return map; |
| | | 1211 | | } |
| | | 1212 | | |
| | | 1213 | | /// <summary> |
| | | 1214 | | /// Add a HTML route from an embedded resource. |
| | | 1215 | | /// </summary> |
| | | 1216 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 1217 | | /// <param name="pattern">The route pattern.</param> |
| | | 1218 | | /// <param name="openApiEndpoint">The OpenAPI endpoint URI.</param> |
| | | 1219 | | /// <param name="embeddedResource">The embedded resource name.</param> |
| | | 1220 | | /// <exception cref="InvalidOperationException"></exception> |
| | | 1221 | | private static IEndpointConventionBuilder? AddHtmlRouteFromEmbeddedResource(KestrunHost host, string pattern, Uri op |
| | | 1222 | | { |
| | 0 | 1223 | | _ = host.AddMapRoute(pattern: pattern, httpVerb: HttpVerb.Get, async (ctx) => |
| | 0 | 1224 | | { |
| | 0 | 1225 | | var asm = typeof(KestrunHostMapExtensions).Assembly; |
| | 0 | 1226 | | using var stream = asm.GetManifestResourceStream(embeddedResource) |
| | 0 | 1227 | | ?? throw new InvalidOperationException($"Embedded HTML resource not found: {embeddedResource}"); |
| | 0 | 1228 | | |
| | 0 | 1229 | | using var ms = new MemoryStream(); |
| | 0 | 1230 | | stream.CopyTo(ms); |
| | 0 | 1231 | | var htmlBuffer = ms.ToArray(); |
| | 0 | 1232 | | ctx.Response.ContentType = "text/html; charset=utf-8"; |
| | 0 | 1233 | | await ctx.Response.WriteHtmlResponseAsync(htmlBuffer, new Dictionary<string, object?> |
| | 0 | 1234 | | { |
| | 0 | 1235 | | { "OPENAPI_ENDPOINT", openApiEndpoint.ToString() } |
| | 0 | 1236 | | }, ctx.Response.StatusCode); |
| | 0 | 1237 | | }, out var map); |
| | 0 | 1238 | | return map; |
| | | 1239 | | } |
| | | 1240 | | |
| | | 1241 | | /// <summary> |
| | | 1242 | | /// Checks if a route with the specified pattern and optional HTTP method exists in the KestrunHost. |
| | | 1243 | | /// </summary> |
| | | 1244 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 1245 | | /// <param name="pattern">The route pattern to check.</param> |
| | | 1246 | | /// <param name="verbs">The optional HTTP method to check for the route.</param> |
| | | 1247 | | /// <returns>True if the route exists; otherwise, false.</returns> |
| | | 1248 | | public static bool MapExists(this KestrunHost host, string pattern, IEnumerable<HttpVerb> verbs) |
| | | 1249 | | { |
| | 80 | 1250 | | var methodSet = verbs.Select(v => v.ToMethodString()).ToHashSet(StringComparer.OrdinalIgnoreCase); |
| | 39 | 1251 | | return host._registeredRoutes.Keys |
| | 11 | 1252 | | .Where(k => string.Equals(k.Pattern, pattern, StringComparison.OrdinalIgnoreCase)) |
| | 48 | 1253 | | .Any(k => methodSet.Contains(k.Method.ToMethodString())); |
| | | 1254 | | } |
| | | 1255 | | |
| | | 1256 | | /// <summary> |
| | | 1257 | | /// Checks if a route with the specified pattern and optional HTTP method exists in the KestrunHost. |
| | | 1258 | | /// </summary> |
| | | 1259 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 1260 | | /// <param name="pattern">The route pattern to check.</param> |
| | | 1261 | | /// <param name="verb">The optional HTTP method to check for the route.</param> |
| | | 1262 | | /// <returns>True if the route exists; otherwise, false.</returns> |
| | | 1263 | | public static bool MapExists(this KestrunHost host, string pattern, HttpVerb verb) => |
| | 9 | 1264 | | host._registeredRoutes.ContainsKey((pattern, verb)); |
| | | 1265 | | |
| | | 1266 | | /// <summary> |
| | | 1267 | | /// Retrieves the <see cref="MapRouteOptions"/> associated with a given route pattern and HTTP verb, if registered. |
| | | 1268 | | /// </summary> |
| | | 1269 | | /// <param name="host">The <see cref="KestrunHost"/> instance to search for registered routes.</param> |
| | | 1270 | | /// <param name="pattern">The route pattern to look up (e.g. <c>"/hello"</c>).</param> |
| | | 1271 | | /// <param name="verb">The HTTP verb to match (e.g. <see cref="HttpVerb.Get"/>).</param> |
| | | 1272 | | /// <returns> |
| | | 1273 | | /// The <see cref="MapRouteOptions"/> instance for the specified route if found; otherwise, <c>null</c>. |
| | | 1274 | | /// </returns> |
| | | 1275 | | /// <remarks> |
| | | 1276 | | /// This method checks the internal route registry and returns the route options if the pattern and verb |
| | | 1277 | | /// combination was previously added via <c>AddMapRoute</c>. |
| | | 1278 | | /// This lookup is case-insensitive for both the pattern and method. |
| | | 1279 | | /// </remarks> |
| | | 1280 | | /// <example> |
| | | 1281 | | /// <code> |
| | | 1282 | | /// var options = host.GetMapRouteOptions("/hello", HttpVerb.Get); |
| | | 1283 | | /// if (options != null) |
| | | 1284 | | /// { |
| | | 1285 | | /// Console.WriteLine($"Route language: {options.Language}"); |
| | | 1286 | | /// } |
| | | 1287 | | /// </code> |
| | | 1288 | | /// </example> |
| | | 1289 | | public static MapRouteOptions? GetMapRouteOptions(this KestrunHost host, string pattern, HttpVerb verb) |
| | | 1290 | | { |
| | 4 | 1291 | | return host._registeredRoutes.TryGetValue((pattern, verb), out var options) |
| | 4 | 1292 | | ? options |
| | 4 | 1293 | | : null; |
| | | 1294 | | } |
| | | 1295 | | |
| | | 1296 | | /// <summary> |
| | | 1297 | | /// Adds a GET endpoint that issues the antiforgery cookie and returns a JSON payload: |
| | | 1298 | | /// { token: "...", headerName: "X-CSRF-TOKEN" }. |
| | | 1299 | | /// The endpoint itself is exempt from antiforgery validation. |
| | | 1300 | | /// </summary> |
| | | 1301 | | /// <param name="host">The KestrunHost instance.</param> |
| | | 1302 | | /// <param name="pattern">The route path to expose (default "/csrf-token").</param> |
| | | 1303 | | /// <returns>IEndpointConventionBuilder for further configuration.</returns> |
| | | 1304 | | public static IEndpointConventionBuilder AddAntiforgeryTokenRoute( |
| | | 1305 | | this KestrunHost host, |
| | | 1306 | | string pattern = "/csrf-token") |
| | | 1307 | | { |
| | 0 | 1308 | | ArgumentException.ThrowIfNullOrWhiteSpace(pattern); |
| | 0 | 1309 | | if (host.App is null) |
| | | 1310 | | { |
| | 0 | 1311 | | throw new InvalidOperationException("WebApplication is not initialized. Call EnableConfiguration first."); |
| | | 1312 | | } |
| | 0 | 1313 | | var options = new MapRouteOptions |
| | 0 | 1314 | | { |
| | 0 | 1315 | | Pattern = pattern, |
| | 0 | 1316 | | HttpVerbs = [HttpVerb.Get], |
| | 0 | 1317 | | ScriptCode = new LanguageOptions |
| | 0 | 1318 | | { |
| | 0 | 1319 | | Language = ScriptLanguage.Native |
| | 0 | 1320 | | }, |
| | 0 | 1321 | | DisableAntiforgery = true, |
| | 0 | 1322 | | AllowAnonymous = true, |
| | 0 | 1323 | | }; |
| | | 1324 | | |
| | | 1325 | | // OpenAPI = new() { Summary = "Get CSRF token", Description = "Returns antiforgery request token and header nam |
| | | 1326 | | |
| | | 1327 | | // Map directly and write directly (no KestrunResponse.ApplyTo) |
| | 0 | 1328 | | var map = host.App.MapMethods(options.Pattern, [HttpMethods.Get], async context => |
| | 0 | 1329 | | { |
| | 0 | 1330 | | var af = context.RequestServices.GetRequiredService<IAntiforgery>(); |
| | 0 | 1331 | | var opts = context.RequestServices.GetRequiredService<IOptions<AntiforgeryOptions>>(); |
| | 0 | 1332 | | |
| | 0 | 1333 | | var tokens = af.GetAndStoreTokens(context); |
| | 0 | 1334 | | |
| | 0 | 1335 | | // Strongly discourage caches (proxies/browsers) from storing this payload |
| | 0 | 1336 | | context.Response.Headers.CacheControl = "no-store, no-cache, must-revalidate"; |
| | 0 | 1337 | | context.Response.Headers.Pragma = "no-cache"; |
| | 0 | 1338 | | context.Response.Headers.Expires = "0"; |
| | 0 | 1339 | | |
| | 0 | 1340 | | context.Response.ContentType = "application/json"; |
| | 0 | 1341 | | await context.Response.WriteAsJsonAsync(new |
| | 0 | 1342 | | { |
| | 0 | 1343 | | token = tokens.RequestToken, |
| | 0 | 1344 | | headerName = opts.Value.HeaderName // may be null if not configured |
| | 0 | 1345 | | }); |
| | 0 | 1346 | | }); |
| | | 1347 | | |
| | | 1348 | | // Apply your pipeline metadata (this adds DisableAntiforgery, CORS, rate limiting, OpenAPI, etc.) |
| | 0 | 1349 | | host.AddMapOptions(map, options); |
| | | 1350 | | |
| | | 1351 | | // (Optional) track in your registry for consistency / duplicate checks |
| | 0 | 1352 | | host._registeredRoutes[(options.Pattern, HttpVerb.Get)] = options; |
| | | 1353 | | |
| | 0 | 1354 | | host.Logger.Information("Added token endpoint: {Pattern} (GET)", options.Pattern); |
| | 0 | 1355 | | return map; |
| | | 1356 | | } |
| | | 1357 | | |
| | | 1358 | | private static bool IsUnsafeVerb(HttpVerb v) |
| | 4 | 1359 | | => v is HttpVerb.Post or HttpVerb.Put or HttpVerb.Patch or HttpVerb.Delete; |
| | | 1360 | | |
| | | 1361 | | private static bool IsUnsafeMethod(string method) |
| | 19 | 1362 | | => HttpMethods.IsPost(method) || HttpMethods.IsPut(method) || HttpMethods.IsPatch(method) || HttpMethods.IsDelet |
| | | 1363 | | |
| | | 1364 | | // New precise helper: only validate for the actual incoming request method when that method is unsafe and antiforge |
| | | 1365 | | private static bool ShouldValidateCsrf(MapRouteOptions o, HttpContext ctx) |
| | | 1366 | | { |
| | 20 | 1367 | | if (o.DisableAntiforgery) |
| | | 1368 | | { |
| | 1 | 1369 | | return false; |
| | | 1370 | | } |
| | 19 | 1371 | | if (!IsUnsafeMethod(ctx.Request.Method)) |
| | | 1372 | | { |
| | 14 | 1373 | | return false; // Safe verb (GET/HEAD/OPTIONS) -> skip |
| | | 1374 | | } |
| | | 1375 | | // Ensure the route was actually configured for this unsafe verb (defensive; normally true inside mapped delegat |
| | 17 | 1376 | | return o.HttpVerbs.Any(v => string.Equals(v.ToMethodString(), ctx.Request.Method, StringComparison.OrdinalIgnore |
| | | 1377 | | } |
| | | 1378 | | |
| | | 1379 | | private static async Task<bool> TryValidateAntiforgeryAsync(HttpContext ctx) |
| | | 1380 | | { |
| | 0 | 1381 | | var af = ctx.RequestServices.GetService<IAntiforgery>(); |
| | 0 | 1382 | | if (af is null) |
| | | 1383 | | { |
| | 0 | 1384 | | return true; // antiforgery not configured → do nothing |
| | | 1385 | | } |
| | | 1386 | | |
| | | 1387 | | try |
| | | 1388 | | { |
| | 0 | 1389 | | await af.ValidateRequestAsync(ctx); |
| | 0 | 1390 | | return true; |
| | | 1391 | | } |
| | 0 | 1392 | | catch (AntiforgeryValidationException ex) |
| | | 1393 | | { |
| | | 1394 | | // short-circuit with RFC 9110 problem+json |
| | 0 | 1395 | | ctx.Response.StatusCode = StatusCodes.Status400BadRequest; |
| | 0 | 1396 | | ctx.Response.ContentType = "application/problem+json"; |
| | 0 | 1397 | | await ctx.Response.WriteAsJsonAsync(new |
| | 0 | 1398 | | { |
| | 0 | 1399 | | type = "https://datatracker.ietf.org/doc/html/rfc9110#section-15.5.1", |
| | 0 | 1400 | | title = "Antiforgery validation failed", |
| | 0 | 1401 | | status = 400, |
| | 0 | 1402 | | detail = ex.Message |
| | 0 | 1403 | | }); |
| | 0 | 1404 | | return false; |
| | | 1405 | | } |
| | 0 | 1406 | | } |
| | | 1407 | | |
| | | 1408 | | /// <summary> |
| | | 1409 | | /// Matches a bracketed IPv6 host:port specification in the format "[ipv6]:port", where: |
| | | 1410 | | /// - ipv6 is a valid IPv6 address (e.g. "::1", "2001:0db8:85a3:0000:0000:8a2e:0370:7334") |
| | | 1411 | | /// - port is a numeric value between 1 and 65535 |
| | | 1412 | | /// Examples of valid inputs: |
| | | 1413 | | /// "[::1]:80" |
| | | 1414 | | /// "[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:443" |
| | | 1415 | | /// </summary> |
| | | 1416 | | [GeneratedRegex(@"^\[([^\]]+)\]:(\d+)$")] |
| | | 1417 | | private static partial Regex BracketedIpv6SpecMatcher(); |
| | | 1418 | | |
| | | 1419 | | /// <summary> |
| | | 1420 | | /// Matches a host:port specification in the format "host:port", where: |
| | | 1421 | | /// - host can be any string excluding ':' (to avoid confusion with IPv6 addresses) |
| | | 1422 | | /// - port is a numeric value between 1 and 65535 |
| | | 1423 | | /// Examples of valid inputs: |
| | | 1424 | | /// "example.com:80" |
| | | 1425 | | /// "localhost:443" |
| | | 1426 | | /// "[::1]:8080" (IPv6 address in brackets) |
| | | 1427 | | /// </summary> |
| | | 1428 | | [GeneratedRegex(@"^([^:]+):(\d+)$")] |
| | | 1429 | | private static partial Regex HostPortSpecMatcher(); |
| | | 1430 | | |
| | | 1431 | | /// <summary> |
| | | 1432 | | /// Matches a URL that starts with "http://" or "https://", followed by a host (excluding '/', '?', or '#'), and end |
| | | 1433 | | /// Examples of valid inputs: |
| | | 1434 | | /// "http://example.com:" |
| | | 1435 | | /// "https://localhost:" |
| | | 1436 | | /// "https://my-server:8080:" |
| | | 1437 | | /// </summary> |
| | | 1438 | | [GeneratedRegex(@"^https?://[^/\?#]+:$", RegexOptions.IgnoreCase, "en-US")] |
| | | 1439 | | private static partial Regex EmptyPortDetectionRegex(); |
| | | 1440 | | } |