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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .agents/skills/nitro/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <token>` header in Nitro's connection settings.
4. With authentication on, add an `Authorization: Bearer <token>` 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
Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/schema-snapshot/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <http://localhost:7330/graphql?sdl>.
3. Copy the new SDL into `schema.graphql`. Either take it from the test output, or run the app without an authority and open <http://localhost:7330/graphql?sdl>. 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.

Expand Down
5 changes: 5 additions & 0 deletions .agents/skills/security-defaults/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

Expand All @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
namespace CleanGraphQLApi.Presentation.Authentication;

using HotChocolate.AspNetCore;
using HotChocolate.Execution;
using Microsoft.AspNetCore.Http;

/// <summary>
/// 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.
/// </summary>
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);
}
}
13 changes: 13 additions & 0 deletions src/Presentation/Extensions/ProgramExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,14 +140,27 @@ 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<IntrospectionRequestInterceptor>()
#endif
.AddInstrumentation()
.AddMutationConventions(applyToAllMutations: true)
// The filter is built from the schema's own services, so its logger comes from the application's.
.AddErrorFilter(services => new ApplicationErrorFilter(
services.GetRootServiceProvider().GetRequiredService<ILogger<ApplicationErrorFilter>>()))
.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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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();
Expand All @@ -123,6 +166,13 @@ private static async Task<GraphData> Send(HttpClient client, string query)
return (await response.Content.ReadAsStringAsync()).Deserialize<GraphData>();
}

private static async Task<JsonDocument> 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
Expand Down
Loading