Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
ae45ac9
Bind every Compose port to 127.0.0.1
stphnwlsh Dec 4, 2026
36b4937
Read the telemetry service.version from VersionInfo
stphnwlsh Dec 4, 2026
81b8e98
Send security headers on every response
stphnwlsh Dec 4, 2026
9716593
Check the Origin header on the MCP endpoint
stphnwlsh Dec 4, 2026
cda82b0
Run dotnet run in the Development environment
stphnwlsh Dec 5, 2026
7397c53
Refuse to start a deployed copy with auth off
stphnwlsh Dec 5, 2026
fb35718
Accept dotnet user-jwts tokens in Development
stphnwlsh Dec 5, 2026
ea7912d
Add optional rate limiting
stphnwlsh Dec 5, 2026
b8b5592
Merge remote-tracking branch 'origin/main' into fix/compose-ports-loc…
stphnwlsh Dec 5, 2026
70eb299
Merge branch 'fix/compose-ports-localhost' into feature/telemetry-ver…
stphnwlsh Dec 5, 2026
7143298
Merge branch 'feature/telemetry-version-from-versioninfo' into featur…
stphnwlsh Dec 5, 2026
bcd8adc
Merge branch 'feature/security-headers' into feature/mcp-origin-check
stphnwlsh Dec 5, 2026
e396937
Merge branch 'feature/mcp-origin-check' into feature/development-envi…
stphnwlsh Dec 5, 2026
288a095
Merge branch 'feature/development-environment' into feature/refuse-de…
stphnwlsh Dec 5, 2026
d5959b5
Merge branch 'feature/refuse-deployed-without-auth' into feature/deve…
stphnwlsh Dec 5, 2026
ec6b2eb
Merge branch 'feature/development-tokens' into feature/optional-rate-…
stphnwlsh Dec 5, 2026
1ba670a
Log a refused Origin
stphnwlsh Dec 5, 2026
42abad5
Keep development tokens to the Development environment
stphnwlsh Dec 5, 2026
db0d951
Say what a deployed copy does without authentication
stphnwlsh Dec 5, 2026
94dcbf5
Merge remote-tracking branch 'origin/main' into feature/optional-rate…
stphnwlsh Dec 5, 2026
1072279
Refuse to start when an authority has no audience
stphnwlsh Dec 6, 2026
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
12 changes: 7 additions & 5 deletions .agents/skills/configuration-and-environments/SKILL.md
Original file line number Diff line number Diff line change
@@ -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
---
Expand All @@ -15,9 +15,9 @@ 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 |
| `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 |
| `Development` | `launchSettings.json` (`DOTNET_ENVIRONMENT=Development`) | `dotnet run` on a developer machine: console logs, sample data 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,8 @@ 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. |
| `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
Expand All @@ -39,7 +41,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
Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/docker-and-compose/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:<host port>: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`.

Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/mcp-inspector/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ metadata:
3. After changing a tool, check its description and every argument's description read well, the annotations are right, and a call returns the result model you expect.
4. Try the failure paths too: an unknown id, a star rating of 6. The model should get a message it can act on.
5. Find the tool call in the Aspire dashboard if something looks wrong: its trace shows the tool, the use case and each SQL command, and its logs sit beside it (`telemetry`).
6. With authentication on, the Inspector needs a token from your authority. Leave `Authentication:Authority` empty for local checks.
6. With authentication on, the Inspector needs a token. For local checks, run `dotnet user-jwts create --project src/Presentation` and paste the token under **Authentication**, **Bearer Token** (`optional-token-auth`), or leave `Authentication:Authority` empty.

## Chat demo

Expand Down
8 changes: 6 additions & 2 deletions .agents/skills/optional-token-auth/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@ 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.

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`, 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 and comes with an audience (`security-defaults`).

## Steps

Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/presentation-integration-tests/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ metadata:

## The rule

`tests/Presentation.Tests.Integration` talks to the whole server the way a real client does. `ModelContextProtocolApplication` (a `WebApplicationFactory<Program>`) starts the server with the `local` environment, its own shared-cache in-memory SQLite database and the sample data on. `BaseToolTests` connects an `McpClient` to it over the streamable HTTP transport before each test and disposes both after.
`tests/Presentation.Tests.Integration` talks to the whole server the way a real client does. `ModelContextProtocolApplication` (a `WebApplicationFactory<Program>`) starts the server with the `Development` environment, its own shared-cache in-memory SQLite database and the sample data on. `BaseToolTests` connects an `McpClient` to it over the streamable HTTP transport before each test and disposes both after.

| Helper | Use it to |
| --- | --- |
Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/sample-data/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
83 changes: 83 additions & 0 deletions .agents/skills/security-defaults/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
---
name: security-defaults
description: What this MCP server does to be safe by default - the startup guard for deployed environments, the security response headers, the Origin check on /mcp, optional rate limiting and where the other protections live. Use when adding a response header, turning on or tuning rate limiting, letting a browser client in with Mcp:AllowedOrigins, changing security middleware, or asked whether the app is safe to deploy.
metadata:
scope: presentation
---

