| | | 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 | | |
| | | 42 | | /// <summary> |
| | | 43 | | /// Adds rate limiting to the application using the specified configuration delegate. |
| | | 44 | | /// </summary> |
| | | 45 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 46 | | /// <param name="cfg">An optional delegate to configure rate limiting options.</param> |
| | | 47 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 48 | | public static KestrunHost AddRateLimiter(this KestrunHost host, Action<RateLimiterOptions>? cfg = null) |
| | | 49 | | { |
| | 3 | 50 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 51 | | { |
| | 0 | 52 | | host.Logger.Debug("Adding rate limiter with configuration: {HasConfig}", cfg != null); |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | // Register the rate limiter service |
| | 3 | 56 | | _ = host.AddService(services => |
| | 3 | 57 | | { |
| | 0 | 58 | | _ = services.AddRateLimiter(cfg ?? (_ => { })); // Always pass a delegate |
| | 3 | 59 | | }); |
| | | 60 | | |
| | | 61 | | // Apply the middleware |
| | 3 | 62 | | return host.Use(app => |
| | 3 | 63 | | { |
| | 0 | 64 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | 3 | 65 | | { |
| | 0 | 66 | | host.Logger.Debug("Registering rate limiter middleware"); |
| | 3 | 67 | | } |
| | 3 | 68 | | |
| | 0 | 69 | | _ = app.UseRateLimiter(); |
| | 3 | 70 | | }); |
| | | 71 | | } |
| | | 72 | | |
| | | 73 | | |
| | | 74 | | |
| | | 75 | | /// <summary> |
| | | 76 | | /// Adds antiforgery protection to the application. |
| | | 77 | | /// This overload allows you to specify configuration options. |
| | | 78 | | /// </summary> |
| | | 79 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 80 | | /// <param name="options">The antiforgery options to configure.</param> |
| | | 81 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 82 | | public static KestrunHost AddAntiforgery(this KestrunHost host, AntiforgeryOptions? options) |
| | | 83 | | { |
| | 2 | 84 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 85 | | { |
| | 0 | 86 | | host.Logger.Debug("Adding Antiforgery with configuration: {@Config}", options); |
| | | 87 | | } |
| | | 88 | | |
| | 2 | 89 | | if (options == null) |
| | | 90 | | { |
| | 1 | 91 | | return host.AddAntiforgery(); // no config, use defaults |
| | | 92 | | } |
| | | 93 | | |
| | | 94 | | // Delegate to the Action-based overload |
| | 1 | 95 | | return host.AddAntiforgery(cfg => |
| | 1 | 96 | | { |
| | 0 | 97 | | cfg.Cookie = options.Cookie; |
| | 0 | 98 | | cfg.FormFieldName = options.FormFieldName; |
| | 0 | 99 | | cfg.HeaderName = options.HeaderName; |
| | 0 | 100 | | cfg.SuppressXFrameOptionsHeader = options.SuppressXFrameOptionsHeader; |
| | 1 | 101 | | #if NET9_0_OR_GREATER |
| | 0 | 102 | | cfg.SuppressReadingTokenFromFormBody = options.SuppressReadingTokenFromFormBody; |
| | 1 | 103 | | #endif |
| | 1 | 104 | | }); |
| | | 105 | | } |
| | | 106 | | |
| | | 107 | | /// <summary> |
| | | 108 | | /// Adds antiforgery protection to the application. |
| | | 109 | | /// </summary> |
| | | 110 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 111 | | /// <param name="setupAction">An optional action to configure the antiforgery options.</param> |
| | | 112 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 113 | | public static KestrunHost AddAntiforgery(this KestrunHost host, Action<AntiforgeryOptions>? setupAction = null) |
| | | 114 | | { |
| | 4 | 115 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 116 | | { |
| | 0 | 117 | | host.Logger.Debug( |
| | 0 | 118 | | setupAction == null |
| | 0 | 119 | | ? "Adding Antiforgery with default configuration (no custom options provided)." |
| | 0 | 120 | | : "Adding Antiforgery with custom configuration via setupAction." |
| | 0 | 121 | | ); |
| | | 122 | | } |
| | | 123 | | // Service side |
| | 4 | 124 | | _ = host.AddService(services => |
| | 4 | 125 | | { |
| | 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 | | |
| | | 134 | | /// <summary> |
| | | 135 | | /// Adds a CORS policy named "AllowAll" that allows any origin, method, and header. |
| | | 136 | | /// </summary> |
| | | 137 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 138 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 139 | | public static KestrunHost AddCorsAllowAll(this KestrunHost host) => |
| | 1 | 140 | | host.AddCors("AllowAll", b => b.AllowAnyOrigin() |
| | 1 | 141 | | .AllowAnyMethod() |
| | 1 | 142 | | .AllowAnyHeader()); |
| | | 143 | | |
| | | 144 | | /// <summary> |
| | | 145 | | /// Registers a named CORS policy that was already composed with a |
| | | 146 | | /// <see cref="CorsPolicyBuilder"/> and applies that policy in the pipeline. |
| | | 147 | | /// </summary> |
| | | 148 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 149 | | /// <param name="policyName">The name to store/apply the policy under.</param> |
| | | 150 | | /// <param name="builder"> |
| | | 151 | | /// A fully‑configured <see cref="CorsPolicyBuilder"/>. |
| | | 152 | | /// Callers typically chain <c>.WithOrigins()</c>, <c>.WithMethods()</c>, |
| | | 153 | | /// etc. before passing it here. |
| | | 154 | | /// </param> |
| | | 155 | | public static KestrunHost AddCors(this KestrunHost host, string policyName, CorsPolicyBuilder builder) |
| | | 156 | | { |
| | 2 | 157 | | ArgumentException.ThrowIfNullOrWhiteSpace(policyName); |
| | 2 | 158 | | ArgumentNullException.ThrowIfNull(builder); |
| | | 159 | | |
| | | 160 | | // 1️⃣ Service‑time registration |
| | 1 | 161 | | _ = host.AddService(services => |
| | 1 | 162 | | { |
| | 0 | 163 | | _ = services.AddCors(options => |
| | 0 | 164 | | { |
| | 0 | 165 | | options.AddPolicy(policyName, builder.Build()); |
| | 0 | 166 | | }); |
| | 1 | 167 | | }); |
| | | 168 | | |
| | | 169 | | // 2️⃣ Middleware‑time application |
| | 1 | 170 | | return host.Use(app => app.UseCors(policyName)); |
| | | 171 | | } |
| | | 172 | | |
| | | 173 | | /// <summary> |
| | | 174 | | /// Registers a named CORS policy that was already composed with a |
| | | 175 | | /// <see cref="CorsPolicyBuilder"/> and applies that policy in the pipeline. |
| | | 176 | | /// </summary> |
| | | 177 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 178 | | /// <param name="policyName">The name to store/apply the policy under.</param> |
| | | 179 | | /// <param name="buildPolicy">An action to configure the CORS policy.</param> |
| | | 180 | | /// <returns>The current KestrunHost instance.</returns> |
| | | 181 | | /// <exception cref="ArgumentException">Thrown when the policy name is null or whitespace.</exception> |
| | | 182 | | public static KestrunHost AddCors(this KestrunHost host, string policyName, Action<CorsPolicyBuilder> buildPolicy) |
| | | 183 | | { |
| | 5 | 184 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 185 | | { |
| | 0 | 186 | | host.Logger.Debug("Adding CORS policy: {PolicyName}", policyName); |
| | | 187 | | } |
| | | 188 | | |
| | 5 | 189 | | if (string.IsNullOrWhiteSpace(policyName)) |
| | | 190 | | { |
| | 2 | 191 | | throw new ArgumentException("Policy name required.", nameof(policyName)); |
| | | 192 | | } |
| | | 193 | | |
| | 3 | 194 | | ArgumentNullException.ThrowIfNull(buildPolicy); |
| | | 195 | | |
| | 2 | 196 | | _ = host.AddService(s => |
| | 2 | 197 | | { |
| | 0 | 198 | | _ = s.AddCors(o => o.AddPolicy(policyName, buildPolicy)); |
| | 2 | 199 | | }); |
| | | 200 | | |
| | | 201 | | // apply only that policy |
| | 2 | 202 | | return host.Use(app => app.UseCors(policyName)); |
| | | 203 | | } |
| | | 204 | | |
| | | 205 | | /// <summary> |
| | | 206 | | /// Adds Host Filtering to the application using the specified configuration delegate. |
| | | 207 | | /// </summary> |
| | | 208 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 209 | | /// <param name="opts">The delegate for configuring host filtering options.</param> |
| | | 210 | | /// <returns>The updated KestrunHost instance.</returns> |
| | | 211 | | public static KestrunHost AddHostFiltering(this KestrunHost host, Action<HostFilteringOptions>? opts = null) |
| | | 212 | | { |
| | 0 | 213 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 214 | | { |
| | 0 | 215 | | host.Logger.Debug("Adding host filtering with configuration: {HostFilteringOptions}", opts != null); |
| | | 216 | | } |
| | | 217 | | |
| | | 218 | | // Register the host filtering service |
| | 0 | 219 | | _ = host.AddService(services => |
| | 0 | 220 | | { |
| | 0 | 221 | | _ = services.AddHostFiltering(opts ?? (_ => { })); // Always pass a delegate |
| | 0 | 222 | | }); |
| | | 223 | | |
| | | 224 | | // Apply the middleware |
| | 0 | 225 | | return host.Use(app => app.UseHostFiltering()); |
| | | 226 | | } |
| | | 227 | | |
| | | 228 | | /// <summary> |
| | | 229 | | /// Adds Host Filtering to the application using the specified <see cref="HostFilteringOptions"/>. |
| | | 230 | | /// </summary> |
| | | 231 | | /// <param name="host">The KestrunHost instance to configure.</param> |
| | | 232 | | /// <param name="opts">The host filtering options.</param> |
| | | 233 | | /// <returns>The updated KestrunHost instance.</returns> |
| | | 234 | | public static KestrunHost AddHostFiltering(this KestrunHost host, HostFilteringOptions opts) |
| | | 235 | | { |
| | 1 | 236 | | if (host.Logger.IsEnabled(LogEventLevel.Debug)) |
| | | 237 | | { |
| | 1 | 238 | | host.Logger.Debug("Adding host filtering with configuration: {HostFilteringOptions}", opts); |
| | | 239 | | } |
| | | 240 | | |
| | | 241 | | // Register the host filtering service |
| | 1 | 242 | | _ = host.AddService(services => |
| | 1 | 243 | | { |
| | 1 | 244 | | _ = services.AddHostFiltering(o => |
| | 1 | 245 | | { |
| | 1 | 246 | | o.AllowedHosts.Clear(); |
| | 4 | 247 | | foreach (var host in opts.AllowedHosts) |
| | 1 | 248 | | { |
| | 1 | 249 | | o.AllowedHosts.Add(host); |
| | 1 | 250 | | } |
| | 1 | 251 | | o.AllowEmptyHosts = opts.AllowEmptyHosts; |
| | 1 | 252 | | o.IncludeFailureMessage = opts.IncludeFailureMessage; |
| | 2 | 253 | | }); |
| | 2 | 254 | | }); |
| | | 255 | | |
| | | 256 | | // Apply the middleware |
| | 2 | 257 | | return host.Use(app => app.UseHostFiltering()); |
| | | 258 | | } |
| | | 259 | | } |