< Summary - Kestrun — Combined Coverage

Information
Class: Kestrun.Hosting.KestrunHttpMiddlewareExtensions
Assembly: Kestrun
File(s): /home/runner/work/Kestrun/Kestrun/src/CSharp/Kestrun/Hosting/KestrunHttpMiddlewareExtensions.cs
Tag: Kestrun/Kestrun@9d3a582b2d63930269564a7591aa77ef297cadeb
Line coverage
67%
Covered lines: 59
Uncovered lines: 28
Coverable lines: 87
Total lines: 253
Line coverage: 67.8%
Branch coverage
39%
Covered branches: 15
Total branches: 38
Branch coverage: 39.4%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
AddResponseCompression(...)50%8660%
AddResponseCompression(...)25%4471.42%
AddRateLimiter(...)50%6677.77%
AddRateLimiter(...)16.66%7666.66%
AddAntiforgery(...)75%6454.54%
AddAntiforgery(...)25%4471.42%
AddCorsAllowAll(...)100%11100%
AddCors(...)0%2260%
AddCors(...)50%6680%

File(s)

/home/runner/work/Kestrun/Kestrun/src/CSharp/Kestrun/Hosting/KestrunHttpMiddlewareExtensions.cs

#LineLine coverage
 1using Kestrun.Utilities;
 2using Microsoft.AspNetCore.Antiforgery;
 3using Microsoft.AspNetCore.Cors.Infrastructure;
 4using Microsoft.AspNetCore.RateLimiting;
 5using Microsoft.AspNetCore.ResponseCompression;
 6using Serilog.Events;
 7
 8namespace Kestrun.Hosting;
 9
 10/// <summary>
 11/// Provides extension methods for configuring common HTTP middleware in Kestrun.
 12/// </summary>
 13public static class KestrunHttpMiddlewareExtensions
 14{
 15    /// <summary>
 16    /// Adds response compression to the application.
 17    /// This overload allows you to specify configuration options.
 18    /// </summary>
 19    /// <param name="host">The KestrunHost instance to configure.</param>
 20    /// <param name="options">The configuration options for response compression.</param>
 21    /// <returns>The current KestrunHost instance.</returns>
 22    public static KestrunHost AddResponseCompression(this KestrunHost host, ResponseCompressionOptions? options)
 23    {
 224        if (host.HostLogger.IsEnabled(LogEventLevel.Debug))
 25        {
 026            host.HostLogger.Debug("Adding response compression with options: {@Options}", options);
 27        }
 28
 229        if (options == null)
 30        {
 131            return host.AddResponseCompression(); // no options, use defaults
 32        }
 33
 34        // delegate shim – re‑use the existing pipeline
 135        return host.AddResponseCompression(o =>
 136        {
 037            o.EnableForHttps = options.EnableForHttps;
 038            o.MimeTypes = options.MimeTypes;
 039            o.ExcludedMimeTypes = options.ExcludedMimeTypes;
 140            // copy provider lists, levels, etc. if you expose them
 041            foreach (var p in options.Providers)
 142            {
 043                o.Providers.Add(p);
 144            }
 145        });
 46    }
 47
 48    /// <summary>
 49    /// Adds response compression to the application.
 50    /// This overload allows you to specify configuration options.
 51    /// </summary>
 52    /// <param name="host">The KestrunHost instance to configure.</param>
 53    /// <param name="cfg">The configuration options for response compression.</param>
 54    /// <returns>The current KestrunHost instance.</returns>
 55    public static KestrunHost AddResponseCompression(this KestrunHost host, Action<ResponseCompressionOptions>? cfg = nu
 56    {
 457        if (host.HostLogger.IsEnabled(LogEventLevel.Debug))
 58        {
 059            host.HostLogger.Debug("Adding response compression with configuration: {Config}", cfg);
 60        }
 61        // Service side
 462        _ = host.AddService(services =>
 463        {
 064            _ = cfg == null ? services.AddResponseCompression() : services.AddResponseCompression(cfg);
 465        });
 66
 67        // Middleware side
 468        return host.Use(app => app.UseResponseCompression());
 69    }
 70
 71    /// <summary>
 72    /// Adds rate limiting to the application using the specified <see cref="RateLimiterOptions"/>.
 73    /// </summary>
 74    /// <param name="host">The KestrunHost instance to configure.</param>
 75    /// <param name="cfg">The configuration options for rate limiting.</param>
 76    /// <returns>The current KestrunHost instance.</returns>
 77    public static KestrunHost AddRateLimiter(this KestrunHost host, RateLimiterOptions cfg)
 78    {
 279        if (host.HostLogger.IsEnabled(LogEventLevel.Debug))
 80        {
 081            host.HostLogger.Debug("Adding rate limiter with configuration: {@Config}", cfg);
 82        }
 83
 284        if (cfg == null)
 85        {
 186            return host.AddRateLimiter();   // fall back to your “blank” overload
 87        }
 88
 189        _ = host.AddService(services =>
 190        {
 091            _ = services.AddRateLimiter(opts => opts.CopyFrom(cfg));   // ← single line!
 192        });
 93
 194        return host.Use(app => app.UseRateLimiter());
 95    }
 96
 97
 98    /// <summary>
 99    /// Adds rate limiting to the application using the specified configuration delegate.
 100    /// </summary>
 101    /// <param name="host">The KestrunHost instance to configure.</param>
 102    /// <param name="cfg">An optional delegate to configure rate limiting options.</param>
 103    /// <returns>The current KestrunHost instance.</returns>
 104    public static KestrunHost AddRateLimiter(this KestrunHost host, Action<RateLimiterOptions>? cfg = null)
 105    {
 3106        if (host.HostLogger.IsEnabled(LogEventLevel.Debug))
 107        {
 0108            host.HostLogger.Debug("Adding rate limiter with configuration: {HasConfig}", cfg != null);
 109        }
 110
 111        // Register the rate limiter service
 3112        _ = host.AddService(services =>
 3113            {
 0114                _ = services.AddRateLimiter(cfg ?? (_ => { })); // Always pass a delegate
 3115            });
 116
 117        // Apply the middleware
 3118        return host.Use(app =>
 3119        {
 0120            if (host.HostLogger.IsEnabled(LogEventLevel.Debug))
 3121            {
 0122                host.HostLogger.Debug("Registering rate limiter middleware");
 3123            }
 3124
 0125            _ = app.UseRateLimiter();
 3126        });
 127    }
 128
 129
 130
 131    /// <summary>
 132    /// Adds antiforgery protection to the application.
 133    /// This overload allows you to specify configuration options.
 134    /// </summary>
 135    /// <param name="host">The KestrunHost instance to configure.</param>
 136    /// <param name="options">The antiforgery options to configure.</param>
 137    /// <returns>The current KestrunHost instance.</returns>
 138    public static KestrunHost AddAntiforgery(this KestrunHost host, AntiforgeryOptions? options)
 139    {
 2140        if (host.HostLogger.IsEnabled(LogEventLevel.Debug))
 141        {
 0142            host.HostLogger.Debug("Adding Antiforgery with configuration: {@Config}", options);
 143        }
 144
 2145        if (options == null)
 146        {
 1147            return host.AddAntiforgery(); // no config, use defaults
 148        }
 149
 150        // Delegate to the Action-based overload
 1151        return host.AddAntiforgery(cfg =>
 1152        {
 0153            cfg.Cookie = options.Cookie;
 0154            cfg.FormFieldName = options.FormFieldName;
 0155            cfg.HeaderName = options.HeaderName;
 0156            cfg.SuppressXFrameOptionsHeader = options.SuppressXFrameOptionsHeader;
 1157        });
 158    }
 159
 160    /// <summary>
 161    /// Adds antiforgery protection to the application.
 162    /// </summary>
 163    /// <param name="host">The KestrunHost instance to configure.</param>
 164    /// <param name="setupAction">An optional action to configure the antiforgery options.</param>
 165    /// <returns>The current KestrunHost instance.</returns>
 166    public static KestrunHost AddAntiforgery(this KestrunHost host, Action<AntiforgeryOptions>? setupAction = null)
 167    {
 4168        if (host.HostLogger.IsEnabled(LogEventLevel.Debug))
 169        {
 0170            host.HostLogger.Debug("Adding Antiforgery with configuration: {@Config}", setupAction);
 171        }
 172        // Service side
 4173        _ = host.AddService(services =>
 4174        {
 0175            _ = setupAction == null ? services.AddAntiforgery() : services.AddAntiforgery(setupAction);
 4176        });
 177
 178        // Middleware side
 4179        return host.Use(app => app.UseAntiforgery());
 180    }
 181
 182
 183    /// <summary>
 184    /// Adds a CORS policy named "AllowAll" that allows any origin, method, and header.
 185    /// </summary>
 186    /// <param name="host">The KestrunHost instance to configure.</param>
 187    /// <returns>The current KestrunHost instance.</returns>
 188    public static KestrunHost AddCorsAllowAll(this KestrunHost host) =>
 1189        host.AddCors("AllowAll", b => b.AllowAnyOrigin()
 1190                                  .AllowAnyMethod()
 1191                                  .AllowAnyHeader());
 192
 193    /// <summary>
 194    /// Registers a named CORS policy that was already composed with a
 195    /// <see cref="CorsPolicyBuilder"/> and applies that policy in the pipeline.
 196    /// </summary>
 197    /// <param name="host">The KestrunHost instance to configure.</param>
 198    /// <param name="policyName">The name to store/apply the policy under.</param>
 199    /// <param name="builder">
 200    ///     A fully‑configured <see cref="CorsPolicyBuilder"/>.
 201    ///     Callers typically chain <c>.WithOrigins()</c>, <c>.WithMethods()</c>,
 202    ///     etc. before passing it here.
 203    /// </param>
 204    public static KestrunHost AddCors(this KestrunHost host, string policyName, CorsPolicyBuilder builder)
 205    {
 2206        ArgumentException.ThrowIfNullOrWhiteSpace(policyName);
 2207        ArgumentNullException.ThrowIfNull(builder);
 208
 209        // 1️⃣ Service‑time registration
 1210        _ = host.AddService(services =>
 1211        {
 0212            _ = services.AddCors(options =>
 0213            {
 0214                options.AddPolicy(policyName, builder.Build());
 0215            });
 1216        });
 217
 218        // 2️⃣ Middleware‑time application
 1219        return host.Use(app => app.UseCors(policyName));
 220    }
 221
 222    /// <summary>
 223    /// Registers a named CORS policy that was already composed with a
 224    /// <see cref="CorsPolicyBuilder"/> and applies that policy in the pipeline.
 225    /// </summary>
 226    /// <param name="host">The KestrunHost instance to configure.</param>
 227    /// <param name="policyName">The name to store/apply the policy under.</param>
 228    /// <param name="buildPolicy">An action to configure the CORS policy.</param>
 229    /// <returns>The current KestrunHost instance.</returns>
 230    /// <exception cref="ArgumentException">Thrown when the policy name is null or whitespace.</exception>
 231    public static KestrunHost AddCors(this KestrunHost host, string policyName, Action<CorsPolicyBuilder> buildPolicy)
 232    {
 5233        if (host.HostLogger.IsEnabled(LogEventLevel.Debug))
 234        {
 0235            host.HostLogger.Debug("Adding CORS policy: {PolicyName}", policyName);
 236        }
 237
 5238        if (string.IsNullOrWhiteSpace(policyName))
 239        {
 2240            throw new ArgumentException("Policy name required.", nameof(policyName));
 241        }
 242
 3243        ArgumentNullException.ThrowIfNull(buildPolicy);
 244
 2245        _ = host.AddService(s =>
 2246        {
 0247            _ = s.AddCors(o => o.AddPolicy(policyName, buildPolicy));
 2248        });
 249
 250        // apply only that policy
 2251        return host.Use(app => app.UseCors(policyName));
 252    }
 253}