Test: merge-proof sign-ins complete into MergeProofs (red; completion cases are stubs)

Adds the two attempt purposes, their start methods, the four outcomes, the step's
return path and the MergeProofs registration; the completion switch cases throw
until the next commit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Heimdall 2026-11-14 09:59:46 +00:00
commit 7bf284876a
3 changed files with 269 additions and 10 deletions

View file

@ -36,7 +36,8 @@ public sealed class HeimdallAuthService(
HeimdallMemberClient memberClient,
LinkedAccountsSnapshots snapshots,
PasskeyCeremonies ceremonies,
PasskeyService passkeys)
PasskeyService passkeys,
MergeProofs mergeProofs)
{
public const string ErrorRedirect = "/?auth=heimdall-error";
public const string AppSecretHeader = "x-heimdall-app-secret";
@ -203,11 +204,12 @@ public sealed class HeimdallAuthService(
bool stepUp,
string? target,
CancellationToken cancellationToken,
string? proof = null) =>
string? proof = null,
string? returnPath = null) =>
StartAsync(
provider,
callbackBaseUrl,
LocalReturnPath.Parse(LinkReturnPath),
LocalReturnPath.Parse(returnPath ?? LinkReturnPath),
requireMemberAccess: false,
requestCookies,
cancellationToken,
@ -228,6 +230,32 @@ public sealed class HeimdallAuthService(
HeimdallAttemptPurpose.ListProof, ProofProviderFor(sessionAccountId, via),
sessionAccountId, callbackBaseUrl, requestCookies, false, null, cancellationToken);
/// <summary>
/// A fresh sign-in as the account signed in here, held as one side of a merge (<see cref="MergeProofs"/>). The member names the
/// provider in <paramref name="via"/>: Bifrost never guesses one, and a sign-in through a login no account holds mints an unrelated
/// Heimdall account. The browser returns to <paramref name="returnPath"/> with the outcome in <c>?result=</c>.
/// </summary>
public Task<HeimdallAuthStartResult> StartMergeProveSelfAsync(
string sessionAccountId, string? via, string returnPath, string callbackBaseUrl,
IEnumerable<KeyValuePair<string, string>> requestCookies, CancellationToken cancellationToken) =>
StartProofAsync(
HeimdallAttemptPurpose.MergeProveSelf, MergeProvider(via),
sessionAccountId, callbackBaseUrl, requestCookies, false, null, cancellationToken, returnPath: returnPath);
/// <summary>
/// A fresh sign-in as the other account of a merge. <paramref name="sessionAccountId"/> is the account that must not be the one
/// proved: signing in again as oneself is not a second account.
/// </summary>
public Task<HeimdallAuthStartResult> StartMergeProveOtherAsync(
string sessionAccountId, string? via, string returnPath, string callbackBaseUrl,
IEnumerable<KeyValuePair<string, string>> requestCookies, CancellationToken cancellationToken) =>
StartProofAsync(
HeimdallAttemptPurpose.MergeProveOther, MergeProvider(via),
sessionAccountId, callbackBaseUrl, requestCookies, false, null, cancellationToken, returnPath: returnPath);
private static string MergeProvider(string? via) =>
ProofProvider(null, via) ?? throw new HeimdallAuthException("A merge proof needs the provider the member names.");
/// <summary>
/// Links another provider: an ordinary sign-in as proof through a provider on the account's current list (there is no
/// guessing without one), then the link start for <paramref name="targetProvider"/> with its bearer.
@ -542,6 +570,10 @@ public sealed class HeimdallAuthService(
return new HeimdallLinkStep(null, cookieName, null, await UnlinkAsync(identity.AccountId, asserted.AccessToken!, attempt.Target, cancellationToken));
}
case HeimdallAttemptPurpose.MergeProveSelf:
case HeimdallAttemptPurpose.MergeProveOther:
throw new NotImplementedException();
default:
throw new HeimdallAuthException("Heimdall completion is not a link attempt.");
}
@ -958,7 +990,8 @@ public sealed record HeimdallAttempt(
/// <summary>
/// What a held attempt is for. SignIn is the default, so a cookie written before purposes existed reads as a sign-in.
/// The other purposes belong to the Linked accounts page: the fresh sign-ins that prove an account for a list, a link or
/// an unlink, and the provider round trips of a link. They never sign anyone in. Values are persisted in cookies: append only.
/// an unlink, and the provider round trips of a link. The merge purposes are fresh sign-ins that prove the account signed in here or a
/// second one, held in <see cref="MergeProofs"/> for a merge's confirm and undo, and started by the page that is to read them. They never sign anyone in. Values are persisted in cookies: append only.
/// </summary>
public enum HeimdallAttemptPurpose
{
@ -970,7 +1003,9 @@ public enum HeimdallAttemptPurpose
UnlinkProof = 5,
LinkAwaitDirect = 6,
EnrolProof = 7,
UnlinkPasskeyProof = 8
UnlinkPasskeyProof = 8,
MergeProveSelf = 9,
MergeProveOther = 10
}
/// <summary>How a Linked accounts action ended. <see cref="HeimdallLinkOutcomes.Code"/> is its closed wire form.</summary>
@ -1001,7 +1036,11 @@ public enum HeimdallLinkOutcome
RateLimited,
StepUpUnavailable,
StepUpReplayed,
StepUpRateLimited
StepUpRateLimited,
MergeProofRecorded,
MergeSameAccount,
MergeNoAccount,
MergeLoginsAmbiguous
}
/// <summary>
@ -1012,8 +1051,9 @@ public static class HeimdallLinkOutcomes
{
public const string ResultParameter = "result";
public static string Redirect(HeimdallLinkOutcome outcome) =>
HeimdallAuthService.LinkReturnPath + "?" + ResultParameter + "=" + Code(outcome);
/// <summary>Back to the page that began the step (<paramref name="returnPath"/>, a local path), else the Linked accounts page.</summary>
public static string Redirect(HeimdallLinkOutcome outcome, string? returnPath = null) =>
(returnPath ?? HeimdallAuthService.LinkReturnPath) + "?" + ResultParameter + "=" + Code(outcome);
public static string Code(HeimdallLinkOutcome outcome) => outcome switch
{
@ -1042,6 +1082,10 @@ public static class HeimdallLinkOutcomes
HeimdallLinkOutcome.StepUpUnavailable => "step_up_unavailable",
HeimdallLinkOutcome.StepUpReplayed => "step_up_replayed",
HeimdallLinkOutcome.StepUpRateLimited => "step_up_rate_limited",
HeimdallLinkOutcome.MergeProofRecorded => "merge_proof_recorded",
HeimdallLinkOutcome.MergeSameAccount => "merge_same_account",
HeimdallLinkOutcome.MergeNoAccount => "merge_no_account",
HeimdallLinkOutcome.MergeLoginsAmbiguous => "merge_logins_ambiguous",
_ => "error"
};
@ -1072,13 +1116,17 @@ public static class HeimdallLinkOutcomes
"step_up_unavailable" => "Your passkey was verified, but Heimdall would not take Bifrost's proof. Nothing was changed.",
"step_up_replayed" => "Heimdall had already seen that proof. Nothing was changed; start the unlink again.",
"step_up_rate_limited" => "Heimdall is limiting proofs for now. Nothing was changed; wait a few minutes and start the unlink again.",
"merge_proof_recorded" => "That sign-in is recorded for the merge. It is held in memory for a few minutes and used only when you confirm.",
"merge_same_account" => "That sign-in is the account you are already signed in as, not a second one. Nothing was recorded.",
"merge_no_account" => "Bifrost has no member account for that sign-in, so there is nothing to merge. Nothing was recorded.",
"merge_logins_ambiguous" => "That account holds two logins of one provider, which Bifrost cannot prove one at a time. Nothing was recorded.",
"list_expired" => "The list was out of date. Nothing was changed; read your linked logins again.",
"error" => "That could not be completed. Nothing was changed.",
_ => null
};
}
public sealed record HeimdallLinkStep(Uri? Next, string CookieName, string? CookieValue, HeimdallLinkOutcome? Outcome, string? EnrolTicket = null);
public sealed record HeimdallLinkStep(Uri? Next, string CookieName, string? CookieValue, HeimdallLinkOutcome? Outcome, string? EnrolTicket = null, string? ReturnPath = null);
public sealed record HeimdallConfirmLinkRequest(
[property: JsonPropertyName("pendingLinkId")] string PendingLinkId);

