Bifrost: Google in the sign-in chooser; a Google start holding a live invite asks Heimdall for the invite grant
The grant rides only a SignIn start for a provider that mints no account itself (google) and only while the invite cookie names an unredeemed, unrevoked, unexpired invite. Redemption stays ChatInviteService.RedeemCarriedAsync. A refused sign-in for a login no account holds lands on the home page with a fixed message. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
0b11e0e72b
commit
a83856234f
8 changed files with 161 additions and 6 deletions
|
|
@ -37,7 +37,8 @@ public sealed class HeimdallAuthService(
|
|||
LinkedAccountsSnapshots snapshots,
|
||||
PasskeyCeremonies ceremonies,
|
||||
PasskeyService passkeys,
|
||||
MergeProofs mergeProofs)
|
||||
MergeProofs mergeProofs,
|
||||
Bifrost.Web.Features.Invites.ChatInviteService chatInvites)
|
||||
{
|
||||
public const string ErrorRedirect = "/?auth=heimdall-error";
|
||||
public const string AppSecretHeader = "x-heimdall-app-secret";
|
||||
|
|
@ -46,9 +47,16 @@ public sealed class HeimdallAuthService(
|
|||
{
|
||||
"discord",
|
||||
"patreon",
|
||||
"twitch"
|
||||
"twitch",
|
||||
"google"
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The providers that mint no account on their own: Heimdall makes one for them only under a first-login grant
|
||||
/// (docs/service-contract.md, "Invite grant"), so only their sign-in starts may ask for it.
|
||||
/// </summary>
|
||||
private static readonly HashSet<string> GrantProviders = new(StringComparer.OrdinalIgnoreCase) { "google" };
|
||||
|
||||
/// <summary>The headers HttpClient logging must never write: the app secret and any bearer.</summary>
|
||||
public static bool RedactsHeader(string header) =>
|
||||
string.Equals(header, AppSecretHeader, StringComparison.OrdinalIgnoreCase)
|
||||
|
|
@ -114,13 +122,19 @@ public sealed class HeimdallAuthService(
|
|||
: null;
|
||||
var nonce = WebEncoders.Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
|
||||
|
||||
// The grant says "Bifrost has invited this person": asked only when this very start carries a live invite. It never
|
||||
// grants membership or chat; ChatInviteService.RedeemCarriedAsync spends the invite after the sign-in completes.
|
||||
var grant = purpose == HeimdallAttemptPurpose.SignIn && GrantProviders.Contains(provider) && await HoldsLiveInviteAsync(requestCookies, cancellationToken)
|
||||
? "invite"
|
||||
: null;
|
||||
var request = new HeimdallStartRequest(
|
||||
options.AppSlug,
|
||||
"sign_in",
|
||||
ToAttemptReturnUrl(callbackBaseUrl, nonce),
|
||||
new HeimdallHandoff("browser_completion"),
|
||||
entitlementPolicy,
|
||||
stepUp ? true : null);
|
||||
stepUp ? true : null,
|
||||
grant);
|
||||
|
||||
// Headers only: a refusal body is read through RefusedStartMessageAsync's own 4 KiB bound, not buffered whole.
|
||||
using var startMessage = new HttpRequestMessage(HttpMethod.Post, $"/v1/oauth/{provider}/start")
|
||||
|
|
@ -156,6 +170,19 @@ public sealed class HeimdallAuthService(
|
|||
}
|
||||
|
||||
/// <summary>A start that cannot reach Heimdall is a refusal like any other, never a 500.</summary>
|
||||
private async Task<bool> HoldsLiveInviteAsync(IEnumerable<KeyValuePair<string, string>> requestCookies, CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var (name, value) in requestCookies)
|
||||
{
|
||||
if (name == Bifrost.Web.Features.Invites.ChatInviteService.CookieName)
|
||||
{
|
||||
return value.Length is > 0 and <= 200 && await chatInvites.IsLiveAsync(value, cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private async Task<HttpResponseMessage> SendStartAsync(HttpRequestMessage message, CancellationToken cancellationToken)
|
||||
{
|
||||
try
|
||||
|
|
@ -1212,7 +1239,9 @@ public sealed record HeimdallStartRequest(
|
|||
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
[property: JsonPropertyName("entitlementPolicy")] HeimdallEntitlementPolicy? EntitlementPolicy,
|
||||
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
[property: JsonPropertyName("stepUp")] bool? StepUp = null);
|
||||
[property: JsonPropertyName("stepUp")] bool? StepUp = null,
|
||||
[property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
|
||||
[property: JsonPropertyName("firstLoginGrant")] string? FirstLoginGrant = null);
|
||||
|
||||
public sealed record HeimdallHandoff(
|
||||
[property: JsonPropertyName("kind")] string Kind);
|
||||
|
|
|
|||
|
|
@ -35,6 +35,11 @@ public static class HeimdallCompletePage
|
|||
history.replaceState(null, "", location.pathname + location.search);
|
||||
// A provider other than Google attaches in Heimdall's callback, which refuses an identity another account
|
||||
// holds. Only this one refusal is carried on, as a fixed result the page words itself; nothing from the fragment is shown.
|
||||
// A sign-in with Google for a login no account holds is refused unless an invite came with it: say so on the home page.
|
||||
if (failed && attempt && fragment.get("heimdall_error") === "identity_not_linked") {
|
||||
location.replace("/?auth=identity-not-linked");
|
||||
return;
|
||||
}
|
||||
if (failed && attempt && fragment.get("heimdall_error") === "link_initiator_mismatch") {
|
||||
location.replace("/Membership/LinkedAccounts?result=identity_linked_elsewhere");
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -20,6 +20,12 @@
|
|||
<code>GitHubOAuth:ClientSecret</code> before using sign-in.
|
||||
</div>
|
||||
}
|
||||
else if (Model.Auth == "identity-not-linked")
|
||||
{
|
||||
<div class="callout warning">
|
||||
No Bifrost account holds that Google login. Sign in another way, then link Google from your linked accounts, or open an invite link first.
|
||||
</div>
|
||||
}
|
||||
else if (Model.Auth == "heimdall-error")
|
||||
{
|
||||
<div class="callout warning">
|
||||
|
|
|
|||
|
|
@ -471,7 +471,7 @@ app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptions<GitHubOAuth
|
|||
await httpContext.Response.WriteAsync(
|
||||
$"""
|
||||
<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><title>Sign in - Bifrost</title></head>
|
||||
<body><main><h1>Use Discord, Patreon or Twitch to accept this invite</h1><p>GitHub sign-in cannot accept a chat invite. <a href="/auth/sign-in?returnUrl={Uri.EscapeDataString(returnPath.Value)}">Choose another sign-in</a>.</p></main></body></html>
|
||||
<body><main><h1>Use Discord, Patreon, Twitch or Google to accept this invite</h1><p>GitHub sign-in cannot accept a chat invite. <a href="/auth/sign-in?returnUrl={Uri.EscapeDataString(returnPath.Value)}">Choose another sign-in</a>.</p></main></body></html>
|
||||
""");
|
||||
return;
|
||||
}
|
||||
|
|
@ -1101,6 +1101,7 @@ static async Task WriteSignInChooserAsync(HttpContext httpContext, string return
|
|||
<a class="secondary" href="/auth/heimdall/discord?returnUrl={{encodedReturnUrl}}">Discord <span>Heimdall</span></a>
|
||||
<a class="secondary" href="/auth/heimdall/patreon?returnUrl={{encodedReturnUrl}}">Patreon <span>Heimdall</span></a>
|
||||
<a class="secondary" href="/auth/heimdall/twitch?returnUrl={{encodedReturnUrl}}">Twitch <span>Heimdall</span></a>
|
||||
<a class="secondary" href="/auth/heimdall/google?returnUrl={{encodedReturnUrl}}">Google <span>Heimdall</span></a>
|
||||
</div>
|
||||
<p><small>After sign-in, Bifrost returns you to {{escapedReturnUrl}}.</small></p>
|
||||
</main>
|
||||
|
|
|
|||
|
|
@ -167,11 +167,12 @@ public sealed class ChatInviteMintTests(TestWebApplicationFactory factory) : ICl
|
|||
var carried = await (await visitor.GetAsync(landed.Headers.Location)).Content.ReadAsStringAsync();
|
||||
Assert.DoesNotContain("provider=github", carried);
|
||||
Assert.Contains("/auth/heimdall/discord", carried);
|
||||
Assert.Contains("/auth/heimdall/google", 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());
|
||||
Assert.Contains("Discord, Patreon, Twitch or Google", await typed.Content.ReadAsStringAsync());
|
||||
using var bare = await Client().GetAsync("/auth/sign-in?provider=github&returnUrl=%2F");
|
||||
Assert.NotEqual(HttpStatusCode.Conflict, bare.StatusCode);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -65,6 +65,7 @@ console.log(
|
|||
run("link-error-with-pending-id", "?attempt=NONCE", "#heimdall_status=error&heimdall_error=denied&heimdall_pending_link_id=PEND1"),
|
||||
run("link-pending-id-in-query-only", "?attempt=NONCE&heimdall_pending_link_id=QPEND", ""),
|
||||
run("link-refused-elsewhere", "?attempt=NONCE", "#heimdall_status=error&heimdall_error=link_initiator_mismatch"),
|
||||
run("sign-in-not-linked", "?attempt=NONCE", "#heimdall_status=error&heimdall_error=identity_not_linked"),
|
||||
run("link-refused-elsewhere-no-attempt", "", "#heimdall_status=error&heimdall_error=link_initiator_mismatch"),
|
||||
run("other-refusal-text", "?attempt=NONCE", "#heimdall_status=error&heimdall_error=%3Cb%3Ex&heimdall_error_description=EVIL"),
|
||||
run("refusal-in-query-only", "?attempt=NONCE&heimdall_error=link_initiator_mismatch", ""),
|
||||
|
|
|
|||
109
tests/Bifrost.Web.Tests/GoogleInviteSignInTests.cs
Normal file
109
tests/Bifrost.Web.Tests/GoogleInviteSignInTests.cs
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
using System.Text.Json;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Features.Invites;
|
||||
using Bifrost.Web.Tests.Support;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Bifrost.Web.Tests;
|
||||
|
||||
/// <summary>A Google sign-in start asks Heimdall for an invite grant only while it carries a live invite; redemption stays ChatInviteService's.</summary>
|
||||
public sealed class GoogleInviteSignInTests
|
||||
{
|
||||
private static async Task<(string Token, Guid Id)> MintAsync(HeimdallHost host)
|
||||
{
|
||||
using var scope = host.Services.CreateScope();
|
||||
var service = scope.ServiceProvider.GetRequiredService<ChatInviteService>();
|
||||
var (invite, token) = await service.MintAsync(Guid.NewGuid(), "google", CancellationToken.None);
|
||||
|
||||
await scope.ServiceProvider.GetRequiredService<BifrostDbContext>().SaveChangesAsync();
|
||||
return (token, invite.Id);
|
||||
}
|
||||
|
||||
private static string Grant(HeimdallHost host)
|
||||
{
|
||||
var root = JsonDocument.Parse(host.Heimdall.StartBodies[^1]).RootElement;
|
||||
return root.TryGetProperty("firstLoginGrant", out var grant) ? grant.GetString()! : "<absent>";
|
||||
}
|
||||
|
||||
private static string Jar(string token) => $"{ChatInviteService.CookieName}={token}";
|
||||
|
||||
[Fact]
|
||||
public async Task Google_is_offered_in_the_sign_in_chooser()
|
||||
{
|
||||
using var host = new HeimdallHost();
|
||||
using var client = host.NewClient();
|
||||
var chooser = await client.GetStringAsync("/auth/sign-in?returnUrl=%2F");
|
||||
Assert.Contains("/auth/heimdall/google", chooser);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_google_start_with_a_live_invite_carries_the_grant()
|
||||
{
|
||||
using var host = new HeimdallHost();
|
||||
var (token, _) = await MintAsync(host);
|
||||
|
||||
var attempt = await host.StartAsync(provider: "google", cookieHeader: Jar(token));
|
||||
|
||||
Assert.NotEqual(string.Empty, attempt.Nonce);
|
||||
Assert.Equal("invite", Grant(host));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_google_start_without_a_live_invite_carries_no_grant()
|
||||
{
|
||||
using var host = new HeimdallHost();
|
||||
var (redeemed, _) = await MintAsync(host);
|
||||
var (revoked, revokedId) = await MintAsync(host);
|
||||
var (expired, _) = await MintAsync(host);
|
||||
using (var scope = host.Services.CreateScope())
|
||||
{
|
||||
var db = scope.ServiceProvider.GetRequiredService<BifrostDbContext>();
|
||||
var hash = ChatInviteService.Hash(redeemed);
|
||||
(await db.ChatInvites.SingleAsync(x => x.TokenHash == hash)).RedeemedAtUtc = host.Clock.Now;
|
||||
await scope.ServiceProvider.GetRequiredService<ChatInviteService>().RevokeAsync(revokedId, Guid.NewGuid(), CancellationToken.None);
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
host.Clock.Advance(ChatInviteService.Lifetime + TimeSpan.FromMinutes(1));
|
||||
var (fresh, _) = await MintAsync(host); // minted after the jump: live, so the three above are the only dead ones.
|
||||
|
||||
foreach (var cookie in new string?[] { null, Jar("not-a-token"), Jar(redeemed), Jar(revoked), Jar(expired) })
|
||||
{
|
||||
await host.StartAsync(provider: "google", cookieHeader: cookie);
|
||||
Assert.Equal("<absent>", Grant(host));
|
||||
}
|
||||
|
||||
await host.StartAsync(provider: "google", cookieHeader: Jar(fresh));
|
||||
Assert.Equal("invite", Grant(host));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_discord_start_with_a_live_invite_is_unchanged()
|
||||
{
|
||||
using var host = new HeimdallHost();
|
||||
var (token, _) = await MintAsync(host);
|
||||
|
||||
await host.StartAsync(provider: "discord", cookieHeader: Jar(token));
|
||||
|
||||
Assert.Equal("<absent>", Grant(host));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_google_sign_in_under_the_grant_is_invited_by_the_redemption_alone()
|
||||
{
|
||||
using var host = new HeimdallHost();
|
||||
var (token, _) = await MintAsync(host);
|
||||
var accountId = HeimdallShapes.NewAccountId();
|
||||
var attempt = await host.StartAsync(provider: "google", cookieHeader: Jar(token));
|
||||
Assert.Equal("invite", Grant(host));
|
||||
Assert.Null(await host.Account(accountId)); // the grant minted nothing and invited no one
|
||||
|
||||
var done = await host.CompleteWithHeaderAsync(attempt.Nonce, host.CodeFor(attempt, accountId), $"{attempt.CookieName}={attempt.Cookie}; {Jar(token)}");
|
||||
|
||||
Assert.True(done.SignedIn);
|
||||
var account = await host.Account(accountId);
|
||||
Assert.NotNull(account!.ChatInvitedAtUtc);
|
||||
Assert.Equal(account.Id, (await host.Db(db => db.ChatInvites.AsNoTracking().SingleAsync(x => x.TokenHash == ChatInviteService.Hash(token)))).RedeemedByUserAccountId);
|
||||
}
|
||||
}
|
||||
|
|
@ -124,6 +124,9 @@ public sealed class HeimdallCompletePageScriptTests
|
|||
Assert.DoesNotContain("submit", run.Events);
|
||||
Assert.Contains(run.Events, x => x.StartsWith("replaceState:", StringComparison.Ordinal) && !x.Contains('#'));
|
||||
|
||||
// A sign-in for a login no account holds names the refusal on the home page.
|
||||
Assert.Equal("replace:/?auth=identity-not-linked", (await RunScenariosAsync())["sign-in-not-linked"].Events[^1]);
|
||||
|
||||
// Without an attempt, from the query only, or for any other refusal text, it is the ordinary error exit.
|
||||
foreach (var name in new[] { "link-refused-elsewhere-no-attempt", "other-refusal-text", "refusal-in-query-only" })
|
||||
{
|
||||
|
|
|
|||
Loading…
Reference in a new issue