-
Notifications
You must be signed in to change notification settings - Fork 12
Add optional Minimal API security defaults #836
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
AndreaCuneo
merged 11 commits into
master
from
copilot/docsmediator-frameworkprogressaspnetcore-hosting-g
Aug 4, 2026
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
93cde93
feat(minimal-api): add security profile
Copilot ec1b81e
test(minimal-api): cover security defaults
Copilot 0bbb0aa
fix(minimal-api): stabilize security tests
Copilot b3f2218
test(minimal-api): fix server header assertion
Copilot 844f257
test(minimal-api): enable production hsts test
Copilot d73003a
test(minimal-api): request https for hsts
Copilot b6b3b8e
test(minimal-api): simulate https in test host
Copilot d72ba2e
test(minimal-api): stabilize header coverage
Copilot 7367e8b
Potential fix for pull request finding
AndreaCuneo 5f639fd
Merge master into branch
Copilot 291452e
test(minimal-api): add scalar COOP tests, fix HSTS localhost, merge m…
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
75 changes: 75 additions & 0 deletions
75
src/aspnetcore/Ark.Tools.AspNetCore.MinimalApi/ArkMinimalApiSecurityExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| // Copyright (C) 2024 Ark Energy S.r.l. All rights reserved. | ||
| // Licensed under the MIT License. See LICENSE file for license information. | ||
|
|
||
| using Microsoft.AspNetCore.Builder; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
|
|
||
| namespace Ark.Tools.AspNetCore.MinimalApi; | ||
|
|
||
| /// <summary>Provides the optional Ark Minimal API security profile.</summary> | ||
| public static class ArkMinimalApiSecurityExtensions | ||
| { | ||
| /// <summary> | ||
| /// Adds the Ark security-header policies used by Minimal API hosts. | ||
| /// </summary> | ||
| /// <param name="services">The application service collection.</param> | ||
| /// <returns>The original service collection.</returns> | ||
| public static IServiceCollection AddArkMinimalApiSecurity( | ||
| this IServiceCollection services) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(services); | ||
|
|
||
| services.AddSecurityHeaderPolicies() | ||
| .SetDefaultPolicy(policy => policy | ||
| .AddDefaultApiSecurityHeaders() | ||
| .RemoveServerHeader()) | ||
| .AddPolicy("Scalar", policy => ConfigureDocumentationPolicy(policy)) | ||
| .AddPolicy("Swagger", policy => ConfigureDocumentationPolicy(policy)) | ||
| .AddPolicy("GrpcReflection", policy => policy | ||
| .AddDefaultSecurityHeaders() | ||
| .RemoveServerHeader()) | ||
| .SetPolicySelector(context => | ||
| { | ||
| var path = context.HttpContext.Request.Path; | ||
|
|
||
| if (path.StartsWithSegments("/scalar", StringComparison.OrdinalIgnoreCase) | ||
| || path.StartsWithSegments("/swagger", StringComparison.OrdinalIgnoreCase) | ||
| || path.StartsWithSegments("/openapi", StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| return context.ConfiguredPolicies["Scalar"]; | ||
| } | ||
|
|
||
| if (path.StartsWithSegments("/grpc.reflection", StringComparison.OrdinalIgnoreCase)) | ||
| { | ||
| return context.ConfiguredPolicies["GrpcReflection"]; | ||
| } | ||
|
|
||
| return context.DefaultPolicy; | ||
| }); | ||
|
|
||
| return services; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Adds the Ark security-header middleware and HSTS middleware to the request pipeline. | ||
| /// </summary> | ||
| /// <param name="app">The application builder.</param> | ||
| /// <returns>The original application builder.</returns> | ||
| public static IApplicationBuilder UseArkMinimalApiSecurity(this IApplicationBuilder app) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(app); | ||
|
|
||
| app.UseSecurityHeaders(); | ||
| app.UseHsts(); | ||
| return app; | ||
| } | ||
|
|
||
| private static void ConfigureDocumentationPolicy(HeaderPolicyCollection policy) | ||
|
AndreaCuneo marked this conversation as resolved.
|
||
| { | ||
| policy | ||
| .AddDefaultSecurityHeaders() | ||
| .RemoveServerHeader(); | ||
| policy.Remove("Cross-Origin-Opener-Policy"); | ||
| policy.AddCrossOriginOpenerPolicy(options => options.UnsafeNone()); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
tests/Ark.Tools.AspNetCore.MinimalApi.Tests/ArkMinimalApiSecurityTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| // Copyright (C) 2024 Ark Energy S.r.l. All rights reserved. | ||
| // Licensed under the MIT License. See LICENSE file for license information. | ||
|
|
||
| using AwesomeAssertions; | ||
|
|
||
| using Microsoft.AspNetCore.Builder; | ||
| using Microsoft.AspNetCore.Hosting; | ||
| using Microsoft.AspNetCore.HttpsPolicy; | ||
| using Microsoft.AspNetCore.TestHost; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Hosting; | ||
|
|
||
| namespace Ark.Tools.AspNetCore.MinimalApi.Tests; | ||
|
|
||
| /// <summary>Verifies the optional Ark Minimal API security profile.</summary> | ||
| [TestClass] | ||
| public sealed class ArkMinimalApiSecurityTests | ||
| { | ||
| [TestMethod] | ||
| public async Task AddsSecurityHeadersAndHsts() | ||
|
AndreaCuneo marked this conversation as resolved.
|
||
| { | ||
| using var host = await CreateHostAsync().ConfigureAwait(false); | ||
| using var client = host.GetTestClient(); | ||
| client.BaseAddress = new Uri("https://localhost"); | ||
|
|
||
| using var response = await client.GetAsync(new Uri("https://localhost/")).ConfigureAwait(false); | ||
|
|
||
| response.Headers.Server.ToString().Should().BeEmpty(); | ||
| response.Headers.Contains("Strict-Transport-Security").Should().BeTrue(); | ||
| response.Headers.GetValues("X-Content-Type-Options").Should().ContainSingle("nosniff"); | ||
| response.Headers.GetValues("X-Frame-Options").Should().ContainSingle("DENY"); | ||
|
Copilot marked this conversation as resolved.
|
||
| } | ||
|
|
||
| [TestMethod] | ||
| public async Task ApiPolicy_HasSameOriginCrossOriginOpenerPolicy() | ||
| { | ||
| using var host = await CreateHostAsync().ConfigureAwait(false); | ||
| using var client = host.GetTestClient(); | ||
| client.BaseAddress = new Uri("https://localhost"); | ||
|
|
||
| using var response = await client.GetAsync(new Uri("https://localhost/")).ConfigureAwait(false); | ||
|
|
||
| response.Headers.GetValues("Cross-Origin-Opener-Policy").Should().ContainSingle("same-origin"); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| [DataRow("/scalar")] | ||
| [DataRow("/scalar/v1")] | ||
| [DataRow("/swagger")] | ||
| [DataRow("/openapi")] | ||
| public async Task DocumentationPolicy_HasUnsafeNoneCrossOriginOpenerPolicy(string path) | ||
| { | ||
| using var host = await CreateHostAsync().ConfigureAwait(false); | ||
| using var client = host.GetTestClient(); | ||
| client.BaseAddress = new Uri("https://localhost"); | ||
|
|
||
| using var response = await client.GetAsync(new Uri($"https://localhost{path}")).ConfigureAwait(false); | ||
|
|
||
| response.Headers.GetValues("Cross-Origin-Opener-Policy").Should().ContainSingle("unsafe-none"); | ||
| } | ||
|
|
||
| private static async Task<IHost> CreateHostAsync() | ||
| { | ||
| var host = new HostBuilder() | ||
| .ConfigureWebHost(web => | ||
| { | ||
| web.UseTestServer(); | ||
| web.UseEnvironment(Environments.Production); | ||
| web.ConfigureServices(services => | ||
| { | ||
| services.AddRouting(); | ||
| services.AddArkMinimalApiSecurity(); | ||
| services.Configure<HstsOptions>(o => o.ExcludedHosts.Clear()); | ||
| }); | ||
| web.Configure(app => | ||
| { | ||
| app.Use((context, next) => | ||
| { | ||
| context.Request.Scheme = "https"; | ||
| return next(); | ||
| }); | ||
| app.UseArkMinimalApiSecurity(); | ||
| app.UseRouting(); | ||
| app.UseEndpoints(endpoints => | ||
| { | ||
| endpoints.MapGet("/", () => "ok"); | ||
| endpoints.MapGet("/scalar/{**path}", () => "scalar ui"); | ||
| endpoints.MapGet("/swagger/{**path}", () => "swagger ui"); | ||
| endpoints.MapGet("/openapi/{**path}", () => "openapi ui"); | ||
| }); | ||
| }); | ||
| }) | ||
| .Build(); | ||
|
|
||
| await host.StartAsync().ConfigureAwait(false); | ||
| return host; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.