View file

@ -141,6 +141,7 @@ builder.Services.AddScoped<NativeRegistration>();
builder.Services.AddHostedService<SealedBallotCloser>();
builder.Services.AddScoped<Bifrost.Web.Features.Membership.AccountMergeLedger>();
builder.Services.AddScoped<Bifrost.Web.Features.Membership.AccountMergeSaga>();
builder.Services.AddSingleton<Bifrost.Web.Features.Membership.MergeProofs>();
builder.Services.AddHostedService<Bifrost.Web.Features.Membership.AccountMergeSweeper>();
builder.Services.AddScoped<MotionEveSurfaceService>();
builder.Services.AddScoped<PatronageService>();
@ -877,7 +878,7 @@ app.MapPost("/auth/heimdall/complete", async (
}
httpContext.Response.Cookies.Delete(step.CookieName, HeimdallAttemptCookie.DeleteOptions());
return Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(step.Outcome!.Value));
return Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(step.Outcome!.Value, step.ReturnPath));
}
var signIn = await heimdallAuthService.CompleteAsync(

View file

@ -0,0 +1,210 @@
using System.Net;
using System.Text.Json;
using Bifrost.Web.Features.Heimdall;
using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Shared;
using Bifrost.Web.Tests.Support;
using Microsoft.AspNetCore.WebUtilities;
using Microsoft.Extensions.DependencyInjection;
namespace Bifrost.Web.Tests;
/// <summary>
/// The two merge-proof sign-ins from the browser's side, against a fake Heimdall: a fresh sign-in as the account signed in here (Self)
/// or as a second account (Other), each held in <see cref="MergeProofs"/> and nowhere else. No page starts them yet, so the tests start
/// them through the service and finish them as the browser does, by posting the completion code with the attempt cookie.
/// </summary>
public sealed class MergeProofCompletionTests
{
private const string Page = "/Membership/MergeStandIn";
private const string Callback = "https://localhost";
private sealed record Member(string Account, string Session, Guid UserAccountId);
private static async Task<Member> SignedIn(HeimdallHost host)
{
var account = HeimdallShapes.NewAccountId();
var session = await host.SignInSessionAsync(account);
return new Member(account, session, (await host.Account(account))!.Id);
}
private static async Task<StartedAttempt> Begin(HeimdallHost host, Member session, MergeSide side, string via = "discord")
{
var auth = host.Services.GetRequiredService<HeimdallAuthService>();
var started = side == MergeSide.Self
? await auth.StartMergeProveSelfAsync(session.Account, via, Page, Callback, [], CancellationToken.None)
: await auth.StartMergeProveOtherAsync(session.Account, via, Page, Callback, [], CancellationToken.None);
var returnTo = JsonDocument.Parse(host.Heimdall.StartBodies[^1]).RootElement.GetProperty("returnTo").GetString()!;
var nonce = QueryHelpers.ParseQuery(new Uri(returnTo).Query)["attempt"].ToString();
return new StartedAttempt(nonce, started.CookieName, started.CookieValue, returnTo, new HttpResponseMessage());
}
private static async Task<HttpResponseMessage> Finish(
HeimdallHost host, Member session, StartedAttempt attempt, string provedAccount, string token, string provider = "discord", string? sessionOverride = null)
{
var code = host.CodeFor(attempt, provedAccount, token, provider: provider);
return await host.PostCompleteAsync(
new Dictionary<string, string> { ["attempt"] = attempt.Nonce, ["code"] = code },
$"{BifrostCookies.Session}={sessionOverride ?? session.Session}; {attempt.CookieName}={attempt.Cookie}");
}
private static string? Location(HttpResponseMessage response) => response.Headers.Location?.OriginalString;
private static MergeProofs Proofs(HeimdallHost host) => host.Services.GetRequiredService<MergeProofs>();
private static void SetList(HeimdallHost host, params string[] providers)
{
host.Heimdall.Identities.Clear();
foreach (var provider in providers)
{
host.Heimdall.AddIdentity(provider, "Name of " + provider);
}
}
[Fact]
public async Task A_self_proof_for_the_signed_in_account_is_held_and_the_browser_goes_back_with_a_closed_code()
{
using var host = new HeimdallHost(realSessions: true);
var me = await SignedIn(host);
SetList(host, "discord", "patreon");
var bearer = host.Token(me.Account);
var done = await Finish(host, me, await Begin(host, me, MergeSide.Self), me.Account, bearer);
Assert.Equal(Page + "?result=merge_proof_recorded", Location(done));
var view = Assert.IsType<MergeSideView>(Proofs(host).Snapshot(me.UserAccountId).Self);
Assert.Equal(me.UserAccountId, view.UserAccountId);
Assert.Equal(["discord"], view.ProvedProviders);
Assert.Equal(["discord", "patreon"], view.LoginProviders.Order().ToArray());
Assert.Equal($"Bearer {bearer}", Assert.Single(host.Heimdall.ListAuthorizations));
var surface = Location(done) + string.Join('\n', done.Headers.Select(x => x.Key + string.Concat(x.Value)));
Assert.DoesNotContain(bearer, surface);
Assert.DoesNotContain(me.Account, surface);
Assert.DoesNotContain(bearer, string.Join('\n', host.Logs.Lines));
}
[Fact]
public async Task A_self_proof_of_a_different_account_is_refused_and_stores_nothing()
{
using var host = new HeimdallHost(realSessions: true);
var me = await SignedIn(host);
var someoneElse = HeimdallShapes.NewAccountId();
SetList(host, "discord");
var done = await Finish(host, me, await Begin(host, me, MergeSide.Self), someoneElse, host.Token(someoneElse));
Assert.Equal(Page + "?result=error", Location(done));
Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(me.UserAccountId));
Assert.Empty(host.Heimdall.ListAuthorizations);
}
[Fact]
public async Task An_other_proof_of_the_sessions_own_account_is_MergeSameAccount_and_stores_nothing()
{
using var host = new HeimdallHost(realSessions: true);
var me = await SignedIn(host);
SetList(host, "discord");
var done = await Finish(host, me, await Begin(host, me, MergeSide.Other), me.Account, host.Token(me.Account));
Assert.Equal(Page + "?result=merge_same_account", Location(done));
Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(me.UserAccountId));
Assert.Empty(host.Heimdall.ListAuthorizations);
}
[Fact]
public async Task An_other_proof_for_a_Heimdall_account_without_a_member_account_is_MergeNoAccount_and_the_bearer_is_dropped()
{
using var host = new HeimdallHost(realSessions: true);
var me = await SignedIn(host);
var stranger = HeimdallShapes.NewAccountId();
SetList(host, "patreon");
var done = await Finish(host, me, await Begin(host, me, MergeSide.Other, "patreon"), stranger, host.Token(stranger), "patreon");
Assert.Equal(Page + "?result=merge_no_account", Location(done));
Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(me.UserAccountId));
Assert.Empty(host.Heimdall.ListAuthorizations);
Assert.Null(await host.Account(stranger));
}
[Fact]
public async Task Both_sides_proved_give_the_actor_the_bearers_that_were_redeemed()
{
using var host = new HeimdallHost(realSessions: true);
var me = await SignedIn(host);
var them = await SignedIn(host);
SetList(host, "discord");
var mine = host.Token(me.Account);
await Finish(host, me, await Begin(host, me, MergeSide.Self), me.Account, mine);
SetList(host, "patreon");
var theirs = host.Token(them.Account);
var done = await Finish(host, me, await Begin(host, me, MergeSide.Other, "patreon"), them.Account, theirs, "patreon");
Assert.Equal(Page + "?result=merge_proof_recorded", Location(done));
var ready = Assert.IsType<PeekResult.Ready>(Proofs(host).Peek(me.UserAccountId, MergeSide.Self));
Assert.Equal((mine, me.Account, "discord"), (ready.Survivor.AccessToken, ready.Survivor.HeimdallAccountId, ready.Survivor.Provider));
var folded = Assert.Single(ready.Folded);
Assert.Equal((theirs, them.Account, "patreon"), (folded.AccessToken, folded.HeimdallAccountId, folded.Provider));
var view = Assert.IsType<MergeSideView>(Proofs(host).Snapshot(me.UserAccountId).Other);
Assert.Equal(them.UserAccountId, view.UserAccountId);
}
[Fact]
public async Task A_list_Heimdall_does_not_give_stores_nothing()
{
using var host = new HeimdallHost(realSessions: true);
var me = await SignedIn(host);
SetList(host, "discord");
host.Heimdall.ListStatus = HttpStatusCode.InternalServerError;
var done = await Finish(host, me, await Begin(host, me, MergeSide.Self), me.Account, host.Token(me.Account));
Assert.Equal(Page + "?result=error", Location(done));
Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(me.UserAccountId));
}
[Fact]
public async Task A_side_holding_two_logins_of_one_provider_is_MergeLoginsAmbiguous_and_stores_nothing()
{
using var host = new HeimdallHost(realSessions: true);
var me = await SignedIn(host);
SetList(host, "discord", "discord");
var done = await Finish(host, me, await Begin(host, me, MergeSide.Self), me.Account, host.Token(me.Account));
Assert.Equal(Page + "?result=merge_logins_ambiguous", Location(done));
Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(me.UserAccountId));
}
[Fact]
public async Task A_completion_in_another_browsers_session_holds_nothing()
{
using var host = new HeimdallHost(realSessions: true);
var me = await SignedIn(host);
var them = await SignedIn(host);
SetList(host, "discord");
var done = await Finish(host, me, await Begin(host, me, MergeSide.Self), me.Account, host.Token(me.Account), sessionOverride: them.Session);
Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(me.UserAccountId));
Assert.Equal(new MergeProofsView(null, null), Proofs(host).Snapshot(them.UserAccountId));
Assert.Empty(host.Heimdall.ListAuthorizations);
Assert.Equal(Page + "?result=error", Location(done));
}
[Fact]
public async Task A_merge_proof_starts_only_through_a_provider_the_member_names()
{
using var host = new HeimdallHost(realSessions: true);
var me = await SignedIn(host);
var auth = host.Services.GetRequiredService<HeimdallAuthService>();
var before = host.Heimdall.StartBodies.Count;
await Assert.ThrowsAsync<HeimdallAuthException>(() => auth.StartMergeProveSelfAsync(me.Account, null, Page, Callback, [], CancellationToken.None));
await Assert.ThrowsAsync<HeimdallAuthException>(() => auth.StartMergeProveOtherAsync(me.Account, "github", Page, Callback, [], CancellationToken.None));
Assert.Equal(before, host.Heimdall.StartBodies.Count);
}
}