From cfd513655ec1b1df0bf1525b60106a46506cdf02 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Fri, 13 Nov 2026 21:47:45 +0000 Subject: [PATCH] Passkeys: spend challenges, tickets and permits only after the caller's preconditions; re-check revocation at completion; loud RP at boot; honest page when unavailable; label by text element Soul fixes on PR #85: junk from a session thief no longer burns the member's ticket, challenge or verification permits; a passkey revoked between assertion and completion does not unlink; PasskeyRelyingParty is resolved at startup and rejects an ExpectedHost with a port; with a strong passkey and an unavailable RP the page shows a message instead of a dead form; Label() cuts by text element and drops format characters. Tests for each, the user-handle owner callback, the account-scoped lookup (allow list stripped through the ceremony store) and the ticket cookie SameSite. Co-Authored-By: Claude Sonnet 5.5 --- .../Features/Heimdall/HeimdallAuthService.cs | 9 +- .../Features/Passkeys/PasskeyCeremonies.cs | 11 +- .../Features/Passkeys/PasskeyRelyingParty.cs | 6 + .../Features/Passkeys/PasskeyService.cs | 94 +++++--- .../Pages/Membership/LinkedAccounts.cshtml | 27 ++- src/Bifrost.Web/Program.cs | 2 + tests/Bifrost.Web.Tests/PasskeyTests.cs | 204 +++++++++++++++++- 7 files changed, 307 insertions(+), 46 deletions(-) diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs index aa0b410..4741fe1 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallAuthService.cs @@ -35,7 +35,8 @@ public sealed class HeimdallAuthService( TimeProvider timeProvider, HeimdallMemberClient memberClient, LinkedAccountsSnapshots snapshots, - PasskeyCeremonies ceremonies) + PasskeyCeremonies ceremonies, + PasskeyService passkeys) { public const string ErrorRedirect = "/?auth=heimdall-error"; public const string AppSecretHeader = "x-heimdall-app-secret"; @@ -525,6 +526,12 @@ public sealed class HeimdallAuthService( return new HeimdallLinkStep(null, cookieName, null, HeimdallLinkOutcome.PasskeyExpired); } + // A passkey revoked since the assertion no longer proves anything: Heimdall is not asked. + if (!await passkeys.StillStrongAsync(identity.AccountId, fact.Data, cancellationToken)) + { + return new HeimdallLinkStep(null, cookieName, null, HeimdallLinkOutcome.PasskeyFailed); + } + var asserted = await StepUpAsync(bearer, cancellationToken); if (asserted.Refusal is { } refusal) { diff --git a/src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs b/src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs index a3c1fe0..3f8619f 100644 --- a/src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs +++ b/src/Bifrost.Web/Features/Passkeys/PasskeyCeremonies.cs @@ -119,15 +119,18 @@ public sealed class PasskeyCeremonies(TimeProvider clock) } /// -/// The one budget on the passkey ceremonies, per Heimdall account, on the shared : every -/// options request, enrolment, assertion and enrolment start spends a permit. +/// The budgets on the passkey ceremonies, per Heimdall account, on the shared . Two separate +/// ones: asking for options or starting an enrolment sign-in (anyone holding the session can do that), and verifying a +/// registration or an assertion, which is spent only after the caller holds what the verification needs (a live ticket, or one of +/// the account's own strong credentials). So junk from a session thief cannot spend the permits a legitimate verification needs. /// public sealed class PasskeyRateLimit(TimeProvider clock) { public const int Permits = 20; public static readonly TimeSpan Window = TimeSpan.FromMinutes(10); - private readonly FixedWindowBudget _budget = new(Permits, Window, 10_000, clock); + private readonly FixedWindowBudget _options = new(Permits, Window, 10_000, clock); + private readonly FixedWindowBudget _verifications = new(Permits, Window, 10_000, clock); - public bool TryAcquire(string account) => _budget.Spend(account) is null; + public bool TryAcquire(string account, bool verification = false) => (verification ? _verifications : _options).Spend(account) is null; } diff --git a/src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs b/src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs index 67febcd..94ae19c 100644 --- a/src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs +++ b/src/Bifrost.Web/Features/Passkeys/PasskeyRelyingParty.cs @@ -17,6 +17,12 @@ public sealed class PasskeyRelyingParty public PasskeyRelyingParty(IOptions hostOptions, ILogger logger) { var host = hostOptions.Value; + if (host.ExpectedHost.Contains(':')) + { + logger.LogWarning("Passkeys are unavailable: Host:ExpectedHost must be a bare host name without a port (it is the RP ID's host); it was written with a port."); + return; + } + if (!Uri.TryCreate(host.PublicBaseUrl, UriKind.Absolute, out var url) || url.Scheme != Uri.UriSchemeHttps || string.IsNullOrWhiteSpace(host.ExpectedHost) diff --git a/src/Bifrost.Web/Features/Passkeys/PasskeyService.cs b/src/Bifrost.Web/Features/Passkeys/PasskeyService.cs index cc6b52b..a25dca5 100644 --- a/src/Bifrost.Web/Features/Passkeys/PasskeyService.cs +++ b/src/Bifrost.Web/Features/Passkeys/PasskeyService.cs @@ -1,3 +1,5 @@ +using System.Globalization; +using System.Text; using Bifrost.Web.Data; using Bifrost.Web.Domain; using Bifrost.Web.Features.Heimdall; @@ -98,16 +100,16 @@ public sealed class PasskeyService( return (HeimdallLinkOutcome.PasskeysUnavailable, null); } - if (!rateLimit.TryAcquire(heimdallAccountId)) - { - return (HeimdallLinkOutcome.RateLimited, null); - } - if (!HasTicket(heimdallAccountId, ticketId) || await AccountAsync(heimdallAccountId, ct) is not { } user) { return (HeimdallLinkOutcome.EnrolNeedsSignIn, null); } + if (!rateLimit.TryAcquire(heimdallAccountId)) + { + return (HeimdallLinkOutcome.RateLimited, null); + } + var existing = await Active(user.Id).Select(x => x.CredentialId).ToListAsync(ct); if (existing.Count >= MaxActive) { @@ -143,23 +145,13 @@ public sealed class PasskeyService( return HeimdallLinkOutcome.PasskeysUnavailable; } - if (!rateLimit.TryAcquire(heimdallAccountId)) - { - return HeimdallLinkOutcome.RateLimited; - } - - var ticket = ticketId is null ? null : ceremonies.Take(CeremonyKind.EnrolTicket, heimdallAccountId, null, ticketId); - var challenge = ceremonies.Take(CeremonyKind.EnrolChallenge, heimdallAccountId, null, null); - if (ticket is null || await AccountAsync(heimdallAccountId, ct) is not { } user) + // The caller's own preconditions first, spending nothing: someone with only the session has no ticket, so junk from them + // can neither burn the member's ticket and challenge nor spend the verification permits. + if (!HasTicket(heimdallAccountId, ticketId) || await AccountAsync(heimdallAccountId, ct) is not { } user) { return HeimdallLinkOutcome.EnrolNeedsSignIn; } - if (challenge?.Data is null) - { - return HeimdallLinkOutcome.PasskeyExpired; - } - if (await Active(user.Id).CountAsync(ct) >= MaxActive) { return HeimdallLinkOutcome.PasskeyLimit; @@ -171,6 +163,24 @@ public sealed class PasskeyService( return HeimdallLinkOutcome.PasskeyFailed; } + if (!rateLimit.TryAcquire(heimdallAccountId, verification: true)) + { + return HeimdallLinkOutcome.RateLimited; + } + + // Now both are spent, whatever the outcome. + var ticket = ceremonies.Take(CeremonyKind.EnrolTicket, heimdallAccountId, null, ticketId); + var challenge = ceremonies.Take(CeremonyKind.EnrolChallenge, heimdallAccountId, null, null); + if (ticket is null) + { + return HeimdallLinkOutcome.EnrolNeedsSignIn; + } + + if (challenge?.Data is null) + { + return HeimdallLinkOutcome.PasskeyExpired; + } + try { var registered = await relyingParty.Fido2!.MakeNewCredentialAsync(new MakeNewCredentialParams @@ -305,17 +315,9 @@ public sealed class PasskeyService( return (HeimdallLinkOutcome.PasskeysUnavailable, null); } - if (!rateLimit.TryAcquire(heimdallAccountId)) - { - return (HeimdallLinkOutcome.RateLimited, null); - } - - var challenge = ceremonies.Take(CeremonyKind.UnlinkChallenge, heimdallAccountId, identityId, null); - if (challenge?.Data is null) - { - return (HeimdallLinkOutcome.PasskeyExpired, null); - } - + // The caller's own preconditions first, spending nothing: a decodable assertion naming one of this account's strong, + // un-revoked credentials. Junk from someone holding only the session fails here and burns neither the member's challenge + // nor the verification permits. if (await AccountAsync(heimdallAccountId, ct) is not { } user || !TryDecode(fields.RawId, out var rawId) || !TryDecode(fields.AuthenticatorData, out var authenticatorData) || !TryDecode(fields.ClientDataJson, out var clientData) || !TryDecode(fields.Signature, out var signature) @@ -337,6 +339,18 @@ public sealed class PasskeyService( return (HeimdallLinkOutcome.PasskeyFailed, null); } + if (!rateLimit.TryAcquire(heimdallAccountId, verification: true)) + { + return (HeimdallLinkOutcome.RateLimited, null); + } + + // Spent from here on, whatever the outcome. + var challenge = ceremonies.Take(CeremonyKind.UnlinkChallenge, heimdallAccountId, identityId, null); + if (challenge?.Data is null) + { + return (HeimdallLinkOutcome.PasskeyExpired, null); + } + try { var result = await relyingParty.Fido2!.MakeAssertionAsync(new MakeAssertionParams @@ -372,19 +386,33 @@ public sealed class PasskeyService( return (HeimdallLinkOutcome.PasskeyFailed, null); } - var fact = ceremonies.Issue(CeremonyKind.UnlinkProof, heimdallAccountId, identityId, null, PasskeyCeremonies.ProofLifetime); + var fact = ceremonies.Issue(CeremonyKind.UnlinkProof, heimdallAccountId, identityId, credential.Id.ToString(), PasskeyCeremonies.ProofLifetime); return fact is null ? (HeimdallLinkOutcome.Error, null) : (null, fact); } public void DiscardFact(string? factId) => ceremonies.Discard(factId); + /// + /// Whether the credential an assertion fact was made with is still this account's own, un-revoked and strong. Asked in the + /// completion, before Heimdall is: a passkey revoked between the assertion and the completion no longer proves anything. + /// + public async Task StillStrongAsync(string heimdallAccountId, string? credentialId, CancellationToken ct) => + Guid.TryParse(credentialId, out var id) && await AccountAsync(heimdallAccountId, ct) is { } user + && await Strong(user.Id).AnyAsync(x => x.Id == id, ct); + /// A label from a form field: trimmed, control characters dropped, bounded; the fallback when nothing is left. private static string Label(string? value, string fallback) { - var cleaned = new string((value ?? string.Empty).Where(c => !char.IsControl(c)).ToArray()).Trim(); - if (cleaned.Length > MaxLabel) + // By rune and by text element, never by UTF-16 unit: a cut inside a surrogate pair is not valid text and Postgres refuses it. + // Control and format characters (bidi overrides, joiners, zero-width marks) are dropped; a lone surrogate becomes U+FFFD. + var runes = (value ?? string.Empty).EnumerateRunes() + .Where(r => Rune.GetUnicodeCategory(r) is not (UnicodeCategory.Control or UnicodeCategory.Format)) + .Take(MaxLabel * 4); + var cleaned = string.Concat(runes.Select(r => r.ToString())).Trim(); + var elements = new StringInfo(cleaned); + if (elements.LengthInTextElements > MaxLabel) { - cleaned = cleaned[..MaxLabel]; + cleaned = elements.SubstringByTextElements(0, MaxLabel); } return cleaned.Length == 0 ? fallback : cleaned; diff --git a/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml b/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml index 123357d..bad0da5 100644 --- a/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml +++ b/src/Bifrost.Web/Pages/Membership/LinkedAccounts.cshtml @@ -63,6 +63,8 @@ } @if (Model.HasStrongPasskey) { + @if (Model.PasskeysAvailable) + {
@@ -73,6 +75,7 @@
+ } } else if (Model.HasGoogle) { @@ -89,7 +92,16 @@

This is your only login. Heimdall will not remove the last one.

} - @if (Model.HasStrongPasskey) + @if (Model.HasStrongPasskey && !Model.PasskeysAvailable) + { +

+ This account has a passkey, so unlinking needs it, but passkeys are not available on this server right now (a + configuration fault the operator must fix), so nothing can be unlinked from here at the moment. Nothing is lost: + try again later. If you cannot wait, revoke your passkeys below; unlinking then falls back to a fresh Google sign-in, + if a Google login is linked to this account. +

+ } + else if (Model.HasStrongPasskey) {

Unlinking asks for one of your passkeys, then signs you in to Heimdall once more and removes only the login you picked.

} @@ -115,15 +127,16 @@

