| | | 1 | | using Kestrun.Utilities; |
| | | 2 | | using Microsoft.AspNetCore.Antiforgery; |
| | | 3 | | using Microsoft.AspNetCore.Cors.Infrastructure; |
| | | 4 | | using Microsoft.AspNetCore.RateLimiting; |
| | | 5 | | using Serilog.Events; |
| | | 6 | | using Microsoft.AspNetCore.HostFiltering; |
| | | 7 | | |
| | | 8 | | namespace Kestrun.Hosting; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Extension methods for adding security-related middleware to a <see cref="KestrunHost"/>. |
| | | 12 | | /// </summary> |
| | | 13 | | public static class KestrunSecurityMiddlewareExtensions |
| | | 14 | | { |
| | | 15 | | /// <summary> |
| | | 16 | | /// Adds rate limiting to the application using the specified <see cref="RateLimiterOptions"/>. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 19 | | /// <param name="cfg">The configuration options for rate limiting.</param> |
| | | 20 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 21 | | public static KestrunHost AddRateLimiter(this KestrunHost host, RateLimiterOptions cfg) |
| | | 22 | | { |
| | 2 | 23 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 24 | | { |
| | 0 | 25 | | host.Logger.Debug("Adding rate limiter with configuration: {@Config}", cfg); |
| | | 26 | | } |
| | | 27 | | |
| | 2 | 28 | | if (cfg == null) |
| | | 29 | | { |
| | 1 | 30 | | return host.AddRateLimiter(); // fall back to your “blank” overload |
| | | 31 | | } |
| | | 32 | | |
| | 1 | 33 | | _ = host.AddService(services => |
| | 1 | 34 | | { |
| | 0 | 35 | | _ = services.AddRateLimiter(opts => opts.CopyFrom(cfg)); // ← single line! |
| | 1 | 36 | | }); |
| | | 37 | | |
| | 1 | 38 | | return host.Use(app => app.UseRateLimiter()); |
| | | 39 | | } |
| | | 40 | | |
| | | 41 | | /// <summary> |
| | | 42 | | /// Adds rate limiting to the application using the specified configuration delegate. |
| | | 43 | | /// </summary> |
| | | 44 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 45 | | /// <param name="cfg">An optional delegate to configure rate limiting options.</param> |
| | | 46 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 47 | | public static KestrunHost AddRateLimiter(this KestrunHost host, Action<RateLimiterOptions>? cfg = null) |
| | | 48 | | { |
| | 3 | 49 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 50 | | { |
| | 0 | 51 | | host.Logger.Debug("Adding rate limiter with configuration: {HasConfig}", cfg != null); |
| | | 52 | | } |
| | | 53 | | |
| | | 54 | | // Register the rate limiter service |
| | 3 | 55 | | _ = host.AddService(services => |
| | 3 | 56 | | { |
| | 0 | 57 | | _ = services.AddRateLimiter(cfg ?? (_ => { })); // Always pass a delegate |
| | 3 | 58 | | }); |
| | | 59 | | |
| | | 60 | | // Apply the middleware |
| | 3 | 61 | | return host.Use(app => |
| | 3 | 62 | | { |
| | 0 | 63 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 3 | 64 | | { |
| | 0 | 65 | | host.Logger.Debug("Registering rate limiter middleware"); |
| | 3 | 66 | | } |
| | 3 | 67 | | |
| | 0 | 68 | | _ = app.UseRateLimiter(); |
| | 3 | 69 | | }); |
| | | 70 | | } |
| | | 71 | | |
| | | 72 | | /// <summary> |
| | | 73 | | /// Adds antiforgery protection to the application. |
| | | 74 | | /// This overload allows you to specify configuration options. |
| | | 75 | | /// </summary> |
| | | 76 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 77 | | /// <param name="options">The antiforgery options to configure.</param> |
| | | 78 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 79 | | public static KestrunHost AddAntiforgery(this KestrunHost host, AntiforgeryOptions? options) |
| | | 80 | | { |
| | 2 | 81 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 82 | | { |
| | 0 | 83 | | host.Logger.Debug("Adding Antiforgery with configuration: {@Config}", options); |
| | | 84 | | } |
| | | 85 | | |
| | 2 | 86 | | if (options == null) |
| | | 87 | | { |
| | 1 | 88 | | return host.AddAntiforgery(); // no config, use defaults |
| | | 89 | | } |
| | | 90 | | |
| | | 91 | | // Delegate to the Action-based overload |
| | 1 | 92 | | return host.AddAntiforgery(cfg => |
| | 1 | 93 | | { |
| | 0 | 94 | | cfg.Cookie = options.Cookie; |
| | 0 | 95 | | cfg.FormFieldName = options.FormFieldName; |
| | 0 | 96 | | cfg.HeaderName = options.HeaderName; |
| | 0 | 97 | | cfg.SuppressXFrameOptionsHeader = options.SuppressXFrameOptionsHeader; |
| | 1 | 98 | | #if NET9_0_OR_GREATER |
| | 1 | 99 | | cfg.SuppressReadingTokenFromFormBody = options.SuppressReadingTokenFromFormBody; |
| | 1 | 100 | | #endif |
| | 1 | 101 | | }); |
| | | 102 | | } |
| | | 103 | | |
| | | 104 | | /// <summary> |
| | | 105 | | /// Adds antiforgery protection to the application. |
| | | 106 | | /// </summary> |
| | | 107 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 108 | | /// <param name="setupAction">An optional action to configure the antiforgery options.</param> |
| | | 109 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 110 | | public static KestrunHost AddAntiforgery(this KestrunHost host, Action<AntiforgeryOptions>? setupAction = null) |
| | | 111 | | { |
| | 4 | 112 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 113 | | { |
| | 0 | 114 | | host.Logger.Debug( |
| | 0 | 115 | | setupAction == null |
| | 0 | 116 | | ? "Adding Antiforgery with default configuration (no custom options provided)." |
| | 0 | 117 | | : "Adding Antiforgery with custom configuration via setupAction." |
| | 0 | 118 | | ); |
| | | 119 | | } |
| | | 120 | | // Service side |
| | 4 | 121 | | _ = host.AddService(services => |
| | 4 | 122 | | { |
| | 0 | 123 | | var options = new AntiforgeryOptions(); |
| | 0 | 124 | | setupAction?.Invoke(options); |
| | 0 | 125 | | host.AntiforgeryOptions = options; |
| | 0 | 126 | | _ = setupAction == null ? services.AddAntiforgery() : services.AddAntiforgery(setupAction); |
| | 4 | 127 | | }); |
| | | 128 | | |
| | | 129 | | // Middleware side |
| | 4 | 130 | | return host.Use(app => app.UseAntiforgery()); |
| | | 131 | | } |
| | | 132 | | |
| | | 133 | | /// <summary> |
| | | 134 | | /// Adds a default CORS policy to the application using the specified <see cref="CorsPolicyBuilder"/>. |
| | | 135 | | /// </summary> |
| | | 136 | | /// <param name="host"> The KestrunHost instance to configure.</param> |
| | | 137 | | /// <param name="builder">The CORS policy builder to use for the default policy.</param> |
| | | 138 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 139 | | public static KestrunHost AddCorsDefaultPolicy(this KestrunHost host, CorsPolicyBuilder builder) |
| | | 140 | | { |
| | 2 | 141 | | ArgumentNullException.ThrowIfNull(builder); |
| | | 142 | | // The name of the default policy is hardcoded here. |
| | | 143 | | const string defaultPolicyName = "__DefaultPolicy__"; |
| | | 144 | | // Service‑time registration |
| | 1 | 145 | | _ = host.AddService(services => |
| | 1 | 146 | | { |
| | 0 | 147 | | _ = services.AddCors(options => |
| | 0 | 148 | | { |
| | 0 | 149 | | options.AddDefaultPolicy(builder.Build()); |
| | 0 | 150 | | }); |
| | 1 | 151 | | }); |
| | | 152 | | |
| | | 153 | | // Add the policy name to the list of defined policies |
| | 1 | 154 | | host.AddCorsPolicyName(defaultPolicyName); |
| | | 155 | | |
| | 1 | 156 | | return host; |
| | | 157 | | } |
| | | 158 | | |
| | | 159 | | /// <summary> |
| | | 160 | | /// Adds a named CORS policy to the application. |
| | | 161 | | /// </summary> |
| | | 162 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 163 | | /// <param name="policyName">The name to store/apply the policy under.</param> |
| | | 164 | | private static void AddCorsPolicyName(this KestrunHost host, string policyName) |
| | | 165 | | { |
| | 14 | 166 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 167 | | { |
| | 0 | 168 | | host.Logger.Debug("Adding CORS policy: {PolicyName}", policyName); |
| | | 169 | | } |
| | 14 | 170 | | if (host.DefinedCorsPolicyNames.Contains(policyName)) |
| | | 171 | | { |
| | 0 | 172 | | if (host.Logger.IsEnabled(LogEventLevel.Warning)) |
| | | 173 | | { |
| | 0 | 174 | | host.Logger.Warning("CORS policy '{PolicyName}' is already defined.", policyName); |
| | | 175 | | } |
| | | 176 | | } |
| | | 177 | | else |
| | | 178 | | { |
| | 14 | 179 | | host.DefinedCorsPolicyNames.Add(policyName); |
| | | 180 | | } |
| | 14 | 181 | | } |
| | | 182 | | /// <summary> |
| | | 183 | | /// Adds a default CORS policy to the application using the specified configuration delegate. |
| | | 184 | | /// </summary> |
| | | 185 | | /// <param name="host"> The KestrunHost instance to configure.</param> |
| | | 186 | | /// <param name="buildPolicy">An action to configure the CORS policy.</param> |
| | | 187 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 188 | | public static KestrunHost AddCorsDefaultPolicy(this KestrunHost host, Action<CorsPolicyBuilder> buildPolicy) |
| | | 189 | | { |
| | 5 | 190 | | ArgumentNullException.ThrowIfNull(buildPolicy); |
| | | 191 | | // The name of the default policy is hardcoded here. |
| | | 192 | | const string defaultPolicyName = "__DefaultPolicy__"; |
| | | 193 | | |
| | 4 | 194 | | _ = host.AddService(services => |
| | 4 | 195 | | { |
| | 0 | 196 | | _ = services.AddCors(options => options.AddDefaultPolicy(buildPolicy)); |
| | 4 | 197 | | }); |
| | | 198 | | |
| | | 199 | | // Add the policy name to the list of defined policies |
| | 4 | 200 | | host.AddCorsPolicyName(defaultPolicyName); |
| | 4 | 201 | | return host; |
| | | 202 | | } |
| | | 203 | | |
| | | 204 | | /// <summary> |
| | | 205 | | /// Adds a CORS policy named "AllowAll" that allows any origin, method, and header. |
| | | 206 | | /// </summary> |
| | | 207 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 208 | | /// <param name="policyName">The name to store/apply the policy under.</param> |
| | | 209 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 210 | | public static KestrunHost AddCorsPolicyAllowAll(this KestrunHost host, string policyName) => |
| | 2 | 211 | | host.AddCorsPolicy(policyName, b => b.AllowAnyOrigin() |
| | 2 | 212 | | .AllowAnyMethod() |
| | 2 | 213 | | .AllowAnyHeader()); |
| | | 214 | | |
| | | 215 | | /// <summary> |
| | | 216 | | /// Adds a default CORS policy that allows any origin, method, and header. |
| | | 217 | | /// </summary> |
| | | 218 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 219 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 220 | | public static KestrunHost AddCorsDefaultPolicyAllowAll(this KestrunHost host) => |
| | 3 | 221 | | host.AddCorsDefaultPolicy(b => b.AllowAnyOrigin() |
| | 3 | 222 | | .AllowAnyMethod() |
| | 3 | 223 | | .AllowAnyHeader()); |
| | | 224 | | |
| | | 225 | | /// <summary> |
| | | 226 | | /// Registers a named CORS policy that was already composed with a |
| | | 227 | | /// <see cref="CorsPolicyBuilder"/> and applies that policy in the pipeline. |
| | | 228 | | /// </summary> |
| | | 229 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 230 | | /// <param name="policyName">The name to store/apply the policy under.</param> |
| | | 231 | | /// <param name="builder"> |
| | | 232 | | /// A fully‑configured <see cref="CorsPolicyBuilder"/>. |
| | | 233 | | /// Callers typically chain <c>.WithOrigins()</c>, <c>.WithMethods()</c>, |
| | | 234 | | /// etc. before passing it here. |
| | | 235 | | /// </param> |
| | | 236 | | public static KestrunHost AddCorsPolicy(this KestrunHost host, string policyName, CorsPolicyBuilder builder) |
| | | 237 | | { |
| | 13 | 238 | | ArgumentException.ThrowIfNullOrWhiteSpace(policyName); |
| | 11 | 239 | | ArgumentNullException.ThrowIfNull(builder); |
| | | 240 | | |
| | | 241 | | // Service‑time registration |
| | 9 | 242 | | _ = host.AddService(services => |
| | 9 | 243 | | { |
| | 0 | 244 | | _ = services.AddCors(options => |
| | 0 | 245 | | { |
| | 0 | 246 | | options.AddPolicy(policyName, builder.Build()); |
| | 0 | 247 | | }); |
| | 9 | 248 | | }); |
| | | 249 | | |
| | | 250 | | // Add the policy name to the list of defined policies |
| | 9 | 251 | | host.AddCorsPolicyName(policyName); |
| | | 252 | | |
| | | 253 | | // 2️⃣ Middleware‑time application |
| | 9 | 254 | | return host; |
| | | 255 | | } |
| | | 256 | | |
| | | 257 | | /// <summary> |
| | | 258 | | /// Registers a named CORS policy that was already composed with a |
| | | 259 | | /// <see cref="CorsPolicyBuilder"/> and applies that policy in the pipeline. |
| | | 260 | | /// </summary> |
| | | 261 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 262 | | /// <param name="policyName">The name to store/apply the policy under.</param> |
| | | 263 | | /// <param name="buildPolicy">An action to configure the CORS policy.</param> |
| | | 264 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 265 | | /// <exception cref="ArgumentException">Thrown when the policy name is null or whitespace.</exception> |
| | | 266 | | public static KestrunHost AddCorsPolicy(this KestrunHost host, string policyName, Action<CorsPolicyBuilder> buildPol |
| | | 267 | | { |
| | 11 | 268 | | ArgumentNullException.ThrowIfNull(host); |
| | 11 | 269 | | ArgumentException.ThrowIfNullOrWhiteSpace(policyName); |
| | | 270 | | |
| | 9 | 271 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 272 | | { |
| | 0 | 273 | | host.Logger.Debug("Adding CORS policy: {PolicyName}", policyName); |
| | | 274 | | } |
| | | 275 | | |
| | 9 | 276 | | ArgumentNullException.ThrowIfNull(buildPolicy); |
| | 7 | 277 | | var builder = new CorsPolicyBuilder(); |
| | 7 | 278 | | buildPolicy(builder); |
| | | 279 | | |
| | 7 | 280 | | return host.AddCorsPolicy(policyName, builder); |
| | | 281 | | } |
| | | 282 | | |
| | | 283 | | /// <summary> |
| | | 284 | | /// Adds Host Filtering to the application using the specified configuration delegate. |
| | | 285 | | /// </summary> |
| | | 286 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 287 | | /// <param name="opts">The delegate for configuring host filtering options.</param> |
| | | 288 | | /// <returns>The updated KestrunHost instance.</returns> |
| | | 289 | | public static KestrunHost AddHostFiltering(this KestrunHost host, Action<HostFilteringOptions>? opts = null) |
| | | 290 | | { |
| | 0 | 291 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 292 | | { |
| | 0 | 293 | | host.Logger.Debug("Adding host filtering with configuration: {HostFilteringOptions}", opts != null); |
| | | 294 | | } |
| | | 295 | | |
| | | 296 | | // Register the host filtering service |
| | 0 | 297 | | _ = host.AddService(services => |
| | 0 | 298 | | { |
| | 0 | 299 | | _ = services.AddHostFiltering(opts ?? (_ => { })); // Always pass a delegate |
| | 0 | 300 | | }); |
| | | 301 | | |
| | | 302 | | // Apply the middleware |
| | 0 | 303 | | return host.Use(app => app.UseHostFiltering()); |
| | | 304 | | } |
| | | 305 | | |
| | | 306 | | /// <summary> |
| | | 307 | | /// Adds Host Filtering to the application using the specified <see cref="HostFilteringOptions"/>. |
| | | 308 | | /// </summary> |
| | | 309 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 310 | | /// <param name="opts">The host filtering options.</param> |
| | | 311 | | /// <returns>The updated KestrunHost instance.</returns> |
| | | 312 | | public static KestrunHost AddHostFiltering(this KestrunHost host, HostFilteringOptions opts) |
| | | 313 | | { |
| | 1 | 314 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 315 | | { |
| | 1 | 316 | | host.Logger.Debug("Adding host filtering with configuration: {HostFilteringOptions}", opts); |
| | | 317 | | } |
| | | 318 | | |
| | | 319 | | // Register the host filtering service |
| | 1 | 320 | | _ = host.AddService(services => |
| | 1 | 321 | | { |
| | 1 | 322 | | _ = services.AddHostFiltering(o => |
| | 1 | 323 | | { |
| | 1 | 324 | | o.AllowedHosts.Clear(); |
| | 4 | 325 | | foreach (var host in opts.AllowedHosts) |
| | 1 | 326 | | { |
| | 1 | 327 | | o.AllowedHosts.Add(host); |
| | 1 | 328 | | } |
| | 1 | 329 | | o.AllowEmptyHosts = opts.AllowEmptyHosts; |
| | 1 | 330 | | o.IncludeFailureMessage = opts.IncludeFailureMessage; |
| | 2 | 331 | | }); |
| | 2 | 332 | | }); |
| | | 333 | | |
| | | 334 | | // Apply the middleware |
| | 2 | 335 | | return host.Use(app => app.UseHostFiltering()); |
| | | 336 | | } |
| | | 337 | | } |