OIDC issuer: per-address and per-client limits, token-row cap, scheduled prune, marker brake
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
42dc46dbc6
commit
d0749d4022
5 changed files with 74 additions and 14 deletions
|
|
@ -44,6 +44,8 @@ echoes its value.
|
|||
| `Bifrost:Oidc:Clients:Mas:ClientId` | The client id MAS presents. |
|
||||
| `Bifrost:Oidc:Clients:Mas:ClientSecretPath` | File holding the client secret. |
|
||||
| `Bifrost:Oidc:Clients:Mas:RedirectUri` | MAS's callback URL, registered exactly. |
|
||||
| `Bifrost:Oidc:BrakePath` | Optional. While a file exists at this path, `/connect/authorize`, `/token` and `/userinfo` answer 503 `temporarily_unavailable` and nothing is issued; delete the file to release. Checked per request, so no restart. Unset: no marker brake. |
|
||||
| `Bifrost:Oidc:Limits:*` | `PerAddressPermits` (30), `PerClientPermits` (300), `Window` (1 min), `MaxTrackedKeys` (10000), `MaxTokenRows` (20000), `PruneInterval` (5 min). |
|
||||
| `Bifrost:Oidc:Clients:Mas:BackchannelLogoutUri` | Optional. MAS's back-channel logout URL, `https://<mas>/upstream/backchannel-logout/<provider ULID>`; absolute http(s) or startup fails. Unset: no logout is sent and no authorization is revoked. |
|
||||
|
||||
There are no development or ephemeral keys in the host. Key files are provisioned like the other
|
||||
|
|
@ -111,17 +113,28 @@ Configure MAS's upstream provider with the issuer above, the client id and secre
|
|||
from `preferred_username`. MAS mints the Matrix localpart on first sign-in, so the claim must never change for an
|
||||
account.
|
||||
|
||||
## Limits, prune, brake
|
||||
|
||||
`OidcGuardMiddleware` sits ahead of OpenIddict and guards the three endpoints. In order: the marker brake (503); a per-address
|
||||
budget (429 with `Retry-After`; the address is the connection's after forwarded-headers handling that trusts only the local
|
||||
proxy, IPv6 keyed by /64); a per-client budget keyed by the client id the caller names (authorize query or form, token Basic
|
||||
header; unreadable or over-long names share one key); and a cap on token rows: a new authorize request (no `request_uri`)
|
||||
is refused with 503 while the table holds `MaxTokenRows`. Any failure inside the guard is a 503, never a pass. MAS's flow is
|
||||
a handful of requests per sign-in from one address, far under the defaults.
|
||||
|
||||
`OidcPruner` runs every `PruneInterval` and deletes tokens past expiry (parked authorize requests, codes, access tokens) or no
|
||||
longer valid, then authorizations no longer valid or ad hoc with no token left (younger than five minutes are left alone).
|
||||
Live rows are untouched. Plain EF queries rather than OpenIddict's own prune, which uses ExecuteDelete and cannot run on the
|
||||
in-memory provider the tests use.
|
||||
|
||||
`docs/oidc-reserved-accounts.sql` is the read-only query for existing accounts that hold one of the 28 reserved names.
|
||||
|
||||
## Not built
|
||||
|
||||
Checked against the Window B list (2026-11-11). Present and tested: discovery, JWKS, authorize/token/userinfo, PKCE S256,
|
||||
the one client, claims to a Matrix-legal localpart (`[a-z0-9._-]`, 3-80, lower case), reserved names at creation and now at
|
||||
issuance, back-channel logout. Not present:
|
||||
|
||||
- **Rate limits and pruning.** No limiter sits on `/connect/*`, and expired OpenIddict rows (parked authorize requests,
|
||||
tokens, authorizations) are never deleted. The authorize endpoint is anonymous and its client id and redirect URI are
|
||||
public, so a caller can park rows without bound. Needs a budget (`FixedWindowBudget`) and a prune.
|
||||
- **A brake.** The Bifrost process has none; the deploy brake belongs to Idunn. The only off switch is removing
|
||||
`Bifrost:Oidc` and restarting, or membership leaving `Active` (the reconciler then logs the person out).
|
||||
- **Non-member sign-in.** The gate is `Active` membership, so an account with no membership gets `access_denied`. A "Users"
|
||||
tier for chat registration, with no vote, is a policy choice not yet made; nothing here writes membership or votes.
|
||||
- **MAS upstream block.** `gamecult-ops` `chat/matrix-auth/config.yaml` has no `upstream_oauth2` (provider ULID,
|
||||
|
|
|
|||
12
docs/oidc-reserved-accounts.sql
Normal file
12
docs/oidc-reserved-accounts.sql
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
-- Read-only. Which existing UserAccounts hold one of the 28 reserved localparts
|
||||
-- (BifrostIdentityService.ReservedIdentities). Written for review; not run on live.
|
||||
-- Run it in a read-only transaction by whoever holds the database:
|
||||
-- psql -v ON_ERROR_STOP=1 -c 'BEGIN READ ONLY' -f docs/oidc-reserved-accounts.sql
|
||||
-- Keep the list in step with ReservedIdentities; the issuer refuses these at authorize (#49).
|
||||
SELECT a."Id", a."BifrostIdentity", a."NormalizedBifrostIdentity", a."CreatedAtUtc", a."LastSeenAtUtc"
|
||||
FROM "UserAccounts" a
|
||||
WHERE lower(a."NormalizedBifrostIdentity") IN (
|
||||
'admin', 'aqua', 'deru', 'eureka', 'heimdall', 'ivixey', 'kiko', 'libby', 'meta', 'nibu', 'unnie', 'void', 'weksa',
|
||||
'root', 'system', 'matrix', 'synapse', 'support', 'bot', 'mod', 'moderator', 'postmaster', 'gamecult',
|
||||
'bifrost', 'idunn', 'odin', 'huginn', 'ratatoskr')
|
||||
ORDER BY a."NormalizedBifrostIdentity";
|
||||
|
|
@ -1,9 +1,13 @@
|
|||
using System.Net;
|
||||
using System.Text;
|
||||
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;
|
||||
|
|
@ -139,17 +143,48 @@ public sealed class OidcRateLimit(OidcIssuerOptions options, TimeProvider clock)
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes expired and orphaned authorizations and tokens on a schedule (OpenIddict's own prune: tokens that are no longer
|
||||
/// valid or have expired, and authorizations that are ad hoc or invalid with no live token). Live rows are never touched.
|
||||
/// 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, so the same code runs on
|
||||
/// Postgres and on the in-memory test provider.
|
||||
/// </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 threshold = clock.GetUtcNow();
|
||||
await scope.ServiceProvider.GetRequiredService<IOpenIddictTokenManager>().PruneAsync(threshold, cancellationToken);
|
||||
await scope.ServiceProvider.GetRequiredService<IOpenIddictAuthorizationManager>().PruneAsync(threshold, cancellationToken);
|
||||
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
|
||||
{
|
||||
var authorizations = await db.Set<OpenIddictEntityFrameworkCoreAuthorization>()
|
||||
.Where(authorization => authorization.CreationDate < young
|
||||
&& (authorization.Status != Statuses.Valid || (authorization.Type == AuthorizationTypes.AdHoc && !authorization.Tokens.Any())))
|
||||
.Take(Batch).ToListAsync(cancellationToken);
|
||||
db.RemoveRange(authorizations);
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
removed = authorizations.Count;
|
||||
}
|
||||
while (removed == Batch);
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
|
|
|
|||
|
|
@ -294,13 +294,13 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
|
|||
parked.Add(response.StatusCode);
|
||||
}
|
||||
|
||||
Assert.Equal(3L, await factory.TokenRowsAsync());
|
||||
Assert.Equal(3, await factory.TokenRowsAsync());
|
||||
Assert.All(parked.Skip(3), status => Assert.Equal(HttpStatusCode.ServiceUnavailable, status));
|
||||
Assert.All(parked.Take(3), status => Assert.NotEqual(HttpStatusCode.ServiceUnavailable, status));
|
||||
|
||||
factory.Clock.Advance(TimeSpan.FromMinutes(11)); // past the ten-minute parked lifetime
|
||||
await factory.PruneAsync();
|
||||
Assert.Equal(0L, await factory.TokenRowsAsync());
|
||||
Assert.Equal(0, await factory.TokenRowsAsync());
|
||||
using var again = await client.GetAsync(NewRequest().Path);
|
||||
Assert.NotEqual(HttpStatusCode.ServiceUnavailable, again.StatusCode);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -280,10 +280,10 @@ public sealed class OidcSettingsFactory(IReadOnlyDictionary<string, string?> set
|
|||
|
||||
public Task PruneAsync() => Services.GetRequiredService<Bifrost.Web.Features.Oidc.OidcPruner>().PruneAsync(CancellationToken.None);
|
||||
|
||||
public async Task<long> TokenRowsAsync()
|
||||
public async Task<int> TokenRowsAsync()
|
||||
{
|
||||
using var scope = Services.CreateScope();
|
||||
return await scope.ServiceProvider.GetRequiredService<OpenIddict.Abstractions.IOpenIddictTokenManager>().CountAsync();
|
||||
return (int)await scope.ServiceProvider.GetRequiredService<OpenIddict.Abstractions.IOpenIddictTokenManager>().CountAsync();
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue