diff --git a/.agents/skills/nitro/SKILL.md b/.agents/skills/nitro/SKILL.md index 77f790b..4710849 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. 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/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 index 4e80364..a0c6e9d 100644 --- a/.agents/skills/security-defaults/SKILL.md +++ b/.agents/skills/security-defaults/SKILL.md @@ -15,6 +15,7 @@ The app ships safe by default, and each protection lives in one place in `src/Pr | --- | --- | --- | | 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 | | HSTS and HTTPS redirection | Security region | HSTS outside local runs | | Compose ports on `127.0.0.1` | `docker-compose.yml` (`docker-and-compose`) | Always | @@ -39,6 +40,10 @@ Don't add environment names to `IsLocal` to get a deployment past the guard; set 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. + ## Steps 1. Add a header in `SecurityHeaders`, not in an endpoint or a filter, so every response gets it. diff --git a/README.md b/README.md index 67ceb51..9a221c2 100644 --- a/README.md +++ b/README.md @@ -81,7 +81,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. +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 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/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 f510940..77ce760 100644 --- a/src/Presentation/Extensions/ProgramExtensions.cs +++ b/src/Presentation/Extensions/ProgramExtensions.cs @@ -140,6 +140,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) @@ -147,7 +150,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; 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