Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions .agents/skills/configuration-and-environments/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ The Lambda template has no appsettings files or environments. Its startup builds
| Environment | Set by | Used for |
| --- | --- | --- |
| `Development` | `launchSettings.json` (`DOTNET_ENVIRONMENT=Development`) | `dotnet run` on a developer machine: console logs, sample data on |
| `docker` | `docker-compose.yml` and the Dockerfile | `docker compose up`: telemetry over OTLP through the collector to the Aspire dashboard, database in `/app/data`, sample data on |
| anything else | the host | Real deployments: base settings only, sample data off, HSTS on |
| `docker` | `docker-compose.yml` | `docker compose up`: telemetry over OTLP through the collector to the Aspire dashboard, database in `/app/data`, sample data on |
| anything else | the host, or `Production`, the image's default | Real deployments: base settings only, sample data off, HSTS on. The web templates refuse to start here without authentication unless `Authentication:AllowAnonymous` is true (`security-defaults`) |

Settings that exist today:

Expand All @@ -26,6 +26,7 @@ Settings that exist today:
| `ConnectionStrings:MovieReviews` | SQLite connection string. `Data Source=Name;Mode=Memory;Cache=Shared` keeps everything in memory. |
| `Database:SeedSampleData` | Seed sample data into an empty database (`sample-data`). |
| `Authentication:Authority`, `Authentication:Audience` | Only in a solution created with `--include-auth`: turn on token authentication (`optional-token-auth`). MCP also has `Authentication:Scopes`, published in its protected resource metadata. |
| `Authentication:AllowAnonymous` | Web templates only: let a deployed environment run without authentication on purpose (`security-defaults`). Off by default. |
| `Serilog:*` | Logging (`serilog`). |

## Steps
Expand Down
2 changes: 2 additions & 0 deletions .agents/skills/optional-token-auth/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ With `--include-auth`, endpoints always ask for authorization. An empty `Authent

Settings are read through `AuthenticationSettings.FromConfiguration` (`Enabled` is true when the authority isn't empty).

Open is only fine on a developer's machine. In the web templates, with or without `--include-auth`, `DeploymentGuard` stops a deployed environment (anything but `Development` and `docker`) starting without authentication unless `Authentication:AllowAnonymous` is `true`, and checks that a set authority is an `https` URL (`security-defaults`).

## Steps

1. In a solution with authentication, a new endpoint or group gets `.RequireAuthorization()` (or the presentation layer's equivalent). That's the default; don't skip it. Without it there's nothing to call.
Expand Down
12 changes: 11 additions & 1 deletion .agents/skills/security-defaults/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: security-defaults
description: What this Minimal API does to be safe by default - the security response headers, and where the other protections live. Use when adding a response header, changing security middleware, or asked whether the app is safe to deploy.
description: What this Minimal API does to be safe by default - the startup guard for deployed environments, the security response headers, and where the other protections live. Use when adding a response header, changing security middleware, or asked whether the app is safe to deploy.
metadata:
scope: presentation
---
Expand All @@ -13,10 +13,20 @@ The app ships safe by default, and each protection lives in one place in `src/Pr

| Protection | Where | Default |
| --- | --- | --- |
| Refuse to start deployed and open | `DeploymentGuard` | On; `Authentication:AllowAnonymous` opts out |
| Security response headers | `SecurityHeaders` | Always on |
| HSTS and HTTPS redirection | Security region | HSTS outside local runs |
| Compose ports on `127.0.0.1` | `docker-compose.yml` (`docker-and-compose`) | Always |

## Deployment guard

`DeploymentGuard.EnsureSafeToStart` runs first in the startup, before any service is added. `Development` (`dotnet run`) and `docker` (Docker Compose) are a developer's machine. Every other environment name, including `Production` (the image's default), `uat` or anything a team invents, counts as deployed, so a new name fails closed.

- A deployed environment without authentication throws at startup, unless `Authentication:AllowAnonymous` is `true`. The message names the setting.
- In a solution with authentication, a set `Authentication:Authority` must be an absolute `https` URL, in every environment. An empty `Authentication:Audience` already fails closed, because every token is rejected.

