OIDC issuer: address budget, token-row cap, scheduled prune, marker brake (#50)

This commit is contained in:
Heimdall 2026-11-11 08:12:48 +00:00
commit 5201508bdc
8 changed files with 581 additions and 7 deletions

View file

@ -16,6 +16,15 @@ public sealed class OidcIssuerOptions
public OidcClientsOptions Clients { get; init; } = new();
public OidcLimitsOptions Limits { get; init; } = new();
/// <summary>
/// Optional path of the issuer's brake marker. While a file exists there, /connect/* answers 503 and nothing is issued;
/// remove it to release. Checked on every request (one stat), so engaging and releasing need no restart.
/// Unset: the issuer has no marker brake (removing this section and restarting is the other off switch).
/// </summary>
public string BrakePath { get; init; } = string.Empty;
/// <summary>Null when the section is absent.</summary>
public static OidcIssuerOptions? FromConfiguration(IConfiguration configuration)
{
@ -42,3 +51,22 @@ public sealed class OidcClientOptions
/// <summary>MAS's back-channel logout URL for this provider. Empty: no logout is sent and no session is ended.</summary>
public string BackchannelLogoutUri { get; init; } = string.Empty;
}
/// <summary>
/// One budget on /connect/authorize, /connect/token and /connect/userinfo together, per source address in one fixed window (a refused caller gets 429 with Retry-After),
/// and the bound on what the anonymous authorize endpoint can park. No per-client budget: the client id is public. The defaults suit one client (MAS) behind one proxy.
/// </summary>
public sealed class OidcLimitsOptions
{
public int PerAddressPermits { get; init; } = 30;
public TimeSpan Window { get; init; } = TimeSpan.FromMinutes(1);
public int MaxTrackedKeys { get; init; } = 10_000;
/// <summary>The most OpenIddict token rows (parked authorize requests, codes, access tokens) allowed to exist; a new authorize request beyond it is refused until the prune frees room.</summary>
public int MaxTokenRows { get; init; } = 20_000;
/// <summary>How often expired and orphaned authorizations and tokens are deleted.</summary>
public TimeSpan PruneInterval { get; init; } = TimeSpan.FromMinutes(5);
}

View file

@ -0,0 +1,195 @@
using System.Net;
using Bifrost.Web.Configuration;
using Bifrost.Web.Data;
using Microsoft.EntityFrameworkCore;
using OpenIddict.EntityFrameworkCore.Models;
using Bifrost.Web.Features.Shared;
using Microsoft.Extensions.Options;
using OpenIddict.Abstractions;
using static OpenIddict.Abstractions.OpenIddictConstants;
using OpenIddict.Server.AspNetCore;
namespace Bifrost.Web.Features.Oidc;
/// <summary>
/// The issuer's front door, ahead of OpenIddict: the marker brake, the per-address budget, and the bound
/// on token rows. The address is the connection's, already corrected by the forwarded-headers handling that trusts only
/// the local proxy, so a caller cannot pick its own. It fails closed: anything this middleware cannot decide is a 503, never a pass.
/// </summary>
public sealed class OidcGuardMiddleware(RequestDelegate next, OidcIssuerOptions options, OidcRateLimit limit, ILogger<OidcGuardMiddleware> logger)
{
public async Task InvokeAsync(HttpContext http, IOpenIddictTokenManager tokens)
{
var endpoint = EndpointOf(http.Request.Path);
if (endpoint is null)
{
await next(http);
return;
}
try
{
if (BrakeEngaged(options.BrakePath))
{
await RefuseAsync(http, StatusCodes.Status503ServiceUnavailable, "temporarily_unavailable", TimeSpan.FromMinutes(1));
return;
}
if (limit.Spend(AddressKey(http.Connection.RemoteIpAddress)) is { } byAddress)
{
await RefuseAsync(http, StatusCodes.Status429TooManyRequests, "too_many_requests", byAddress.RetryAfter);
return;
}
// A new authorize request parks a row for anyone who can name the (public) client; a resumed one carries request_uri and parks none.
if (endpoint == Authorize && !http.Request.Query.ContainsKey("request_uri") && await tokens.CountAsync(http.RequestAborted) >= options.Limits.MaxTokenRows)
{
await RefuseAsync(http, StatusCodes.Status503ServiceUnavailable, "temporarily_unavailable", options.Limits.PruneInterval);
return;
}
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
logger.LogError("OIDC guard could not decide ({ExceptionType}); the request is refused.", exception.GetType().Name);
await RefuseAsync(http, StatusCodes.Status503ServiceUnavailable, "temporarily_unavailable", TimeSpan.FromMinutes(1));
return;
}
await next(http);
}
private const string Authorize = "authorize";
// OpenIddict answers these paths with or without a trailing slash, so the match is by segments, never exact equality.
private static string? EndpointOf(PathString path) =>
path.StartsWithSegments(OidcServiceCollectionExtensions.AuthorizationPath, StringComparison.OrdinalIgnoreCase) ? Authorize
: path.StartsWithSegments(OidcServiceCollectionExtensions.TokenPath, StringComparison.OrdinalIgnoreCase) ? "token"
: path.StartsWithSegments(OidcServiceCollectionExtensions.UserInfoPath, StringComparison.OrdinalIgnoreCase) ? "userinfo"
: null;
// A marker that cannot be told apart from an absent one (a permission or I/O error) throws, and the guard answers 503: the brake never releases by accident.
private static bool BrakeEngaged(string path)
{
if (string.IsNullOrWhiteSpace(path))
{
return false;
}
try
{
File.GetAttributes(path);
return true;
}
catch (Exception exception) when (exception is FileNotFoundException or DirectoryNotFoundException)
{
return false;
}
}
// An IPv6 caller owns its /64, so rotating the low bits buys nothing.
private static string AddressKey(IPAddress? address)
{
if (address is null)
{
return "unknown";
}
if (address.IsIPv4MappedToIPv6)
{
address = address.MapToIPv4();
}
if (address.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
{
return address.ToString();
}
var bytes = address.GetAddressBytes();
Array.Clear(bytes, 8, 8);
return new IPAddress(bytes).ToString() + "/64";
}
private static Task RefuseAsync(HttpContext http, int status, string error, TimeSpan retryAfter)
{
http.Response.StatusCode = status;
http.Response.Headers.RetryAfter = Math.Max(1, (int)Math.Ceiling(retryAfter.TotalSeconds)).ToString(System.Globalization.CultureInfo.InvariantCulture);
http.Response.ContentType = "application/json";
return http.Response.WriteAsync($"{{\"error\":\"{error}\"}}", http.RequestAborted);
}
}
/// <summary>
/// The issuer's per-address permits on the shared fixed-window budget. There is no per-client budget: the one client's id is
/// public and what a caller names unverified, so a budget on it would let anyone spend the real client's permits.
/// </summary>
public sealed class OidcRateLimit(OidcIssuerOptions options, TimeProvider clock)
{
private readonly FixedWindowBudget addresses = new(options.Limits.PerAddressPermits, options.Limits.Window, options.Limits.MaxTrackedKeys, clock);
public BudgetDenial? Spend(string address) => addresses.Spend(address);
}
/// <summary>
/// Deletes expired and orphaned authorizations and tokens on a schedule: tokens past their expiry (parked authorize
/// requests, codes, access tokens) or no longer valid, then authorizations that are no longer valid or are ad hoc with no
/// token left. Live rows are never touched. Plain queries, not OpenIddict's ExecuteDelete prune, which the in-memory test provider
/// cannot run; an authorization takes its remaining tokens with it, because the foreign key has no cascade on Postgres.
/// </summary>
public sealed class OidcPruner(IServiceScopeFactory scopes, OidcIssuerOptions options, TimeProvider clock, ILogger<OidcPruner> logger) : BackgroundService
{
private const int Batch = 500;
// A fresh authorization briefly has no token yet; leave anything younger than this alone.
private static readonly TimeSpan AuthorizationGrace = TimeSpan.FromMinutes(5);
public async Task PruneAsync(CancellationToken cancellationToken)
{
await using var scope = scopes.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
var now = clock.GetUtcNow();
var young = now - AuthorizationGrace;
int removed;
do
{
var tokens = await db.Set<OpenIddictEntityFrameworkCoreToken>()
.Where(token => token.ExpirationDate < now || (token.Status != Statuses.Valid && token.CreationDate < young))
.Take(Batch).ToListAsync(cancellationToken);
db.RemoveRange(tokens);
await db.SaveChangesAsync(cancellationToken);
removed = tokens.Count;
}
while (removed == Batch);
do
{
// A token row references its authorization (no cascade in the database), so the tokens go with it.
var authorizations = await db.Set<OpenIddictEntityFrameworkCoreAuthorization>()
.Include(authorization => authorization.Tokens)
.Where(authorization => authorization.CreationDate < young
&& (authorization.Status != Statuses.Valid || (authorization.Type == AuthorizationTypes.AdHoc && !authorization.Tokens.Any())))
.Take(Batch).ToListAsync(cancellationToken);
db.RemoveRange(authorizations.SelectMany(authorization => authorization.Tokens));
db.RemoveRange(authorizations);
await db.SaveChangesAsync(cancellationToken);
removed = authorizations.Count;
}
while (removed == Batch);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(options.Limits.PruneInterval, clock);
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
await PruneAsync(stoppingToken);
}
catch (Exception exception) when (exception is not OperationCanceledException)
{
logger.LogError("OIDC prune failed ({ExceptionType}); the next tick tries again.", exception.GetType().Name);
}
}
}
}

View file

@ -67,6 +67,9 @@ public static class OidcServiceCollectionExtensions
server.Issuer = issuer;
});
services.AddSingleton<OidcRateLimit>();
services.AddSingleton<OidcPruner>();
services.AddHostedService(provider => provider.GetRequiredService<OidcPruner>());
services.AddHostedService<OidcClientSeeder>();
if (!string.IsNullOrWhiteSpace(options.Clients.Mas.BackchannelLogoutUri))
{

View file

@ -285,6 +285,11 @@ if (!app.Environment.IsDevelopment())
app.UseHttpLogging();
app.UseHttpsRedirection();
if (oidcOptions is not null)
{
app.UseMiddleware<OidcGuardMiddleware>(); // before authentication: OpenIddict answers /connect/* inside it
}
app.UseStaticFiles();
app.UseRouting();
app.UseConceptTallyCors();