Skip to content

Commit

Permalink
Fix anti-forgery
Browse files Browse the repository at this point in the history
Fix anti-forgery by ensuring a valid anti-forgery cookie is set for each RazorSlices page render.
  • Loading branch information
martincostello committed Sep 16, 2024
1 parent 38a70be commit d984a1e
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/Costellobot/AdminEndpoints.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Text.Json.Nodes;
using MartinCostello.Costellobot.Models;
using MartinCostello.Costellobot.Slices;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
Expand Down Expand Up @@ -103,6 +104,7 @@ public static IEndpointRouteBuilder MapAdminRoutes(this IEndpointRouteBuilder bu
var admin = new CostellobotAdminAttribute();

builder.MapMethods("/", [HttpMethod.Get.Method, HttpMethod.Head.Method], () => Results.Extensions.RazorSlice<Home>())
.AddEndpointFilter<AntiforgeryFilter>()
.WithMetadata(admin);

builder
Expand All @@ -111,6 +113,7 @@ public static IEndpointRouteBuilder MapAdminRoutes(this IEndpointRouteBuilder bu
(var deliveries, _) = await GetDeliveries(client, cursor: null);
return Results.Extensions.RazorSlice<Deliveries, IReadOnlyList<WebhookDelivery>>(deliveries);
})
.AddEndpointFilter<AntiforgeryFilter>()
.WithName(DeliveriesRoute)
.WithMetadata(admin);

Expand Down Expand Up @@ -202,6 +205,7 @@ static void TryPopulateHeaders(JsonElement element, IDictionary<string, string>
}
}
})
.AddEndpointFilter<AntiforgeryFilter>()
.WithName(DeliveryRoute)
.WithMetadata(admin);

Expand All @@ -216,6 +220,7 @@ static void TryPopulateHeaders(JsonElement element, IDictionary<string, string>
}).WithMetadata(admin);

builder.MapGet("/github-webhook", (IOptions<GitHubOptions> options) => Results.Extensions.RazorSlice<Debug, GitHubOptions>(options.Value))
.AddEndpointFilter<AntiforgeryFilter>()
.WithMetadata(admin);

return builder;
Expand Down Expand Up @@ -281,4 +286,15 @@ static void TryPopulateHeaders(JsonElement element, IDictionary<string, string>

return cursor;
}

private sealed class AntiforgeryFilter : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var antiforgery = context.HttpContext.RequestServices.GetRequiredService<IAntiforgery>();
antiforgery.SetCookieTokenAndHeader(context.HttpContext);

return await next(context);
}
}
}

0 comments on commit d984a1e

Please sign in to comment.