Don't add environment names to `IsLocal` to get a deployment past the guard; set `Authentication:AllowAnonymous` there instead, so the choice is visible in that environment's settings. `tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs` starts the app in each kind of environment.

## Security headers

`UseSecurityHeaders` adds three headers to every response, errors and health checks included:
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/build-pipeline.yml
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,7 @@ jobs:
# The database goes in /app/data, the only folder the non-root user can write to, as it does
# in docker-compose.yml. Logs stay on the console so a failure shows up below.
docker run --detach --name api --publish 7310:7310 \
--env DOTNET_ENVIRONMENT=docker \
--env ConnectionStrings__MovieReviews="Data Source=/app/data/movie-reviews.db" \
--env Database__SeedSampleData=true "$IMAGE"
for attempt in $(seq 1 30); do
Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ FROM ${BASE_IMAGE_REPO}/${BASE_IMAGE_BUILD}:${BASE_IMAGE_BUILD_TAG} AS build
# Build, Test and Publish ARGS
ARG VERSION_PREFIX=1.0.0.0
ARG VERSION_SUFFIX
ARG ENVIRONMENT=docker
ARG ENVIRONMENT=Production

# Build, Test and Publish ENVS
ENV DOTNET_ENVIRONMENT=${ENVIRONMENT}
Expand Down
2 changes: 1 addition & 1 deletion docs/RUN.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Running Clean Minimal API

There are two pre-configured environments, `Development` and `docker`. Logs go to the console in both. Traces, metrics and logs also leave over OTLP whenever `OTEL_EXPORTER_OTLP_ENDPOINT` is set, which Docker Compose does for you.
There are two pre-configured environments: `Development` for `dotnet run` and `docker` for Docker Compose. Every other environment name counts as deployed, including `Production`, which is what the image runs as unless you say otherwise. A deployed copy with no authentication refuses to start, so nobody ships an open API by accident; set `Authentication:AllowAnonymous` to `true` (`Authentication__AllowAnonymous=true`) if open is what you want. Logs go to the console in both. Traces, metrics and logs also leave over OTLP whenever `OTEL_EXPORTER_OTLP_ENDPOINT` is set, which Docker Compose does for you.

