UpsertUserAccountAsync(
HeimdallVerifiedIdentity identity,
@@ -448,7 +659,65 @@ public sealed record HeimdallAttempt(
string Provider,
bool RequiresMemberAccess,
LocalReturnPath ReturnPath,
- DateTimeOffset ExpiresAt);
+ DateTimeOffset ExpiresAt,
+ HeimdallAttemptPurpose Purpose = HeimdallAttemptPurpose.SignIn,
+ string? ExpectedAccountId = null,
+ string? PendingLinkId = null);
+
+///
+/// What a held attempt is for. SignIn is the default, so a cookie written before purposes existed reads as a sign-in.
+/// The link purposes are the fresh sign-ins and the Google round trip of an explicit link; they never sign anyone in.
+///
+public enum HeimdallAttemptPurpose
+{
+ SignIn = 0,
+ LinkStart = 1,
+ LinkAwaitGoogle = 2,
+ LinkConfirm = 3
+}
+
+public enum HeimdallLinkOutcome
+{
+ Linked,
+ IdentityLinkedElsewhere,
+ Expired,
+ Error
+}
+
+///
+/// Where a link step sends the browser: to with a new attempt cookie in the held slot, or, when the
+/// link is finished, back to the account page with .
+///
+public static class HeimdallLinkOutcomes
+{
+ public static string Redirect(HeimdallLinkOutcome outcome) => HeimdallAuthService.LinkReturnPath + "?link=" + Code(outcome);
+
+ public static string Code(HeimdallLinkOutcome outcome) => outcome switch
+ {
+ HeimdallLinkOutcome.Linked => "linked",
+ HeimdallLinkOutcome.IdentityLinkedElsewhere => "identity_linked_elsewhere",
+ HeimdallLinkOutcome.Expired => "expired",
+ _ => "error"
+ };
+
+ /// The words for an outcome code: a closed set, never Heimdall's text. Anything else gets none.
+ public static string? Wording(string? code) => code switch
+ {
+ "linked" => "Google is now linked to your Heimdall account.",
+ "identity_linked_elsewhere" => "That Google identity is already linked to a different Heimdall account. Nothing was linked.",
+ "expired" => "The Google link expired before it was confirmed. Nothing was linked; start the link again.",
+ "error" => "The Google link could not be completed. Nothing was linked.",
+ _ => null
+ };
+}
+
+public sealed record HeimdallLinkStep(Uri? Next, string CookieName, string? CookieValue, HeimdallLinkOutcome? Outcome);
+
+public sealed record HeimdallConfirmLinkRequest(
+ [property: JsonPropertyName("pendingLinkId")] string PendingLinkId);
+
+public sealed record HeimdallConfirmLinkResponse(
+ [property: JsonPropertyName("status")] string? Status);
public sealed record HeimdallStartRequest(
[property: JsonPropertyName("appSlug")] string AppSlug,
diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallCompletePage.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallCompletePage.cs
index 662fb16..b7d67b2 100644
--- a/src/Bifrost.Web/Features/Heimdall/HeimdallCompletePage.cs
+++ b/src/Bifrost.Web/Features/Heimdall/HeimdallCompletePage.cs
@@ -3,7 +3,8 @@ namespace Bifrost.Web.Features.Heimdall;
///
/// The page Heimdall's "Return to the app" lands on. The completion code arrives in the URL fragment, which
/// the server never sees, so the page's script reads it, drops it from the address bar, and posts it with
-/// the attempt to the same path. The page is static: it never contains a code.
+/// the attempt to the same path. A Google link returns a pending link id the same way instead of a code. The page
+/// is static: it never contains a code or an id.
///
public static class HeimdallCompletePage
{
@@ -22,21 +23,24 @@ public static class HeimdallCompletePage
diff --git a/src/Bifrost.Web/Pages/Membership/Status.cshtml b/src/Bifrost.Web/Pages/Membership/Status.cshtml
index 2c1ab8f..8f683a4 100644
--- a/src/Bifrost.Web/Pages/Membership/Status.cshtml
+++ b/src/Bifrost.Web/Pages/Membership/Status.cshtml
@@ -24,6 +24,19 @@
@Model.StatusMessage
+ @if (Model.LinkMessage is not null)
+ {
+ @Model.LinkMessage
+ }
+
+ @if (Model.CanLinkGoogle)
+ {
+
+ }
+
@if (Model.Invitation is not null)
{
diff --git a/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs b/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs
index d579dd3..13b47ca 100644
--- a/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs
+++ b/src/Bifrost.Web/Pages/Membership/Status.cshtml.cs
@@ -1,17 +1,62 @@
using Bifrost.Web.Data;
using Bifrost.Web.Domain;
+using System.Security.Claims;
+using Bifrost.Web.Configuration;
+using Bifrost.Web.Features.Heimdall;
+using Bifrost.Web.Features.Membership;
using Bifrost.Web.Features.Shared;
using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
+using Microsoft.Extensions.Options;
namespace Bifrost.Web.Pages.Membership;
[Authorize]
public sealed class StatusModel(
ICurrentBifrostActorAccessor actorAccessor,
- BifrostDbContext dbContext) : PageModel
+ BifrostDbContext dbContext,
+ HeimdallAuthService heimdallAuthService,
+ IOptions hostOptions,
+ ILogger logger) : PageModel
{
+ /// The wording of the link outcome the page was sent back with: a closed set, null for anything else.
+ public string? LinkMessage { get; private set; }
+
+ /// Whether this session belongs to a Heimdall account a Google login can be attached to.
+ public bool CanLinkGoogle => User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId) is { Length: > 0 };
+
+ ///
+ /// Begins an explicit Google link: an ordinary Heimdall sign-in for the account already signed in here, kept as
+ /// an attempt that is only the proof for the link. POST with antiforgery only; nothing is started without a session.
+ ///
+ public async Task OnPostLinkGoogleAsync(CancellationToken cancellationToken)
+ {
+ var accountId = User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId);
+ if (string.IsNullOrEmpty(accountId))
+ {
+ return RedirectToPage(null, new { link = HeimdallLinkOutcomes.Code(HeimdallLinkOutcome.Error) });
+ }
+
+ try
+ {
+ var start = await heimdallAuthService.StartLinkAsync(
+ accountId,
+ User.FindFirstValue(BifrostClaimTypes.AuthProvider),
+ hostOptions.Value.PublicBaseUrl,
+ Request.Cookies,
+ cancellationToken);
+ Response.Cookies.Append(start.CookieName, start.CookieValue, HeimdallAttemptCookie.Options());
+ return Redirect(start.AuthorizationUrl.ToString());
+ }
+ catch (HeimdallAuthException error)
+ {
+ logger.LogWarning("Heimdall link start refused: {Reason}", error.Message);
+ return RedirectToPage(null, new { link = HeimdallLinkOutcomes.Code(HeimdallLinkOutcome.Error) });
+ }
+ }
+
public CurrentBifrostActor Actor { get; private set; } = CurrentBifrostActor.Anonymous;
public MembershipInvitation? Invitation { get; private set; }
@@ -45,6 +90,7 @@ public sealed class StatusModel(
public async Task OnGetAsync(CancellationToken cancellationToken)
{
Actor = await actorAccessor.GetAsync(cancellationToken);
+ LinkMessage = HeimdallLinkOutcomes.Wording(Request.Query["link"].ToString());
if (Actor.UserAccount is null)
{
diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs
index be3df54..ef92be8 100644
--- a/src/Bifrost.Web/Program.cs
+++ b/src/Bifrost.Web/Program.cs
@@ -152,7 +152,7 @@ builder.Services.AddSingleton();
builder.Services.AddScoped();
builder.Services.AddHttpClient((serviceProvider, client) =>
HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value))
- .RedactLoggedHeaders(header => string.Equals(header, HeimdallAuthService.AppSecretHeader, StringComparison.OrdinalIgnoreCase));
+ .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
builder.Services.AddSingleton();
builder.Services.AddHttpClient(HeimdallTokenVerifier.ClientName, (serviceProvider, client) =>
HeimdallTokenVerifier.ConfigureClient(client, serviceProvider.GetRequiredService>().Value));
@@ -826,8 +826,32 @@ app.MapPost("/auth/heimdall/complete", async (
var form = await ReadFormOrNullAsync(httpContext.Request, cancellationToken);
var attempt = form?["attempt"].ToString();
var held = heimdallAuthService.FindAttemptCookie(httpContext.Request.Cookies, attempt);
+ var linking = held is not null
+ && heimdallAuthService.PurposeOf(held.Value.Value, attempt) is not (null or HeimdallAttemptPurpose.SignIn);
try
{
+ if (linking)
+ {
+ // A link step never signs anyone in: the session in this browser is the one being linked.
+ var step = await heimdallAuthService.ContinueLinkAsync(
+ hostOptions.Value.PublicBaseUrl,
+ attempt,
+ held!.Value.Name,
+ held.Value.Value,
+ form?["code"].ToString(),
+ form?["pendingLinkId"].ToString(),
+ httpContext.User.FindFirstValue(BifrostClaimTypes.HeimdallAccountId),
+ cancellationToken);
+ if (step.Next is not null)
+ {
+ httpContext.Response.Cookies.Append(step.CookieName, step.CookieValue!, HeimdallAttemptCookie.Options());
+ return Results.Redirect(step.Next.ToString());
+ }
+
+ httpContext.Response.Cookies.Delete(step.CookieName, HeimdallAttemptCookie.DeleteOptions());
+ return Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(step.Outcome!.Value));
+ }
+
var signIn = await heimdallAuthService.CompleteAsync(
hostOptions.Value.PublicBaseUrl,
attempt,
@@ -846,7 +870,9 @@ app.MapPost("/auth/heimdall/complete", async (
httpContext.Response.Cookies.Delete(held.Value.Name, HeimdallAttemptCookie.DeleteOptions());
}
- return Results.Redirect(HeimdallAuthService.ErrorRedirect);
+ return linking
+ ? Results.LocalRedirect(HeimdallLinkOutcomes.Redirect(HeimdallLinkOutcome.Error))
+ : Results.Redirect(HeimdallAuthService.ErrorRedirect);
}
}).AllowAnonymous();