Oidc behaviour fixes: remove stale clients at seeding, re-check Active at the token endpoint, pin issuer and parked lifetime by tests, one PKCE owner, drop the unread consent type

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-10-27 04:06:37 +01:00
commit 443b0fd4fb
6 changed files with 151 additions and 17 deletions

View file

@ -27,8 +27,8 @@ client-credentials or device flow, no refresh token, and no dynamic client regis
## The one client
Exactly one client is registered, from configuration, and seeded or updated at startup. Consent is implicit
(first-party). Any other `client_id`, an unregistered `redirect_uri`, or a request without PKCE is refused by the
Exactly one client is registered, from configuration, and seeded or updated at startup; every other application
row (with its authorizations and tokens) is deleted at startup. Any other `client_id`, an unregistered `redirect_uri`, or a request without PKCE is refused by the
provider before any sign-in redirect.
## Configuration
@ -70,6 +70,7 @@ The authorize endpoint reads the cookie session and the same actor facts the `/A
- Signed in, `Active`, but `NormalizedBifrostIdentity` empty: `error=access_denied` with
`error_description=The account has no Bifrost identity.`
- Signed in and `Active`: a code is issued.
- Token endpoint: membership is read again; an account no longer `Active` gets `invalid_grant` and no tokens.
## MAS configuration

View file

@ -7,8 +7,8 @@ using static OpenIddict.Abstractions.OpenIddictConstants;
namespace Bifrost.Web.Features.Oidc;
/// <summary>
/// Makes the provider's one client match configuration at startup, creating it or updating it in place.
/// Nothing else registers clients: any other client_id is refused by OpenIddict.
/// Makes the provider's one client match configuration at startup, creating it or updating it in place, and removes
/// every other application (with its authorizations and tokens), so a client left by an older configuration cannot get codes.
/// </summary>
public sealed class OidcClientSeeder(
IServiceScopeFactory scopeFactory,
@ -30,7 +30,6 @@ public sealed class OidcClientSeeder(
ClientId = mas.ClientId,
ClientSecret = material.ClientSecret,
ClientType = ClientTypes.Confidential,
ConsentType = ConsentTypes.Implicit,
DisplayName = "Matrix Authentication Service",
RedirectUris = { new Uri(mas.RedirectUri, UriKind.Absolute) },
Permissions =
@ -41,8 +40,7 @@ public sealed class OidcClientSeeder(
Permissions.ResponseTypes.Code,
Permissions.Scopes.Profile,
Permissions.Prefixes.Scope + Scopes.OpenId
},
Requirements = { Requirements.Features.ProofKeyForCodeExchange }
}
};
var existing = await manager.FindByClientIdAsync(mas.ClientId, cancellationToken);
@ -54,6 +52,20 @@ public sealed class OidcClientSeeder(
{
await manager.UpdateAsync(existing, descriptor, cancellationToken);
}
var applications = new List<object>();
await foreach (var application in manager.ListAsync(cancellationToken: cancellationToken))
{
applications.Add(application);
}
foreach (var application in applications)
{
if (!string.Equals(await manager.GetClientIdAsync(application, cancellationToken), mas.ClientId, StringComparison.Ordinal))
{
await manager.DeleteAsync(application, cancellationToken);
}
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;

View file

@ -1,6 +1,9 @@
using System.Security.Claims;
using Microsoft.AspNetCore;
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
using Bifrost.Web.Features.Shared;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using OpenIddict.Abstractions;
@ -75,11 +78,26 @@ public static class OidcEndpoints
return Results.SignIn(principal, properties: null, OpenIddictScheme);
}
private static async Task<IResult> ExchangeAsync(HttpContext http)
private static async Task<IResult> ExchangeAsync(HttpContext http, BifrostDbContext db)
{
// Only the authorization code grant is enabled, so OpenIddict has refused every other grant already.
// The code's own principal carries the claims chosen at authorize time.
// The code's own principal carries the claims chosen at authorize time; membership is read again here,
// because the code outlives the authorize decision (a member suspended since gets no tokens).
var result = await http.AuthenticateAsync(OpenIddictScheme);
var subject = result.Principal?.GetClaim(Claims.Subject);
UserAccount? account = null;
if (Guid.TryParse(subject, out var accountId))
{
account = await db.UserAccounts.AsNoTracking()
.Include(x => x.Membership)
.SingleOrDefaultAsync(x => x.Id == accountId, http.RequestAborted);
}
if (!new CurrentBifrostActor(true, account).IsActiveMember)
{
return Deny(Errors.InvalidGrant, NotActiveDescription);
}
return Results.SignIn(result.Principal!, properties: null, OpenIddictScheme);
}

View file

@ -14,7 +14,7 @@ public static class OidcServiceCollectionExtensions
public const string UserInfoPath = "/connect/userinfo";
/// <summary>How long a parked authorize request (OpenIddict's request token) can wait for the user to sign in.</summary>
public static readonly TimeSpan ParkedRequestLifetime = TimeSpan.FromMinutes(10);
private static readonly TimeSpan ParkedRequestLifetime = TimeSpan.FromMinutes(10);
/// <summary>
/// Registers Bifrost as an OIDC provider whose issuer is <see cref="BifrostHostOptions.PublicBaseUrl"/>: authorization-code flow with

View file

@ -202,19 +202,24 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
private async Task ParkedRequestIsRefusedAfterItsLifetimeAsync()
{
var request = NewRequest();
// Fixed probe times, not the constant: a lifetime of a day, or of a minute, must show.
var early = NewRequest();
var late = NewRequest();
using var client = NewClient();
var signIn = await DriveAsync(client, request);
var resume = ReturnUrl(signIn);
var earlyResume = ReturnUrl(await DriveAsync(client, early));
var lateResume = ReturnUrl(await DriveAsync(client, late));
var identity = await RegisterAsync(client, $"late-{Guid.NewGuid():N}");
await _factory.SetMembershipAsync(identity, MembershipStatus.Active);
_factory.Clock.Advance(Bifrost.Web.Features.Oidc.OidcServiceCollectionExtensions.ParkedRequestLifetime + TimeSpan.FromMinutes(1));
_factory.Clock.Advance(TimeSpan.FromMinutes(5));
using var withinLifetime = await client.GetAsync(earlyResume);
Assert.True(AssertRedirectToClient(withinLifetime, early.State).ContainsKey("code"), "five minutes is within the lifetime");
using var late = await client.GetAsync(resume);
var location = late.Headers.Location?.OriginalString ?? string.Empty;
_factory.Clock.Advance(TimeSpan.FromMinutes(25));
using var expired = await client.GetAsync(lateResume);
var location = expired.Headers.Location?.OriginalString ?? string.Empty;
Assert.DoesNotContain("code=", location);
Assert.NotEqual(HttpStatusCode.OK, late.StatusCode);
Assert.NotEqual(HttpStatusCode.OK, expired.StatusCode);
}
[Fact]
@ -329,6 +334,90 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
Assert.False(await manager.ValidateClientSecretAsync(stored, "drifted-secret"));
}
[Fact]
public async Task A_member_suspended_after_authorize_gets_no_tokens()
{
var (client, identity) = await SignedInAsync(MembershipStatus.Active, "Soon Suspended");
var request = NewRequest();
var code = await CodeAsync(client, request);
await _factory.SetMembershipAsync(identity, MembershipStatus.Suspended);
using var response = await TokenAsync(client, request, code);
var body = await response.Content.ReadAsStringAsync();
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
Assert.Contains("invalid_grant", body);
Assert.DoesNotContain("id_token", body);
Assert.DoesNotContain("access_token", body);
}
[Fact]
public async Task Startup_removes_every_client_but_the_configured_one()
{
// Own host: the stale client is a row the other tests must not see.
using var own = new OidcWebApplicationFactory();
await new OidcIssuerTests(own).StaleClientIsRemovedAsync();
}
private async Task StaleClientIsRemovedAsync()
{
const string staleId = "old-mas";
const string staleRedirect = "https://old.example.test/callback";
var (client, _) = await SignedInAsync(MembershipStatus.Active, "Member");
using (var scope = _factory.Services.CreateScope())
{
var manager = scope.ServiceProvider.GetRequiredService<OpenIddict.Abstractions.IOpenIddictApplicationManager>();
await manager.CreateAsync(new OpenIddict.Abstractions.OpenIddictApplicationDescriptor
{
ClientId = staleId,
ClientSecret = "stale-secret",
ClientType = OpenIddict.Abstractions.OpenIddictConstants.ClientTypes.Confidential,
ConsentType = OpenIddict.Abstractions.OpenIddictConstants.ConsentTypes.Implicit,
RedirectUris = { new Uri(staleRedirect) },
Permissions =
{
OpenIddict.Abstractions.OpenIddictConstants.Permissions.Endpoints.Authorization,
OpenIddict.Abstractions.OpenIddictConstants.Permissions.Endpoints.Token,
OpenIddict.Abstractions.OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode,
OpenIddict.Abstractions.OpenIddictConstants.Permissions.ResponseTypes.Code,
OpenIddict.Abstractions.OpenIddictConstants.Permissions.Prefixes.Scope + OpenIddict.Abstractions.OpenIddictConstants.Scopes.OpenId
}
});
}
// The control: before seeding, the stale client really can obtain a code.
var before = NewRequest(staleId, staleRedirect);
using (var issued = await DriveAsync(client, before))
{
Assert.Contains("code=", issued.Headers.Location?.OriginalString ?? string.Empty);
}
var seeder = Assert.Single(_factory.Services.GetServices<IHostedService>().OfType<Bifrost.Web.Features.Oidc.OidcClientSeeder>());
await seeder.StartAsync(CancellationToken.None);
var after = NewRequest(staleId, staleRedirect);
using var refused = await DriveAsync(client, after);
var location = refused.Headers.Location?.OriginalString ?? string.Empty;
Assert.DoesNotContain("code=", location);
Assert.NotEqual(HttpStatusCode.OK, refused.StatusCode);
using var fresh = _factory.Services.CreateScope();
var rows = fresh.ServiceProvider.GetRequiredService<Bifrost.Web.Data.BifrostDbContext>()
.Set<OpenIddict.EntityFrameworkCore.Models.OpenIddictEntityFrameworkCoreApplication>()
.AsNoTracking().ToList();
Assert.Equal([OidcTestKit.ClientId], rows.Select(x => x.ClientId).ToArray());
}
[Fact]
public async Task The_issuer_is_the_configured_public_base_url_not_the_request_origin()
{
using var factory = new OidcForeignIssuerFactory();
using var client = factory.CreateClient(ClientOptions());
var discovery = await client.GetFromJsonAsync<JsonElement>("/.well-known/openid-configuration");
Assert.Equal(OidcForeignIssuerFactory.PublicBaseUrl, discovery.GetProperty("issuer").GetString());
}
// ---- helpers ----
private static WebApplicationFactoryClientOptions ClientOptions() => new()

View file

@ -5,6 +5,7 @@ using Bifrost.Web.Features.Shared;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
@ -216,3 +217,16 @@ public sealed class OidcNoIdentityFactory : OidcWebApplicationFactory
}));
}
}
/// <summary>An OIDC host whose public base URL differs from the origin its requests arrive on, so the issuer cannot be request-derived.</summary>
public sealed class OidcForeignIssuerFactory : OidcWebApplicationFactory
{
public const string PublicBaseUrl = "https://id.example.test/";
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
builder.ConfigureAppConfiguration((_, configuration) =>
configuration.AddInMemoryCollection(new Dictionary<string, string?> { ["Host:PublicBaseUrl"] = PublicBaseUrl }));
}
}