diff --git a/.agents/skills/configuration-and-environments/SKILL.md b/.agents/skills/configuration-and-environments/SKILL.md index 9bd1fae..c1572e5 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,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: @@ -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 @@ -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 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/.agents/skills/nitro/SKILL.md b/.agents/skills/nitro/SKILL.md index 77f790b..e5aa0e1 100644 --- a/.agents/skills/nitro/SKILL.md +++ b/.agents/skills/nitro/SKILL.md @@ -22,7 +22,7 @@ metadata: 1. Run the app (`dotnet run --project ./src/Presentation`) or the compose file, and open Nitro. 2. Check the new field's description, arguments and nullability in the schema reference. They come from XML comments (`xml-docs-and-openapi`). 3. Run the happy path and the failure paths, and check the `extensions.code` of each error. -4. With authentication on, add an `Authorization: Bearer ` header in Nitro's connection settings. +4. With authentication on, add an `Authorization: Bearer ` header in Nitro's connection settings. For a local token, run `dotnet user-jwts create --project src/Presentation` (`optional-token-auth`). Introspection needs the token too, so the schema explorer stays empty until it's set, and `/graphql?sdl` is off (`security-defaults`). 5. Write the integration test as well (`presentation-integration-tests`). ## Don't diff --git a/.agents/skills/optional-token-auth/SKILL.md b/.agents/skills/optional-token-auth/SKILL.md index b8741ef..65d4b1e 100644 --- a/.agents/skills/optional-token-auth/SKILL.md +++ b/.agents/skills/optional-token-auth/SKILL.md @@ -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 diff --git a/.agents/skills/presentation-integration-tests/SKILL.md b/.agents/skills/presentation-integration-tests/SKILL.md index 94bcf80..21edec4 100644 --- a/.agents/skills/presentation-integration-tests/SKILL.md +++ b/.agents/skills/presentation-integration-tests/SKILL.md @@ -9,7 +9,7 @@ metadata: ## The rule -The GraphQL layer is tested through HTTP in `tests/Presentation.Tests.Integration`. `ApplicationErrorFilter`, `PageExtensions` and, with authentication, `AuthenticationSettings` are also tested on their own in `tests/Presentation.Tests.Unit` (`unit-tests`). `GraphQLApplication` (a `WebApplicationFactory`) starts the app with the `local` environment, its own shared-cache in-memory SQLite database and the sample data on. Each test class creates one in a field, implements `IDisposable` and disposes it, so no class shares data with another. +The GraphQL layer is tested through HTTP in `tests/Presentation.Tests.Integration`. `ApplicationErrorFilter`, `PageExtensions` and, with authentication, `AuthenticationSettings` are also tested on their own in `tests/Presentation.Tests.Unit` (`unit-tests`). `GraphQLApplication` (a `WebApplicationFactory`) starts the app with the `Development` environment, its own shared-cache in-memory SQLite database and the sample data on. Each test class creates one in a field, implements `IDisposable` and disposes it, so no class shares data with another. | Piece | Where | Use it to | | --- | --- | --- | 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/schema-snapshot/SKILL.md b/.agents/skills/schema-snapshot/SKILL.md index b546fc3..54123fb 100644 --- a/.agents/skills/schema-snapshot/SKILL.md +++ b/.agents/skills/schema-snapshot/SKILL.md @@ -17,7 +17,7 @@ The test ignores lines that start with `#`, which GraphQL treats as comments. In 1. Make the schema change. 2. Run the tests. The snapshot test fails and prints the new schema. -3. Copy the new SDL into `schema.graphql`. Either take it from the test output, or run the app and open . +3. Copy the new SDL into `schema.graphql`. Either take it from the test output, or run the app without an authority and open . With an authority set, the schema download is off. 4. Read the diff. A removed field, a renamed one, or a field that became non-null breaks clients, so say so in the pull request. 5. Run the tests again. diff --git a/.agents/skills/security-defaults/SKILL.md b/.agents/skills/security-defaults/SKILL.md new file mode 100644 index 0000000..11e8195 --- /dev/null +++ b/.agents/skills/security-defaults/SKILL.md @@ -0,0 +1,76 @@ +--- +name: security-defaults +description: What this GraphQL API does to be safe by default - the startup guard for deployed environments, the security response headers, optional rate limiting and where the other protections live. Use when adding a response header, turning on or tuning rate limiting, changing security middleware, or asked whether the app is safe to deploy. +metadata: + scope: presentation +--- + +# Security defaults (GraphQL API) + +## 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 `ProgramExtensions`. 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 | +| Schema behind the token | `IntrospectionRequestInterceptor` and the GraphQL region | With an authority set only | +| 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. Nitro is served from the same app and needs scripts, styles and frames of its own, so a strict policy would break it. The headers are set in `Response.OnStarting`, because the exception handler clears headers set before it runs. + +## Schema behind the token + +With an authority set, the schema is part of what a token unlocks. The GraphQL region calls `DisableIntrospection(authentication.Enabled)` and registers `IntrospectionRequestInterceptor` (in `src/Presentation/Authentication/`, so it leaves with `--include-auth`), which allows introspection again for a request whose user is authenticated. The schema download at `/graphql?sdl` skips the introspection check, so `EnableSchemaRequests` is off with an authority. The Nitro page itself stays open; it asks for the schema with whatever token you give it in its connection settings. Without an authority everything is open, which is how the schema snapshot test reads `/graphql?sdl`. `AuthenticationTests` covers introspection and the download with and without a token. + +## Rate limiting + +A solution created with `--include-rate-limiting` has a fixed window limiter in `src/Presentation/RateLimiting/`, wired in by `ProgramExtensions`. 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 HTTP request to `/graphql`, however many operations it carries, 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:7330/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. diff --git a/.agents/skills/serilog/SKILL.md b/.agents/skills/serilog/SKILL.md index 9f0c53f..0f00dae 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/.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/.agents/skills/template-authoring/SKILL.md b/.agents/skills/template-authoring/SKILL.md index 06afccf..32dbdc3 100644 --- a/.agents/skills/template-authoring/SKILL.md +++ b/.agents/skills/template-authoring/SKILL.md @@ -14,7 +14,8 @@ 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) | | `skipRestore` | `--no-restore` | Nothing; it turns the restore post action off | @@ -44,7 +45,7 @@ The repository itself stays all on. The Presentation project and the presentatio A toggle's inputs, such as `authority` and `audience`, are separate symbols, enabled with `isEnabled` and made required with `isRequired` only when the toggle is on. Only `dotnet new` honours those two. Visual Studio and Rider show every input whatever the toggle says ([dotnet/templating#7860](https://github.com/dotnet/templating/issues/7860)), and Rider lists checkboxes first, then text fields in alphabetical order by label. So an input's label starts with its feature, such as "Authentication authority", to sit right under its checkbox, and its IDE description says it's only used when that box is ticked. A toggle that needs another one says so in its conditions, such as `(includeTests && includeArchitectureTests)`. Verify Template checks the defaults, everything on, everything off, and each toggle flipped on its own. -Every generated solution gets `.lmca.json`, which records the template release and the options it was made with, so the docs site's upgrade guide can generate the same solution from the old and new releases and diff them. The repository's copy says `0.0.0-local`; `template/template.csproj` swaps in the package version when it packs. Its options come through the usual replacements: the `sourceName` becomes the name, `Stephen Walsh` the author name and, where the template has `--include-auth`, the `"Authority": ""` and `"Audience": ""` lines the authentication values, inside `//#if (includeAuth)`. A new option gets a line there too. Name the template by its `lmca-` short name, never by anything containing the `sourceName`, which `dotnet new` would replace. +Every generated solution gets `.lmca.json`, which records the template release and the options it was made with, so the docs site's upgrade guide can generate the same solution from the old and new releases and diff them. The repository's copy says `0.0.0-local`; `template/template.csproj` swaps in the package version when it packs. Its options come through the usual replacements: the `sourceName` becomes the name, `Stephen Walsh` the author name and, where the template has `--include-auth`, the `"Authority": ""` and `"Audience": ""` lines the authentication values, inside `//#if (includeAuth)`, and, where the template has `--include-rate-limiting`, `"rateLimiting"` as `true` or `false`. A new option gets a line there too. Name the template by its `lmca-` short name, never by anything containing the `sourceName`, which `dotnet new` would replace. The package includes `src/`, `tests/`, `docs/RUN.md`, the root build files, `AGENTS.md`, `CLAUDE.md` and the engineering skills. It also packs `template/README.md` as the generated solution's `README.md` and `template/ci.yml` as `.github/workflows/ci.yml`, while leaving the template repository's own `README.md`, the rest of `.github/`, the community files and the repository and maintainer skills out. Those skills are listed in `RepositorySkills` in `template/template.csproj`; a new one is added there. The pipeline fails a package over 1 MB. @@ -73,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. @@ -97,4 +98,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`) that it has `README.md` and `.github/workflows/ci.yml`, and that `.lmca.json` names the version and the options it was made with, 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`), that it has `README.md` and `.github/workflows/ci.yml`, and that `.lmca.json` names the version and the options it was made with, 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. 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 diff --git a/.github/workflows/build-pipeline.yml b/.github/workflows/build-pipeline.yml index da229b7..ff4f416 100644 --- a/.github/workflows/build-pipeline.yml +++ b/.github/workflows/build-pipeline.yml @@ -302,6 +302,7 @@ jobs: verify() { dotnet new "$SHORT_NAME" --name "$1" --output "$1" "${@:2}" clean "$1" includeAuth + clean "$1" includeRateLimiting clean "$1" "$SOURCE_NAME" test ! -e "$1/icon.png" test -f "$1/README.md" @@ -314,17 +315,30 @@ jobs: verify Template.Verification VARIANTS="the generated solution carries nothing of the template, records the release and options that made it, passes its format check, builds and passes its tests" - # Templates with an auth option are verified a second time with it on, and --include-auth without - # --authority has to stop before anything is written (exit code 102, a missing mandatory option). + # Templates with a rate limiting option are verified with only that toggle on. + ALL_ON=() + if jq -e '.symbols.includeRateLimiting' .template.config/template.json > /dev/null; then + verify Template.RateLimiting --include-rate-limiting + jq -e '.options.rateLimiting == true' Template.RateLimiting/.lmca.json + jq -e '.options.rateLimiting == false' Template.Verification/.lmca.json + ALL_ON+=(--include-rate-limiting) + VARIANTS="$VARIANTS, with --include-rate-limiting on its own" + fi + + # Templates with an auth option are verified again with every toggle on, and --include-auth without + # --authority or --audience has to stop before anything is written (exit code 102, a missing mandatory option). if jq -e '.symbols.includeAuth' .template.config/template.json > /dev/null; then - verify Template.Authentication --include-auth --authority https://login.example.com --audience https://api.example.com + verify Template.Authentication --include-auth --authority https://login.example.com --audience https://api.example.com "${ALL_ON[@]}" jq -e '.options.authentication.Authority == "https://login.example.com"' Template.Authentication/.lmca.json set +e - dotnet new "$SHORT_NAME" --name Template.NoAuthority --output Template.NoAuthority --include-auth + dotnet new "$SHORT_NAME" --name Template.NoAuthority --output Template.NoAuthority --include-auth --audience https://api.example.com NO_AUTHORITY=$? + dotnet new "$SHORT_NAME" --name Template.NoAudience --output Template.NoAudience --include-auth --authority https://login.example.com + NO_AUDIENCE=$? set -e test "$NO_AUTHORITY" -eq 102 || { echo "::error::--include-auth without --authority exited $NO_AUTHORITY, not 102"; exit 1; } - VARIANTS="$VARIANTS with and without --include-auth, and --include-auth without --authority is refused" + test "$NO_AUDIENCE" -eq 102 || { echo "::error::--include-auth without --audience exited $NO_AUDIENCE, not 102"; exit 1; } + VARIANTS="$VARIANTS, with every toggle on, and --include-auth without --authority or --audience is refused" fi echo "### Template" >> "$GITHUB_STEP_SUMMARY" @@ -432,6 +446,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 7330:7330 \ + --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 diff --git a/.lmca.json b/.lmca.json index 03d650b..056bd1b 100644 --- a/.lmca.json +++ b/.lmca.json @@ -5,6 +5,11 @@ "options": { "name": "CleanGraphQLApi", "authorName": "Stephen Walsh", +//#if (includeRateLimiting) + "rateLimiting": true, +//#else + "rateLimiting": false, +//#endif //#if (includeAuth) "authentication": { "Authority": "", diff --git a/.template.config/dotnetcli.host.json b/.template.config/dotnetcli.host.json index f65268e..d238cfc 100644 --- a/.template.config/dotnetcli.host.json +++ b/.template.config/dotnetcli.host.json @@ -9,6 +9,10 @@ "longName": "include-auth", "shortName": "" }, + "includeRateLimiting": { + "longName": "include-rate-limiting", + "shortName": "" + }, "authority": { "longName": "authority", "shortName": "iss" diff --git a/.template.config/ide.host.json b/.template.config/ide.host.json index 625d2ca..5eab83f 100644 --- a/.template.config/ide.host.json +++ b/.template.config/ide.host.json @@ -41,6 +41,16 @@ }, "isVisible": true }, + { + "id": "includeRateLimiting", + "name": { + "text": "Include rate limiting" + }, + "description": { + "text": "Add the built-in rate limiter, a fixed window per client IP address, off until RateLimiting:PermitLimit is set. Default: off." + }, + "isVisible": true + }, { "id": "authority", "name": { @@ -54,10 +64,10 @@ { "id": "audience", "name": { - "text": "Authentication audience (optional)" + "text": "Authentication audience" }, "description": { - "text": "Who the tokens are for, usually the API's own URL. Only used when Include authentication is ticked." + "text": "Who the tokens are for, usually the API's own URL. Only used when Include authentication is ticked, and needed then." }, "isVisible": true } diff --git a/.template.config/template.json b/.template.config/template.json index 1cdaf78..64fcfad 100644 --- a/.template.config/template.json +++ b/.template.config/template.json @@ -56,6 +56,14 @@ "tests/Presentation.Tests.Unit/Authentication/**", "tests/Presentation.Tests.Integration/Authentication/**" ] + }, + { + "condition": "(!includeRateLimiting)", + "exclude": [ + "src/Presentation/RateLimiting/**", + "tests/Presentation.Tests.Unit/RateLimiting/**", + "tests/Presentation.Tests.Integration/RateLimiting/**" + ] } ] } @@ -99,7 +107,14 @@ "type": "parameter", "datatype": "bool", "displayName": "Include authentication", - "description": "Add JWT bearer token authentication. Leave it off and the API has no auth code at all, which is fine on your machine and brave anywhere else.", + "description": "Add JWT bearer token authentication. Leave it off and the API has no auth code at all, which is fine on your machine. Anywhere else it won't start until you say open is what you want.", + "defaultValue": "false" + }, + "includeRateLimiting": { + "type": "parameter", + "datatype": "bool", + "displayName": "Include rate limiting", + "description": "Add ASP.NET Core's rate limiter, a fixed window per client IP address, switched on by setting RateLimiting:PermitLimit. For when there's no gateway doing it for you.", "defaultValue": "false" }, "authority": { @@ -114,10 +129,11 @@ "audience": { "type": "parameter", "datatype": "string", - "displayName": "Authentication audience (optional)", - "description": "The audience access tokens must be issued for, usually the API's own URL. Not the people in the room, who are lovely but don't carry tokens.", + "displayName": "Authentication audience", + "description": "The audience access tokens must be issued for, usually the API's own URL. Not the people in the room, who are lovely but don't carry tokens. Required with --include-auth.", "defaultValue": "", - "isEnabled": "includeAuth" + "isEnabled": "includeAuth", + "isRequired": "includeAuth" }, "skipRestore": { "type": "parameter", diff --git a/AGENTS.md b/AGENTS.md index 01793f2..a510a63 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,6 +131,7 @@ These are for this GraphQL API's presentation layer. The other templates have th | `dataloaders` | Load data for every item in a list without a query per item | | `schema-snapshot` | Change the schema, or the snapshot test fails | | `presentation-integration-tests` | Write a test that sends a real GraphQL request | +| `security-defaults` | Add a response header or other protection, or check what the app does to stay safe | | `nitro` | Try the API by hand in the GraphQL IDE | diff --git a/Dockerfile b/Dockerfile index 26bdf1d..de5f8b3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -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} diff --git a/NUGET.md b/NUGET.md index d42c3dc..73ea6c5 100644 --- a/NUGET.md +++ b/NUGET.md @@ -32,8 +32,9 @@ cd WorksOnMyMachine.Movies | `--name` | `-n` | The folder's name | Names the solution and its root namespace | | `--authorName` | `-an` | `Stephen Walsh` | Puts your name on the assembly instead of ours | | `--include-auth` | | Off | Adds JWT bearer token authentication. Leave it out and the API has no auth code at all | +| `--include-rate-limiting` | | Off | Adds the built-in rate limiter, a fixed window per client IP address, switched on by `RateLimiting:PermitLimit` | | `--authority` | `-iss` | Empty | Your OAuth authorization server. Required with `--include-auth` | -| `--audience` | `-aud` | Empty | The audience tokens must be issued for, usually the API's own URL. Only used with `--include-auth` | +| `--audience` | `-aud` | Empty | The audience tokens must be issued for, usually the API's own URL. Required with `--include-auth` | | `--no-restore` | | Off | Skips the package restore that normally runs once the solution is created | Rather click than type? Visual Studio and Rider show the same options in their new project dialogs. They always show the authority and audience fields, but only use them when **Include authentication** is ticked. In the terminal, `dotnet new cleangraphqlapi --help` lists them all. @@ -50,7 +51,7 @@ dotnet test Then open [Nitro](https://chillicream.com/docs/nitro), the GraphQL IDE, at and ask it for some movies. -The API is open unless you create it with `--include-auth --authority` (and usually `--audience`), and then the queries and mutations ask for a JWT bearer token. Leave `--include-auth` out and there's no auth code at all. +On your machine the API is open unless you create it with `--include-auth`, `--authority` and `--audience`, and then the queries and mutations ask for a JWT bearer token. Leave `--include-auth` out and there's no auth code at all, and a deployed copy refuses to start until you set `Authentication:AllowAnonymous`. ## What's inside diff --git a/README.md b/README.md index 67ceb51..e72b513 100644 --- a/README.md +++ b/README.md @@ -31,8 +31,9 @@ cd WorksOnMyMachine.Movies | `--name`
`-n` | The folder's name | Names the solution and its root namespace | | `--authorName`
`-an` | `Stephen Walsh` | Puts your name on the assembly instead of ours | | `--include-auth` | Off | Adds JWT bearer token authentication. Leave it out and the API has no auth code at all | +| `--include-rate-limiting` | Off | Adds the built-in rate limiter, a fixed window per client IP address, switched on by `RateLimiting:PermitLimit` | | `--authority`
`-iss` | Empty | Your OAuth authorization server. Required with `--include-auth` | -| `--audience`
`-aud` | Empty | The audience tokens must be issued for, usually the API's own URL. Only used with `--include-auth` | +| `--audience`
`-aud` | Empty | The audience tokens must be issued for, usually the API's own URL. Required with `--include-auth` | | `--no-restore` | Off | Skips the package restore that normally runs once the solution is created | Rather click than type? Visual Studio and Rider show the same options in their new project dialogs. They always show the authority and audience fields, but only use them when **Include authentication** is ticked. In the terminal, `dotnet new cleangraphqlapi --help` lists them all. @@ -81,7 +82,7 @@ The `movies`, `authors` and `reviews` queries use Relay-style cursor paging (`fi No Docker? `dotnet run --project src/Presentation` works too. Every other way to run it, from plain `docker run` to stamping a version into the image, is in [docs/RUN.md](docs/RUN.md). -The API is open unless you ask for authentication. Create the solution with `--include-auth --authority https://login.example.com --audience https://api.example.com` and the movie, author and review queries and the review mutations ask for a JWT bearer token. The `version` query asks for one too. Health checks, the schema and Nitro stay open. Leave `--include-auth` out and there's no authentication code in the solution at all, so there's nothing to leave switched off by accident. [Securing the API](https://leanmeanclean.dev/graphql/guides/secure-the-api/) has the details, including how to add it later. +On your machine the API is open unless you ask for authentication. Deployed anywhere else without it, the API refuses to start until you set `Authentication:AllowAnonymous`, so nobody ships an open API by accident. Create the solution with `--include-auth --authority https://login.example.com --audience https://api.example.com` and the movie, author and review queries and the review mutations ask for a JWT bearer token. The `version` query asks for one too. Health checks and the Nitro page stay open, but the schema is part of the map, so introspection needs the token too: add it in Nitro's connection settings. Leave `--include-auth` out and there's no authentication code in the solution at all, so there's nothing to leave switched off by accident. [Securing the API](https://leanmeanclean.dev/graphql/guides/secure-the-api/) has the details, including how to add it later. ## What's inside diff --git a/docker-compose.yml b/docker-compose.yml index 97449db..da3e813 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,7 +7,7 @@ services: VERSION_PREFIX: 1.0.0.0 VERSION_SUFFIX: docker ports: - - "7330:7330" + - "127.0.0.1:7330:7330" environment: DOTNET_ENVIRONMENT: docker OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4317 @@ -23,8 +23,8 @@ services: volumes: - ./otel-collector.yaml:/etc/otelcol/config.yaml:ro ports: - - "7333:4317" - - "7334:4318" + - "127.0.0.1:7333:4317" + - "127.0.0.1:7334:4318" networks: - cleangraphqlapi_network depends_on: @@ -32,7 +32,7 @@ services: aspire-dashboard: image: mcr.microsoft.com/dotnet/aspire-dashboard:13.6.5 ports: - - "7332:18888" + - "127.0.0.1:7332:18888" environment: ASPIRE_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS: "true" networks: diff --git a/docs/RUN.md b/docs/RUN.md index 3689334..10bc1bd 100644 --- a/docs/RUN.md +++ b/docs/RUN.md @@ -1,10 +1,10 @@ # Running Clean GraphQL API -There are two pre-configured environments, `local` 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 -The app stores its data in a SQLite file, `movie-reviews.db`, next to the app. In Docker the file is `/app/data/movie-reviews.db`, on the `movie-reviews-data` volume, so it survives a restart. On startup the app applies any pending Entity Framework Core migrations. When `Database:SeedSampleData` is `true`, it also seeds the same sample data into an empty database. It's on in `appsettings.local.json` and `appsettings.docker.json` and off everywhere else, so a deployed copy never starts with fake data. Delete the file, or run `docker compose down -v`, to start again. Change `ConnectionStrings:MovieReviews` to point somewhere else, or to `Data Source=MovieReviews;Mode=Memory;Cache=Shared` to keep everything in memory. +The app stores its data in a SQLite file, `movie-reviews.db`, next to the app. In Docker the file is `/app/data/movie-reviews.db`, on the `movie-reviews-data` volume, so it survives a restart. On startup the app applies any pending Entity Framework Core migrations. When `Database:SeedSampleData` is `true`, it also seeds the same sample data into an empty database. It's on in `appsettings.Development.json` and `appsettings.docker.json` and off everywhere else, so a deployed copy never starts with fake data. Delete the file, or run `docker compose down -v`, to start again. Change `ConnectionStrings:MovieReviews` to point somewhere else, or to `Data Source=MovieReviews;Mode=Memory;Cache=Shared` to keep everything in memory. To add a migration after changing the data model: @@ -72,10 +72,30 @@ OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:7333 dotnet run --project ./src/Pre Every span, metric and log carries `service.version`, so you can always tell which build sent it. + +## Trying it with a token + +With an authority set, every call needs a token from it. To try the app on your machine without one, let .NET make you a development token: + +```bash +dotnet user-jwts create --project src/Presentation +``` + +It prints a token, adds a `UserSecretsId` to the project, keeps the signing key in your user secrets and writes the issuer and audiences into `appsettings.Development.json`. From then on a `dotnet run` accepts its tokens instead of your authority's. Nothing changes anywhere else: user secrets and that file only load in `Development`, and the app refuses to start with development tokens set up in any other environment. If you commit the file, everyone's `dotnet run` switches to development tokens, and each person makes their own with the same command. + +In Nitro at , open the connection settings and add a header: `Authorization` with `Bearer `. The schema loads once the header is there. Run `dotnet user-jwts create` again for a fresh token, and `dotnet user-jwts clear --project src/Presentation` and delete the `Authentication` block from `appsettings.Development.json` to go back to your authority. + + ## HTTPS -The app redirects HTTP to HTTPS whenever it has an HTTPS port, which is why `dotnet run` sends on to . Outside the `local` and `Development` environments it also sends an HSTS header. The container only listens on HTTP, so in production put it behind a proxy or load balancer that ends TLS, and set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` so the app knows the original request was HTTPS. +The app redirects HTTP to HTTPS whenever it has an HTTPS port, which is why `dotnet run` sends on to . Outside the `Development` environment it also sends an HSTS header. The container only listens on HTTP, so in production put it behind a proxy or load balancer that ends TLS, and set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` so the app knows the original request was HTTPS. + + +## Rate limiting + +The rate limiter is in the code but off. Turn it on by setting how many requests each client IP address may make in each window, in `appsettings.json` or as environment variables (`RateLimiting__PermitLimit=100`, `RateLimiting__Window=00:01:00`). Past the limit, calls get `429 Too Many Requests` with a `Retry-After` header. Health checks are never limited. Behind a reverse proxy every call looks like it comes from the proxy, so set `ASPNETCORE_FORWARDEDHEADERS_ENABLED=true` (as in HTTPS above) and the app reads the client's address from the proxy's `X-Forwarded-For` header, or limit at the proxy instead. + ## Tests ``` bash diff --git a/src/Presentation/Authentication/AuthenticationSettings.cs b/src/Presentation/Authentication/AuthenticationSettings.cs index 15dc241..9a7340e 100644 --- a/src/Presentation/Authentication/AuthenticationSettings.cs +++ b/src/Presentation/Authentication/AuthenticationSettings.cs @@ -15,10 +15,29 @@ public class AuthenticationSettings /// The audience access tokens must be issued for. This is usually the API's own URL. public string? Audience { get; init; } - public bool Enabled => !string.IsNullOrWhiteSpace(this.Authority); + /// + /// The issuer dotnet user-jwts writes to appsettings.Development.json, read from + /// Authentication:Schemes:Bearer:ValidIssuer. When it's set, the app accepts the tokens that tool creates. + /// + public string? DevelopmentTokenIssuer { get; private set; } + + /// Whether requests need a token: true when an authority or dotnet user-jwts is set up. + public bool Enabled => !string.IsNullOrWhiteSpace(this.Authority) || this.UsesDevelopmentTokens; + + /// + /// Whether the tokens come from dotnet user-jwts. They win over the authority, so running the tool switches + /// a dotnet run to them and clearing it switches back. + /// + public bool UsesDevelopmentTokens => !string.IsNullOrWhiteSpace(this.DevelopmentTokenIssuer); + + /// Whether a real authorization server issues the tokens. + public bool HasAuthority => !string.IsNullOrWhiteSpace(this.Authority) && !this.UsesDevelopmentTokens; public static AuthenticationSettings FromConfiguration(IConfiguration configuration) { - return configuration.GetSection(SectionName).Get() ?? new AuthenticationSettings(); + var settings = configuration.GetSection(SectionName).Get() ?? new AuthenticationSettings(); + settings.DevelopmentTokenIssuer = configuration[$"{SectionName}:Schemes:Bearer:ValidIssuer"]; + + return settings; } } diff --git a/src/Presentation/Authentication/IntrospectionRequestInterceptor.cs b/src/Presentation/Authentication/IntrospectionRequestInterceptor.cs new file mode 100644 index 0000000..647e3e9 --- /dev/null +++ b/src/Presentation/Authentication/IntrospectionRequestInterceptor.cs @@ -0,0 +1,26 @@ +namespace CleanGraphQLApi.Presentation.Authentication; + +using HotChocolate.AspNetCore; +using HotChocolate.Execution; +using Microsoft.AspNetCore.Http; + +/// +/// With authentication on, introspection is off for everyone and switched back on for each request that carries a valid +/// token, so the schema is only handed to callers who could use it. Nitro still works: add the token in its headers. +/// +public sealed class IntrospectionRequestInterceptor : DefaultHttpRequestInterceptor +{ + public override ValueTask OnCreateAsync( + HttpContext context, + IRequestExecutor requestExecutor, + OperationRequestBuilder requestBuilder, + CancellationToken cancellationToken) + { + if (context.User.Identity?.IsAuthenticated == true) + { + _ = requestBuilder.AllowIntrospection(); + } + + return base.OnCreateAsync(context, requestExecutor, requestBuilder, cancellationToken); + } +} diff --git a/src/Presentation/Extensions/ProgramExtensions.cs b/src/Presentation/Extensions/ProgramExtensions.cs index e153c9b..8bca101 100644 --- a/src/Presentation/Extensions/ProgramExtensions.cs +++ b/src/Presentation/Extensions/ProgramExtensions.cs @@ -1,7 +1,6 @@ namespace CleanGraphQLApi.Presentation.Extensions; using System.Diagnostics.CodeAnalysis; -using System.Reflection; using Application; using Application.Common.Paging; using Application.Common.Telemetry; @@ -26,6 +25,10 @@ namespace CleanGraphQLApi.Presentation.Extensions; using OpenTelemetry.Metrics; using OpenTelemetry.Resources; using OpenTelemetry.Trace; +#if includeRateLimiting +using RateLimiting; +#endif +using Security; using Serilog; using Telemetry; @@ -34,10 +37,14 @@ public static class ProgramExtensions { public static WebApplicationBuilder ConfigureBuilder(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(ProgramExtensions).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); var openTelemetry = builder.Services.AddOpenTelemetry() .ConfigureResource(resource => resource.AddAttributes(telemetry.ResourceAttributes)) @@ -82,10 +89,10 @@ public static WebApplicationBuilder ConfigureBuilder(this WebApplicationBuilder _ = loggerConfiguration.ReadFrom.Configuration(configuration) .Enrich.WithProperty( "AssemblyVersion", - assembly.GetCustomAttribute()?.Version) + version.FileVersion) .Enrich.WithProperty( "AssemblyInformationalVersion", - assembly.GetCustomAttribute()?.InformationalVersion); + version.InformationalVersion); // Logs leave over OTLP too, carrying the trace and span IDs of whatever was running when they were written. if (telemetry.Enabled) @@ -113,7 +120,9 @@ public static WebApplicationBuilder ConfigureBuilder(this WebApplicationBuilder .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { - options.Authority = authentication.Authority; + // With dotnet user-jwts set up, there's no authority to ask: the tool has put the issuer, audiences + // and signing key in the settings, and the handler reads them from Authentication:Schemes:Bearer. + options.Authority = authentication.HasAuthority ? authentication.Authority : null; options.Audience = authentication.Audience; options.MapInboundClaims = false; }); @@ -136,6 +145,9 @@ public static WebApplicationBuilder ConfigureBuilder(this WebApplicationBuilder .AddPresentationTypes() #if includeAuth .AddAuthorization() + // With an authority, introspection needs a token too: the schema is a map of the API. + .DisableIntrospection(authentication.Enabled) + .AddHttpRequestInterceptor() #endif .AddInstrumentation() .AddMutationConventions(applyToAllMutations: true) @@ -143,7 +155,17 @@ public static WebApplicationBuilder ConfigureBuilder(this WebApplicationBuilder .AddErrorFilter(services => new ApplicationErrorFilter( services.GetRootServiceProvider().GetRequiredService>())) .AddMaxExecutionDepthRule(15) +#if includeAuth + .ModifyServerOptions(options => + { + options.Tool.ServeMode = ServeMode.Embedded; + + // The schema download skips the introspection check, so with an authority it's off. + options.EnableSchemaRequests = !authentication.Enabled; + }) +#else .ModifyServerOptions(options => options.Tool.ServeMode = ServeMode.Embedded) +#endif .ModifyPagingOptions(options => { options.DefaultPageSize = Paging.DefaultLimit; @@ -154,12 +176,20 @@ public static WebApplicationBuilder ConfigureBuilder(this WebApplicationBuilder #endregion GraphQL +#if includeRateLimiting + #region Rate Limiting + + _ = builder.Services.AddRateLimiting(builder.Configuration); + + #endregion Rate Limiting + +#endif #region Project Dependencies _ = builder.Services.AddMediator(options => options.ServiceLifetime = ServiceLifetime.Scoped); _ = builder.Services.AddInfrastructure(builder.Configuration.GetConnectionString("MovieReviews")); _ = builder.Services.AddApplication(); - _ = builder.Services.AddSingleton(VersionInfo.FromAssembly(typeof(ProgramExtensions).Assembly)); + _ = builder.Services.AddSingleton(version); _ = builder.Services.AddHealthChecks().AddInfrastructureHealthChecks("ready"); #endregion Project Dependencies @@ -177,8 +207,10 @@ public static WebApplication ConfigureApplication(this WebApplication app) #region Security - // HSTS tells browsers to only use HTTPS from then on, so it's left off for local runs. - if (!app.Environment.IsDevelopment() && !app.Environment.IsEnvironment("local")) + _ = app.UseSecurityHeaders(); + + // HSTS tells browsers to only use HTTPS from then on, so it's left off in Development. + if (!app.Environment.IsDevelopment()) { _ = app.UseHsts(); } @@ -193,6 +225,15 @@ public static WebApplication ConfigureApplication(this WebApplication app) #endregion Logging +#if includeRateLimiting + #region Rate Limiting + + // Before authentication, so a client over its limit is turned away before its token is checked. + _ = app.UseRateLimiting(app.Configuration); + + #endregion Rate Limiting + +#endif #if includeAuth #region Authentication diff --git a/src/Presentation/Presentation.csproj b/src/Presentation/Presentation.csproj index 7975847..2759f11 100644 --- a/src/Presentation/Presentation.csproj +++ b/src/Presentation/Presentation.csproj @@ -11,8 +11,8 @@ Linux $(NoWarn);1573 - - $(DefineConstants);includeAuth + + $(DefineConstants);includeAuth;includeRateLimiting diff --git a/src/Presentation/Properties/launchSettings.json b/src/Presentation/Properties/launchSettings.json index b6386d8..4bf5277 100644 --- a/src/Presentation/Properties/launchSettings.json +++ b/src/Presentation/Properties/launchSettings.json @@ -8,7 +8,7 @@ "launchUrl": "graphql", "applicationUrl": "https://localhost:7331;http://localhost:7330", "environmentVariables": { - "DOTNET_ENVIRONMENT": "local" + "DOTNET_ENVIRONMENT": "Development" } } } diff --git a/src/Presentation/RateLimiting/RateLimitingExtensions.cs b/src/Presentation/RateLimiting/RateLimitingExtensions.cs new file mode 100644 index 0000000..2772ff6 --- /dev/null +++ b/src/Presentation/RateLimiting/RateLimitingExtensions.cs @@ -0,0 +1,62 @@ +namespace CleanGraphQLApi.Presentation.RateLimiting; + +using System.Globalization; +using System.Threading.RateLimiting; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; + +/// +/// Adds ASP.NET Core's built-in rate limiter when RateLimiting:PermitLimit is set. Each client IP address gets +/// its own fixed window; a client over its limit gets a 429 with a Retry-After header. Health checks are never +/// limited, so probes keep working when a client is being turned away. +/// +public static class RateLimitingExtensions +{ + /// + /// Registers the limiter, if it's switched on. + /// + /// The services to add the limiter to. + /// The settings to read RateLimiting from. + /// The services, for chaining. + public static IServiceCollection AddRateLimiting(this IServiceCollection services, IConfiguration configuration) + { + var settings = RateLimitingSettings.FromConfiguration(configuration); + + if (!settings.Enabled) + { + return services; + } + + return services.AddRateLimiter(options => + { + options.RejectionStatusCode = StatusCodes.Status429TooManyRequests; + options.GlobalLimiter = PartitionedRateLimiter.Create(context => + context.Request.Path.StartsWithSegments("/health") + ? RateLimitPartition.GetNoLimiter("health") + : RateLimitPartition.GetFixedWindowLimiter( + context.Connection.RemoteIpAddress?.ToString() ?? "unknown", + _ => new FixedWindowRateLimiterOptions { PermitLimit = settings.PermitLimit, Window = settings.Window })); + options.OnRejected = (context, _) => + { + if (context.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter)) + { + context.HttpContext.Response.Headers.RetryAfter = ((int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(CultureInfo.InvariantCulture); + } + + return ValueTask.CompletedTask; + }; + }); + } + + /// + /// Puts the limiter in the pipeline, if it's switched on. + /// + /// The application to add the limiter to. + /// The settings to read RateLimiting from. + /// The application, for chaining. + public static IApplicationBuilder UseRateLimiting(this IApplicationBuilder app, IConfiguration configuration) + { + return RateLimitingSettings.FromConfiguration(configuration).Enabled ? app.UseRateLimiter() : app; + } +} diff --git a/src/Presentation/RateLimiting/RateLimitingSettings.cs b/src/Presentation/RateLimiting/RateLimitingSettings.cs new file mode 100644 index 0000000..95f493b --- /dev/null +++ b/src/Presentation/RateLimiting/RateLimitingSettings.cs @@ -0,0 +1,25 @@ +namespace CleanGraphQLApi.Presentation.RateLimiting; + +using Microsoft.Extensions.Configuration; + +/// +/// The built-in rate limiter's settings: a fixed window per client IP address. Leave at 0 to +/// switch it off, which is the default. +/// +public class RateLimitingSettings +{ + public const string SectionName = "RateLimiting"; + + /// How many requests one client IP address may make in each window. 0 switches the limiter off. + public int PermitLimit { get; init; } + + /// How long each window lasts. One minute unless set. + public TimeSpan Window { get; init; } = TimeSpan.FromMinutes(1); + + public bool Enabled => this.PermitLimit > 0 && this.Window > TimeSpan.Zero; + + public static RateLimitingSettings FromConfiguration(IConfiguration configuration) + { + return configuration.GetSection(SectionName).Get() ?? new RateLimitingSettings(); + } +} diff --git a/src/Presentation/Security/DeploymentGuard.cs b/src/Presentation/Security/DeploymentGuard.cs new file mode 100644 index 0000000..eb0cfa6 --- /dev/null +++ b/src/Presentation/Security/DeploymentGuard.cs @@ -0,0 +1,84 @@ +namespace CleanGraphQLApi.Presentation.Security; + +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Hosting; +#if includeAuth +using Presentation.Authentication; +#endif + +/// +/// Stops a deployed copy starting wide open by accident. Development (dotnet run) and docker +/// (Docker Compose) are a developer's machine; every other environment name counts as deployed. +/// +public static class DeploymentGuard +{ + /// The setting that lets a deployed copy run without authentication on purpose. + public const string AllowAnonymousKey = "Authentication:AllowAnonymous"; + + /// + /// Whether the environment is a developer's machine rather than a deployment. + /// + /// The host's environment. + /// True for Development and docker. + public static bool IsLocal(IHostEnvironment environment) + { + return environment.IsDevelopment() || environment.IsEnvironment("docker"); + } + + /// + /// Throws when the app shouldn't start: a deployed environment without authentication, unless + /// Authentication:AllowAnonymous is true. + /// + /// The host's environment. + /// The settings to check. + /// The settings aren't safe to start with. + public static void EnsureSafeToStart(IHostEnvironment environment, IConfiguration configuration) + { +#if includeAuth + var authentication = AuthenticationSettings.FromConfiguration(configuration); + + // dotnet user-jwts tokens replace the authority, so they're kept to the one environment they're made for. + if (authentication.UsesDevelopmentTokens && !environment.IsDevelopment()) + { + throw new InvalidOperationException( + "Authentication:Schemes:Bearer:ValidIssuer is set, which switches the app to dotnet user-jwts development tokens. " + + $"They're only for the Development environment, so remove it from the '{environment.EnvironmentName}' environment's settings."); + } + + if (authentication.Enabled) + { + if (!string.IsNullOrWhiteSpace(authentication.Authority) && + (!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}'."); + } + + // An authority's tokens are checked against the audience, so without one every token would be rejected. + if (authentication.HasAuthority && string.IsNullOrWhiteSpace(authentication.Audience)) + { + throw new InvalidOperationException( + "Authentication:Authority is set without Authentication:Audience, so every token would be rejected. " + + "Set Authentication:Audience to the audience your tokens are issued for, usually this app's own URL."); + } + + return; + } + +#endif + if (IsLocal(environment) || configuration.GetValue(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 + } +} diff --git a/src/Presentation/Security/SecurityHeaders.cs b/src/Presentation/Security/SecurityHeaders.cs new file mode 100644 index 0000000..10359e4 --- /dev/null +++ b/src/Presentation/Security/SecurityHeaders.cs @@ -0,0 +1,34 @@ +namespace CleanGraphQLApi.Presentation.Security; + +using Microsoft.AspNetCore.Builder; + +/// +/// The response headers every response carries, errors included. No Content-Security-Policy, so the browser tools keep +/// working. +/// +public static class SecurityHeaders +{ + /// + /// Adds X-Content-Type-Options: nosniff, X-Frame-Options: DENY and Referrer-Policy: no-referrer + /// to every response. + /// + /// The application to add the headers to. + /// The application, for chaining. + public static IApplicationBuilder UseSecurityHeaders(this IApplicationBuilder app) + { + return app.Use(async (context, next) => + { + // Set as the response starts, because the exception handler clears headers set earlier. + context.Response.OnStarting(() => + { + var headers = context.Response.Headers; + headers.XContentTypeOptions = "nosniff"; + headers.XFrameOptions = "DENY"; + headers["Referrer-Policy"] = "no-referrer"; + return Task.CompletedTask; + }); + + await next(context); + }); + } +} diff --git a/src/Presentation/Telemetry/TelemetrySettings.cs b/src/Presentation/Telemetry/TelemetrySettings.cs index 406203e..4c30ff0 100644 --- a/src/Presentation/Telemetry/TelemetrySettings.cs +++ b/src/Presentation/Telemetry/TelemetrySettings.cs @@ -1,6 +1,6 @@ namespace CleanGraphQLApi.Presentation.Telemetry; -using System.Reflection; +using Application.Versions.Entities; using Microsoft.Extensions.Configuration; /// @@ -16,10 +16,10 @@ 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, such as local or docker. + /// The deployment.environment.name, such as Development or docker. public required string EnvironmentName { get; init; } /// Where the OTLP exporters send everything. Empty means nothing is exported. @@ -35,14 +35,14 @@ public class TelemetrySettings ["deployment.environment.name"] = this.EnvironmentName }; - 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/src/Presentation/appsettings.local.json b/src/Presentation/appsettings.Development.json similarity index 86% rename from src/Presentation/appsettings.local.json rename to src/Presentation/appsettings.Development.json index 2399a91..3501b7b 100644 --- a/src/Presentation/appsettings.local.json +++ b/src/Presentation/appsettings.Development.json @@ -12,7 +12,7 @@ } ], "Properties": { - "ApplicationName": "CleanGraphQLApi-Local" + "ApplicationName": "CleanGraphQLApi-Development" } }, "Database": { diff --git a/src/Presentation/appsettings.json b/src/Presentation/appsettings.json index cd584da..02c6dd8 100644 --- a/src/Presentation/appsettings.json +++ b/src/Presentation/appsettings.json @@ -24,13 +24,20 @@ "ConnectionStrings": { "MovieReviews": "Data Source=movie-reviews.db" }, - //#if (includeAuth) "Authentication": { + //#if (includeAuth) "Authority": "", - "Audience": "" + "Audience": "", + //#endif + "AllowAnonymous": false }, - //#endif "AllowedHosts": "*", + //#if (includeRateLimiting) + "RateLimiting": { + "PermitLimit": 0, + "Window": "00:01:00" + }, + //#endif "Database": { "SeedSampleData": false } diff --git a/tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs b/tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs index 1bdd645..8de1a6f 100644 --- a/tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs +++ b/tests/Presentation.Tests.Integration/Authentication/AuthenticationTests.cs @@ -3,6 +3,7 @@ namespace CleanGraphQLApi.Presentation.Tests.Integration.Authentication; using System.Net.Http.Headers; using System.Security.Claims; using System.Text; +using System.Text.Json; using GraphQL.Common; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.Extensions.DependencyInjection; @@ -110,6 +111,48 @@ public async Task Version_WithToken_ShouldReturn_Version() result.Data.Version.FileVersion.ShouldNotBeNullOrWhiteSpace(); } + [Fact] + public async Task Introspection_WithoutToken_ShouldReturn_Error() + { + // Arrange + using var client = this.application.CreateClient(); + + // Act + using var result = await SendRaw(client, "{__schema{queryType{name}}}"); + + // Assert + result.RootElement.TryGetProperty("errors", out var errors).ShouldBeTrue(); + errors.GetArrayLength().ShouldBeGreaterThan(0); + } + + [Fact] + public async Task Introspection_WithToken_ShouldReturn_Schema() + { + // Arrange + using var client = this.application.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateToken(Audience)); + + // Act + using var result = await SendRaw(client, "{__schema{queryType{name}}}"); + + // Assert + result.RootElement.TryGetProperty("errors", out _).ShouldBeFalse(); + result.RootElement.GetProperty("data").GetProperty("__schema").GetProperty("queryType").GetProperty("name").GetString().ShouldBe("Query"); + } + + [Fact] + public async Task SchemaDownload_WithoutToken_ShouldNotReturn_Schema() + { + // Arrange + using var client = this.application.CreateClient(); + + // Act + using var response = await client.GetAsync("/graphql?sdl"); + + // Assert + (await response.Content.ReadAsStringAsync()).ShouldNotContain("type Query"); + } + public void Dispose() { this.application.Dispose(); @@ -123,6 +166,13 @@ private static async Task Send(HttpClient client, string query) return (await response.Content.ReadAsStringAsync()).Deserialize(); } + private static async Task SendRaw(HttpClient client, string query) + { + using var response = await client.PostAsync("/graphql", new { query }.ToStringContent()); + + return JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + } + private static string CreateToken(string audience) { return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor diff --git a/tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs b/tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs new file mode 100644 index 0000000..d650f46 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Authentication/DevelopmentTokenTests.cs @@ -0,0 +1,91 @@ +namespace CleanGraphQLApi.Presentation.Tests.Integration.Authentication; + +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text; +using System.Text.Json; +using System.Threading.Tasks; +using Microsoft.IdentityModel.JsonWebTokens; +using Microsoft.IdentityModel.Tokens; +using Shouldly; +using Xunit; + +public class DevelopmentTokenTests : IDisposable +{ + private const string Issuer = "dotnet-user-jwts"; + private const string Audience = "http://localhost"; + + private static readonly byte[] KeyBytes = Encoding.UTF8.GetBytes("a-development-signing-key-for-the-tests-1234"); + + // What dotnet user-jwts writes: the issuer and audiences in appsettings.Development.json, the key in user secrets. + private readonly GraphQLApplication application = new(settings: new Dictionary + { + ["Authentication:Schemes:Bearer:ValidIssuer"] = Issuer, + ["Authentication:Schemes:Bearer:ValidAudiences:0"] = Audience, + ["Authentication:Schemes:Bearer:SigningKeys:0:Id"] = "test", + ["Authentication:Schemes:Bearer:SigningKeys:0:Issuer"] = Issuer, + ["Authentication:Schemes:Bearer:SigningKeys:0:Value"] = Convert.ToBase64String(KeyBytes), + ["Authentication:Schemes:Bearer:SigningKeys:0:Length"] = "32" + }); + + [Fact] + public async Task Query_WithoutToken_ShouldReturn_NotAuthenticated() + { + // Arrange + using var client = this.application.CreateClient(); + + // Act + using var result = await Send(client); + + // Assert + result.RootElement.GetProperty("errors")[0].GetProperty("extensions").GetProperty("code").GetString().ShouldBe("AUTH_NOT_AUTHENTICATED"); + } + + [Fact] + public async Task Query_WithDevelopmentToken_ShouldReturn_Data() + { + // Arrange + using var client = this.application.CreateClient(); + client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", CreateToken(KeyBytes)); + + // Act + using var result = await Send(client); + + // Assert + result.RootElement.TryGetProperty("errors", out _).ShouldBeFalse(); + result.RootElement.GetProperty("data").GetProperty("version").GetProperty("fileVersion").GetString().ShouldNotBeNullOrWhiteSpace(); + } + + private static async Task Send(HttpClient client) + { + using var response = await client.PostAsync("/graphql", new { query = "{version{fileVersion}}" }.ToStringContent()); + + return JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + } + + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this.application.Dispose(); + } + } + + private static string CreateToken(byte[] key) + { + return new JsonWebTokenHandler().CreateToken(new SecurityTokenDescriptor + { + Issuer = Issuer, + Audience = Audience, + Subject = new ClaimsIdentity([new Claim("sub", "developer")]), + Expires = DateTime.UtcNow.AddMinutes(5), + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256) + }); + } +} diff --git a/tests/Presentation.Tests.Integration/GraphQLApplication.cs b/tests/Presentation.Tests.Integration/GraphQLApplication.cs index 04637d0..f6ae06d 100644 --- a/tests/Presentation.Tests.Integration/GraphQLApplication.cs +++ b/tests/Presentation.Tests.Integration/GraphQLApplication.cs @@ -6,7 +6,7 @@ namespace CleanGraphQLApi.Presentation.Tests.Integration; using Microsoft.Extensions.Hosting; internal sealed class GraphQLApplication( - string environment = "local", + string environment = "Development", Dictionary? settings = null, Action? configureServices = null) : WebApplicationFactory { diff --git a/tests/Presentation.Tests.Integration/Presentation.Tests.Integration.csproj b/tests/Presentation.Tests.Integration/Presentation.Tests.Integration.csproj index 7490f07..baf1389 100644 --- a/tests/Presentation.Tests.Integration/Presentation.Tests.Integration.csproj +++ b/tests/Presentation.Tests.Integration/Presentation.Tests.Integration.csproj @@ -4,8 +4,8 @@ false true - - $(DefineConstants);includeAuth + + $(DefineConstants);includeAuth;includeRateLimiting $(NoWarn);S3903;CA1707;CS8602;CS8618 diff --git a/tests/Presentation.Tests.Integration/RateLimiting/RateLimitingTests.cs b/tests/Presentation.Tests.Integration/RateLimiting/RateLimitingTests.cs new file mode 100644 index 0000000..dcd0758 --- /dev/null +++ b/tests/Presentation.Tests.Integration/RateLimiting/RateLimitingTests.cs @@ -0,0 +1,73 @@ +namespace CleanGraphQLApi.Presentation.Tests.Integration.RateLimiting; + +using System.Net; +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +public class RateLimitingTests +{ + private static readonly Dictionary TwoPerMinute = new() + { + ["RateLimiting:PermitLimit"] = "2", + ["RateLimiting:Window"] = "00:01:00" + }; + + [Fact] + public async Task Request_OverTheLimit_ShouldReturn_TooManyRequestsWithRetryAfter() + { + // Arrange + using var application = new GraphQLApplication(settings: TwoPerMinute); + using var client = application.CreateClient(); + var path = new Uri("/not-a-real-path", UriKind.Relative); + + // Act + using var first = await client.GetAsync(path); + using var second = await client.GetAsync(path); + using var third = await client.GetAsync(path); + + // Assert + first.StatusCode.ShouldNotBe(HttpStatusCode.TooManyRequests); + second.StatusCode.ShouldNotBe(HttpStatusCode.TooManyRequests); + third.StatusCode.ShouldBe(HttpStatusCode.TooManyRequests); + third.Headers.RetryAfter.ShouldNotBeNull(); + } + + [Fact] + public async Task Health_OverTheLimit_ShouldReturn_Healthy() + { + // Arrange + using var application = new GraphQLApplication(settings: TwoPerMinute); + using var client = application.CreateClient(); + + for (var i = 0; i < 3; i++) + { + using var _ = await client.GetAsync(new Uri("/not-a-real-path", UriKind.Relative)); + } + + // Act + using var response = await client.GetAsync(new Uri("/health/live", UriKind.Relative)); + + // Assert + response.StatusCode.ShouldBe(HttpStatusCode.OK); + } + + [Fact] + public async Task Request_WithoutALimit_ShouldNotReturn_TooManyRequests() + { + // Arrange + using var application = new GraphQLApplication(); + using var client = application.CreateClient(); + var statusCodes = new List(); + + // Act + for (var i = 0; i < 5; i++) + { + using var response = await client.GetAsync(new Uri("/not-a-real-path", UriKind.Relative)); + statusCodes.Add(response.StatusCode); + } + + // Assert + statusCodes.ShouldNotContain(HttpStatusCode.TooManyRequests); + } +} diff --git a/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs b/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs new file mode 100644 index 0000000..deab6b2 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Security/DeploymentGuardTests.cs @@ -0,0 +1,129 @@ +namespace CleanGraphQLApi.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 GraphQLApplication(environment); + + // Act + var exception = Should.Throw(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 GraphQLApplication(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 GraphQLApplication("Production", new Dictionary { ["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 GraphQLApplication("Production", new Dictionary + { + ["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("Development")] + [InlineData("Production")] + public void AnyEnvironment_WithAuthorityButNoAudience_ShouldNotStart(string environment) + { + // Arrange + using var application = new GraphQLApplication(environment, new Dictionary + { + ["Authentication:Authority"] = "https://login.example.com", + ["Authentication:Audience"] = string.Empty + }); + + // Act + var exception = Should.Throw(application.CreateClient); + + // Assert + exception.Message.ShouldContain("Authentication:Authority is set without Authentication:Audience"); + } + + [Theory] + [InlineData("Production")] + [InlineData("docker")] + public void EnvironmentOtherThanDevelopment_WithDevelopmentTokens_ShouldNotStart(string environment) + { + // Arrange + using var application = new GraphQLApplication(environment, new Dictionary + { + ["Authentication:Authority"] = "https://login.example.com", + ["Authentication:Schemes:Bearer:ValidIssuer"] = "dotnet-user-jwts" + }); + + // Act + var exception = Should.Throw(application.CreateClient); + + // Assert + exception.Message.ShouldContain("development tokens"); + exception.Message.ShouldContain($"'{environment}' environment"); + } + + [Theory] + [InlineData("http://login.example.com")] + [InlineData("login.example.com")] + public void AnyEnvironment_WithAuthorityThatIsNotHttps_ShouldNotStart(string authority) + { + // Arrange + using var application = new GraphQLApplication(settings: new Dictionary { ["Authentication:Authority"] = authority }); + + // Act + var exception = Should.Throw(application.CreateClient); + + // Assert + exception.Message.ShouldContain("Authentication:Authority must be an absolute https URL"); + } +#endif +} diff --git a/tests/Presentation.Tests.Integration/Security/SecurityHeadersTests.cs b/tests/Presentation.Tests.Integration/Security/SecurityHeadersTests.cs new file mode 100644 index 0000000..8416878 --- /dev/null +++ b/tests/Presentation.Tests.Integration/Security/SecurityHeadersTests.cs @@ -0,0 +1,41 @@ +namespace CleanGraphQLApi.Presentation.Tests.Integration.Security; + +using System.Threading.Tasks; +using Shouldly; +using Xunit; + +public class SecurityHeadersTests : IDisposable +{ + private readonly GraphQLApplication application = new(); + + [Theory] + [InlineData("/health/live")] + [InlineData("/not-a-real-path")] + public async Task Response_ShouldCarry_SecurityHeaders(string path) + { + // Arrange + using var client = this.application.CreateClient(); + + // Act + using var response = await client.GetAsync(path); + + // Assert + response.Headers.GetValues("X-Content-Type-Options").ShouldBe(["nosniff"]); + response.Headers.GetValues("X-Frame-Options").ShouldBe(["DENY"]); + response.Headers.GetValues("Referrer-Policy").ShouldBe(["no-referrer"]); + } + + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this.application.Dispose(); + } + } +} diff --git a/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs b/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs index dafc577..a70a0a9 100644 --- a/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs +++ b/tests/Presentation.Tests.Unit/Authentication/AuthenticationSettingsTests.cs @@ -40,4 +40,26 @@ public void FromConfiguration_ShouldReturn_EnabledSettings_WhenAuthorityIsSet() result.Authority.ShouldBe("https://login.example.com"); result.Audience.ShouldBe("https://api.example.com"); } + + [Fact] + public void FromConfiguration_ShouldReturn_EnabledSettings_WhenDevelopmentTokensAreSetUp_EvenWithAnAuthority() + { + // Arrange + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["Authentication:Authority"] = "https://login.example.com", + ["Authentication:Schemes:Bearer:ValidIssuer"] = "dotnet-user-jwts" + }) + .Build(); + + // Act + var result = AuthenticationSettings.FromConfiguration(configuration); + + // Assert + result.Enabled.ShouldBeTrue(); + result.UsesDevelopmentTokens.ShouldBeTrue(); + result.HasAuthority.ShouldBeFalse(); + result.DevelopmentTokenIssuer.ShouldBe("dotnet-user-jwts"); + } } diff --git a/tests/Presentation.Tests.Unit/RateLimiting/RateLimitingSettingsTests.cs b/tests/Presentation.Tests.Unit/RateLimiting/RateLimitingSettingsTests.cs new file mode 100644 index 0000000..8b91f69 --- /dev/null +++ b/tests/Presentation.Tests.Unit/RateLimiting/RateLimitingSettingsTests.cs @@ -0,0 +1,63 @@ +namespace CleanGraphQLApi.Presentation.Tests.Unit.RateLimiting; + +using Microsoft.Extensions.Configuration; +using Presentation.RateLimiting; +using Shouldly; +using Xunit; + +public class RateLimitingSettingsTests +{ + [Fact] + public void FromConfiguration_ShouldReturn_DisabledSettings_WhenSectionIsMissing() + { + // Arrange + var configuration = new ConfigurationBuilder().Build(); + + // Act + var result = RateLimitingSettings.FromConfiguration(configuration); + + // Assert + result.Enabled.ShouldBeFalse(); + result.Window.ShouldBe(TimeSpan.FromMinutes(1)); + } + + [Fact] + public void FromConfiguration_ShouldReturn_EnabledSettings_WhenPermitLimitIsSet() + { + // Arrange + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["RateLimiting:PermitLimit"] = "100", + ["RateLimiting:Window"] = "00:00:10" + }) + .Build(); + + // Act + var result = RateLimitingSettings.FromConfiguration(configuration); + + // Assert + result.Enabled.ShouldBeTrue(); + result.PermitLimit.ShouldBe(100); + result.Window.ShouldBe(TimeSpan.FromSeconds(10)); + } + + [Fact] + public void FromConfiguration_ShouldReturn_DisabledSettings_WhenWindowIsZero() + { + // Arrange + var configuration = new ConfigurationBuilder() + .AddInMemoryCollection(new Dictionary + { + ["RateLimiting:PermitLimit"] = "100", + ["RateLimiting:Window"] = "00:00:00" + }) + .Build(); + + // Act + var result = RateLimitingSettings.FromConfiguration(configuration); + + // Assert + result.Enabled.ShouldBeFalse(); + } +} diff --git a/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs b/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs index ed4e041..f4132e4 100644 --- a/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs +++ b/tests/Presentation.Tests.Unit/Telemetry/TelemetrySettingsTests.cs @@ -1,7 +1,6 @@ namespace CleanGraphQLApi.Presentation.Tests.Unit.Telemetry; -using System.Reflection; -using System.Reflection.Emit; +using Application.Versions.Entities; using Microsoft.Extensions.Configuration; using Presentation.Telemetry; using Shouldly; @@ -14,16 +13,16 @@ 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, "Development", version); // Assert result.Enabled.ShouldBeFalse(); result.ServiceName.ShouldBe(TelemetrySettings.DefaultServiceName); - result.ServiceVersion.ShouldBe(assembly.GetCustomAttribute()!.InformationalVersion); - result.EnvironmentName.ShouldBe("local"); + result.ServiceVersion.ShouldBe("1.2.3+e30eba8"); + result.EnvironmentName.ShouldBe("Development"); } [Fact] @@ -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, "Development", version); // Assert result.ServiceVersion.ShouldBe("unknown");