diff --git a/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs b/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs index 15c50c6..6d164e2 100644 --- a/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs +++ b/src/Bifrost.Web/Features/Oidc/OidcEndpoints.cs @@ -85,15 +85,7 @@ public static class OidcEndpoints // 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) + if (!await IsStillActiveMemberAsync(db, subject, http.RequestAborted)) { return Deny(Errors.InvalidGrant, NotActiveDescription); } @@ -101,7 +93,7 @@ public static class OidcEndpoints return Results.SignIn(result.Principal!, properties: null, OpenIddictScheme); } - private static async Task UserInfoAsync(HttpContext http) + private static async Task UserInfoAsync(HttpContext http, BifrostDbContext db) { var result = await http.AuthenticateAsync(OpenIddictScheme); if (!result.Succeeded || result.Principal is null) @@ -109,6 +101,12 @@ public static class OidcEndpoints return Results.Challenge(authenticationSchemes: [OpenIddictScheme]); } + // An access token outlives the authorize decision too: a member suspended since is no longer answered. + if (!await IsStillActiveMemberAsync(db, result.Principal.GetClaim(Claims.Subject), http.RequestAborted)) + { + return Deny(Errors.InsufficientAccess, NotActiveDescription); + } + var claims = new Dictionary { [Claims.Subject] = result.Principal.GetClaim(Claims.Subject) }; if (result.Principal.HasScope(Scopes.Profile)) { @@ -119,6 +117,20 @@ public static class OidcEndpoints return Results.Json(claims); } + /// The one reading of "this subject is still an Active member", shared by the token and userinfo endpoints. + private static async Task IsStillActiveMemberAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken) + { + if (!Guid.TryParse(subject, out var accountId)) + { + return false; + } + + var account = await db.UserAccounts.AsNoTracking() + .Include(x => x.Membership) + .SingleOrDefaultAsync(x => x.Id == accountId, cancellationToken); + return new CurrentBifrostActor(true, account).IsActiveMember; + } + private static IResult Deny(string error, string description) => Results.Forbid( new AuthenticationProperties(new Dictionary diff --git a/tests/Bifrost.Web.Tests/OidcIssuerTests.cs b/tests/Bifrost.Web.Tests/OidcIssuerTests.cs index c0df422..08e8595 100644 --- a/tests/Bifrost.Web.Tests/OidcIssuerTests.cs +++ b/tests/Bifrost.Web.Tests/OidcIssuerTests.cs @@ -334,14 +334,18 @@ public sealed class OidcIssuerTests : IClassFixture Assert.False(await manager.ValidateClientSecretAsync(stored, "drifted-secret")); } - [Fact] - public async Task A_member_suspended_after_authorize_gets_no_tokens() + [Theory] + [InlineData(MembershipStatus.Authenticated)] + [InlineData(MembershipStatus.PendingApproval)] + [InlineData(MembershipStatus.Suspended)] + [InlineData(null)] + public async Task A_member_no_longer_active_after_authorize_gets_no_tokens(MembershipStatus? status) { - var (client, identity) = await SignedInAsync(MembershipStatus.Active, "Soon Suspended"); + var (client, identity) = await SignedInAsync(MembershipStatus.Active, "Soon Gone"); var request = NewRequest(); var code = await CodeAsync(client, request); - await _factory.SetMembershipAsync(identity, MembershipStatus.Suspended); + await LeaveActiveAsync(identity, status); using var response = await TokenAsync(client, request, code); var body = await response.Content.ReadAsStringAsync(); @@ -351,62 +355,130 @@ public sealed class OidcIssuerTests : IClassFixture Assert.DoesNotContain("access_token", body); } - [Fact] - public async Task Startup_removes_every_client_but_the_configured_one() + [Theory] + [InlineData(MembershipStatus.Authenticated)] + [InlineData(MembershipStatus.PendingApproval)] + [InlineData(MembershipStatus.Suspended)] + [InlineData(null)] + public async Task Userinfo_refuses_an_access_token_whose_member_is_no_longer_active(MembershipStatus? status) { - // Own host: the stale client is a row the other tests must not see. - using var own = new OidcInMemoryStoreFactory(); - await new OidcIssuerTests(own).StaleClientIsRemovedAsync(); + var (client, identity) = await SignedInAsync(MembershipStatus.Active, "Soon Gone"); + var tokens = await CompleteFlowAsync(client); + + using (var before = await UserInfoAsync(tokens.AccessToken)) + { + Assert.Equal(HttpStatusCode.OK, before.StatusCode); + } + + await LeaveActiveAsync(identity, status); + + using var after = await UserInfoAsync(tokens.AccessToken); + Assert.Equal(HttpStatusCode.Forbidden, after.StatusCode); + Assert.DoesNotContain(identity, await after.Content.ReadAsStringAsync()); } - private async Task StaleClientIsRemovedAsync() + private Task UserInfoAsync(string accessToken) { - const string staleId = "old-mas"; - const string staleRedirect = "https://old.example.test/callback"; + var request = new HttpRequestMessage(HttpMethod.Get, "/connect/userinfo"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); + return NewClient().SendAsync(request); + } + + /// A null status deletes the account instead. + private Task LeaveActiveAsync(string identity, MembershipStatus? status) => + status is { } value ? _factory.SetMembershipAsync(identity, value) : _factory.DeleteAccountAsync(identity); + + [Fact] + public async Task Startup_removes_every_client_but_the_configured_one_with_its_tokens_and_authorizations() + { + // Own host: the stale clients are rows the other tests must not see. + using var own = new OidcCascadeFactory(); + await new OidcIssuerTests(own).StaleClientsAreRemovedAsync(); + } + + private async Task StaleClientsAreRemovedAsync() + { + // Two stale clients, one of them differing from the configured id only in case. + var stale = new[] + { + (Id: "old-mas", Redirect: "https://old.example.test/callback"), + (Id: OidcTestKit.ClientId.ToUpperInvariant(), Redirect: "https://shouting.example.test/callback") + }; var (client, _) = await SignedInAsync(MembershipStatus.Active, "Member"); using (var scope = _factory.Services.CreateScope()) { var manager = scope.ServiceProvider.GetRequiredService(); - await manager.CreateAsync(new OpenIddict.Abstractions.OpenIddictApplicationDescriptor + foreach (var (id, redirect) in stale) { - ClientId = staleId, - ClientSecret = "stale-secret", - ClientType = OpenIddict.Abstractions.OpenIddictConstants.ClientTypes.Confidential, - ConsentType = OpenIddict.Abstractions.OpenIddictConstants.ConsentTypes.Implicit, - RedirectUris = { new Uri(staleRedirect) }, - Permissions = + await manager.CreateAsync(new OpenIddict.Abstractions.OpenIddictApplicationDescriptor { - 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.Scopes.Profile, - OpenIddict.Abstractions.OpenIddictConstants.Permissions.Prefixes.Scope + OpenIddict.Abstractions.OpenIddictConstants.Scopes.OpenId - } - }); + ClientId = id, + ClientSecret = "stale-secret", + ClientType = OpenIddict.Abstractions.OpenIddictConstants.ClientTypes.Confidential, + RedirectUris = { new Uri(redirect) }, + 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.Scopes.Profile, + 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)) + // The control: before seeding every client, stale or configured, really can obtain a code and so holds + // an authorization and a token. + foreach (var (id, redirect) in stale) { + using var issued = await DriveAsync(client, NewRequest(id, redirect)); Assert.Contains("code=", issued.Headers.Location?.OriginalString ?? string.Empty); } + _ = await CodeAsync(client, NewRequest()); + var staleCounts = Counts(stale.Select(x => x.Id)); + Assert.Equal(stale.Length, staleCounts.Count); + Assert.All(staleCounts, x => Assert.True(x.Tokens > 0 && x.Authorizations > 0, "the control must leave grants to remove")); + var configuredBefore = Counts([OidcTestKit.ClientId]).Single(); + Assert.True(configuredBefore.Tokens > 0 && configuredBefore.Authorizations > 0); + var seeder = Assert.Single(_factory.Services.GetServices().OfType()); 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); + foreach (var (id, redirect) in stale) + { + using var refused = await DriveAsync(client, NewRequest(id, redirect)); + Assert.DoesNotContain("code=", refused.Headers.Location?.OriginalString ?? string.Empty); + Assert.NotEqual(HttpStatusCode.OK, refused.StatusCode); + } using var fresh = _factory.Services.CreateScope(); - var rows = fresh.ServiceProvider.GetRequiredService() - .Set() - .AsNoTracking().ToList(); + var db = fresh.ServiceProvider.GetRequiredService(); + var rows = db.Set().AsNoTracking().ToList(); Assert.Equal([OidcTestKit.ClientId], rows.Select(x => x.ClientId).ToArray()); + + // Nothing issued to a removed client survives, and the configured client's grants are untouched. + var keptId = rows.Single().Id; + Assert.Empty(db.Set().AsNoTracking().Where(x => x.Application!.Id != keptId)); + Assert.Empty(db.Set().AsNoTracking().Where(x => x.Application!.Id != keptId)); + Assert.Equal(configuredBefore, Counts([OidcTestKit.ClientId]).Single()); + } + + private sealed record GrantCount(int Tokens, int Authorizations); + + private List Counts(IEnumerable clientIds) + { + using var scope = _factory.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var applications = db.Set().AsNoTracking().ToList(); + return clientIds + .Select(id => applications.Single(x => x.ClientId == id).Id) + .Select(applicationId => new GrantCount( + db.Set().Count(x => x.Application!.Id == applicationId), + db.Set().Count(x => x.Application!.Id == applicationId))) + .ToList(); } [Fact] diff --git a/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs b/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs index e006b7f..231cd33 100644 --- a/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs +++ b/tests/Bifrost.Web.Tests/Support/OidcTestKit.cs @@ -190,6 +190,15 @@ public class OidcWebApplicationFactory : TestWebApplicationFactory await db.SaveChangesAsync(); } + /// Removes the account (and with it its membership), as an owner deleting themselves would. + public async Task DeleteAccountAsync(string identity) + { + using var scope = Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.UserAccounts.Remove(db.UserAccounts.Single(x => x.NormalizedBifrostIdentity == identity)); + await db.SaveChangesAsync(); + } + public Guid AccountId(string identity) { using var scope = Services.CreateScope(); @@ -236,37 +245,16 @@ public sealed class OidcForeignIssuerFactory : OidcWebApplicationFactory } /// -/// An OIDC host whose application store removes a client row without OpenIddict's bulk delete of its tokens and -/// authorizations, which the in-memory test database cannot run (the cascade is the store's, exercised on Postgres only). -/// What the seeder decides to remove is what the host then loses. +/// An OIDC host on OpenIddict's own non-bulk deletion path. The in-memory test database cannot run the bulk +/// ExecuteDelete the library otherwise uses to remove an application's tokens and authorizations, so this switches +/// that option and the library's cascade runs unchanged. /// -public sealed class OidcInMemoryStoreFactory : OidcWebApplicationFactory +public sealed class OidcCascadeFactory : OidcWebApplicationFactory { protected override void ConfigureWebHost(IWebHostBuilder builder) { base.ConfigureWebHost(builder); builder.ConfigureServices(services => - { - services.RemoveAll>(); - services.AddScoped, RowOnlyApplicationStore>(); - }); - } - - private sealed class RowOnlyApplicationStore( - IMemoryCache cache, - IOpenIddictEntityFrameworkCoreContext openIddictContext, - IOptionsMonitor options, - BifrostDbContext context) - : OpenIddictEntityFrameworkCoreApplicationStore< - OpenIddictEntityFrameworkCoreApplication, - OpenIddictEntityFrameworkCoreAuthorization, - OpenIddictEntityFrameworkCoreToken, - string>(cache, openIddictContext, options) - { - public override async ValueTask DeleteAsync(OpenIddictEntityFrameworkCoreApplication application, CancellationToken cancellationToken) - { - context.Remove(application); - await context.SaveChangesAsync(cancellationToken); - } + services.Configure(options => options.DisableBulkOperations = true)); } }