diff --git a/docs/guest-accounts.md b/docs/guest-accounts.md index 6046d93..56e6271 100644 --- a/docs/guest-accounts.md +++ b/docs/guest-accounts.md @@ -19,7 +19,7 @@ These four are the Bifrost steward's; they replace the recommendations further d 1. **Name and shape: a stored `Membership.Role` (enum `AccountRole`), not a boolean.** One stored field is one reading, and an account with no role is denied by default (least privilege). `MemberRole` keeps its name and meaning; renaming it is not needed, and nothing existing is removed. 2. **Invite: a single-use code redeemed from a form, never a token in a URL.** The issuer is shown the code once; the guest pastes it into `POST /invite/guest` (a body, not a path or query), so it reaches no log, referrer or browser history. Hashed at rest, seven days, one use, receipted on issue, accept and revoke. The issuer may bind `ExpectedProvider` (optional, narrows the invite). The sign-in return path carries only the Heimdall attempt, never the code. -3. **Provider lists: Bifrost narrows to the intersection with Heimdall's `bifrost` profile, `discord, patreon`; no widening.** Twitch cannot start in Heimdall, so dropping it removes nothing live; it logs a deprecation warning for one release before the entry goes (deprecate before remove). Google stays link-only (PRs #81, #82) and becomes a sign-in provider only when an issued invite needs it, by a profile change in Heimdall first. Which provider sletz uses is still the issuer's to learn. +3. **Provider lists: Bifrost narrows to the intersection with Heimdall's `bifrost` profile, `discord, patreon`; no widening.** Twitch cannot start in Heimdall, so dropping it removes nothing live; it logs a deprecation warning for one release before the entry goes (deprecate before remove). Google is a sign-in provider too: a Google start carrying a live invite asks Heimdall for an invite grant, and Heimdall mints an account only under it (Bifrost PR #92). Which provider sletz uses is still the issuer's to learn. 4. **Collector: a guest has no `member_id` and none of their messages are collected.** A sender with no linked member is already dropped (`docs/answer-collector-consent.md` l.197 in Heimdall). A `member_id`, and a consent record under it, exists only on promotion to `member`. ## The shape in one paragraph @@ -108,13 +108,7 @@ issuer may not have); the issuer may still set `ExpectedProvider` (see Rulings). are added and the invite is spent. If the existing account is `Left` or `Erased`, refuse. 4. Bifrost issues its own cookie as for any account. From there the guest reaches chat through the one OIDC client. -Gap, drift found while reading, still true on main: Bifrost's `AllowedProviders` is `discord, patreon, twitch` -(`HeimdallAuthService.cs:37-42`), but Heimdall's `bifrost` app profile allows `discord, patreon, google` -(`app-profiles.ts:152`, `bifrostProfile`). Twitch cannot start in Heimdall and Google is refused by Bifrost as a sign-in provider. -Main's only Google path is the explicit link by an already signed-in member (`HeimdallAttemptPurpose.LinkAwaitGoogle`, -`HeimdallAuthService.cs:672`, PRs #81 and #82); it never signs anyone in, so it does not close the gap. A guest with -neither Discord, Patreon nor a Google account cannot sign in, and GitHub is not a Heimdall sign-in provider for -this app. Which provider sletz uses is unknown to me; align the two lists before the first invite. +Bifrost's `AllowedProviders` is `discord, patreon, twitch, google` (`HeimdallAuthService.cs`); Heimdall's `bifrost` app profile allows `discord, patreon, google` (`app-profiles.ts`, `bifrostProfile`), so Twitch cannot start in Heimdall. A Google start carrying a live invite asks Heimdall for an invite grant (PR #92); Google also stays the explicit link by a signed-in member (`HeimdallAttemptPurpose.LinkAwaitGoogle`, PRs #81 and #82). Which provider sletz uses is unknown; the issuer learns it before the first invite. ## Guest rights diff --git a/docs/linked-accounts.md b/docs/linked-accounts.md index c8c10f5..08a2240 100644 --- a/docs/linked-accounts.md +++ b/docs/linked-accounts.md @@ -24,7 +24,7 @@ Every action is a POST with antiforgery; a GET starts nothing. The completion ro ## Which provider proves the account -An ordinary proof sign-in through Discord or Patreon when the account no longer holds that login makes Heimdall mint a new, unrelated account that holds it (those providers are `mints_account`), and the freed login then answers `identity_linked_elsewhere` when the member tries to link it back. Google is `requires_link`: Heimdall refuses a Google sign-in for a login no account holds (`identity_not_linked`) and never mints. 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). This guarantee covers this page's proofs only: the older anonymous `GET /auth/heimdall/{provider}` still starts an ordinary sign-in through any named provider, and can overwrite an in-flight attempt slot; that route is unchanged here. +An ordinary proof sign-in through Discord or Patreon when the account no longer holds that login makes Heimdall mint a new, unrelated account that holds it (those providers are `mints_account`), and the freed login then answers `identity_linked_elsewhere` when the member tries to link it back. Google is `requires_link`: Heimdall refuses a Google sign-in for a login no account holds (`identity_not_linked`) and mints only under an invite grant, which a proof never asks for. 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). This guarantee covers this page's proofs only: the older anonymous `GET /auth/heimdall/{provider}` still starts an ordinary sign-in through any named provider, and can overwrite an in-flight attempt slot; that route is unchanged here. - 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 Google (cannot create an account) / Discord / Patreon" and says plainly that Bifrost cannot tell what the account holds, so the member picks a login they know it holds. A named Discord or Patreon 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`). diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs index e6bd0e6..dc7981a 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") @@ -155,6 +169,20 @@ public sealed class HeimdallAuthService( new Uri(payload.AuthorizationUrl, UriKind.Absolute), replaceSlot ?? ChooseSlot(requestCookies), Protect(attempt)); } + /// True when the cookie names a live invite, read through ChatInviteService, the one owner of invites. + 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; + } + /// A start that cannot reach Heimdall is a refusal like any other, never a 500. private async Task SendStartAsync(HttpRequestMessage message, CancellationToken cancellationToken) { @@ -1212,7 +1240,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..a00973b --- /dev/null +++ b/tests/Bifrost.Web.Tests/GoogleInviteSignInTests.cs @@ -0,0 +1,156 @@ +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_with_no_cookie_or_a_junk_cookie_carries_no_grant() + { + using var host = new HeimdallHost(); + await MintAsync(host); + + foreach (var cookie in new string?[] { null, Jar("not-a-token") }) + { + await host.StartAsync(provider: "google", cookieHeader: cookie); + Assert.Equal("", Grant(host)); + } + } + + [Fact] + public async Task A_google_start_with_a_redeemed_invite_carries_no_grant() + { + using var host = new HeimdallHost(); + var (token, _) = await MintAsync(host); + using (var scope = host.Services.CreateScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var hash = ChatInviteService.Hash(token); + (await db.ChatInvites.SingleAsync(x => x.TokenHash == hash)).RedeemedAtUtc = host.Clock.Now; + await db.SaveChangesAsync(); + } + + await host.StartAsync(provider: "google", cookieHeader: Jar(token)); + Assert.Equal("", Grant(host)); + } + + [Fact] + public async Task A_google_start_with_a_revoked_invite_carries_no_grant() + { + using var host = new HeimdallHost(); + var (token, id) = await MintAsync(host); + using (var scope = host.Services.CreateScope()) + { + Assert.True(await scope.ServiceProvider.GetRequiredService().RevokeAsync(id, Guid.NewGuid(), CancellationToken.None)); + } + + await host.StartAsync(provider: "google", cookieHeader: Jar(token)); + Assert.Equal("", Grant(host)); + } + + [Fact] + public async Task A_google_start_with_an_expired_invite_carries_no_grant() + { + using var host = new HeimdallHost(); + var (token, _) = await MintAsync(host); + await host.StartAsync(provider: "google", cookieHeader: Jar(token)); + Assert.Equal("invite", Grant(host)); + + host.Clock.Advance(ChatInviteService.Lifetime + TimeSpan.FromMinutes(1)); + + await host.StartAsync(provider: "google", cookieHeader: Jar(token)); + Assert.Equal("", Grant(host)); + } + + [Fact] + public async Task A_link_or_proof_start_with_a_live_invite_held_sends_no_grant() + { + using var host = new HeimdallHost(); + var (token, _) = await MintAsync(host); + var cookies = new[] { new KeyValuePair(ChatInviteService.CookieName, token) }; + using var scope = host.Services.CreateScope(); + var service = scope.ServiceProvider.GetRequiredService(); + + foreach (var purpose in Enum.GetValues().Where(x => x != Bifrost.Web.Features.Heimdall.HeimdallAttemptPurpose.SignIn)) + { + var before = host.Heimdall.StartBodies.Count; + await service.StartAsync("google", "https://localhost", Bifrost.Web.Features.Shared.LocalReturnPath.Parse("/"), false, cookies, CancellationToken.None, purpose, Guid.NewGuid().ToString()); + Assert.Equal(before + 1, host.Heimdall.StartBodies.Count); + Assert.Equal("", 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" }) { diff --git a/tests/Bifrost.Web.Tests/HeimdallGoogleLinkTests.cs b/tests/Bifrost.Web.Tests/HeimdallGoogleLinkTests.cs index f773eb5..b0e4836 100644 --- a/tests/Bifrost.Web.Tests/HeimdallGoogleLinkTests.cs +++ b/tests/Bifrost.Web.Tests/HeimdallGoogleLinkTests.cs @@ -374,13 +374,12 @@ public sealed class HeimdallGoogleLinkTests Assert.DoesNotContain("now linked to your", hostile); } - // ---- 6. google stays out of sign-in and member access ---- + // ---- 6. google is a sign-in provider, but gives no member access ---- [Theory] - [InlineData("/auth/heimdall/google")] [InlineData("/auth/heimdall/google?access=member")] - [InlineData("/auth/heimdall/Google")] - public async Task Google_is_refused_as_a_sign_in_provider_and_asks_Heimdall_for_nothing(string url) + [InlineData("/auth/heimdall/Google?access=member")] + public async Task Google_is_refused_for_member_access_and_asks_Heimdall_for_nothing(string url) { using var host = new HeimdallHost(realSessions: true); @@ -391,6 +390,17 @@ public sealed class HeimdallGoogleLinkTests Assert.Empty(host.Heimdall.StartBodies); } + [Fact] + public async Task A_plain_google_sign_in_starts_at_Heimdall_with_no_grant_when_no_invite_is_held() + { + using var host = new HeimdallHost(realSessions: true); + + var start = await host.StartAtAsync("/auth/heimdall/google"); + + Assert.NotEqual(ErrorRedirect, Location(start.Response)); + Assert.DoesNotContain("firstLoginGrant", Assert.Single(host.Heimdall.StartBodies)); + } + // ---- 7. nothing secret leaves the request ---- [Fact]