# Security defaults (MCP server)

## The rule

The app ships safe by default, and each protection lives in one place in `src/Presentation/Security/`, switched on in the Security region of `WebApplicationExtensions.ConfigureApplication`. Keep that shape: a new protection gets its own small class there and a line in that region, never a check scattered across endpoints.

| Protection | Where | Default |
| --- | --- | --- |
| Refuse to start deployed and open | `DeploymentGuard` | On; `Authentication:AllowAnonymous` opts out |
| Security response headers | `SecurityHeaders` | Always on |
| `Origin` check on `/mcp` | `OriginCheck` | No `Origin` or localhost only, plus `Mcp:AllowedOrigins` |
| Rate limiting per client IP address | `RateLimiting/` | Only with `--include-rate-limiting`, and off until `RateLimiting:PermitLimit` is set |
| 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 and come with an `Authentication:Audience`, in every environment. Without an audience every token would be rejected, so the app stops at startup and says so.
- In a solution with authentication, `dotnet user-jwts` development tokens (`Authentication:Schemes:Bearer:ValidIssuer`) set up outside `Development` throw at startup, because they replace the authority.

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:

| Header | Value | Why |
| --- | --- | --- |
| `X-Content-Type-Options` | `nosniff` | Browsers use the declared content type instead of guessing |
| `X-Frame-Options` | `DENY` | No other site can show the app in a frame |
| `Referrer-Policy` | `no-referrer` | Links out of the app don't leak its URLs |

There's no `Content-Security-Policy` on purpose. The headers are set in `Response.OnStarting`, because the exception handler clears headers set before it runs.

## Origin check

The MCP spec says a Streamable HTTP server must check the `Origin` header, so a web page can't reach a server on the developer's machine by DNS rebinding. `UseOriginCheck` guards `/mcp` and nothing else:

- No `Origin` header: allowed. Desktop clients and server-side clients don't send one.
- `http` or `https` on `localhost`, `127.0.0.1` or `[::1]`, any port: allowed. That covers the MCP Inspector and the chat demo.
- An origin listed in `Mcp:AllowedOrigins`, matched exactly: allowed.
- Anything else, including `null`: 403 before authentication runs.

To let a web page on another host in, add its origin to `Mcp:AllowedOrigins` in settings; a page on a different origin from the server also needs a CORS policy, which isn't here. A refused origin is logged as a warning, because the check runs before request logging. Don't widen `IsAllowed` itself, and don't set `AllowedHosts` to work around it. Unit tests for `IsAllowed` live in `tests/Presentation.Tests.Unit/Security/`, and `tests/Presentation.Tests.Integration/Security/OriginCheckTests.cs` sends real requests.

## Rate limiting

A solution created with `--include-rate-limiting` has a fixed window limiter in `src/Presentation/RateLimiting/`, wired in by `WebApplicationBuilderExtensions` and `WebApplicationExtensions`. It's the one protection outside `Security/`, because the whole folder is left out without the toggle. It stays off until `RateLimiting:PermitLimit` is above `0`:

``` json
"RateLimiting": {
"PermitLimit": 100,
"Window": "00:01:00"
}
```

- Every request, so each MCP message a client posts to `/mcp`, counts against the caller's IP address. Past the limit the app answers `429 Too Many Requests` with a `Retry-After` header.
- `/health` is never limited, so a busy client can't make the app look down to its host.
- The limiter runs before authentication, so a flood of calls without a token is limited too.
- Behind a reverse proxy or load balancer every request comes from the proxy's address, so all clients share one window. Set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` there, which makes the app read the client's address from the proxy's `X-Forwarded-For` header before any of its own middleware runs, or limit at the proxy instead.

`tests/Presentation.Tests.Integration/RateLimiting/RateLimitingTests.cs` checks the 429, the health exemption and that nothing is limited by default. To try it by hand, set a `PermitLimit` of `2` and make three calls inside a minute: the third gets the 429.

## Steps

1. Add a header in `SecurityHeaders`, not in an endpoint or a filter, so every response gets it.
2. Add it to the theory in `tests/Presentation.Tests.Integration/Security/SecurityHeadersTests.cs`, which checks a healthy response and a 404.
3. Check it by hand: `curl -sI http://localhost:7320/health/live`.

## Check

- [ ] The header is set in `SecurityHeaders` and tested for a success and an error response.
- [ ] No `Content-Security-Policy` unless the browser tools have been checked with it.
4 changes: 2 additions & 2 deletions .agents/skills/serilog/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`) |
Expand All @@ -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:

Expand Down
Loading
Loading