## Database

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ namespace CleanMinimalApi.Presentation.Extensions;
#endif
using Presentation.Errors;
using Presentation.OpenApi;
using Presentation.Security;
using Presentation.Serialization;
using Presentation.Telemetry;
using Serilog;
Expand All @@ -31,6 +32,9 @@ public static class WebApplicationBuilderExtensions
{
public static WebApplicationBuilder ConfigureApplicationBuilder(this WebApplicationBuilder builder)
{
// Before anything else, so a deployed copy with no authentication never gets as far as listening.
DeploymentGuard.EnsureSafeToStart(builder.Environment, builder.Configuration);

#region Telemetry

var assembly = typeof(WebApplicationBuilderExtensions).Assembly;
Expand Down
67 changes: 67 additions & 0 deletions src/Presentation/Security/DeploymentGuard.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
namespace CleanMinimalApi.Presentation.Security;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
#if includeAuth
using Presentation.Authentication;
#endif

/// <summary>
/// Stops a deployed copy starting wide open by accident. <c>Development</c> (<c>dotnet run</c>) and <c>docker</c>
/// (Docker Compose) are a developer's machine; every other environment name counts as deployed.
/// </summary>
public static class DeploymentGuard
{
/// <summary>The setting that lets a deployed copy run without authentication on purpose.</summary>
public const string AllowAnonymousKey = "Authentication:AllowAnonymous";

/// <summary>
/// Whether the environment is a developer's machine rather than a deployment.
/// </summary>
/// <param name="environment">The host's environment.</param>
/// <returns>True for <c>Development</c> and <c>docker</c>.</returns>
public static bool IsLocal(IHostEnvironment environment)
{
return environment.IsDevelopment() || environment.IsEnvironment("docker");
}

/// <summary>
/// Throws when the app shouldn't start: a deployed environment without authentication, unless
/// <c>Authentication:AllowAnonymous</c> is true.
/// </summary>
/// <param name="environment">The host's environment.</param>
/// <param name="configuration">The settings to check.</param>
/// <exception cref="InvalidOperationException">The settings aren't safe to start with.</exception>
public static void EnsureSafeToStart(IHostEnvironment environment, IConfiguration configuration)
{
#if includeAuth
var authentication = AuthenticationSettings.FromConfiguration(configuration);

if (authentication.Enabled)
{
if (!Uri.TryCreate(authentication.Authority, UriKind.Absolute, out var authority) || authority.Scheme != Uri.UriSchemeHttps)
{
throw new InvalidOperationException(
$"Authentication:Authority must be an absolute https URL, such as https://login.example.com, not '{authentication.Authority}'.");
}

return;
}

#endif
if (IsLocal(environment) || configuration.GetValue<bool>(AllowAnonymousKey))
{
return;
}

#if includeAuth
throw new InvalidOperationException(
$"The '{environment.EnvironmentName}' environment has no authentication, so anyone could call it. Set Authentication:Authority, " +
$"or set {AllowAnonymousKey} to true to run it open on purpose.");
#else
throw new InvalidOperationException(
$"The '{environment.EnvironmentName}' environment has no authentication, so anyone could call it. " +
$"Set {AllowAnonymousKey} to true to run it open on purpose.");
#endif
}
}
7 changes: 4 additions & 3 deletions src/Presentation/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,13 @@
"ConnectionStrings": {
"MovieReviews": "Data Source=movie-reviews.db"
},
//#if (includeAuth)
"Authentication": {
//#if (includeAuth)
"Authority": "",
"Audience": ""
"Audience": "",
//#endif
"AllowAnonymous": false
},
//#endif
"AllowedHosts": "*",
"Database": {
"SeedSampleData": false
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
namespace CleanMinimalApi.Presentation.Tests.Integration.Security;

using System.Net;
using System.Threading.Tasks;
using Shouldly;
using Xunit;

public class DeploymentGuardTests
{
[Theory]
[InlineData("Production")]
[InlineData("uat")]
public void DeployedEnvironment_WithoutAuthentication_ShouldNotStart(string environment)
{
// Arrange
using var application = new MinimalApiApplication(environment);

// Act
var exception = Should.Throw<InvalidOperationException>(application.CreateClient);

// Assert
exception.Message.ShouldContain($"'{environment}' environment has no authentication");
exception.Message.ShouldContain("Authentication:AllowAnonymous");
}

[Theory]
[InlineData("Development")]
[InlineData("docker")]
public async Task LocalEnvironment_WithoutAuthentication_ShouldStart(string environment)
{
// Arrange
using var application = new MinimalApiApplication(environment);
using var client = application.CreateClient();

// Act
using var response = await client.GetAsync(new Uri("/health/live", UriKind.Relative));

// Assert
response.StatusCode.ShouldBe(HttpStatusCode.OK);
}

[Fact]
public async Task DeployedEnvironment_WithAllowAnonymous_ShouldStart()
{
// Arrange
using var application = new MinimalApiApplication("Production", new Dictionary<string, string?> { ["Authentication:AllowAnonymous"] = "true" });
using var client = application.CreateClient();

// Act
using var response = await client.GetAsync(new Uri("/health/live", UriKind.Relative));

// Assert
response.StatusCode.ShouldBe(HttpStatusCode.OK);
}
#if includeAuth

[Fact]
public async Task DeployedEnvironment_WithAuthority_ShouldStart()
{
// Arrange
using var application = new MinimalApiApplication("Production", new Dictionary<string, string?>
{
["Authentication:Authority"] = "https://login.example.com",
["Authentication:Audience"] = "https://api.example.com"
});
using var client = application.CreateClient();

// Act
using var response = await client.GetAsync(new Uri("/health/live", UriKind.Relative));

// Assert
response.StatusCode.ShouldBe(HttpStatusCode.OK);
}

[Theory]
[InlineData("http://login.example.com")]
[InlineData("login.example.com")]
public void AnyEnvironment_WithAuthorityThatIsNotHttps_ShouldNotStart(string authority)
{
// Arrange
using var application = new MinimalApiApplication(settings: new Dictionary<string, string?> { ["Authentication:Authority"] = authority });

// Act
var exception = Should.Throw<InvalidOperationException>(application.CreateClient);

// Assert
exception.Message.ShouldContain("Authentication:Authority must be an absolute https URL");
}
#endif
}
Loading