Passkeys

@if (!Model.PasskeysAvailable) { -

Passkeys are not available on this server right now.

+

Passkeys are not available on this server right now, so none can be added or used. You can still revoke the ones listed.

} - else - { + @if (Model.PasskeysAvailable) + {

A passkey is the strong proof for unlinking a login: it stays on your device, and a site that is not Bifrost cannot use it. A new passkey is added only right after you sign in to Heimdall again, and it counts as strong proof 48 hours later, so someone who borrows your open browser cannot add one and use it at once. You can revoke a passkey here at any time.

+ } @if (Model.Passkeys.Count > 0) {
    @@ -153,7 +166,10 @@
} - @if (Model.PasskeyLimitReached) + @if (!Model.PasskeysAvailable) + { + } + else if (Model.PasskeyLimitReached) {

This is the most passkeys an account can hold. Revoke one to add another.

} @@ -182,7 +198,6 @@ }

- } @if (Model.Identities is not null) { diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs index 8ff08d6..48c0f74 100644 --- a/src/Bifrost.Web/Program.cs +++ b/src/Bifrost.Web/Program.cs @@ -285,6 +285,8 @@ var app = builder.Build(); var appJsonSerializerOptions = CreateAppJsonSerializerOptions(); app.Services.GetRequiredService().Validate(); +// Resolved now so a misconfigured RP (not https, host differs, a port in ExpectedHost) is logged once at boot, not on the first ceremony. +_ = app.Services.GetRequiredService(); await using (var scope = app.Services.CreateAsyncScope()) { await scope.ServiceProvider diff --git a/tests/Bifrost.Web.Tests/PasskeyTests.cs b/tests/Bifrost.Web.Tests/PasskeyTests.cs index bb360d2..bde2a95 100644 --- a/tests/Bifrost.Web.Tests/PasskeyTests.cs +++ b/tests/Bifrost.Web.Tests/PasskeyTests.cs @@ -239,6 +239,7 @@ public sealed class PasskeyTests Assert.Contains("httponly", header); Assert.Contains("path=/", header); Assert.Contains("max-age=300", header); + Assert.Contains("samesite=lax", header); Assert.DoesNotContain("domain", header); } @@ -347,7 +348,7 @@ public sealed class PasskeyTests StartedAttempt? last = null; for (var i = 0; i < PasskeyRateLimit.Permits + 1; i++) { - last = await host.PostLinkedAccountsAsync(member.Session, "PasskeyEnrolOptions"); + last = await host.PostLinkedAccountsAsync(member.Session, "PasskeyChallenge", new Dictionary { ["identityId"] = member.Patreon }); } Assert.Equal(HttpStatusCode.TooManyRequests, last!.Response.StatusCode); @@ -475,7 +476,7 @@ public sealed class PasskeyTests var withOwnKey = await PostAssertion(host, member, fields, member.Patreon); var viaGoogleRoute = await host.StartUnlinkAsync(member.Session, member.Patreon); - Assert.Equal(Page + "?result=passkey_expired", Location(noChallenge.Response)); + Assert.Equal(Page + "?result=passkey_failed", Location(noChallenge.Response)); Assert.Equal(Page + "?result=passkey_failed", Location(withOwnKey.Response)); Assert.Equal(Page + "?result=passkey_required", Location(viaGoogleRoute.Response)); Assert.Equal(starts, host.Heimdall.StartBodies.Count); @@ -818,4 +819,203 @@ public sealed class PasskeyTests Assert.DoesNotContain("innerHTML", source); Assert.DoesNotContain("document.write", source); } + + // ---- a thief holding only the session cannot grief the member's flows ---- + + [Fact] + public async Task Junk_from_a_session_thief_burns_neither_the_members_challenge_nor_ticket_nor_permits() + { + using var host = new HeimdallHost(realSessions: true); + var member = await NewMember(host); + var authenticator = new SoftwareAuthenticator(); + var ticket = await SignInForEnrolment(host, member); + var options = await host.PostLinkedAccountsAsync(member.Session, "PasskeyEnrolOptions", extraCookies: Ticket(ticket)); + var registration = authenticator.Register(await JsonOf(options)); + + // The thief has the session cookie and no ticket: many junk registrations, all refused, nothing spent. + for (var i = 0; i < PasskeyRateLimit.Permits + 5; i++) + { + var junk = await host.PostLinkedAccountsAsync(member.Session, "PasskeyEnrol", new Dictionary { ["rawId"] = "AAAA" }); + Assert.Equal(Page + "?result=enrol_needs_sign_in", Location(junk.Response)); + } + + var enrolled = await host.PostLinkedAccountsAsync(member.Session, "PasskeyEnrol", registration, extraCookies: Ticket(ticket)); + Assert.Equal(Page + "?result=passkey_added", Location(enrolled.Response)); + + await CoolOff(host, member); + var (json, _) = await Challenge(host, member, member.Patreon); + for (var i = 0; i < PasskeyRateLimit.Permits + 5; i++) + { + var junk = await PostAssertion(host, member, new Dictionary { ["rawId"] = "AAAA" }, member.Patreon); + Assert.Equal(Page + "?result=passkey_failed", Location(junk.Response)); + } + + var real = await PostAssertion(host, member, authenticator.Assert(json), member.Patreon); + Assert.StartsWith("https://heimdall.test", Location(real.Response)); + } + + [Fact] + public async Task A_passkey_revoked_after_the_assertion_does_not_unlink_at_the_completion() + { + using var host = new HeimdallHost(realSessions: true); + var member = await NewMember(host); + var authenticator = new SoftwareAuthenticator(); + await AddPasskey(host, member, authenticator); + await CoolOff(host, member); + var attempt = await Unlink(host, member, authenticator, member.Patreon); + var id = (await Credentials(host)).Single().Id.ToString(); + await host.PostLinkedAccountsAsync(member.Session, "PasskeyRevoke", new Dictionary { ["credentialId"] = id }); + + var done = await Finish(host, member, attempt); + + Assert.Equal(Page + "?result=passkey_failed", Location(done)); + Assert.Empty(host.Heimdall.StepUps); + Assert.Empty(host.Heimdall.Unlinks); + Assert.Contains(host.Heimdall.Identities, x => (string?)x["id"] == member.Patreon); + } + + [Fact] + public async Task An_assertion_whose_user_handle_names_another_account_is_refused() + { + using var host = new HeimdallHost(realSessions: true); + var member = await NewMember(host); + var authenticator = new SoftwareAuthenticator(); + await AddPasskey(host, member, authenticator); + await CoolOff(host, member); + var own = (await host.Account(member.Account))!.Id.ToByteArray(); + + var (foreign, _) = await Challenge(host, member, member.Patreon); + var refused = await PostAssertion(host, member, authenticator.Assert(foreign, Guid.NewGuid().ToByteArray()), member.Patreon); + var (mine, _) = await Challenge(host, member, member.Patreon); + var accepted = await PostAssertion(host, member, authenticator.Assert(mine, own), member.Patreon); + + Assert.Equal(Page + "?result=passkey_failed", Location(refused.Response)); + Assert.StartsWith("https://heimdall.test", Location(accepted.Response)); + } + + [Fact] + public async Task The_credential_lookup_is_scoped_to_the_session_account_even_when_the_allow_list_is_empty() + { + using var host = new HeimdallHost(realSessions: true); + var victim = await NewMember(host); + var victimKey = new SoftwareAuthenticator(); + await AddPasskey(host, victim, victimKey); + var other = await NewMember(host); + await AddPasskey(host, other, new SoftwareAuthenticator()); + await CoolOff(host, other); + await ReadList(host, victim); + var (json, _) = await Challenge(host, other, other.Patreon); + // The allow list is a second guard; take it out of the other account's challenge (the way a test can without weakening + // the server) so only the account-scoped lookup stands between the victim's credential and the other account. + var node = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject(); + node["allowCredentials"] = new System.Text.Json.Nodes.JsonArray(); + var stripped = node.ToJsonString(); + Assert.NotNull(host.Services.GetRequiredService() + .Issue(CeremonyKind.UnlinkChallenge, other.Account, other.Patreon, stripped, TimeSpan.FromMinutes(2))); + var starts = host.Heimdall.StartBodies.Count; + + var borrowed = await PostAssertion(host, other, victimKey.Assert(stripped), other.Patreon); + + Assert.Equal(Page + "?result=passkey_failed", Location(borrowed.Response)); + Assert.Equal(starts, host.Heimdall.StartBodies.Count); + } + + // ---- configuration ---- + + [Fact] + public async Task A_misconfigured_relying_party_is_logged_once_at_boot_before_any_ceremony() + { + using var host = new HeimdallHost(realSessions: true, publicBaseUrl: "http://localhost"); + + _ = host.Services; + + Assert.Single(host.Logs.Lines, x => x.Contains("Passkeys are unavailable")); + } + + [Fact] + public void An_expected_host_written_with_a_port_makes_passkeys_unavailable_and_says_why() + { + var logs = new CapturedLogs(); + var party = new PasskeyRelyingParty( + Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.BifrostHostOptions { PublicBaseUrl = "https://localhost", ExpectedHost = "localhost:443" }), + new Microsoft.Extensions.Logging.Abstractions.NullLogger()); + var loud = new PasskeyRelyingParty( + Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.BifrostHostOptions { PublicBaseUrl = "https://localhost:8443", ExpectedHost = "localhost:8443" }), + new TestLogger(logs)); + var fine = new PasskeyRelyingParty( + Microsoft.Extensions.Options.Options.Create(new Bifrost.Web.Configuration.BifrostHostOptions { PublicBaseUrl = "https://localhost:8443", ExpectedHost = "localhost" }), + new Microsoft.Extensions.Logging.Abstractions.NullLogger()); + + Assert.False(party.IsAvailable); + Assert.False(loud.IsAvailable); + Assert.Contains("without a port", Assert.Single(logs.Lines)); + Assert.True(fine.IsAvailable); + Assert.Equal("https://localhost:8443", fine.Origin); + Assert.Equal("localhost", fine.RpId); + } + + private sealed class TestLogger(CapturedLogs logs) : Microsoft.Extensions.Logging.ILogger + { + private readonly Microsoft.Extensions.Logging.ILogger _inner = logs.CreateLogger(typeof(T).Name); + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(Microsoft.Extensions.Logging.LogLevel logLevel) => true; + + public void Log(Microsoft.Extensions.Logging.LogLevel logLevel, Microsoft.Extensions.Logging.EventId eventId, TState state, Exception? exception, Func formatter) => + _inner.Log(logLevel, eventId, state, exception, formatter); + } + + [Fact] + public async Task With_a_strong_passkey_and_an_unavailable_relying_party_the_page_says_so_and_offers_no_form() + { + using var host = new HeimdallHost(realSessions: true, publicBaseUrl: "https://other.example"); + var member = await NewMember(host); + var user = (await host.Account(member.Account))!; + await host.Db(async db => + { + db.PasskeyCredentials.Add(new Bifrost.Web.Domain.PasskeyCredential + { + UserAccountId = user.Id, + CredentialId = [1, 2, 3, 4], + PublicKey = [1], + Label = "Old key", + CreatedUtc = host.Clock.Now - TimeSpan.FromDays(3), + StrongFromUtc = host.Clock.Now - TimeSpan.FromDays(1) + }); + await db.SaveChangesAsync(); + return 0; + }); + + var (_, html) = await host.GetLinkedAccountsAsync(member.Session); + + Assert.DoesNotContain("UnlinkPasskey", html); + Assert.DoesNotContain("Unlink with passkey", html); + Assert.DoesNotContain("passkeys.js", html); + Assert.Contains("passkeys are not available on this server right now", html); + Assert.Contains("revoke your passkeys below", html); + Assert.Contains("Old key", html); + Assert.Contains("PasskeyRevoke", html); + } + + [Fact] + public async Task A_label_is_cut_by_text_element_never_inside_a_surrogate_pair_and_loses_format_characters() + { + using var host = new HeimdallHost(realSessions: true); + var member = await NewMember(host); + var ticket = await SignInForEnrolment(host, member); + + var done = await Enrol(host, member, new SoftwareAuthenticator(), ticket, new string('a', 39) + "\U0001F600" + "tail\u202Eevil"); + + Assert.Equal(Page + "?result=passkey_added", Location(done)); + var label = Assert.Single(await Credentials(host)).Label; + Assert.Equal(new string('a', 39) + "\U0001F600", label); + Assert.DoesNotContain(label.EnumerateRunes(), x => x == System.Text.Rune.ReplacementChar); + Assert.Equal(label, System.Text.Encoding.UTF8.GetString(System.Text.Encoding.UTF8.GetBytes(label))); + + var second = await SignInForEnrolment(host, member); + var again = await Enrol(host, member, new SoftwareAuthenticator(), second, "\u202Eab\u200Bc"); + Assert.Equal(Page + "?result=passkey_added", Location(again)); + Assert.Contains((await Credentials(host)), x => x.Label == "abc"); + } }