diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs index e6bd0e6..775b0ca 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs @@ -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" }; + /// + /// 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. + /// + private static readonly HashSet GrantProviders = new(StringComparer.OrdinalIgnoreCase) { "google" }; + /// The headers HttpClient logging must never write: the app secret and any bearer. 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( } /// A start that cannot reach Heimdall is a refusal like any other, never a 500. + private async Task HoldsLiveInviteAsync(IEnumerable> 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 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); diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallCompletePage.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallCompletePage.cs index 4488d7b..08ba617 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallCompletePage.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallCompletePage.cs @@ -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; diff --git a/src/Bifrost.Web/Pages/Index.cshtml b/src/Bifrost.Web/Pages/Index.cshtml index cfaaacd..ce04f9f 100644 --- a/src/Bifrost.Web/Pages/Index.cshtml +++ b/src/Bifrost.Web/Pages/Index.cshtml @@ -20,6 +20,12 @@ GitHubOAuth:ClientSecret before using sign-in. } + else if (Model.Auth == "identity-not-linked") + { +
+ No Bifrost account holds that Google login. Sign in another way, then link Google from your linked accounts, or open an invite link first. +
+ } else if (Model.Auth == "heimdall-error") {
diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs index 116871a..a626fe7 100644 --- a/src/Bifrost.Web/Program.cs +++ b/src/Bifrost.Web/Program.cs @@ -471,7 +471,7 @@ app.MapGet("/auth/sign-in", async (HttpContext httpContext, IOptionsSign in - Bifrost -

Use Discord, Patreon or Twitch to accept this invite

GitHub sign-in cannot accept a chat invite. Choose another sign-in.

+

Use Discord, Patreon, Twitch or Google to accept this invite

GitHub sign-in cannot accept a chat invite. Choose another sign-in.

"""); return; } @@ -1101,6 +1101,7 @@ static async Task WriteSignInChooserAsync(HttpContext httpContext, string return Discord Heimdall Patreon Heimdall Twitch Heimdall + Google Heimdall

After sign-in, Bifrost returns you to {{escapedReturnUrl}}.

diff --git a/tests/Bifrost.Web.Tests/ChatInviteTests.cs b/tests/Bifrost.Web.Tests/ChatInviteTests.cs index 536f799..9dffb84 100644 --- a/tests/Bifrost.Web.Tests/ChatInviteTests.cs +++ b/tests/Bifrost.Web.Tests/ChatInviteTests.cs @@ -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); } diff --git a/tests/Bifrost.Web.Tests/Fixtures/complete-page-harness.cjs b/tests/Bifrost.Web.Tests/Fixtures/complete-page-harness.cjs index 6feea08..fc565ad 100644 --- a/tests/Bifrost.Web.Tests/Fixtures/complete-page-harness.cjs +++ b/tests/Bifrost.Web.Tests/Fixtures/complete-page-harness.cjs @@ -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", ""), diff --git a/tests/Bifrost.Web.Tests/GoogleInviteSignInTests.cs b/tests/Bifrost.Web.Tests/GoogleInviteSignInTests.cs new file mode 100644 index 0000000..61e1e53 --- /dev/null +++ b/tests/Bifrost.Web.Tests/GoogleInviteSignInTests.cs @@ -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; + +/// A Google sign-in start asks Heimdall for an invite grant only while it carries a live invite; redemption stays ChatInviteService's. +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(); + var (invite, token) = await service.MintAsync(Guid.NewGuid(), "google", CancellationToken.None); + + await scope.ServiceProvider.GetRequiredService().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()! : ""; + } + + 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(); + var hash = ChatInviteService.Hash(redeemed); + (await db.ChatInvites.SingleAsync(x => x.TokenHash == hash)).RedeemedAtUtc = host.Clock.Now; + await scope.ServiceProvider.GetRequiredService().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("", 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("", 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); + } +} diff --git a/tests/Bifrost.Web.Tests/HeimdallCompletePageScriptTests.cs b/tests/Bifrost.Web.Tests/HeimdallCompletePageScriptTests.cs index c79be6d..6b60913 100644 --- a/tests/Bifrost.Web.Tests/HeimdallCompletePageScriptTests.cs +++ b/tests/Bifrost.Web.Tests/HeimdallCompletePageScriptTests.cs @@ -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" }) {