Chat invites: an operator-minted single-use link decides who may chat; an uninvited account gets no chat token (#89)
This commit is contained in:
parent
3414143125
commit
5d9fc14598
28 changed files with 1286 additions and 184 deletions
|
|
@ -53,7 +53,7 @@ public sealed class MergePostgres : IAsyncLifetime
|
|||
public Task InitializeAsync() => Task.CompletedTask;
|
||||
|
||||
/// <summary>A fresh database, built by the real migrations, and a world over it.</summary>
|
||||
public async Task<AccountMergeLedgerTests.World> NewWorldAsync()
|
||||
public async Task<AccountMergeLedgerTests.World> NewWorldAsync(params Microsoft.EntityFrameworkCore.Diagnostics.SaveChangesInterceptor[] interceptors)
|
||||
{
|
||||
var name = $"bifrost_merge_{Guid.NewGuid():N}";
|
||||
await using (var admin = new NpgsqlConnection(Admin))
|
||||
|
|
@ -64,7 +64,7 @@ public sealed class MergePostgres : IAsyncLifetime
|
|||
}
|
||||
|
||||
_databases.Add(name);
|
||||
var world = AccountMergeLedgerTests.World.OnPostgres(new NpgsqlConnectionStringBuilder(Admin) { Database = name }.ConnectionString);
|
||||
var world = AccountMergeLedgerTests.World.OnPostgres(new NpgsqlConnectionStringBuilder(Admin) { Database = name }.ConnectionString, interceptors);
|
||||
await using var db = world.Db();
|
||||
await db.Database.MigrateAsync();
|
||||
return world;
|
||||
|
|
@ -416,7 +416,7 @@ public sealed class AccountMergePostgresTests(MergePostgres postgres) : IClassFi
|
|||
await down.GetService<IMigrator>().MigrateAsync("20261113120000_AddPasskeyCredentials");
|
||||
Assert.Equal("20261113120000_AddPasskeyCredentials", (await down.Database.GetAppliedMigrationsAsync()).Last());
|
||||
await down.GetService<IMigrator>().MigrateAsync(); // and up again, trigger and index and all
|
||||
Assert.Equal("20261114140000_AddAccountMergeNoticeAcks", (await down.Database.GetAppliedMigrationsAsync()).Last());
|
||||
Assert.Equal(down.Database.GetMigrations().Last(), (await down.Database.GetAppliedMigrationsAsync()).Last()); // the newest the assembly knows, whatever it is
|
||||
}
|
||||
|
||||
// ---- restage and intake journal ----
|
||||
|
|
|
|||
|
|
@ -147,7 +147,7 @@ public sealed class BootstrapAdminTests
|
|||
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||
var actor = new CurrentBifrostActor(true, await db.UserAccounts.Include(x => x.Membership!).ThenInclude(x => x.RoleAssignments).SingleAsync(x => x.Id == by));
|
||||
var page = new IndexModel(db, new FixedActor(actor), scope.ServiceProvider.GetRequiredService<AuditTrailService>(),
|
||||
scope.ServiceProvider.GetRequiredService<MembershipSuspensionService>(), TimeProvider.System);
|
||||
scope.ServiceProvider.GetRequiredService<MembershipSuspensionService>(), scope.ServiceProvider.GetRequiredService<Bifrost.Web.Features.Invites.ChatInviteService>(), TimeProvider.System);
|
||||
Assert.IsType<RedirectToPageResult>(await page.OnPostToggleRoleAsync(target, role, CancellationToken.None));
|
||||
}
|
||||
|
||||
|
|
|
|||
539
tests/Bifrost.Web.Tests/ChatInviteTests.cs
Normal file
539
tests/Bifrost.Web.Tests/ChatInviteTests.cs
Normal file
|
|
@ -0,0 +1,539 @@
|
|||
using System.Net;
|
||||
using System.Text.RegularExpressions;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Invites;
|
||||
using Bifrost.Web.Tests.Support;
|
||||
using Microsoft.AspNetCore.Mvc.Testing;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Bifrost.Web.Tests;
|
||||
|
||||
/// <summary>The Members page mints, lists and revokes chat invites; only a membership manager may. The link is shown once.</summary>
|
||||
public sealed class ChatInviteMintTests(TestWebApplicationFactory factory) : IClassFixture<TestWebApplicationFactory>
|
||||
{
|
||||
private static readonly Regex Link = new("https://localhost/invite#([A-Za-z0-9_-]+)", RegexOptions.Compiled);
|
||||
|
||||
private HttpClient Client(string? bifrostIdentity = null)
|
||||
{
|
||||
var client = factory.CreateClient(new WebApplicationFactoryClientOptions
|
||||
{
|
||||
AllowAutoRedirect = false,
|
||||
BaseAddress = new Uri("https://localhost"),
|
||||
HandleCookies = true
|
||||
});
|
||||
if (bifrostIdentity is not null)
|
||||
{
|
||||
client.DefaultRequestHeaders.Add("X-Test-Bifrost-Identity", bifrostIdentity);
|
||||
}
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
private static async Task<string> AntiforgeryAsync(HttpClient client)
|
||||
{
|
||||
var html = await (await client.GetAsync("/App/Members")).Content.ReadAsStringAsync();
|
||||
var token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value;
|
||||
Assert.True(token.Length > 0, html.Length > 3000 ? html[..3000] : html);
|
||||
return token;
|
||||
}
|
||||
|
||||
private static async Task<HttpResponseMessage> PostAsync(HttpClient client, string handler, Dictionary<string, string> fields)
|
||||
{
|
||||
fields["__RequestVerificationToken"] = await AntiforgeryAsync(client);
|
||||
return await client.PostAsync($"/App/Members?handler={handler}", new FormUrlEncodedContent(fields));
|
||||
}
|
||||
|
||||
private async Task SeedActiveMemberAsync(string identity)
|
||||
{
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||
db.UserAccounts.Add(new UserAccount
|
||||
{
|
||||
DisplayName = identity, BifrostIdentity = identity, NormalizedBifrostIdentity = identity,
|
||||
Membership = new Bifrost.Web.Domain.Membership { Status = MembershipStatus.Active, ApprovedAtUtc = DateTimeOffset.UtcNow }
|
||||
});
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private async Task<List<ChatInvite>> RowsAsync()
|
||||
{
|
||||
using var scope = factory.Services.CreateScope();
|
||||
return await scope.ServiceProvider.GetRequiredService<BifrostDbContext>().ChatInvites.AsNoTracking().ToListAsync();
|
||||
}
|
||||
|
||||
private async Task<List<string>> AuditActionsAsync()
|
||||
{
|
||||
using var scope = factory.Services.CreateScope();
|
||||
return await scope.ServiceProvider.GetRequiredService<BifrostDbContext>().AuditEvents.AsNoTracking()
|
||||
.Where(x => x.EntityType == ChatInviteService.EntityType).Select(x => x.Action).ToListAsync();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_manager_mints_a_link_shown_once_lists_it_and_revokes_it()
|
||||
{
|
||||
var admin = Client();
|
||||
using var _ = await admin.GetAsync("/App/Members"); // sign-in sync creates and promotes the bootstrap admin
|
||||
var before = (await RowsAsync()).Count;
|
||||
|
||||
using var minted = await PostAsync(admin, "Invite", new() { ["Input.Note"] = "for Ada" });
|
||||
Assert.Equal(HttpStatusCode.OK, minted.StatusCode);
|
||||
var html = await minted.Content.ReadAsStringAsync();
|
||||
var token = Link.Match(html).Groups[1].Value;
|
||||
Assert.True(token.Length > 0, "no invite link on the mint response");
|
||||
|
||||
var row = Assert.Single((await RowsAsync()).Where(x => x.Note == "for Ada"));
|
||||
Assert.Equal(ChatInviteService.Hash(token), row.TokenHash);
|
||||
Assert.Equal(before + 1, (await RowsAsync()).Count);
|
||||
Assert.Equal(row.IssuedAtUtc + ChatInviteService.Lifetime, row.ExpiresAtUtc);
|
||||
|
||||
// Shown once: the list names the note and a revoke, never the link.
|
||||
var again = await (await admin.GetAsync("/App/Members")).Content.ReadAsStringAsync();
|
||||
Assert.Contains("for Ada", again);
|
||||
Assert.DoesNotContain(token, again);
|
||||
|
||||
using var revoked = await PostAsync(admin, "RevokeInvite", new() { ["inviteId"] = row.Id.ToString() });
|
||||
Assert.Equal(HttpStatusCode.Redirect, revoked.StatusCode);
|
||||
Assert.NotNull(Assert.Single((await RowsAsync()).Where(x => x.Id == row.Id)).RevokedAtUtc);
|
||||
using var opened = await Client().OpenInviteAsync(token);
|
||||
Assert.Equal(HttpStatusCode.NotFound, opened.StatusCode);
|
||||
Assert.Contains("chat.invite.minted", await AuditActionsAsync());
|
||||
Assert.Contains("chat.invite.revoked", await AuditActionsAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_member_who_is_not_a_manager_cannot_mint_or_revoke()
|
||||
{
|
||||
var identity = $"plain-{Guid.NewGuid():N}"[..20];
|
||||
await SeedActiveMemberAsync(identity);
|
||||
var plain = Client(identity);
|
||||
var before = (await RowsAsync()).Count;
|
||||
|
||||
using var mint = await PostAsync(plain, "Invite", new() { ["Input.Note"] = "nope" });
|
||||
Assert.Equal(HttpStatusCode.Found, mint.StatusCode); // Forbid() redirects to the access-denied path
|
||||
Assert.Contains("/Membership/Status", mint.Headers.Location!.OriginalString);
|
||||
|
||||
var admin = Client();
|
||||
using var _ = await admin.GetAsync("/App/Members");
|
||||
using var minted = await PostAsync(admin, "Invite", new() { ["Input.Note"] = "keep" });
|
||||
var keep = Assert.Single((await RowsAsync()).Where(x => x.Note == "keep"));
|
||||
using var revoke = await PostAsync(plain, "RevokeInvite", new() { ["inviteId"] = keep.Id.ToString() });
|
||||
|
||||
Assert.Equal(HttpStatusCode.Found, revoke.StatusCode);
|
||||
Assert.Contains("/Membership/Status", revoke.Headers.Location!.OriginalString);
|
||||
Assert.Null(Assert.Single((await RowsAsync()).Where(x => x.Id == keep.Id)).RevokedAtUtc);
|
||||
Assert.Equal(before + 1, (await RowsAsync()).Count);
|
||||
Assert.DoesNotContain("keep", await (await plain.GetAsync("/App/Members")).Content.ReadAsStringAsync());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_token_never_travels_in_a_request_line_the_link_keeps_it_in_the_fragment()
|
||||
{
|
||||
var admin = Client();
|
||||
using var _ = await admin.GetAsync("/App/Members");
|
||||
using var minted = await PostAsync(admin, "Invite", new() { ["Input.Note"] = "fragment" });
|
||||
var html = await minted.Content.ReadAsStringAsync();
|
||||
var token = Link.Match(html).Groups[1].Value;
|
||||
Assert.Contains("/invite#" + token, html);
|
||||
|
||||
// The landing page carries no token and posts what its fragment holds; the old path form opens nothing.
|
||||
using var page = await Client().GetAsync("/invite");
|
||||
Assert.Equal(HttpStatusCode.OK, page.StatusCode);
|
||||
var body = await page.Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain(token, body);
|
||||
Assert.Contains("location.hash", body);
|
||||
// The page's policy decides what Origin its form posts with: no-referrer would make it "null", which the guard refuses (see the Origin: null test).
|
||||
Assert.Equal("same-origin", Assert.Single(page.Headers.GetValues("Referrer-Policy")));
|
||||
using var oldPath = await Client().GetAsync("/invite/" + token);
|
||||
Assert.Equal(HttpStatusCode.NotFound, oldPath.StatusCode);
|
||||
Assert.False(oldPath.Headers.Contains("Set-Cookie"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_chooser_a_carried_invite_lands_on_offers_only_the_sign_ins_that_redeem_it()
|
||||
{
|
||||
var admin = Client();
|
||||
using var _ = await admin.GetAsync("/App/Members");
|
||||
using var minted = await PostAsync(admin, "Invite", new() { ["Input.Note"] = "chooser" });
|
||||
var token = Link.Match(await minted.Content.ReadAsStringAsync()).Groups[1].Value;
|
||||
|
||||
var visitor = Client();
|
||||
var plain = await (await visitor.GetAsync("/auth/sign-in?returnUrl=%2F")).Content.ReadAsStringAsync();
|
||||
Assert.Contains("provider=github", plain);
|
||||
|
||||
using var landed = await visitor.OpenInviteAsync(token);
|
||||
Assert.Equal(HttpStatusCode.Redirect, landed.StatusCode);
|
||||
var carried = await (await visitor.GetAsync(landed.Headers.Location)).Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("provider=github", carried);
|
||||
Assert.Contains("/auth/heimdall/discord", carried);
|
||||
|
||||
// The hand-typed URL is refused with the way forward; without the cookie it is not.
|
||||
using var typed = await visitor.GetAsync("/auth/sign-in?provider=github&returnUrl=%2F");
|
||||
Assert.Equal(HttpStatusCode.Conflict, typed.StatusCode);
|
||||
Assert.Contains("Discord, Patreon or Twitch", await typed.Content.ReadAsStringAsync());
|
||||
using var bare = await Client().GetAsync("/auth/sign-in?provider=github&returnUrl=%2F");
|
||||
Assert.NotEqual(HttpStatusCode.Conflict, bare.StatusCode);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A Heimdall sign-in carrying the invite cookie spends the invite onto the account that signed in.</summary>
|
||||
public sealed class ChatInviteHeimdallTests
|
||||
{
|
||||
private static async Task<string> MintAsync(HeimdallHost host)
|
||||
{
|
||||
using var scope = host.Services.CreateScope();
|
||||
var (_, token) = await scope.ServiceProvider.GetRequiredService<ChatInviteService>().MintAsync(Guid.NewGuid(), "via heimdall", CancellationToken.None);
|
||||
return token;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_new_heimdall_account_carrying_the_cookie_is_invited_once_and_the_cookie_is_cleared()
|
||||
{
|
||||
using var host = new HeimdallHost();
|
||||
var token = await MintAsync(host);
|
||||
var jar = ChatInviteService.CookieName + "=" + token;
|
||||
var first = HeimdallShapes.NewAccountId();
|
||||
var attempt = await host.StartAsync();
|
||||
|
||||
var done = await host.CompleteWithHeaderAsync(attempt.Nonce, host.CodeFor(attempt, first), $"{attempt.CookieName}={attempt.Cookie}; {jar}");
|
||||
|
||||
Assert.True(done.SignedIn);
|
||||
var account = await host.Account(first);
|
||||
Assert.NotNull(account!.ChatInvitedAtUtc);
|
||||
var row = await host.Db(db => db.ChatInvites.AsNoTracking().SingleAsync(x => x.TokenHash == ChatInviteService.Hash(token)));
|
||||
Assert.Equal(account.Id, row.RedeemedByUserAccountId);
|
||||
var cleared = HeimdallHost.SetCookieHeader(done.Response, ChatInviteService.CookieName);
|
||||
Assert.NotNull(cleared);
|
||||
Assert.Contains("1970", cleared);
|
||||
|
||||
// A second account carrying the same link signs in but is not invited.
|
||||
var second = HeimdallShapes.NewAccountId();
|
||||
var again = await host.StartAsync();
|
||||
var refused = await host.CompleteWithHeaderAsync(again.Nonce, host.CodeFor(again, second), $"{again.CookieName}={again.Cookie}; {jar}");
|
||||
Assert.True(refused.SignedIn);
|
||||
Assert.Null((await host.Account(second))!.ChatInvitedAtUtc);
|
||||
Assert.Equal(account.Id, (await host.Db(db => db.ChatInvites.AsNoTracking().SingleAsync(x => x.TokenHash == ChatInviteService.Hash(token)))).RedeemedByUserAccountId);
|
||||
Assert.NotNull((await host.Account(first))!.ChatInvitedAtUtc);
|
||||
Assert.Contains("chat.invite.redeemed", await host.Db(db => db.AuditEvents.AsNoTracking().Select(x => x.Action).ToListAsync()));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_invite_revoked_after_its_link_was_carried_redeems_nothing()
|
||||
{
|
||||
using var host = new HeimdallHost();
|
||||
string token;
|
||||
using (var scope = host.Services.CreateScope())
|
||||
{
|
||||
var service = scope.ServiceProvider.GetRequiredService<ChatInviteService>();
|
||||
var (invite, minted) = await service.MintAsync(Guid.NewGuid(), "revoked in flight", CancellationToken.None);
|
||||
token = minted;
|
||||
Assert.True(await service.RevokeAsync(invite.Id, Guid.NewGuid(), CancellationToken.None));
|
||||
}
|
||||
|
||||
var accountId = HeimdallShapes.NewAccountId();
|
||||
var attempt = await host.StartAsync();
|
||||
var done = await host.CompleteWithHeaderAsync(attempt.Nonce, host.CodeFor(attempt, accountId), $"{attempt.CookieName}={attempt.Cookie}; {ChatInviteService.CookieName}={token}");
|
||||
|
||||
Assert.True(done.SignedIn);
|
||||
Assert.Null((await host.Account(accountId))!.ChatInvitedAtUtc);
|
||||
Assert.Null((await host.Db(db => db.ChatInvites.AsNoTracking().SingleAsync(x => x.TokenHash == ChatInviteService.Hash(token)))).RedeemedAtUtc);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_heimdall_sign_in_without_the_cookie_is_not_invited()
|
||||
{
|
||||
using var host = new HeimdallHost();
|
||||
await MintAsync(host);
|
||||
var accountId = HeimdallShapes.NewAccountId();
|
||||
var attempt = await host.StartAsync();
|
||||
|
||||
var done = await host.CompleteAsync(attempt, host.CodeFor(attempt, accountId));
|
||||
|
||||
Assert.True(done.SignedIn);
|
||||
Assert.Null((await host.Account(accountId))!.ChatInvitedAtUtc);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The single-use fact rests on a concurrency token and the migration, which the in-memory provider does not enforce: proven on a real server (skipped without BIFROST_TEST_PG).</summary>
|
||||
public sealed class ChatInvitePostgresTests(MergePostgres postgres) : IClassFixture<MergePostgres>
|
||||
{
|
||||
[PostgresFact]
|
||||
public async Task Two_accounts_racing_for_one_link_leave_it_with_exactly_one_and_the_token_is_stored_only_hashed()
|
||||
{
|
||||
var world = await postgres.NewWorldAsync();
|
||||
var time = TimeProvider.System;
|
||||
const string token = "race-token-0123456789";
|
||||
Guid first, second;
|
||||
await using (var seed = world.Db())
|
||||
{
|
||||
var a = new UserAccount { BifrostIdentity = "racer-a", NormalizedBifrostIdentity = "racer-a", DisplayName = "A" };
|
||||
var b = new UserAccount { BifrostIdentity = "racer-b", NormalizedBifrostIdentity = "racer-b", DisplayName = "B" };
|
||||
seed.UserAccounts.AddRange(a, b);
|
||||
seed.ChatInvites.Add(new ChatInvite { TokenHash = ChatInviteService.Hash(token), Note = "race", IssuedAtUtc = time.GetUtcNow(), ExpiresAtUtc = time.GetUtcNow().AddDays(1) });
|
||||
await seed.SaveChangesAsync();
|
||||
(first, second) = (a.Id, b.Id);
|
||||
}
|
||||
|
||||
async Task Redeem(Guid account)
|
||||
{
|
||||
await using var db = world.Db();
|
||||
var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
|
||||
http.Request.Headers.Cookie = ChatInviteService.CookieName + "=" + token;
|
||||
var options = Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.BifrostHostOptions());
|
||||
await new ChatInviteService(db, new Bifrost.Web.Features.Shared.AuditTrailService(db, time), time, options).RedeemCarriedAsync(http, account, CancellationToken.None);
|
||||
}
|
||||
|
||||
await Task.WhenAll(Task.Run(() => Redeem(first)), Task.Run(() => Redeem(second)));
|
||||
|
||||
await using var read = world.Db();
|
||||
var invite = await read.ChatInvites.AsNoTracking().SingleAsync();
|
||||
Assert.NotNull(invite.RedeemedByUserAccountId);
|
||||
Assert.Equal(1, await read.UserAccounts.CountAsync(x => x.ChatInvitedAtUtc != null));
|
||||
Assert.Equal(invite.RedeemedByUserAccountId, (await read.UserAccounts.SingleAsync(x => x.ChatInvitedAtUtc != null)).Id);
|
||||
Assert.Equal(1, await read.AuditEvents.CountAsync(x => x.Action == "chat.invite.redeemed"));
|
||||
}
|
||||
|
||||
/// <summary>Holds each redemption's save until both have loaded the invite, so the interleave the concurrency token exists for is forced, not left to timing.</summary>
|
||||
private sealed class BothLoadedBeforeEitherSaves : Microsoft.EntityFrameworkCore.Diagnostics.SaveChangesInterceptor
|
||||
{
|
||||
private int _arrived;
|
||||
private readonly TaskCompletionSource _both = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
public override async ValueTask<Microsoft.EntityFrameworkCore.Diagnostics.InterceptionResult<int>> SavingChangesAsync(
|
||||
Microsoft.EntityFrameworkCore.Diagnostics.DbContextEventData eventData,
|
||||
Microsoft.EntityFrameworkCore.Diagnostics.InterceptionResult<int> result,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (eventData.Context!.ChangeTracker.Entries<ChatInvite>().Any(x => x.State == EntityState.Modified))
|
||||
{
|
||||
if (Interlocked.Increment(ref _arrived) == 2)
|
||||
{
|
||||
_both.TrySetResult();
|
||||
}
|
||||
|
||||
await _both.Task.WaitAsync(TimeSpan.FromSeconds(20), cancellationToken);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
[PostgresFact]
|
||||
public async Task Two_redemptions_that_both_loaded_the_invite_before_either_saved_still_leave_it_with_one()
|
||||
{
|
||||
var world = await postgres.NewWorldAsync(new BothLoadedBeforeEitherSaves());
|
||||
var time = TimeProvider.System;
|
||||
const string token = "interleave-token-0123456789";
|
||||
Guid first, second;
|
||||
await using (var seed = world.Db())
|
||||
{
|
||||
var a = new UserAccount { BifrostIdentity = "inter-a", NormalizedBifrostIdentity = "inter-a", DisplayName = "A" };
|
||||
var b = new UserAccount { BifrostIdentity = "inter-b", NormalizedBifrostIdentity = "inter-b", DisplayName = "B" };
|
||||
seed.UserAccounts.AddRange(a, b);
|
||||
seed.ChatInvites.Add(new ChatInvite { TokenHash = ChatInviteService.Hash(token), Note = "interleave", IssuedAtUtc = time.GetUtcNow(), ExpiresAtUtc = time.GetUtcNow().AddDays(1) });
|
||||
await seed.SaveChangesAsync();
|
||||
(first, second) = (a.Id, b.Id);
|
||||
}
|
||||
|
||||
async Task Redeem(Guid account)
|
||||
{
|
||||
await using var db = world.Db();
|
||||
var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
|
||||
http.Request.Headers.Cookie = ChatInviteService.CookieName + "=" + token;
|
||||
var options = Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.BifrostHostOptions());
|
||||
await new ChatInviteService(db, new Bifrost.Web.Features.Shared.AuditTrailService(db, time), time, options).RedeemCarriedAsync(http, account, CancellationToken.None);
|
||||
}
|
||||
|
||||
await Task.WhenAll(Task.Run(() => Redeem(first)), Task.Run(() => Redeem(second)));
|
||||
|
||||
await using var read = world.Db();
|
||||
var invite = await read.ChatInvites.AsNoTracking().SingleAsync();
|
||||
var invited = await read.UserAccounts.Where(x => x.ChatInvitedAtUtc != null).Select(x => x.Id).ToListAsync();
|
||||
Assert.Single(invited);
|
||||
Assert.Equal(invite.RedeemedByUserAccountId, invited[0]);
|
||||
Assert.Equal(1, await read.AuditEvents.CountAsync(x => x.Action == "chat.invite.redeemed"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An account merge leaves the person invited while the merge stands: the fact is read from the merges that stand, never copied, so undo in any order leaves what the surviving merges give.</summary>
|
||||
public sealed class ChatInviteMergeTests
|
||||
{
|
||||
private static readonly DateTimeOffset Early = new(2026, 11, 1, 9, 0, 0, TimeSpan.Zero);
|
||||
private static readonly DateTimeOffset Late = new(2026, 11, 10, 9, 0, 0, TimeSpan.Zero);
|
||||
|
||||
private static async Task<UserAccount> AccountAsync(AccountMergeLedgerTests.World world, string name, DateTimeOffset? invitedAt = null)
|
||||
{
|
||||
var account = await world.AccountAsync(name, MembershipStatus.Authenticated);
|
||||
if (invitedAt is { } at)
|
||||
{
|
||||
await using var db = world.Db();
|
||||
(await db.UserAccounts.SingleAsync(x => x.Id == account.Id)).ChatInvitedAtUtc = at;
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
return account;
|
||||
}
|
||||
|
||||
private static async Task<bool> RefusedAsNotInvitedAsync(AccountMergeLedgerTests.World world, UserAccount account)
|
||||
{
|
||||
await using var db = world.Db();
|
||||
return await Bifrost.Web.Features.Oidc.OidcEndpoints.ChatRefusalAsync(db, account.Id.ToString(), default) == Bifrost.Web.Features.Oidc.OidcEndpoints.NotInvitedDescription;
|
||||
}
|
||||
|
||||
private static async Task UndoAsync(AccountMergeLedgerTests.World world, AccountMerge merge)
|
||||
{
|
||||
await world.SetStateAsync(merge, AccountMergeState.HeimdallReversed);
|
||||
await using var db = world.Db();
|
||||
await world.Ledger(db).UndoLocalAsync(merge.Id, default);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_invited_account_folded_into_an_uninvited_survivor_leaves_the_person_invited_until_the_merge_is_undone()
|
||||
{
|
||||
var world = new AccountMergeLedgerTests.World();
|
||||
var survivor = await AccountAsync(world, "survivor");
|
||||
var folded = await AccountAsync(world, "folded", Early);
|
||||
Assert.True(await RefusedAsNotInvitedAsync(world, survivor));
|
||||
|
||||
var merge = await world.CommitAsync(await world.MergeAsync(survivor, folded));
|
||||
Assert.False(await RefusedAsNotInvitedAsync(world, survivor));
|
||||
|
||||
await UndoAsync(world, merge);
|
||||
Assert.True(await RefusedAsNotInvitedAsync(world, survivor));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_folded_account_that_was_never_invited_gives_the_survivor_nothing()
|
||||
{
|
||||
var world = new AccountMergeLedgerTests.World();
|
||||
var survivor = await AccountAsync(world, "survivor");
|
||||
var folded = await AccountAsync(world, "folded");
|
||||
await world.CommitAsync(await world.MergeAsync(survivor, folded));
|
||||
Assert.True(await RefusedAsNotInvitedAsync(world, survivor));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task Two_invited_accounts_merged_into_one_survivor_undone_in_either_order_leave_the_survivor_uninvited(bool earlierMergeFirst)
|
||||
{
|
||||
var world = new AccountMergeLedgerTests.World();
|
||||
var survivor = await AccountAsync(world, "survivor");
|
||||
var late = await AccountAsync(world, "late", Late);
|
||||
var early = await AccountAsync(world, "early", Early);
|
||||
var first = await world.CommitAsync(await world.MergeAsync(survivor, late));
|
||||
var second = await world.CommitAsync(await world.MergeAsync(survivor, early));
|
||||
|
||||
await UndoAsync(world, earlierMergeFirst ? first : second);
|
||||
Assert.False(await RefusedAsNotInvitedAsync(world, survivor)); // the other merge still stands
|
||||
|
||||
await UndoAsync(world, earlierMergeFirst ? second : first);
|
||||
Assert.True(await RefusedAsNotInvitedAsync(world, survivor));
|
||||
}
|
||||
}
|
||||
|
||||
public static class InviteRequests
|
||||
{
|
||||
/// <summary>What a browser sends from the landing page's form under its Referrer-Policy: same-origin: the site's Origin and Sec-Fetch-Site: same-origin.</summary>
|
||||
public static Task<HttpResponseMessage> OpenInviteAsync(this HttpClient client, string token, string? origin = "https://localhost", string? fetchSite = "same-origin", int padding = 0)
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, "/invite")
|
||||
{
|
||||
Content = new StringContent("token=" + token + new string('a', padding), System.Text.Encoding.UTF8, "application/x-www-form-urlencoded")
|
||||
};
|
||||
if (origin is not null)
|
||||
{
|
||||
request.Headers.Add("Origin", origin);
|
||||
}
|
||||
|
||||
if (fetchSite is not null)
|
||||
{
|
||||
request.Headers.Add("Sec-Fetch-Site", fetchSite);
|
||||
}
|
||||
|
||||
return client.SendAsync(request);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>POST /invite plants a cookie, so a foreign page must not be able to make the post, and the body is only as big as a token.</summary>
|
||||
public sealed class ChatInvitePostTests(TestWebApplicationFactory factory) : IClassFixture<TestWebApplicationFactory>
|
||||
{
|
||||
private HttpClient Client() => factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, BaseAddress = new Uri("https://localhost"), HandleCookies = false });
|
||||
|
||||
private async Task<string> MintAsync()
|
||||
{
|
||||
using var scope = factory.Services.CreateScope();
|
||||
var (_, token) = await scope.ServiceProvider.GetRequiredService<ChatInviteService>().MintAsync(Guid.NewGuid(), "post", CancellationToken.None);
|
||||
return token;
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_cross_site_post_with_a_live_token_sets_no_cookie_and_the_same_origin_post_does()
|
||||
{
|
||||
var token = await MintAsync();
|
||||
foreach (var (origin, site) in new (string?, string?)[] { ("https://evil.example", "cross-site"), (null, "cross-site"), (null, "same-site"), (null, null) })
|
||||
{
|
||||
using var refused = await Client().OpenInviteAsync(token, origin, site);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode);
|
||||
Assert.False(refused.Headers.Contains("Set-Cookie"));
|
||||
}
|
||||
|
||||
using var own = await Client().OpenInviteAsync(token);
|
||||
Assert.Equal(HttpStatusCode.Redirect, own.StatusCode);
|
||||
Assert.Contains(own.Headers.GetValues("Set-Cookie"), x => x.StartsWith(ChatInviteService.CookieName + "=", StringComparison.Ordinal));
|
||||
using var fetch = await Client().OpenInviteAsync(token, origin: null, fetchSite: "same-origin");
|
||||
Assert.Equal(HttpStatusCode.Redirect, fetch.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_post_with_Origin_null_is_refused_which_is_why_the_page_must_not_send_no_referrer()
|
||||
{
|
||||
var token = await MintAsync();
|
||||
using var refused = await Client().OpenInviteAsync(token, origin: "null", fetchSite: "same-origin");
|
||||
Assert.Equal(HttpStatusCode.Forbidden, refused.StatusCode);
|
||||
Assert.False(refused.Headers.Contains("Set-Cookie"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_body_bigger_than_a_token_needs_is_refused_unread()
|
||||
{
|
||||
var token = await MintAsync();
|
||||
using var big = await Client().OpenInviteAsync(token, padding: 3_000_000);
|
||||
Assert.Equal(HttpStatusCode.RequestEntityTooLarge, big.StatusCode);
|
||||
Assert.False(big.Headers.Contains("Set-Cookie"));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Redemption asks the same question as every other decision: an account already invited through a merge spends no second invite.</summary>
|
||||
public sealed class ChatInviteDerivedRedemptionTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task A_survivor_invited_through_a_merge_keeps_a_second_invite_unspent()
|
||||
{
|
||||
var world = new AccountMergeLedgerTests.World();
|
||||
var survivor = await world.AccountAsync("survivor", MembershipStatus.Authenticated);
|
||||
var folded = await world.AccountAsync("folded", MembershipStatus.Authenticated);
|
||||
await using (var seed = world.Db())
|
||||
{
|
||||
(await seed.UserAccounts.SingleAsync(x => x.Id == folded.Id)).ChatInvitedAtUtc = new DateTimeOffset(2026, 11, 1, 9, 0, 0, TimeSpan.Zero);
|
||||
await seed.SaveChangesAsync();
|
||||
}
|
||||
|
||||
await world.CommitAsync(await world.MergeAsync(survivor, folded));
|
||||
|
||||
await using var db = world.Db();
|
||||
var service = new ChatInviteService(db, new Bifrost.Web.Features.Shared.AuditTrailService(db, world.Clock), world.Clock,
|
||||
Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.BifrostHostOptions()));
|
||||
var (invite, token) = await service.MintAsync(Guid.NewGuid(), "second", CancellationToken.None);
|
||||
var http = new Microsoft.AspNetCore.Http.DefaultHttpContext();
|
||||
http.Request.Headers.Cookie = ChatInviteService.CookieName + "=" + token;
|
||||
|
||||
await service.RedeemCarriedAsync(http, survivor.Id, CancellationToken.None);
|
||||
|
||||
await using var read = world.Db();
|
||||
var row = await read.ChatInvites.AsNoTracking().SingleAsync(x => x.Id == invite.Id);
|
||||
Assert.Null(row.RedeemedAtUtc);
|
||||
Assert.Null((await read.UserAccounts.AsNoTracking().SingleAsync(x => x.Id == survivor.Id)).ChatInvitedAtUtc);
|
||||
}
|
||||
}
|
||||
|
|
@ -195,6 +195,18 @@ public sealed class DeskCredentialTests : IDisposable
|
|||
Assert.Empty(factory.Door.Calls);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_desk_token_asks_no_chat_invite()
|
||||
{
|
||||
var (client, identity) = await SignedInAsync();
|
||||
await factory.SetMembershipAsync(identity, MembershipStatus.Authenticated);
|
||||
var request = NewRequest(DeskClient, DeskRedirect, "desk.read");
|
||||
|
||||
var code = await CodeAsync(client, request);
|
||||
|
||||
Assert.False(string.IsNullOrEmpty(code));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_session_cookie_alone_authenticates_nothing_on_the_desk()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -164,7 +164,7 @@ public sealed class MembershipSuspensionTests : IClassFixture<TestWebApplication
|
|||
{
|
||||
var page = new IndexModel(
|
||||
db, new FixedActor(await ActorAsync(seed.AdminId)), sp.GetRequiredService<AuditTrailService>(),
|
||||
sp.GetRequiredService<MembershipSuspensionService>(), TimeProvider.System);
|
||||
sp.GetRequiredService<MembershipSuspensionService>(), sp.GetRequiredService<Bifrost.Web.Features.Invites.ChatInviteService>(), TimeProvider.System);
|
||||
return await page.OnPostApproveAsync(seed.MemberId, CancellationToken.None);
|
||||
});
|
||||
|
||||
|
|
@ -181,7 +181,7 @@ public sealed class MembershipSuspensionTests : IClassFixture<TestWebApplication
|
|||
{
|
||||
var page = new IndexModel(
|
||||
db, new FixedActor(await ActorAsync(seed.OrdinaryId)), sp.GetRequiredService<AuditTrailService>(),
|
||||
sp.GetRequiredService<MembershipSuspensionService>(), TimeProvider.System);
|
||||
sp.GetRequiredService<MembershipSuspensionService>(), sp.GetRequiredService<Bifrost.Web.Features.Invites.ChatInviteService>(), TimeProvider.System);
|
||||
return await page.OnPostSuspendAsync(seed.MemberId, "nope", CancellationToken.None);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -32,6 +32,7 @@ public sealed class MigrationDiscoveryTests
|
|||
"20261114120000_AddAccountMerges",
|
||||
"20261114130000_AddAccountMergeSaga",
|
||||
"20261114140000_AddAccountMergeNoticeAcks",
|
||||
"20261127120000_AddChatInvites",
|
||||
];
|
||||
|
||||
// Database.GetMigrations() reads assembly metadata only; no connection is opened.
|
||||
|
|
|
|||
|
|
@ -192,6 +192,133 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
|
|||
Assert.Equal(["name", "preferred_username", "sub"], info.EnumerateObject().Select(x => x.Name).Order().ToArray());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_uninvited_account_gets_no_chat_token_at_authorize_or_exchange()
|
||||
{
|
||||
var (client, identity) = await SignedInAsync(MembershipStatus.Authenticated, "Not Invited", invited: false);
|
||||
var request = NewRequest();
|
||||
|
||||
var redirect = AssertRedirectToClient(await DriveAsync(client, request), request.State);
|
||||
|
||||
Assert.Equal("access_denied", redirect["error"]);
|
||||
Assert.Equal(Bifrost.Web.Features.Oidc.OidcEndpoints.NotInvitedDescription, redirect["error_description"]);
|
||||
Assert.False(redirect.ContainsKey("code"));
|
||||
|
||||
// A code and a token issued while invited stop working when the invite is gone: the same reading at every endpoint.
|
||||
await _factory.SetInvitedAsync(identity, true);
|
||||
var pending = NewRequest();
|
||||
var pendingCode = await CodeAsync(client, pending);
|
||||
var tokens = await CompleteFlowAsync(client);
|
||||
await _factory.SetInvitedAsync(identity, false);
|
||||
|
||||
using var exchange = await TokenAsync(client, pending, pendingCode);
|
||||
var body = await exchange.Content.ReadAsStringAsync();
|
||||
Assert.Equal(HttpStatusCode.BadRequest, exchange.StatusCode);
|
||||
Assert.Contains("invalid_grant", body);
|
||||
Assert.DoesNotContain("access_token", body);
|
||||
using var userinfo = await UserInfoAsync(tokens.AccessToken);
|
||||
Assert.Equal(HttpStatusCode.Forbidden, userinfo.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_active_member_needs_no_invite()
|
||||
{
|
||||
var (client, identity) = await SignedInAsync(MembershipStatus.Active, "Member", invited: false);
|
||||
|
||||
var tokens = await CompleteFlowAsync(client);
|
||||
|
||||
Assert.Equal(identity, (await ValidateIdTokenAsync(tokens.IdToken, tokens.Request.Nonce)).Claim("preferred_username"));
|
||||
Assert.Null(await _factory.InvitedAtAsync(identity));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_invite_link_is_redeemed_at_native_sign_in_once_and_the_cookie_is_cleared()
|
||||
{
|
||||
var token = await _factory.MintInviteAsync("first");
|
||||
var client = NewClient();
|
||||
using (var opened = await client.OpenInviteAsync(token))
|
||||
{
|
||||
Assert.Equal(HttpStatusCode.Redirect, opened.StatusCode);
|
||||
var cookie = Assert.Single(opened.Headers.GetValues("Set-Cookie"), x => x.StartsWith(Bifrost.Web.Features.Invites.ChatInviteService.CookieName + "=", StringComparison.Ordinal));
|
||||
Assert.Contains("httponly", cookie, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("samesite=lax", cookie, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
using var registered = await RegistrationKit.RegisterAsync(client, $"invited-{Guid.NewGuid():N}");
|
||||
Assert.Equal(HttpStatusCode.OK, registered.StatusCode);
|
||||
var identity = (await registered.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("bifrostIdentity").GetString()!.ToLowerInvariant();
|
||||
|
||||
Assert.NotNull(await _factory.InvitedAtAsync(identity));
|
||||
var row = await _factory.InviteRowAsync(token);
|
||||
Assert.Equal(_factory.AccountId(identity), row.RedeemedByUserAccountId);
|
||||
Assert.Contains(registered.Headers.GetValues("Set-Cookie"), x =>
|
||||
x.StartsWith(Bifrost.Web.Features.Invites.ChatInviteService.CookieName + "=;", StringComparison.Ordinal) && x.Contains("expires=", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
// Invited and agreed (registration carried the notice): chat works with no further step.
|
||||
var tokens = await CompleteFlowAsync(client);
|
||||
Assert.Equal(identity, (await ValidateIdTokenAsync(tokens.IdToken, tokens.Request.Nonce)).Claim("preferred_username"));
|
||||
|
||||
// Single use: a second account carrying the same token is refused and the first keeps it.
|
||||
var other = NewClient();
|
||||
other.DefaultRequestHeaders.Add("Cookie", Bifrost.Web.Features.Invites.ChatInviteService.CookieName + "=" + token);
|
||||
using var second = await RegistrationKit.RegisterAsync(other, $"second-{Guid.NewGuid():N}");
|
||||
var secondIdentity = (await second.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("bifrostIdentity").GetString()!.ToLowerInvariant();
|
||||
Assert.Null(await _factory.InvitedAtAsync(secondIdentity));
|
||||
Assert.Equal(_factory.AccountId(identity), (await _factory.InviteRowAsync(token)).RedeemedByUserAccountId);
|
||||
Assert.NotNull(await _factory.InvitedAtAsync(identity));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task An_expired_or_revoked_invite_sets_no_cookie_and_redeems_nothing()
|
||||
{
|
||||
var expired = await _factory.MintInviteAsync("expires");
|
||||
var revoked = await _factory.MintInviteAsync("revoked");
|
||||
using (var scope = _factory.Services.CreateScope())
|
||||
{
|
||||
var invites = scope.ServiceProvider.GetRequiredService<Bifrost.Web.Features.Invites.ChatInviteService>();
|
||||
Assert.True(await invites.RevokeAsync((await _factory.InviteRowAsync(revoked)).Id, Guid.NewGuid(), CancellationToken.None));
|
||||
}
|
||||
|
||||
_factory.Clock.Advance(Bifrost.Web.Features.Invites.ChatInviteService.Lifetime + TimeSpan.FromMinutes(1));
|
||||
var fresh = await _factory.MintInviteAsync("fresh");
|
||||
|
||||
foreach (var token in new[] { expired, revoked, "not-a-token" })
|
||||
{
|
||||
using var client = NewClient();
|
||||
using var opened = await client.OpenInviteAsync(token);
|
||||
Assert.Equal(HttpStatusCode.NotFound, opened.StatusCode);
|
||||
Assert.False(opened.Headers.Contains("Set-Cookie"));
|
||||
Assert.DoesNotContain("expire", await opened.Content.ReadAsStringAsync(), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
// A cookie carried anyway (set before the link lapsed) redeems nothing either.
|
||||
var carried = NewClient();
|
||||
carried.DefaultRequestHeaders.Add("Cookie", Bifrost.Web.Features.Invites.ChatInviteService.CookieName + "=" + expired);
|
||||
using var registered = await RegistrationKit.RegisterAsync(carried, $"lapsed-{Guid.NewGuid():N}");
|
||||
var identity = (await registered.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("bifrostIdentity").GetString()!.ToLowerInvariant();
|
||||
Assert.Null(await _factory.InvitedAtAsync(identity));
|
||||
Assert.Null((await _factory.InviteRowAsync(expired)).RedeemedAtUtc);
|
||||
|
||||
using var live = await NewClient().OpenInviteAsync(fresh);
|
||||
Assert.Equal(HttpStatusCode.Redirect, live.StatusCode);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_database_holds_only_the_token_hash()
|
||||
{
|
||||
var token = await _factory.MintInviteAsync("hashed");
|
||||
|
||||
var row = await _factory.InviteRowAsync(token);
|
||||
|
||||
Assert.Equal(Bifrost.Web.Features.Invites.ChatInviteService.Hash(token), row.TokenHash);
|
||||
Assert.NotEqual(token, row.TokenHash);
|
||||
Assert.Equal(64, row.TokenHash.Length);
|
||||
using var scope = _factory.Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<Bifrost.Web.Data.BifrostDbContext>();
|
||||
Assert.DoesNotContain(db.ChatInvites.AsNoTracking().AsEnumerable(), x => x.Note == token || x.TokenHash == token);
|
||||
Assert.DoesNotContain(db.AuditEvents.AsNoTracking().AsEnumerable(), x => x.Detail.Contains(token));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_chat_tier_account_with_a_reserved_identity_is_still_refused()
|
||||
{
|
||||
|
|
@ -1029,7 +1156,7 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
|
|||
return identity.ToLowerInvariant();
|
||||
}
|
||||
|
||||
private async Task<(HttpClient Client, string Identity)> SignedInAsync(MembershipStatus status, string displayName, ReceiptState receipt = ReceiptState.Current)
|
||||
private async Task<(HttpClient Client, string Identity)> SignedInAsync(MembershipStatus status, string displayName, ReceiptState receipt = ReceiptState.Current, bool invited = true)
|
||||
{
|
||||
var client = NewClient();
|
||||
var identity = await RegisterAsync(client, $"member-{Guid.NewGuid():N}", agree: receipt != ReceiptState.None);
|
||||
|
|
@ -1040,6 +1167,7 @@ public sealed class OidcIssuerTests : IClassFixture<OidcWebApplicationFactory>
|
|||
|
||||
await _factory.SetMembershipAsync(identity, status);
|
||||
await _factory.SetDisplayNameAsync(identity, displayName);
|
||||
await _factory.SetInvitedAsync(identity, invited);
|
||||
return (client, identity);
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -414,6 +414,7 @@ public sealed class OidcLogoutFactory : OidcWebApplicationFactory
|
|||
}
|
||||
|
||||
await SetMembershipAsync(identity, MembershipStatus.Active);
|
||||
await SetInvitedAsync(identity, true);
|
||||
if (suspensionReason is not null)
|
||||
{
|
||||
using var scope = Services.CreateScope();
|
||||
|
|
|
|||
|
|
@ -276,6 +276,36 @@ public class OidcWebApplicationFactory : TestWebApplicationFactory
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>Marks the account as holding a redeemed chat invite (or clears it), as a redemption or a revoked grant would leave it.</summary>
|
||||
public async Task SetInvitedAsync(string identity, bool invited)
|
||||
{
|
||||
using var scope = Services.CreateScope();
|
||||
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||
db.UserAccounts.Single(x => x.NormalizedBifrostIdentity == identity).ChatInvitedAtUtc = invited ? DateTimeOffset.UtcNow : null;
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
/// <summary>Mints a chat invite through the one service and returns its token.</summary>
|
||||
public async Task<string> MintInviteAsync(string note = "test")
|
||||
{
|
||||
using var scope = Services.CreateScope();
|
||||
var (_, token) = await scope.ServiceProvider.GetRequiredService<Bifrost.Web.Features.Invites.ChatInviteService>().MintAsync(Guid.NewGuid(), note, CancellationToken.None);
|
||||
return token;
|
||||
}
|
||||
|
||||
public async Task<ChatInvite> InviteRowAsync(string token)
|
||||
{
|
||||
using var scope = Services.CreateScope();
|
||||
var hash = Bifrost.Web.Features.Invites.ChatInviteService.Hash(token);
|
||||
return await scope.ServiceProvider.GetRequiredService<BifrostDbContext>().ChatInvites.AsNoTracking().SingleAsync(x => x.TokenHash == hash);
|
||||
}
|
||||
|
||||
public async Task<DateTimeOffset?> InvitedAtAsync(string identity)
|
||||
{
|
||||
using var scope = Services.CreateScope();
|
||||
return (await scope.ServiceProvider.GetRequiredService<BifrostDbContext>().UserAccounts.AsNoTracking().SingleAsync(x => x.NormalizedBifrostIdentity == identity)).ChatInvitedAtUtc;
|
||||
}
|
||||
|
||||
public Guid AccountId(string identity)
|
||||
{
|
||||
using var scope = Services.CreateScope();
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ public sealed class SuspensionReasonExposureTests
|
|||
{
|
||||
viewer.Membership!.IsPlatformAdmin = admin;
|
||||
var model = new Bifrost.Web.Pages.App.Members.IndexModel(db, new FixedActor(new CurrentBifrostActor(true, viewer)),
|
||||
sp.GetRequiredService<AuditTrailService>(), sp.GetRequiredService<MembershipSuspensionService>(), TimeProvider.System);
|
||||
sp.GetRequiredService<AuditTrailService>(), sp.GetRequiredService<MembershipSuspensionService>(), sp.GetRequiredService<Bifrost.Web.Features.Invites.ChatInviteService>(), TimeProvider.System);
|
||||
await model.OnGetAsync(CancellationToken.None);
|
||||
return model.Users;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue