From 050b2fa90531733b5473cb45586e24855f38e18b Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:33:28 +0000 Subject: [PATCH 1/9] Bind every Compose port to 127.0.0.1 --- .agents/skills/docker-and-compose/SKILL.md | 2 +- docker-compose.yml | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.agents/skills/docker-and-compose/SKILL.md b/.agents/skills/docker-and-compose/SKILL.md index 9bcda42..bb3e225 100644 --- a/.agents/skills/docker-and-compose/SKILL.md +++ b/.agents/skills/docker-and-compose/SKILL.md @@ -19,7 +19,7 @@ One multi-stage `Dockerfile` does everything the pipeline needs: | `publish` | Publishes the Presentation project | | `run` | The runtime image: non-root `$APP_UID`, `WORKDIR /app`, data in `/app/data`, a `HEALTHCHECK` on `/health/live` | -`docker-compose.yml` runs the app with `DOTNET_ENVIRONMENT=docker`, the `movie-reviews-data` volume a pinned OpenTelemetry Collector that receives the app's OTLP logs, traces and metrics, configured by `otel-collector.yaml`, and a pinned Aspire dashboard the collector forwards them to (`telemetry`). The dashboard UI and the collector's OTLP ports are published on the template's own ports (below), so a `dotnet run` can send to the collector too. The dashboard runs with `ASPIRE_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS` and the collector's OTLP ports take anything sent to them, on purpose: the compose file is for a developer's machine, with nothing to sign in to. Keep it that way rather than adding sign-in, and don't offer the compose file for a shared or deployed environment. Images are built by CI but not pushed anywhere; the template ships the Dockerfile so users can. +`docker-compose.yml` runs the app with `DOTNET_ENVIRONMENT=docker`, the `movie-reviews-data` volume a pinned OpenTelemetry Collector that receives the app's OTLP logs, traces and metrics, configured by `otel-collector.yaml`, and a pinned Aspire dashboard the collector forwards them to (`telemetry`). The dashboard UI and the collector's OTLP ports are published on the template's own ports (below), so a `dotnet run` can send to the collector too. The dashboard runs with `ASPIRE_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS` and the collector's OTLP ports take anything sent to them, on purpose: the compose file is for a developer's machine, with nothing to sign in to. That's why every published port binds to `127.0.0.1`, as in `"127.0.0.1::18888"`, so nobody else on the same network can reach the app, the dashboard or the collector. Keep it that way rather than adding sign-in, and don't offer the compose file for a shared or deployed environment. Images are built by CI but not pushed anywhere; the template ships the Dockerfile so users can. The Lambda template's `run` stage is the AWS Lambda .NET base image instead. It runs as user `65534` from `/var/task`, keeps its database in `/tmp`, and has no `HEALTHCHECK`. Its compose file runs the collector and the Aspire dashboard as well. Compose maps the runtime interface emulator to 7350, so the function can be invoked with a `POST` to `/2015-03-31/functions/function/invocations`. diff --git a/docker-compose.yml b/docker-compose.yml index 3fda19c..d604e62 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,7 +7,7 @@ services: VERSION_PREFIX: 1.0.0.0 VERSION_SUFFIX: docker ports: - - "7350:8080" + - "127.0.0.1:7350:8080" environment: Database__SeedSampleData: "true" Serilog__MinimumLevel__Default: "Debug" @@ -20,13 +20,13 @@ services: volumes: - ./otel-collector.yaml:/etc/otelcol/config.yaml:ro ports: - - "7353:4317" - - "7354:4318" + - "127.0.0.1:7353:4317" + - "127.0.0.1:7354:4318" depends_on: - aspire-dashboard aspire-dashboard: image: mcr.microsoft.com/dotnet/aspire-dashboard:13.6.5 ports: - - "7352:18888" + - "127.0.0.1:7352:18888" environment: ASPIRE_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS: "true" From 302c14f53ec4061782fa761623c6004b861606e5 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:38:34 +0000 Subject: [PATCH 2/9] Read the telemetry service.version from VersionInfo --- .agents/skills/telemetry/SKILL.md | 2 +- src/Presentation/LambdaFunction/Startup.cs | 10 +++++----- .../Telemetry/TelemetrySettings.cs | 10 +++++----- .../Telemetry/TelemetrySettingsTests.cs | 19 +++++++++---------- 4 files changed, 20 insertions(+), 21 deletions(-) diff --git a/.agents/skills/telemetry/SKILL.md b/.agents/skills/telemetry/SKILL.md index 1c7e7ae..7e25043 100644 --- a/.agents/skills/telemetry/SKILL.md +++ b/.agents/skills/telemetry/SKILL.md @@ -25,7 +25,7 @@ Each layer publishes under its own name, and only the presentation layer's start | --- | --- | --- | | Application | `ApplicationTelemetry.Name` activity source: a span per use case, named after the request, tagged with `application.request.name` and `application.request.outcome` | `LoggingBehaviour`, with `System.Diagnostics` only, so Application stays free of telemetry packages | | Infrastructure | `Microsoft.EntityFrameworkCore` meter: queries, saves, active contexts, compiled query cache | Built into EF Core; startup subscribes to it by name | -| Presentation | `service.name`, `service.version` and `deployment.environment.name` on everything, plus its own instrumentation | `TelemetrySettings` and the startup's Telemetry region | +| Presentation | `service.name`, `service.version` and `deployment.environment.name` on everything, plus its own instrumentation | `TelemetrySettings`, which takes `service.version` from `VersionInfo`, and the startup's Telemetry region | What each presentation layer adds: diff --git a/src/Presentation/LambdaFunction/Startup.cs b/src/Presentation/LambdaFunction/Startup.cs index e8bcc9a..dbd23f9 100644 --- a/src/Presentation/LambdaFunction/Startup.cs +++ b/src/Presentation/LambdaFunction/Startup.cs @@ -1,6 +1,5 @@ namespace CleanLambdaFunction.Presentation.LambdaFunction; -using System.Reflection; using Amazon.Lambda.Annotations; using Application; using Application.Common.Telemetry; @@ -66,7 +65,8 @@ public HostApplicationBuilder ConfigureHostBuilder() #region Telemetry var assembly = typeof(Startup).Assembly; - var telemetry = TelemetrySettings.FromConfiguration(builder.Configuration, builder.Environment.EnvironmentName, assembly); + var version = VersionInfo.FromAssembly(assembly); + var telemetry = TelemetrySettings.FromConfiguration(builder.Configuration, builder.Environment.EnvironmentName, version); // The generated classes build two service providers from these services, one for the functions and one for // the host. The providers are built here, once, so both share them and nothing is exported twice. @@ -109,10 +109,10 @@ public HostApplicationBuilder ConfigureHostBuilder() .Enrich.WithProperty("ApplicationName", ApplicationName) .Enrich.WithProperty( "AssemblyVersion", - assembly.GetCustomAttribute()?.Version) + version.FileVersion) .Enrich.WithProperty( "AssemblyInformationalVersion", - assembly.GetCustomAttribute()?.InformationalVersion) + version.InformationalVersion) .WriteTo.Console(new RenderedCompactJsonFormatter()) .ReadFrom.Configuration(configuration); @@ -136,7 +136,7 @@ public HostApplicationBuilder ConfigureHostBuilder() _ = builder.Services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped); _ = builder.Services.AddInfrastructure(builder.Configuration.GetConnectionString("MovieReviews") ?? DefaultConnectionString); _ = builder.Services.AddApplication(); - _ = builder.Services.AddSingleton(VersionInfo.FromAssembly(typeof(Startup).Assembly)); + _ = builder.Services.AddSingleton(version); #endregion Services diff --git a/src/Presentation/LambdaFunction/Telemetry/TelemetrySettings.cs b/src/Presentation/LambdaFunction/Telemetry/TelemetrySettings.cs index 7164c85..2d6c0b6 100644 --- a/src/Presentation/LambdaFunction/Telemetry/TelemetrySettings.cs +++ b/src/Presentation/LambdaFunction/Telemetry/TelemetrySettings.cs @@ -1,6 +1,6 @@ namespace CleanLambdaFunction.Presentation.LambdaFunction.Telemetry; -using System.Reflection; +using Application.Versions.Entities; using Microsoft.Extensions.Configuration; /// @@ -16,7 +16,7 @@ public class TelemetrySettings /// The service.name on everything this app sends. public required string ServiceName { get; init; } - /// The service.version: the informational version of the presentation assembly. + /// The service.version: the informational version from , the same one the version endpoint returns. public required string ServiceVersion { get; init; } /// The deployment.environment.name, from DOTNET_ENVIRONMENT, or Production when it isn't set. @@ -41,16 +41,16 @@ public class TelemetrySettings /// /// The settings to read OTEL_SERVICE_NAME and OTEL_EXPORTER_OTLP_ENDPOINT from. /// The host's environment name. - /// The assembly whose informational version becomes service.version. + /// The app's version, whose informational version becomes service.version. /// The telemetry settings. - public static TelemetrySettings FromConfiguration(IConfiguration configuration, string environmentName, Assembly assembly) + public static TelemetrySettings FromConfiguration(IConfiguration configuration, string environmentName, VersionInfo version) { var serviceName = configuration["OTEL_SERVICE_NAME"]; return new TelemetrySettings { ServiceName = string.IsNullOrWhiteSpace(serviceName) ? DefaultServiceName : serviceName, - ServiceVersion = assembly.GetCustomAttribute()?.InformationalVersion ?? "unknown", + ServiceVersion = string.IsNullOrWhiteSpace(version.InformationalVersion) ? "unknown" : version.InformationalVersion, EnvironmentName = environmentName, OtlpEndpoint = configuration["OTEL_EXPORTER_OTLP_ENDPOINT"] }; diff --git a/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs b/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs index e2526e4..a3c361e 100644 --- a/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs +++ b/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs @@ -1,7 +1,6 @@ namespace CleanLambdaFunction.Presentation.Tests.Unit.Telemetry; -using System.Reflection; -using System.Reflection.Emit; +using Application.Versions.Entities; using Microsoft.Extensions.Configuration; using Presentation.LambdaFunction.Telemetry; using Shouldly; @@ -14,15 +13,15 @@ public void FromConfiguration_ShouldReturn_DisabledDefaults_WhenNothingIsSet() { // Arrange var configuration = new ConfigurationBuilder().Build(); - var assembly = typeof(TelemetrySettingsTests).Assembly; + var version = new VersionInfo { FileVersion = "1.2.3.0", InformationalVersion = "1.2.3+e30eba8" }; // Act - var result = TelemetrySettings.FromConfiguration(configuration, "local", assembly); + var result = TelemetrySettings.FromConfiguration(configuration, "local", version); // Assert result.Enabled.ShouldBeFalse(); result.ServiceName.ShouldBe(TelemetrySettings.DefaultServiceName); - result.ServiceVersion.ShouldBe(assembly.GetCustomAttribute()!.InformationalVersion); + result.ServiceVersion.ShouldBe("1.2.3+e30eba8"); result.EnvironmentName.ShouldBe("local"); } @@ -39,25 +38,25 @@ public void FromConfiguration_ShouldReturn_EnabledSettings_WhenEndpointIsSet() .Build(); // Act - var result = TelemetrySettings.FromConfiguration(configuration, "docker", typeof(TelemetrySettingsTests).Assembly); + var result = TelemetrySettings.FromConfiguration(configuration, "docker", new VersionInfo { FileVersion = "1.2.3.0", InformationalVersion = "1.2.3" }); // Assert result.Enabled.ShouldBeTrue(); result.OtlpEndpoint.ShouldBe("http://aspire-dashboard:18889"); result.ResourceAttributes["service.name"].ShouldBe("movie-reviews"); - result.ResourceAttributes["service.version"].ShouldBe(result.ServiceVersion); + result.ResourceAttributes["service.version"].ShouldBe("1.2.3"); result.ResourceAttributes["deployment.environment.name"].ShouldBe("docker"); } [Fact] - public void FromConfiguration_ShouldReturn_UnknownVersion_WhenAssemblyHasNone() + public void FromConfiguration_ShouldReturn_UnknownVersion_WhenVersionIsEmpty() { // Arrange var configuration = new ConfigurationBuilder().Build(); - var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("NoVersion"), AssemblyBuilderAccess.Run); + var version = VersionInfo.FromAssembly(null); // Act - var result = TelemetrySettings.FromConfiguration(configuration, "local", assembly); + var result = TelemetrySettings.FromConfiguration(configuration, "local", version); // Assert result.ServiceVersion.ShouldBe("unknown"); From 6b8ca20000140434de5283710c4d0226989b66c1 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Fri, 4 Dec 2026 23:46:01 +0000 Subject: [PATCH 3/9] Throttle the Lambda HTTP API --- .agents/skills/security-defaults/SKILL.md | 31 +++++++++++++++++++++++ AGENTS.md | 1 + README.md | 2 +- docs/RUN.md | 2 +- src/Presentation/serverless.template | 8 ++++++ 5 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 .agents/skills/security-defaults/SKILL.md diff --git a/.agents/skills/security-defaults/SKILL.md b/.agents/skills/security-defaults/SKILL.md new file mode 100644 index 0000000..d789f92 --- /dev/null +++ b/.agents/skills/security-defaults/SKILL.md @@ -0,0 +1,31 @@ +--- +name: security-defaults +description: What this Lambda function does to be safe by default - IAM on direct invocations, throttling on the public HTTP API routes, and where an authorizer would go. Use when adding an HTTP route, changing throttling or access, or asked whether the function is safe to deploy. +metadata: + scope: presentation +--- + +# Security defaults (Lambda Function) + +## The rule + +The function has no authentication code of its own. AWS does the guarding, in `src/Presentation/serverless.template`, so keep it there rather than checking callers in a handler. + +| Protection | Where | Default | +| --- | --- | --- | +| Direct invocations | AWS IAM | Only callers with `lambda:InvokeFunction` | +| HTTP API routes | `Globals.HttpApi.DefaultRouteSettings` | Public, throttled to 50 requests a second, bursts of 100 | +| Compose ports on `127.0.0.1` | `docker-compose.yml` (`docker-and-compose`) | Always | + +The HTTP routes are read only and public on purpose, so a browser or `curl` can call them. The throttle is there so a busy caller can't run up the bill. It applies to every route on the stack's implicit HTTP API, so a new `[HttpApi]` function gets it without anything else. + +## Steps + +1. Change the limits in `Globals.HttpApi.DefaultRouteSettings`. Lambda Annotations rewrites the functions in `serverless.template` on build but leaves `Globals` alone. +2. To require a token, add a JWT authorizer to the HTTP API in `serverless.template` (see the AWS guide for HTTP API JWT authorizers) rather than reading headers in a handler. +3. Check the template still deploys: `cfn-lint src/Presentation/serverless.template`, if you have it, runs the same transform CloudFormation does. + +## Check + +- [ ] New HTTP routes go on the stack's HTTP API, so the throttle covers them. +- [ ] Nothing in a handler decides who may call it. diff --git a/AGENTS.md b/AGENTS.md index 76996d2..32eb00d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -130,6 +130,7 @@ These are for this Lambda function's presentation layer. The other templates hav | `api-conventions` | Name a function, shape its request or response, or decide how a failure reaches the caller | | `json-serialization` | Add a request or response type, or change how JSON looks | | `presentation-integration-tests` | Write a test that calls the handler | +| `security-defaults` | Add an HTTP route, change throttling or access, or check what the function does to stay safe | | `lambda-emulator` | Invoke the function by hand as Lambda would | diff --git a/README.md b/README.md index 135a9ab..3a9bd53 100644 --- a/README.md +++ b/README.md @@ -98,7 +98,7 @@ When you're ready for the real thing, fill in your profile, region and stack nam The lists also come over HTTP. `HttpGetMovies`, `HttpGetAuthors` and `HttpGetReviews` sit behind an API Gateway HTTP API at `GET /movies`, `GET /authors` and `GET /reviews`, taking `query`, `offset` and `limit` (or `movieId` and `authorId`) from the query string. They answer `200` with the page, or `400` with problem details when the request doesn't add up. The deployed stack prints the URL as `ApiUrl`. -Direct invocations are guarded by AWS IAM, and the HTTP routes are open until you say otherwise. Want bearer tokens? Add a JWT authorizer to the HTTP API. Either way, the bouncer stands outside the door, not inside your code. +Direct invocations are guarded by AWS IAM. The HTTP routes are open until you say otherwise, but throttled to 50 requests a second with bursts of 100, so a keen caller can't run up your bill. Want bearer tokens? Add a [JWT authorizer](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html) to the HTTP API. Either way, the bouncer stands outside the door, not inside your code. ## What's inside diff --git a/docs/RUN.md b/docs/RUN.md index 158dcbd..fb4aecb 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -96,7 +96,7 @@ dotnet test ## Deploying to AWS -`src/Presentation/serverless.template` is a CloudFormation template with a Lambda function for each handler method, all running the same container image. Lambda Annotations writes each function into it when the project builds, so a new function appears there by itself. The three `Http*` functions also get a route on the stack's API Gateway HTTP API, and the stack's `ApiUrl` output is its address. Add any other resources you need beside them. +`src/Presentation/serverless.template` is a CloudFormation template with a Lambda function for each handler method, all running the same container image. Lambda Annotations writes each function into it when the project builds, so a new function appears there by itself. The three `Http*` functions also get a route on the stack's API Gateway HTTP API, and the stack's `ApiUrl` output is its address. The routes are public, so `Globals` throttles every one of them to 50 requests a second with bursts of 100; change `DefaultRouteSettings` to suit. To ask for a token, add a [JWT authorizer](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html) to the HTTP API. Add any other resources you need beside them. `src/Presentation/aws-lambda-tools-defaults.json` holds the defaults for the [Amazon.Lambda.Tools](https://github.com/aws/aws-extensions-for-dotnet-cli) CLI. Fill in your profile, region and stack name, then deploy the stack. The CLI builds the image from the Dockerfile, pushes it to Amazon ECR and creates or updates every function in one go. diff --git a/src/Presentation/serverless.template b/src/Presentation/serverless.template index 3d5bd20..8416a7c 100644 --- a/src/Presentation/serverless.template +++ b/src/Presentation/serverless.template @@ -2,6 +2,14 @@ "AWSTemplateFormatVersion": "2010-09-09", "Transform": "AWS::Serverless-2016-10-31", "Description": "The movie reviews functions: one container image, with a Lambda function for each handler method.", + "Globals": { + "HttpApi": { + "DefaultRouteSettings": { + "ThrottlingRateLimit": 50, + "ThrottlingBurstLimit": 100 + } + } + }, "Resources": { "GetMovies": { "Type": "AWS::Serverless::Function", From ba3597be3bab49180e4ee5c97f1f45b3b3413935 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:01:32 +0000 Subject: [PATCH 4/9] Run dotnet run in the Development environment --- .agents/skills/configuration-and-environments/SKILL.md | 6 +++--- .agents/skills/sample-data/SKILL.md | 2 +- .agents/skills/serilog/SKILL.md | 4 ++-- .../Telemetry/TelemetrySettingsTests.cs | 6 +++--- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.agents/skills/configuration-and-environments/SKILL.md b/.agents/skills/configuration-and-environments/SKILL.md index 9bd1fae..f9bf0e4 100644 --- a/.agents/skills/configuration-and-environments/SKILL.md +++ b/.agents/skills/configuration-and-environments/SKILL.md @@ -1,6 +1,6 @@ --- name: configuration-and-environments -description: How settings are layered with appsettings files and environment variables, what the local and docker environments are, and how to add a new setting. Use when adding configuration, a connection string or environment-specific behaviour. +description: How settings are layered with appsettings files and environment variables, what the Development and docker environments are, and how to add a new setting. Use when adding configuration, a connection string or environment-specific behaviour. metadata: scope: shared --- @@ -15,7 +15,7 @@ The Lambda template has no appsettings files or environments. Its startup builds | Environment | Set by | Used for | | --- | --- | --- | -| `local` | `launchSettings.json` (`DOTNET_ENVIRONMENT=local`) | `dotnet run` on a developer machine: console logs, sample data on | +| `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 | @@ -39,7 +39,7 @@ Settings that exist today: ## Don't - Put secrets, passwords or tokens in any `appsettings*.json` file. Use environment variables or user secrets. -- Check `IsEnvironment("local")` for behaviour that should be a setting. Add a setting instead. +- Check `IsDevelopment()` or `IsEnvironment("docker")` for behaviour that should be a setting. Add a setting instead. - Read `Environment.GetEnvironmentVariable` directly. Go through `IConfiguration`. ## Check diff --git a/.agents/skills/sample-data/SKILL.md b/.agents/skills/sample-data/SKILL.md index 614c449..bbba8e9 100644 --- a/.agents/skills/sample-data/SKILL.md +++ b/.agents/skills/sample-data/SKILL.md @@ -16,7 +16,7 @@ There are two kinds of data, and they never mix. | Sample data | `src/Infrastructure/Databases/MovieReviews/Extensions/MovieReviewsDbContextExtensions.cs` (`AddData`) | Local runs, Docker and the presentation integration tests | 15 authors, 50 movies, 150 reviews from Bogus with a fixed seed | | Test data | `tests/Infrastructure.Tests.Integration/Databases/MovieReviews/Extensions/MovieReviewsCollectionData.cs` (`AddTestData`) | Repository tests | A handful of hand-written rows named "One", "Two", "Three" so assertions can find them | -Sample data is only added when `Database:SeedSampleData` is `true` (on in `appsettings.local.json` and `appsettings.docker.json`, off in `appsettings.json`; Lambda turns it on only in `docker-compose.yml`) and the database is empty. A deployed copy never starts with fake data. +Sample data is only added when `Database:SeedSampleData` is `true` (on in `appsettings.Development.json` and `appsettings.docker.json`, off in `appsettings.json`; Lambda turns it on only in `docker-compose.yml`) and the database is empty. A deployed copy never starts with fake data. ## Steps diff --git a/.agents/skills/serilog/SKILL.md b/.agents/skills/serilog/SKILL.md index 857d8ed..464fcbb 100644 --- a/.agents/skills/serilog/SKILL.md +++ b/.agents/skills/serilog/SKILL.md @@ -13,7 +13,7 @@ Serilog is the logger. Application and Infrastructure code log through `Microsof | Environment | Sink | Where to look | | --- | --- | --- | -| `local` | Console, with the output template in `appsettings.local.json` | The terminal | +| `Development` | Console, with the output template in `appsettings.Development.json` | The terminal | | `docker` | Console, and OTLP through the collector to the Aspire dashboard | The Aspire dashboard, on the port `docs/RUN.md` lists, or `docker compose logs` | | Lambda, anywhere | Console, as compact JSON, and OTLP when the endpoint is set | CloudWatch Logs, or `docker compose logs` for the emulator, and the Aspire dashboard in Docker Compose | | Any, when `OTEL_EXPORTER_OTLP_ENDPOINT` is set | Also OTLP, through `Serilog.Sinks.OpenTelemetry` | Whatever receives the OTLP (`telemetry`) | @@ -29,7 +29,7 @@ Every event carries these properties: | `AssemblyVersion`, `AssemblyInformationalVersion` | Added in code at startup | | Anything pushed with `LogContext` | `FromLogContext` | -Levels are set in configuration, never in code: `Information` by default and `Debug` in `local`, with `Information` for `Microsoft`, `Warning` for `Microsoft.AspNetCore` and `Microsoft.EntityFrameworkCore.Database.Command` (a line per SQL statement buries everything else, and EF Core's meter already counts them), and `Error` for `System`. The built-in `Logging` section is set to `None` so nothing is written twice. +Levels are set in configuration, never in code: `Information` by default and `Debug` in `Development`, with `Information` for `Microsoft`, `Warning` for `Microsoft.AspNetCore` and `Microsoft.EntityFrameworkCore.Database.Command` (a line per SQL statement buries everything else, and EF Core's meter already counts them), and `Error` for `System`. The built-in `Logging` section is set to `None` so nothing is written twice. Three things log a request, and each says something the others don't: diff --git a/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs b/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs index a3c361e..9a1b67a 100644 --- a/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs +++ b/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs @@ -16,13 +16,13 @@ public void FromConfiguration_ShouldReturn_DisabledDefaults_WhenNothingIsSet() var version = new VersionInfo { FileVersion = "1.2.3.0", InformationalVersion = "1.2.3+e30eba8" }; // Act - var result = TelemetrySettings.FromConfiguration(configuration, "local", version); + var result = TelemetrySettings.FromConfiguration(configuration, "Development", version); // Assert result.Enabled.ShouldBeFalse(); result.ServiceName.ShouldBe(TelemetrySettings.DefaultServiceName); result.ServiceVersion.ShouldBe("1.2.3+e30eba8"); - result.EnvironmentName.ShouldBe("local"); + result.EnvironmentName.ShouldBe("Development"); } [Fact] @@ -56,7 +56,7 @@ public void FromConfiguration_ShouldReturn_UnknownVersion_WhenVersionIsEmpty() var version = VersionInfo.FromAssembly(null); // Act - var result = TelemetrySettings.FromConfiguration(configuration, "local", version); + var result = TelemetrySettings.FromConfiguration(configuration, "Development", version); // Assert result.ServiceVersion.ShouldBe("unknown"); From 03653a738ad55957b2476de916b46966d9f2ea1c Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:08:14 +0000 Subject: [PATCH 5/9] Run the image as Production unless told otherwise --- .agents/skills/configuration-and-environments/SKILL.md | 5 +++-- .agents/skills/optional-token-auth/SKILL.md | 2 ++ Dockerfile | 2 +- docker-compose.yml | 1 + 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.agents/skills/configuration-and-environments/SKILL.md b/.agents/skills/configuration-and-environments/SKILL.md index f9bf0e4..3f9b296 100644 --- a/.agents/skills/configuration-and-environments/SKILL.md +++ b/.agents/skills/configuration-and-environments/SKILL.md @@ -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: @@ -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 diff --git a/.agents/skills/optional-token-auth/SKILL.md b/.agents/skills/optional-token-auth/SKILL.md index b8741ef..a750d70 100644 --- a/.agents/skills/optional-token-auth/SKILL.md +++ b/.agents/skills/optional-token-auth/SKILL.md @@ -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. diff --git a/Dockerfile b/Dockerfile index d273054..120226c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,7 +12,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} diff --git a/docker-compose.yml b/docker-compose.yml index d604e62..b9d1554 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,6 +9,7 @@ services: ports: - "127.0.0.1:7350:8080" environment: + DOTNET_ENVIRONMENT: docker Database__SeedSampleData: "true" Serilog__MinimumLevel__Default: "Debug" OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4317 From f6d9c62771d692e940a013c87dfbcb8e25f7246c Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:22:11 +0000 Subject: [PATCH 6/9] Describe development tokens in the auth skill --- .agents/skills/optional-token-auth/SKILL.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.agents/skills/optional-token-auth/SKILL.md b/.agents/skills/optional-token-auth/SKILL.md index a750d70..93a43d5 100644 --- a/.agents/skills/optional-token-auth/SKILL.md +++ b/.agents/skills/optional-token-auth/SKILL.md @@ -13,7 +13,9 @@ Authentication is a choice made when the solution is created. With `--include-au With `--include-auth`, endpoints always ask for authorization. An empty `Authentication:Authority` still runs everything open, because the default policy then lets every request through, which is how the tests run unless they set an authority. Only health checks and the API reference (where a template has them) are anonymous. The version endpoint is protected like everything else; telemetry carries `service.version` for anyone who needs to know what's deployed. The Lambda template has no token authentication; API Gateway or the caller's IAM role does that job. -Settings are read through `AuthenticationSettings.FromConfiguration` (`Enabled` is true when the authority isn't empty). +Settings are read through `AuthenticationSettings.FromConfiguration`. `Enabled` is true when the authority isn't empty or `dotnet user-jwts` is set up. + +For a token on a developer's machine, `dotnet user-jwts create --project src/Presentation` writes `Authentication:Schemes:Bearer` (issuer and audiences) into `appsettings.Development.json` and the signing key into user secrets. When that issuer is there, `UsesDevelopmentTokens` is true and wins over the authority: the JWT bearer handler gets no authority and reads the issuer, audiences and key from that section by itself. Both files only load in `Development`, so deployed copies keep using the authority. `DevelopmentTokenTests` sets the same keys in memory and signs a token with them. 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`). From 8815116f6e9a36c993ec19e79861e5ed719b83a5 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:46:54 +0000 Subject: [PATCH 7/9] Describe the rate limiting toggle in the shared skills --- .agents/skills/configuration-and-environments/SKILL.md | 1 + .agents/skills/template-authoring/SKILL.md | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.agents/skills/configuration-and-environments/SKILL.md b/.agents/skills/configuration-and-environments/SKILL.md index 3f9b296..c1572e5 100644 --- a/.agents/skills/configuration-and-environments/SKILL.md +++ b/.agents/skills/configuration-and-environments/SKILL.md @@ -27,6 +27,7 @@ Settings that exist today: | `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. | +| `RateLimiting:PermitLimit`, `RateLimiting:Window` | Web templates, only in a solution created with `--include-rate-limiting`: requests each client IP address may make in each window. `0`, the default, leaves the limiter off (`security-defaults`). | | `Serilog:*` | Logging (`serilog`). | ## Steps diff --git a/.agents/skills/template-authoring/SKILL.md b/.agents/skills/template-authoring/SKILL.md index d7d7df2..8e153c5 100644 --- a/.agents/skills/template-authoring/SKILL.md +++ b/.agents/skills/template-authoring/SKILL.md @@ -15,6 +15,7 @@ The repository is both a working solution and a `dotnet new` template. `.templat | --- | --- | --- | | `authorName` | `--authorName`
`-an` | `Stephen Walsh` (`--author` is reserved by `dotnet new`) | | `includeAuth` | `--include-auth` | Nothing. A toggle, off by default. Off, every line of authentication code is left out; on, `authority` and `audience` switch on through `isEnabled` and `authority` becomes required through `isRequired` (web templates) | +| `includeRateLimiting` | `--include-rate-limiting` | Nothing. A toggle, off by default. Off, the `RateLimiting` folders and every line that wires them in are left out; on, the limiter is still off until `RateLimiting:PermitLimit` is set (web templates) | | `authority` | `--authority`
`-iss` | The empty `Authentication:Authority` setting in `appsettings.json`, only with `--include-auth`. Passed without it, it's ignored without a word (web templates) | | `audience` | `--audience`
`-aud` | The empty `Authentication:Audience` setting in `appsettings.json`, only with `--include-auth`. Passed without it, it's ignored without a word (web templates) | | `skipRestore` | `--no-restore` | Nothing; it turns the restore post action off | @@ -95,4 +96,4 @@ The README and `NUGET.md` name the aliases under the install commands, and the d ## Check -The Test job's Verify Template step installs the packed template, generates a solution and checks that nothing of the template leaked into it (no `includeAuth` markers, no trace of the template's own name, no `icon.png`) and that it has `README.md` and `.github/workflows/ci.yml`, then checks its format and runs its tests. Where the template has `--include-auth` it does it again with the toggle on, and checks that `--include-auth` without `--authority` is refused with exit code 102. +The Test job's Verify Template step installs the packed template, generates a solution and checks that nothing of the template leaked into it (no toggle markers such as `includeAuth`, no trace of the template's own name, no `icon.png`) and that it has `README.md` and `.github/workflows/ci.yml`, then checks its format and runs its tests. Where the template has `--include-auth` it does it again with every toggle on, and checks that `--include-auth` without `--authority` is refused with exit code 102. Where it has `--include-rate-limiting` it also verifies a solution with only that toggle on. From cad879fd4653ab5d293d4dd2de3c6ca3a3699837 Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sat, 5 Dec 2026 20:29:15 +0000 Subject: [PATCH 8/9] Update the shared skills for development tokens --- .agents/skills/optional-token-auth/SKILL.md | 2 +- .agents/skills/time-provider/SKILL.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.agents/skills/optional-token-auth/SKILL.md b/.agents/skills/optional-token-auth/SKILL.md index 93a43d5..72af74a 100644 --- a/.agents/skills/optional-token-auth/SKILL.md +++ b/.agents/skills/optional-token-auth/SKILL.md @@ -15,7 +15,7 @@ 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 or `dotnet user-jwts` is set up. -For a token on a developer's machine, `dotnet user-jwts create --project src/Presentation` writes `Authentication:Schemes:Bearer` (issuer and audiences) into `appsettings.Development.json` and the signing key into user secrets. When that issuer is there, `UsesDevelopmentTokens` is true and wins over the authority: the JWT bearer handler gets no authority and reads the issuer, audiences and key from that section by itself. Both files only load in `Development`, so deployed copies keep using the authority. `DevelopmentTokenTests` sets the same keys in memory and signs a token with them. +For a token on a developer's machine, `dotnet user-jwts create --project src/Presentation` writes `Authentication:Schemes:Bearer` (issuer and audiences) into `appsettings.Development.json` and the signing key into user secrets. When that issuer is there, `UsesDevelopmentTokens` is true and wins over the authority: the JWT bearer handler gets no authority and reads the issuer, audiences and key from that section by itself. Both files only load in `Development`, and `DeploymentGuard` refuses to start with that issuer set in any other environment, so deployed copies keep using the authority. `DevelopmentTokenTests` sets the same keys in memory and signs a token with them. 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`). diff --git a/.agents/skills/time-provider/SKILL.md b/.agents/skills/time-provider/SKILL.md index e5f270c..f45016e 100644 --- a/.agents/skills/time-provider/SKILL.md +++ b/.agents/skills/time-provider/SKILL.md @@ -54,7 +54,7 @@ updatedReview.DateModified.ShouldBe(this.database.TimeProvider.GetUtcNow().UtcDa - Store local times. - Assert a date with a tolerance ("within a second of now"). Fix the clock and assert the exact value. -The one exception, in a solution with authentication, is the test that creates a token for the real JWT handler, which checks expiry against the system clock (`tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs`, in the templates that have token authentication). +The one exception, in a solution with authentication, is the tests that create a token for the real JWT handler, which checks expiry against the system clock (`AuthenticationTests.cs` and `DevelopmentTokenTests.cs` in `tests/Presentation.Tests.Integration/Authentication`, in the templates that have token authentication). ## Check From 088e01d9d5b4a9d7e99dd1ae9a7c2ae495be8d2c Mon Sep 17 00:00:00 2001 From: Stephen Walsh <868017+stphnwlsh@users.noreply.github.com> Date: Sun, 6 Dec 2026 02:57:44 +0000 Subject: [PATCH 9/9] Say the audience is required with authentication Keeps the shared skills in step with the web templates, where --audience is now required with --include-auth. --- .agents/skills/optional-token-auth/SKILL.md | 4 ++-- .agents/skills/template-authoring/SKILL.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.agents/skills/optional-token-auth/SKILL.md b/.agents/skills/optional-token-auth/SKILL.md index 72af74a..65d4b1e 100644 --- a/.agents/skills/optional-token-auth/SKILL.md +++ b/.agents/skills/optional-token-auth/SKILL.md @@ -9,7 +9,7 @@ metadata: ## The rule -Authentication is a choice made when the solution is created. With `--include-auth`, `--authority` and usually `--audience`, every request needs a valid JWT bearer token from that authority (an OAuth access token in the MCP server), and those options fill in `Authentication:Authority` and `Authentication:Audience`. Without `--include-auth` there's no authentication code at all: no settings, no package, no policy and nothing asking for authorization. If `AuthenticationSettings` isn't in the solution, it was created without `--include-auth`; see "Adding it later". +Authentication is a choice made when the solution is created. With `--include-auth`, `--authority` and `--audience`, every request needs a valid JWT bearer token from that authority (an OAuth access token in the MCP server), and those options fill in `Authentication:Authority` and `Authentication:Audience`. Without `--include-auth` there's no authentication code at all: no settings, no package, no policy and nothing asking for authorization. If `AuthenticationSettings` isn't in the solution, it was created without `--include-auth`; see "Adding it later". With `--include-auth`, endpoints always ask for authorization. An empty `Authentication:Authority` still runs everything open, because the default policy then lets every request through, which is how the tests run unless they set an authority. Only health checks and the API reference (where a template has them) are anonymous. The version endpoint is protected like everything else; telemetry carries `service.version` for anyone who needs to know what's deployed. The Lambda template has no token authentication; API Gateway or the caller's IAM role does that job. @@ -17,7 +17,7 @@ Settings are read through `AuthenticationSettings.FromConfiguration`. `Enabled` For a token on a developer's machine, `dotnet user-jwts create --project src/Presentation` writes `Authentication:Schemes:Bearer` (issuer and audiences) into `appsettings.Development.json` and the signing key into user secrets. When that issuer is there, `UsesDevelopmentTokens` is true and wins over the authority: the JWT bearer handler gets no authority and reads the issuer, audiences and key from that section by itself. Both files only load in `Development`, and `DeploymentGuard` refuses to start with that issuer set in any other environment, so deployed copies keep using the authority. `DevelopmentTokenTests` sets the same keys in memory and signs a token with them. -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`). +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 and comes with an audience (`security-defaults`). ## Steps diff --git a/.agents/skills/template-authoring/SKILL.md b/.agents/skills/template-authoring/SKILL.md index 7ca5234..32dbdc3 100644 --- a/.agents/skills/template-authoring/SKILL.md +++ b/.agents/skills/template-authoring/SKILL.md @@ -14,7 +14,7 @@ The repository is both a working solution and a `dotnet new` template. `.templat | Symbol | Option | Replaces | | --- | --- | --- | | `authorName` | `--authorName`
`-an` | `Stephen Walsh` (`--author` is reserved by `dotnet new`) | -| `includeAuth` | `--include-auth` | Nothing. A toggle, off by default. Off, every line of authentication code is left out; on, `authority` and `audience` switch on through `isEnabled` and `authority` becomes required through `isRequired` (web templates) | +| `includeAuth` | `--include-auth` | Nothing. A toggle, off by default. Off, every line of authentication code is left out; on, `authority` and `audience` switch on through `isEnabled` and both become required through `isRequired` (web templates) | | `includeRateLimiting` | `--include-rate-limiting` | Nothing. A toggle, off by default. Off, the `RateLimiting` folders and every line that wires them in are left out; on, the limiter is still off until `RateLimiting:PermitLimit` is set (web templates) | | `authority` | `--authority`
`-iss` | The empty `Authentication:Authority` setting in `appsettings.json`, only with `--include-auth`. Passed without it, it's ignored without a word (web templates) | | `audience` | `--audience`
`-aud` | The empty `Authentication:Audience` setting in `appsettings.json`, only with `--include-auth`. Passed without it, it's ignored without a word (web templates) | @@ -74,7 +74,7 @@ The README and `NUGET.md` name the aliases under the install commands, and the d dotnet new uninstall ./ ``` - With `--include-auth`, also create one with `--include-auth --authority https://login.example.com --output ../Secured` and test that. Leave the authority out and `dotnet new` should stop with exit code 102. + With `--include-auth`, also create one with `--include-auth --authority https://login.example.com --audience https://api.example.com --output ../Secured` and test that. Leave the authority or the audience out and `dotnet new` should stop with exit code 102. `--help` shows the short flags and descriptions. Creating the solution should end with `Restoring .../Sample.slnx` and `Restore succeeded`, which is the post action at work; `--no-restore` should skip it.