Linked accounts: never guess a proof provider; require stepUpRequested; no-store on completion

With no current list the proof goes only through a provider the member names, never the
session's sign-in provider: a sign-in through an unlinked provider makes Heimdall mint an
orphan account holding that login. Link buttons need a current list. The unlink completion
must say a step-up was requested. POST /auth/heimdall/complete answers no-store. The fake
Heimdall now models orphan minting, derives step_up_at from the start's stepUp flag, and
enforces the app secret, sign_in-only, unsupported-provider and 600 s rules.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Heimdall 2026-11-13 20:08:07 +00:00
commit 8e65f56b0c
7 changed files with 325 additions and 69 deletions

View file

@ -6,8 +6,8 @@
| Action | What Bifrost does | Heimdall call |
|---|---|---|
| Show my linked logins | A fresh ordinary Heimdall sign-in as the session's account; inside its completion, the list | `GET /v1/me/identities` with that sign-in's bearer |
| Link Discord, Patreon or Google | The same fresh sign-in as proof, then the link start for the chosen provider with its bearer. Discord and Patreon attach in Heimdall's callback and return a link completion; Google writes a pending link, and a second fresh sign-in confirms it | `POST /v1/oauth/{provider}/start` `mode: "link"`, then for Google `POST /v1/apps/bifrost/links/confirm` |
| Show my logins | A fresh ordinary Heimdall sign-in as the session's account, through the proof provider (below); inside its completion, the list | `GET /v1/me/identities` with that sign-in's bearer |
| Link Discord, Patreon or Google | The same fresh sign-in as proof, then the link start for the chosen provider with its bearer. Needs a current list. Discord and Patreon attach in Heimdall's callback and return a link completion; Google writes a pending link, and a second fresh sign-in confirms it | `POST /v1/oauth/{provider}/start` `mode: "link"`, then for Google `POST /v1/apps/bifrost/links/confirm` |
| Unlink | A sign-in through Google with `stepUp: true` (app secret); inside its completion, the unlink | `POST /v1/me/identities/{id}/unlink` with that sign-in's bearer |
The linkable providers are the ones Heimdall's `bifrost` profile admits (`identityProviders` in Heimdall `src/app-profiles.ts`): Discord, Patreon, Google. Twitch is offered for sign-in elsewhere in Bifrost but the profile refuses it, so it is not offered here.
@ -18,7 +18,15 @@ Bifrost keeps no Heimdall token. Each action is an attempt: a Data Protection co
The list is kept for five minutes in this process only (`LinkedAccountsSnapshots`), keyed by the Heimdall account id, so the page can render after the completion's redirect: identity id, provider, display name (or username when there is none) and link date. Never the bearer, the email, the provider user id or the scopes. It is not given to the browser. A restart or the five minutes empties it and the page offers "Show my linked logins" again.
Every action is a POST with antiforgery; a GET starts nothing. The page and every redirect carry only a code from a closed set (`HeimdallLinkOutcomes`, `?result=`); the wording is Bifrost's, never Heimdall's text or the query's.
Every action is a POST with antiforgery; a GET starts nothing. The completion route's answers are `Cache-Control: no-store`. The page and every redirect carry only a code from a closed set (`HeimdallLinkOutcomes`, `?result=`); the wording is Bifrost's, never Heimdall's text or the query's.
## Which provider proves the account
An ordinary proof sign-in through a provider the account no longer holds makes Heimdall mint a new, unrelated account that holds that login, and the freed login then answers `identity_linked_elsewhere` when the member tries to link it back. So Bifrost never guesses a provider, and it does not use the "provider you signed in with" claim in the session (that records how you signed in once, not what the account holds now):
- With a current list (the five-minute snapshot), the proof goes through a provider on it: Discord, else Patreon, else Google.
- With no list (first visit, five minutes passed, a restart), the page offers only "Show my logins through Discord / Patreon / Google" and says plainly that Bifrost cannot tell what the account holds, so the member picks a login they know it holds. A named provider the account turns out not to hold still mints at Heimdall: that is the member's choice and the page says so beforehand. A refresh with no list and no named provider starts nothing (`provider_needed`).
- Link buttons appear only with a current list; a posted link with none starts nothing (`list_expired`). Unlink needs the list too.
## The proof limit
@ -29,7 +37,7 @@ Unlinking needs fresh proof: Heimdall refuses `403 step_up_required` unless the
- Linking Google needs the same client. Until then the Google link button ends in "That could not be completed. Nothing was changed."
- A Google step-up proof is as strong as Google's `prompt=login`; Heimdall says "asked", not "verified" (`stepUpRequested`).
Heimdall's other answers are shown as plain outcomes with nothing changed: `409 last_identity` (the last login is never removed), `404 identity_not_found` (the list is dropped as stale), `401 sign_in_required`, `403 step_up_required`, and any failure to reach Heimdall.
The unlink completion must also say a step-up was requested (`stepUpRequested`, set by Heimdall when the start asked for one); one that does not is refused without calling Heimdall. Heimdall's other answers are shown as plain outcomes with nothing changed: `409 last_identity` (the last login is never removed), `404 identity_not_found` (the list is dropped as stale), `401 sign_in_required`, `403 step_up_required`, and any failure to reach Heimdall.
A link refused because the login already belongs to another account (`409 identity_linked_elsewhere` from `links/confirm`; for Discord and Patreon the callback's `link_initiator_mismatch`, carried on by the complete page as a fixed result) is shown as "That login belongs to another account." The other account is never named.
@ -47,3 +55,7 @@ A link refused because the login already belongs to another account (`409 identi
- `Features/Heimdall/HeimdallMemberClient.cs`: the two member calls and their outcome mapping.
- `Features/Heimdall/LinkedAccountsSnapshots.cs`: the five-minute list.
- Tests: `tests/Bifrost.Web.Tests/LinkedAccountsTests.cs`, `HeimdallGoogleLinkTests.cs`, with the fake Heimdall in `Support/HeimdallTestKit.cs`.
## Known leftover
When Discord or Patreon's callback refuses a link because the login belongs to another account, the complete page's script redirects to the page with the fixed result and does not post anything. The held attempt cookie (`__Host-bifrost_heimdall_<slot>`, HttpOnly, so script cannot clear it) stays until its ten minutes end and occupies one of the two slots meanwhile; a new start reuses a free or the oldest slot, so nothing blocks. Clearing it would need a server route reached by GET or a post from the failure path, which the hardened script deliberately does not do.

View file

@ -163,27 +163,28 @@ public sealed class HeimdallAuthService(
}
/// <summary>
/// The provider an ordinary proof sign-in uses: the one the person signed in with when the account still holds it,
/// else the first held one of Discord, Patreon, Google. With no list to go by, the session's provider, else Discord.
/// Signing in through a provider the account no longer holds would only mint an unrelated Heimdall account.
/// The provider an ordinary proof sign-in uses, or null when none is safe. A sign-in through a provider the account no
/// longer holds makes Heimdall mint an unrelated account that holds that login, so it is never guessed: with the account's
/// current list, the first held one of the person's choice, Discord, Patreon, Google; with no list, only a provider the
/// member named (<paramref name="via"/>), who is the one who knows what they hold. The session's provider claim is not
/// consulted: it records how they signed in once, not what the account holds now.
/// </summary>
public static string ProofProvider(string? sessionProvider, IReadOnlyCollection<string>? held)
public static string? ProofProvider(IReadOnlyCollection<string>? held, string? via)
{
var session = sessionProvider is not null && ProofProviders.Contains(sessionProvider) ? sessionProvider.ToLowerInvariant() : null;
if (held is { Count: > 0 })
var chosen = via is not null && ProofProviders.Contains(via) ? via.ToLowerInvariant() : null;
if (held is null)
{
foreach (var candidate in new[] { session, "discord", "patreon", "google" })
{
if (candidate is not null && held.Contains(candidate, StringComparer.OrdinalIgnoreCase))
{
return candidate;
}
}
return chosen;
}
return session ?? "discord";
return new[] { chosen, "discord", "patreon", "google" }
.FirstOrDefault(x => x is not null && held.Contains(x, StringComparer.OrdinalIgnoreCase));
}
private string ProofProviderFor(string accountId, string? via) =>
ProofProvider(snapshots.Get(accountId)?.Select(x => x.Provider).ToArray(), via)
?? throw new HeimdallAuthException("No provider the account is known to hold can prove it.");
/// <summary>
/// The page's proof sign-ins. Each is a Heimdall sign-in for the account already signed in here, kept as an attempt
/// that says what it is the proof for (list, link, unlink) and which person it must prove. The session is never replaced.
@ -209,17 +210,23 @@ public sealed class HeimdallAuthService(
stepUp: stepUp,
target: target);
/// <summary>Reads the account's logins: an ordinary sign-in, then GET /v1/me/identities inside its completion.</summary>
/// <summary>
/// Reads the account's logins: an ordinary sign-in, then GET /v1/me/identities inside its completion. Through a provider on
/// the current list, or, when there is none, the one the member names in <paramref name="via"/>.
/// </summary>
public Task<HeimdallAuthStartResult> StartListAsync(
string sessionAccountId, string? sessionProvider, string callbackBaseUrl,
string sessionAccountId, string? via, string callbackBaseUrl,
IEnumerable<KeyValuePair<string, string>> requestCookies, CancellationToken cancellationToken) =>
StartProofAsync(
HeimdallAttemptPurpose.ListProof, ProofProvider(sessionProvider, snapshots.Get(sessionAccountId)?.Select(x => x.Provider).ToArray()),
HeimdallAttemptPurpose.ListProof, ProofProviderFor(sessionAccountId, via),
sessionAccountId, callbackBaseUrl, requestCookies, false, null, cancellationToken);
/// <summary>Links another provider: an ordinary sign-in as proof, then the link start for <paramref name="targetProvider"/> with its bearer.</summary>
/// <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.
/// </summary>
public Task<HeimdallAuthStartResult> StartLinkAsync(
string sessionAccountId, string? sessionProvider, string targetProvider, string callbackBaseUrl,
string sessionAccountId, string targetProvider, string callbackBaseUrl,
IEnumerable<KeyValuePair<string, string>> requestCookies, CancellationToken cancellationToken)
{
if (!LinkableProviders.Contains(targetProvider))
@ -228,7 +235,7 @@ public sealed class HeimdallAuthService(
}
return StartProofAsync(
HeimdallAttemptPurpose.LinkStart, ProofProvider(sessionProvider, snapshots.Get(sessionAccountId)?.Select(x => x.Provider).ToArray()),
HeimdallAttemptPurpose.LinkStart, ProofProviderFor(sessionAccountId, null),
sessionAccountId, callbackBaseUrl, requestCookies, false, targetProvider.ToLowerInvariant(), cancellationToken);
}
@ -458,7 +465,13 @@ public sealed class HeimdallAuthService(
case HeimdallAttemptPurpose.UnlinkProof:
{
var (identity, bearer) = await RedeemOwnerAsync(callbackBaseUrl, attempt, code, cancellationToken);
var (identity, bearer, redeemed) = await RedeemOwnerWithBodyAsync(callbackBaseUrl, attempt, code, cancellationToken);
if (redeemed.StepUpRequested != true)
{
// Heimdall reports "asked" on a step-up completion; one that does not was not a step-up sign-in.
return new HeimdallLinkStep(null, cookieName, null, HeimdallLinkOutcome.StepUpRequired);
}
var unlinked = await memberClient.UnlinkAsync(bearer, attempt.Target ?? string.Empty, cancellationToken);
switch (unlinked.Call)
{
@ -838,7 +851,8 @@ public enum HeimdallLinkOutcome
IdentityNotFound,
SignInRequired,
ProofUnavailable,
ListExpired
ListExpired,
ProviderNeeded
}
/// <summary>
@ -865,6 +879,7 @@ public static class HeimdallLinkOutcomes
HeimdallLinkOutcome.SignInRequired => "sign_in_required",
HeimdallLinkOutcome.ProofUnavailable => "proof_unavailable",
HeimdallLinkOutcome.ListExpired => "list_expired",
HeimdallLinkOutcome.ProviderNeeded => "provider_needed",
_ => "error"
};
@ -881,6 +896,7 @@ public static class HeimdallLinkOutcomes
"identity_not_found" => "That login is no longer on your account. Nothing was changed; the list below is read again when you ask.",
"sign_in_required" => "Heimdall no longer accepts that sign-in. Nothing was changed; try again.",
"proof_unavailable" => "Fresh proof could not be started, so nothing was changed. Unlinking needs a fresh Google sign-in, and it is not available right now.",
"provider_needed" => "Bifrost does not know which logins this account holds right now, so it will not guess. Pick one you know it holds to read the list. Nothing was changed.",
"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
@ -928,7 +944,8 @@ public sealed record HeimdallRedeemResponse(
[property: JsonPropertyName("accessToken")] string? AccessToken,
[property: JsonPropertyName("account")] HeimdallAccount? Account,
[property: JsonPropertyName("mode")] string? Mode = null,
[property: JsonPropertyName("provider")] string? Provider = null);
[property: JsonPropertyName("provider")] string? Provider = null,
[property: JsonPropertyName("stepUpRequested")] bool? StepUpRequested = null);
public sealed record HeimdallAccount(
[property: JsonPropertyName("id")] string Id);

View file

@ -29,10 +29,21 @@
<h2>Your logins</h2>
@if (Model.Identities is null)
{
<form method="post" asp-page-handler="Refresh" class="panel-actions">
<button class="button secondary" type="submit">Show my linked logins</button>
<span class="muted">You will sign in to Heimdall again, which reads the list. It is kept for five minutes, then asked for again.</span>
</form>
<p class="muted">
Bifrost does not hold the list: it asks Heimdall, which means signing in to Heimdall again, and keeps the answer for
five minutes. It also cannot tell which logins this account holds right now, so it will not choose one for you.
Pick a login you know it holds. Signing in through one it no longer holds would create a separate Heimdall account
holding that login.
</p>
<div class="panel-actions">
@foreach (var provider in Model.LinkableProviders)
{
<form method="post" asp-page-handler="Refresh" class="inline-actions">
<input type="hidden" name="via" value="@provider" />
<button class="button secondary" type="submit">Show my logins through @LinkedAccountsModel.ProviderName(provider)</button>
</form>
}
</div>
}
else
{
@ -82,20 +93,23 @@
</form>
}
<h2>Link another login</h2>
<p class="muted">
You will sign in to Heimdall again, then to the provider you pick. If that login already belongs to another account,
nothing is linked and nothing is merged.
</p>
<div class="panel-actions">
@foreach (var provider in Model.LinkableProviders)
{
<form method="post" asp-page-handler="Link" class="inline-actions">
<input type="hidden" name="provider" value="@provider" />
<button class="button secondary" type="submit">Link @LinkedAccountsModel.ProviderName(provider)</button>
</form>
}
</div>
@if (Model.Identities is not null)
{
<h2>Link another login</h2>
<p class="muted">
You will sign in to Heimdall again, then to the provider you pick. If that login already belongs to another account,
nothing is linked and nothing is merged.
</p>
<div class="panel-actions">
@foreach (var provider in Model.LinkableProviders)
{
<form method="post" asp-page-handler="Link" class="inline-actions">
<input type="hidden" name="provider" value="@provider" />
<button class="button secondary" type="submit">Link @LinkedAccountsModel.ProviderName(provider)</button>
</form>
}
</div>
}
}
<div class="panel-actions">

View file

@ -55,13 +55,21 @@ public sealed class LinkedAccountsModel(
}
/// <summary>Reads the account's logins: an ordinary Heimdall sign-in, then the list inside its completion.</summary>
public Task<IActionResult> OnPostRefreshAsync(CancellationToken cancellationToken) =>
BeginAsync(
(id, ct) => heimdallAuthService.StartListAsync(id, SessionProvider, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
public Task<IActionResult> OnPostRefreshAsync(string? via, CancellationToken cancellationToken)
{
// With no current list Bifrost cannot tell which provider the account still holds, so the member names one.
if (AccountId is not { } id || (snapshots.Get(id) is null && (via is null || !HeimdallAuthService.LinkableProviders.Contains(via))))
{
return Task.FromResult(Done(HeimdallLinkOutcome.ProviderNeeded));
}
return BeginAsync(
(account, ct) => heimdallAuthService.StartListAsync(account, via, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
HeimdallLinkOutcome.Error,
cancellationToken);
}
/// <summary>Links another provider. The provider is one Heimdall's bifrost profile admits; anything else starts nothing.</summary>
/// <summary>Links another provider. The provider is one Heimdall's bifrost profile admits; anything else starts nothing, and so does a missing list.</summary>
public Task<IActionResult> OnPostLinkAsync(string? provider, CancellationToken cancellationToken)
{
if (provider is null || !HeimdallAuthService.LinkableProviders.Contains(provider))
@ -69,8 +77,13 @@ public sealed class LinkedAccountsModel(
return Task.FromResult(Done(HeimdallLinkOutcome.Error));
}
if (AccountId is not { } id || snapshots.Get(id) is null)
{
return Task.FromResult(Done(HeimdallLinkOutcome.ListExpired));
}
return BeginAsync(
(id, ct) => heimdallAuthService.StartLinkAsync(id, SessionProvider, provider, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
(account, ct) => heimdallAuthService.StartLinkAsync(account, provider, hostOptions.Value.PublicBaseUrl, Request.Cookies, ct),
HeimdallLinkOutcome.Error,
cancellationToken);
}
@ -98,8 +111,6 @@ public sealed class LinkedAccountsModel(
cancellationToken);
}
private string? SessionProvider => User.FindFirstValue(BifrostClaimTypes.AuthProvider);
private IActionResult Done(HeimdallLinkOutcome outcome) =>
RedirectToPage(null, new Dictionary<string, string?> { [HeimdallLinkOutcomes.ResultParameter] = HeimdallLinkOutcomes.Code(outcome) });

View file

@ -829,6 +829,8 @@ app.MapPost("/auth/heimdall/complete", async (
ILogger<HeimdallAuthService> logger,
CancellationToken cancellationToken) =>
{
// Every answer here sets or clears an attempt cookie or signs someone in: none may be stored.
httpContext.Response.Headers.CacheControl = "no-store";
var form = await ReadFormOrNullAsync(httpContext.Request, cancellationToken);
var attempt = form?["attempt"].ToString();
var held = heimdallAuthService.FindAttemptCookie(httpContext.Request.Cookies, attempt);

View file

@ -28,9 +28,9 @@ public sealed class LinkedAccountsTests
/// <summary>The fresh sign-in's completion as the browser posts it: Heimdall minted a code for <paramref name="proofAccount"/>.</summary>
private static async Task<HttpResponseMessage> Finish(
HeimdallHost host, string session, StartedAttempt attempt, string proofAccount, string? token = null,
string mode = "sign_in", string provider = "discord", string? sessionOverride = null)
string mode = "sign_in", string provider = "discord", string? sessionOverride = null, bool? stepUpRequested = null)
{
var code = host.CodeFor(attempt, proofAccount, token, mode: mode, provider: provider);
var code = host.CodeFor(attempt, proofAccount, token, mode: mode, provider: provider, stepUpRequested: stepUpRequested);
return await host.PostCompleteAsync(
new Dictionary<string, string> { ["attempt"] = attempt.Nonce, ["code"] = code }, Jar(sessionOverride ?? session, attempt));
}
@ -50,9 +50,10 @@ public sealed class LinkedAccountsTests
host.Heimdall.AddIdentity(provider, "Name of " + provider);
}
var start = await host.StartListAsync(session);
var start = await host.StartListAsync(session, providers[0]);
var done = await Finish(host, session, start, account);
Assert.Equal(Page + "?result=listed", Location(done));
Assert.Empty(host.Heimdall.OrphanMints);
return new Member(account, session);
}
@ -82,12 +83,83 @@ public sealed class LinkedAccountsTests
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("no-store", response.Headers.CacheControl?.ToString());
Assert.Contains("Show my linked logins", html);
Assert.Contains("Show my logins through", html);
Assert.Contains("Show my logins through Patreon", html);
Assert.Contains("will not choose one for you", html);
Assert.DoesNotContain("Link Discord", html);
Assert.DoesNotContain("Unlink", html);
}
[Fact]
public async Task With_a_list_the_page_offers_each_admitted_provider_to_link_and_never_twitch()
{
using var host = new HeimdallHost(realSessions: true);
var member = await ListedMember(host, "discord", "google");
var (_, html) = await host.GetLinkedAccountsAsync(member.Session);
Assert.Contains("Link Discord", html);
Assert.Contains("Link Patreon", html);
Assert.Contains("Link Google", html);
Assert.DoesNotContain("Link Twitch", html);
Assert.DoesNotContain("Unlink", html);
}
[Fact]
public async Task After_the_list_expired_a_proof_is_never_started_through_a_provider_the_member_unlinked()
{
using var host = new HeimdallHost(realSessions: true);
var account = HeimdallShapes.NewAccountId();
var session = await host.SignInSessionAsync(account); // signed in through Discord
var discord = host.Heimdall.AddIdentity("discord", "D");
host.Heimdall.AddIdentity("google", "G");
var list = await host.StartListAsync(session, "discord");
await Finish(host, session, list, account);
var unlink = await host.StartUnlinkAsync(session, discord);
var done = await Finish(host, session, unlink, account, provider: "google");
Assert.Equal(Page + "?result=unlinked", Location(done));
host.Clock.Advance(LinkedAccountsSnapshots.Lifetime + TimeSpan.FromSeconds(1));
var starts = host.Heimdall.StartBodies.Count;
var refresh = await host.StartListAsync(session, via: null);
var link = await host.StartLinkAsync(session, "patreon", seedList: false);
var (_, html) = await host.GetLinkedAccountsAsync(session);
// Signing in through Discord again would mint an unrelated account holding that login: nothing is started.
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
Assert.Equal(Page + "?result=provider_needed", Location(refresh.Response));
Assert.Equal(Page + "?result=list_expired", Location(link.Response));
Assert.Empty(host.Heimdall.OrphanMints);
Assert.Contains("will not choose one for you", html);
Assert.DoesNotContain("Link Patreon", html);
}
[Theory]
[InlineData(null)]
[InlineData("twitch")]
[InlineData("nonsense")]
public async Task Without_a_list_the_member_must_name_an_admitted_provider_or_nothing_is_started(string? via)
{
using var host = new HeimdallHost(realSessions: true);
var session = await host.SignInSessionAsync(HeimdallShapes.NewAccountId());
var starts = host.Heimdall.StartBodies.Count;
var post = await host.StartListAsync(session, via);
Assert.Equal(starts, host.Heimdall.StartBodies.Count);
Assert.Equal(Page + "?result=provider_needed", Location(post.Response));
}
[Fact]
public async Task With_a_list_the_member_cannot_steer_the_proof_to_a_provider_the_account_does_not_hold()
{
using var host = new HeimdallHost(realSessions: true);
var member = await ListedMember(host, "patreon", "google");
var post = await host.StartListAsync(member.Session, "discord");
Assert.Equal("/v1/oauth/patreon/start", host.Heimdall.StartPaths[^1]);
Assert.Empty(host.Heimdall.OrphanMints);
Assert.NotNull(post.Cookie);
}
[Fact]
@ -226,13 +298,13 @@ public sealed class LinkedAccountsTests
Assert.Contains("Name of discord", (await host.GetLinkedAccountsAsync(member.Session)).Html);
var (_, other) = await host.GetLinkedAccountsAsync(stranger);
Assert.DoesNotContain("Name of discord", other);
Assert.Contains("Show my linked logins", other);
Assert.Contains("Show my logins through", other);
host.Clock.Advance(LinkedAccountsSnapshots.Lifetime + TimeSpan.FromSeconds(1));
var (_, later) = await host.GetLinkedAccountsAsync(member.Session);
Assert.DoesNotContain("Name of discord", later);
Assert.Contains("Show my linked logins", later);
Assert.Contains("Show my logins through", later);
}
[Theory]
@ -251,7 +323,7 @@ public sealed class LinkedAccountsTests
Assert.Equal($"{Page}?result={outcome}", Location(done));
Assert.DoesNotContain("HEIMDALL FREE TEXT", string.Join("\n", host.Logs.Lines));
Assert.Contains("Show my linked logins", (await host.GetLinkedAccountsAsync(session)).Html);
Assert.Contains("Show my logins through", (await host.GetLinkedAccountsAsync(session)).Html);
}
[Fact]
@ -267,7 +339,7 @@ public sealed class LinkedAccountsTests
var done = await Finish(host, session, start, account);
Assert.Equal(Page + "?result=error", Location(done));
Assert.Contains("Show my linked logins", (await host.GetLinkedAccountsAsync(session)).Html);
Assert.Contains("Show my logins through", (await host.GetLinkedAccountsAsync(session)).Html);
}
[Fact]
@ -356,6 +428,54 @@ public sealed class LinkedAccountsTests
Assert.Contains("Name of discord", (await host.GetLinkedAccountsAsync(member.Session)).Html);
}
[Fact]
public async Task A_completion_that_does_not_say_a_step_up_was_asked_unlinks_nothing()
{
using var host = new HeimdallHost(realSessions: true);
var member = await ListedMember(host, "discord", "google");
var start = await host.StartUnlinkAsync(member.Session, (string)host.Heimdall.Identities[0]["id"]!);
// The token even carries step_up_at, but the completion is not the answer to a step-up start.
var done = await Finish(host, member.Session, start, member.Account, StepUpToken(host, member.Account), provider: "google",
stepUpRequested: false);
Assert.Equal(Page + "?result=step_up_required", Location(done));
Assert.Empty(host.Heimdall.Unlinks);
Assert.Equal(2, host.Heimdall.Identities.Count);
}
[Fact]
public async Task A_proof_older_than_600_seconds_is_refused_by_Heimdall_and_changes_nothing()
{
using var host = new HeimdallHost(realSessions: true);
var member = await ListedMember(host, "discord", "google");
var start = await host.StartUnlinkAsync(member.Session, (string)host.Heimdall.Identities[0]["id"]!);
// The sign-in happened 601 seconds before the unlink reaches Heimdall (the attempt itself lives ten minutes).
var stale = host.Token(member.Account, mutate: claims => claims["step_up_at"] = host.Clock.Now.ToUnixTimeSeconds() - 601);
var done = await Finish(host, member.Session, start, member.Account, stale, provider: "google");
Assert.Equal(Page + "?result=step_up_required", Location(done));
Assert.Single(host.Heimdall.Unlinks);
Assert.Equal(2, host.Heimdall.Identities.Count);
}
[Fact]
public async Task Every_completion_answer_is_no_store()
{
using var host = new HeimdallHost(realSessions: true);
var account = HeimdallShapes.NewAccountId();
var session = await host.SignInSessionAsync(account);
host.Heimdall.AddIdentity("discord");
var start = await host.StartListAsync(session);
var done = await Finish(host, session, start, account);
var refused = await host.PostCompleteAsync(new Dictionary<string, string> { ["attempt"] = "nope" }, null);
Assert.Contains("no-store", done.Headers.CacheControl?.ToString());
Assert.Contains("no-store", refused.Headers.CacheControl?.ToString());
}
[Theory]
[InlineData(HttpStatusCode.NotFound, "identity_not_found")]
[InlineData(HttpStatusCode.Unauthorized, "sign_in_required")]
@ -701,6 +821,7 @@ public sealed class LinkedAccountsTests
[InlineData("sign_in_required")]
[InlineData("proof_unavailable")]
[InlineData("list_expired")]
[InlineData("provider_needed")]
[InlineData("error")]
public void Every_outcome_code_has_words_and_nothing_else_does(string code)
{

View file

@ -244,6 +244,18 @@ public sealed class FakeHeimdall : HttpMessageHandler
public List<string?> ListAuthorizations { get; } = [];
/// <summary>The clock the fake judges a step-up proof's age by (the host sets it to its test clock).</summary>
public Func<DateTimeOffset> Now { get; set; } = () => DateTimeOffset.UtcNow;
/// <summary>The returnTo of every start that asked for a step-up and passed Heimdall's checks: its completion carries the proof.</summary>
public HashSet<string> StepUpReturnTos { get; } = new(StringComparer.Ordinal);
/// <summary>
/// Providers an ordinary sign-in came through that the fake account (once it holds any login) does not hold. Heimdall mints an
/// unrelated account for such a sign-in, which would then hold that login.
/// </summary>
public List<string> OrphanMints { get; } = [];
/// <summary>When set, GET /v1/me/identities answers this status with an error body.</summary>
public HttpStatusCode? ListStatus { get; set; }
@ -304,9 +316,12 @@ public sealed class FakeHeimdall : HttpMessageHandler
};
}
// Heimdall's rule: the bearer must carry a step_up_at claim. (The 600 second window is Heimdall's own and not modelled.)
// Heimdall's rule: the bearer must carry a step_up_at claim from the last 600 seconds, and not from the future.
var payload = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(authorization["Bearer ".Length..].Split('.')[1]));
if (!payload.Contains("\"step_up_at\"", StringComparison.Ordinal))
using var claims = JsonDocument.Parse(payload);
var fresh = claims.RootElement.TryGetProperty("step_up_at", out var at) && at.TryGetInt64(out var seconds)
&& seconds <= Now().ToUnixTimeSeconds() && Now().ToUnixTimeSeconds() - seconds <= 600;
if (!fresh)
{
return Json(HttpStatusCode.Forbidden, """{"error":"step_up_required"}""");
}
@ -398,6 +413,28 @@ public sealed class FakeHeimdall : HttpMessageHandler
StartPaths.Add(path);
StartAuthorizations.Add(authorization);
var root = JsonDocument.Parse(body).RootElement;
static HttpResponseMessage Refuse(HttpStatusCode status, string error) =>
new(status) { Content = new StringContent($$"""{"error":"{{error}}"}""", Encoding.UTF8, "application/json") };
var startProvider = path.Split('/')[3];
if (root.TryGetProperty("stepUp", out var stepUp) && stepUp.ValueKind == JsonValueKind.True)
{
// Heimdall's step-up rules (service-contract.md, "Step-up"): the app's request, sign_in only, a provider that can re-authenticate.
if (secret != RequiredAppSecret)
{
return Refuse(HttpStatusCode.Unauthorized, "app_auth_required");
}
if (root.TryGetProperty("mode", out var stepMode) && stepMode.GetString() != "sign_in")
{
return Refuse(HttpStatusCode.BadRequest, "step_up_only_in_sign_in");
}
if (startProvider is not ("google" or "twitch" or "youtube"))
{
return Refuse(HttpStatusCode.BadRequest, "step_up_not_supported");
}
}
if (root.TryGetProperty("mode", out var mode) && mode.GetString() == "link")
{
if (authorization is null)
@ -416,6 +453,16 @@ public sealed class FakeHeimdall : HttpMessageHandler
};
}
if (Identities.Count > 0 && Identities.All(x => (string?)x["provider"] != startProvider))
{
OrphanMints.Add(startProvider);
}
if (StartStatus == HttpStatusCode.OK && root.TryGetProperty("stepUp", out var asked) && asked.ValueKind == JsonValueKind.True)
{
StepUpReturnTos.Add(root.GetProperty("returnTo").GetString()!);
}
var wantsPolicy = JsonDocument.Parse(body).RootElement.TryGetProperty("entitlementPolicy", out _);
if (wantsPolicy && RequiredAppSecret is not null && secret != RequiredAppSecret)
{
@ -580,6 +627,7 @@ public sealed class HeimdallHost : TestWebApplicationFactory
_publicBaseUrl = publicBaseUrl;
_discordRoles = discordRoles;
Heimdall.Published.Add(Key);
Heimdall.Now = () => Clock.Now;
Heimdall.RequiredAppSecret = AppSecret;
}
@ -679,10 +727,21 @@ public sealed class HeimdallHost : TestWebApplicationFactory
/// <summary>Registers a completion code as Heimdall would mint it after authenticating this attempt.</summary>
public string CodeFor(StartedAttempt attempt, string accountId, string? accessToken = null, string[]? looseCapabilities = null,
string[]? looseFacts = null, string looseName = "Loose Name", string? returnTo = null, string mode = "sign_in", string provider = "discord")
string[]? looseFacts = null, string looseName = "Loose Name", string? returnTo = null, string mode = "sign_in", string provider = "discord",
bool? stepUpRequested = null)
{
// A completion of a start that asked for a step-up carries the proof the way Heimdall's does: step_up_at in the token and stepUpRequested.
var asked = Heimdall.StepUpReturnTos.Contains(returnTo ?? attempt.ReturnTo);
var token = accessToken ?? (asked
? Token(accountId, mutate: claims => claims["step_up_at"] = Clock.Now.ToUnixTimeSeconds())
: Token(accountId));
var completion = HeimdallShapes.Completion(
returnTo ?? attempt.ReturnTo, accountId, accessToken ?? Token(accountId), looseCapabilities, looseFacts, looseName, mode, provider);
returnTo ?? attempt.ReturnTo, accountId, token, looseCapabilities, looseFacts, looseName, mode, provider);
if (stepUpRequested ?? asked)
{
completion["stepUpRequested"] = true;
}
return Heimdall.RegisterCode(completion);
}
@ -718,11 +777,15 @@ public sealed class HeimdallHost : TestWebApplicationFactory
}
/// <summary>A browser session: a normal Heimdall sign-in, answered with the session cookie it earned.</summary>
private readonly Dictionary<string, string> _sessionAccounts = new(StringComparer.Ordinal);
public async Task<string> SignInSessionAsync(string accountId, string provider = "discord")
{
var attempt = await StartAsync(provider: provider);
var done = await CompleteAsync(attempt, CodeFor(attempt, accountId));
return CookieValue(done.Response, BifrostCookies.Session) ?? throw new InvalidOperationException("sign-in set no session");
var session = CookieValue(done.Response, BifrostCookies.Session) ?? throw new InvalidOperationException("sign-in set no session");
_sessionAccounts[session] = accountId;
return session;
}
/// <summary>The raw POST of the complete page, whatever fields and cookies the caller names.</summary>
@ -805,11 +868,27 @@ public sealed class HeimdallHost : TestWebApplicationFactory
return AttemptFrom(await client.SendAsync(request), before);
}
/// <summary>
/// A link start needs the account's current list (Bifrost will not guess a provider to prove with). Link tests that are not
/// about the list get one seeded for a session of this host: the Discord login it signed in with. <paramref name="seedList"/> false leaves it.
/// </summary>
public Task<StartedAttempt> StartLinkAsync(
string? session, string provider = "google", bool antiforgery = true, HttpMethod? method = null, string? extraCookies = null) =>
PostLinkedAccountsAsync(session, "Link", new Dictionary<string, string> { ["provider"] = provider }, antiforgery, method, extraCookies);
string? session, string provider = "google", bool antiforgery = true, HttpMethod? method = null, string? extraCookies = null,
bool seedList = true)
{
if (seedList && session is not null && _sessionAccounts.TryGetValue(session, out var account)
&& Services.GetRequiredService<LinkedAccountsSnapshots>().Get(account) is null)
{
Services.GetRequiredService<LinkedAccountsSnapshots>().Put(
account, [new LinkedIdentitySummary(Guid.NewGuid().ToString(), "discord", "Seeded", null)]);
}
public Task<StartedAttempt> StartListAsync(string? session) => PostLinkedAccountsAsync(session, "Refresh");
return PostLinkedAccountsAsync(session, "Link", new Dictionary<string, string> { ["provider"] = provider }, antiforgery, method, extraCookies);
}
/// <summary>The list button. <paramref name="via"/> is the provider the member names, needed only when no current list is held.</summary>
public Task<StartedAttempt> StartListAsync(string? session, string? via = "discord") =>
PostLinkedAccountsAsync(session, "Refresh", via is null ? null : new Dictionary<string, string> { ["via"] = via });
public Task<StartedAttempt> StartUnlinkAsync(string? session, string identityId) =>
PostLinkedAccountsAsync(session, "Unlink", new Dictionary<string, string> { ["identityId"] = identityId });