From b54cf271012e0f9d5deffa9fb56c529b116f5230 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sat, 14 Nov 2026 02:27:38 +0000 Subject: [PATCH 1/6] Heimdall identity-move client: closed Moved/Refused/Unknown outcome POST /v1/apps/bifrost/identity-moves under the app secret (HeimdallAuthService.ConfigureClient, same header redaction), 15 s timeout, request validated to the contract's closed body before any I/O, 200 trusted only as a whole receipt answering this request. HeimdallRefusal gains ReadAsync (code plus safe proof side and provider); CodeAsync delegates to it. Co-Authored-By: Claude Sonnet 5.5 --- .../Heimdall/HeimdallIdentityMoveClient.cs | 267 ++++++++++++++++++ .../Features/Heimdall/HeimdallRefusal.cs | 30 +- src/Bifrost.Web/Program.cs | 7 + 3 files changed, 297 insertions(+), 7 deletions(-) create mode 100644 src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs new file mode 100644 index 0000000..b670aee --- /dev/null +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs @@ -0,0 +1,267 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Bifrost.Web.Configuration; +using Microsoft.Extensions.Options; + +namespace Bifrost.Web.Features.Heimdall; + +/// +/// What Bifrost asks Heimdall to move (docs/service-contract.md, POST /v1/apps/{app}/identity-moves). Exactly one of +/// (a forward move, optionally of ) and (the undo). The body +/// never names an account: the proofs, live Heimdall access tokens, say which accounts are meant. +/// +public sealed record HeimdallMoveRequest( + string MoveId, IReadOnlyList FromProofs, string? ToProof = null, IReadOnlyList? IdentityIds = null, string? ReversesMoveId = null); + +public enum HeimdallProofTier +{ + Strong, + Weak +} + +/// The receipt of a move: the destination account, the logins that moved and the tier of the proofs that carried it. +public sealed record HeimdallMoveReceipt( + string MoveId, string AccountId, IReadOnlyList MovedIdentityIds, HeimdallProofTier ProofFrom, HeimdallProofTier? ProofTo, string? ReversesMoveId); + +/// Heimdall's fixed refusal codes for a move, plus the two local classes: a 400, and a 4xx this client does not know. +public enum HeimdallMoveRefusal +{ + AppAuthRequired, + NotAllowedForApp, + NotReversible, + ProofInvalid, + SameAccount, + ProofStale, + IdentityNotProved, + AlreadyMoved, + ProviderConflict, + MoveIdConflict, + IdentityNotFound, + RequestInvalid, + Unrecognized +} + +public enum HeimdallProofSide +{ + From, + To +} + +/// +/// The closed answer to a move. Moved: the receipt. Refused: Heimdall answered a 4xx before applying anything, so nothing changed. +/// Unknown: anything else (a 5xx may follow a committed move, a timeout may hide one): the caller replays the same request. +/// +public abstract record HeimdallMoveOutcome +{ + private HeimdallMoveOutcome() + { + } + + public sealed record Moved(HeimdallMoveReceipt Receipt) : HeimdallMoveOutcome; + + public sealed record Refused(HeimdallMoveRefusal Code, HeimdallProofSide? Side = null, string? Provider = null) : HeimdallMoveOutcome; + + public sealed record Unknown(string Reason) : HeimdallMoveOutcome; +} + +/// +/// Heimdall's move route under Bifrost's app secret (HeimdallAuthService.ConfigureClient adds the header). Each call sends one request and +/// retries nothing: replay with the same is the caller's, and Heimdall answers it with the stored +/// receipt. Logs name the outcome class and refusal code only. +/// +public sealed partial class HeimdallIdentityMoveClient( + HttpClient httpClient, IOptions heimdallOptions, ILogger logger) +{ + public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(15); + + private const int MaxMovedIdentities = 256; + + [GeneratedRegex("^[A-Za-z0-9_-]{16,64}$")] + private static partial Regex MoveIdShape(); + + public async Task MoveAsync(HeimdallMoveRequest request, CancellationToken cancellationToken) + { + var body = Serialize(request); + var outcome = await SendAsync(request, body, cancellationToken); + logger.LogInformation("Heimdall identity move: {Outcome} {Code}", outcome.GetType().Name, outcome is HeimdallMoveOutcome.Refused refused ? refused.Code : null); + return outcome; + } + + private async Task SendAsync(HeimdallMoveRequest request, string body, CancellationToken cancellationToken) + { + try + { + using var message = new HttpRequestMessage( + HttpMethod.Post, $"/v1/apps/{Uri.EscapeDataString(heimdallOptions.Value.AppSlug)}/identity-moves") + { + Content = new StringContent(body, Encoding.UTF8, "application/json") + }; + using var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + var status = (int)response.StatusCode; + if (response.StatusCode == HttpStatusCode.OK) + { + return await ReadReceiptAsync(response, request, cancellationToken) is { } receipt + ? new HeimdallMoveOutcome.Moved(receipt) + : new HeimdallMoveOutcome.Unknown("malformed or mismatched receipt"); + } + + if (status is < 400 or >= 500 || status == 429) + { + return new HeimdallMoveOutcome.Unknown($"HTTP {status}"); + } + + var refusal = await HeimdallRefusal.ReadAsync(response, cancellationToken); + return status == 400 ? new HeimdallMoveOutcome.Refused(HeimdallMoveRefusal.RequestInvalid) : Refused(refusal); + } + catch (Exception error) when (error is HttpRequestException or JsonException or NotSupportedException or TaskCanceledException + && !cancellationToken.IsCancellationRequested) + { + return new HeimdallMoveOutcome.Unknown("transport"); + } + } + + private static HeimdallMoveOutcome.Refused Refused(HeimdallRefusalBody? refusal) + { + var code = refusal?.Code switch + { + "app_auth_required" => HeimdallMoveRefusal.AppAuthRequired, + "not_allowed_for_app" => HeimdallMoveRefusal.NotAllowedForApp, + "not_reversible" => HeimdallMoveRefusal.NotReversible, + "proof_invalid" => HeimdallMoveRefusal.ProofInvalid, + "same_account" => HeimdallMoveRefusal.SameAccount, + "proof_stale" => HeimdallMoveRefusal.ProofStale, + "identity_not_proved" => HeimdallMoveRefusal.IdentityNotProved, + "already_moved" => HeimdallMoveRefusal.AlreadyMoved, + "provider_conflict" => HeimdallMoveRefusal.ProviderConflict, + "move_id_conflict" => HeimdallMoveRefusal.MoveIdConflict, + "identity_not_found" => HeimdallMoveRefusal.IdentityNotFound, + _ => HeimdallMoveRefusal.Unrecognized + }; + return code switch + { + HeimdallMoveRefusal.ProofInvalid or HeimdallMoveRefusal.ProofStale => new(code, Side: refusal?.Proof switch + { + "from" => HeimdallProofSide.From, + "to" => HeimdallProofSide.To, + _ => null + }), + HeimdallMoveRefusal.ProviderConflict => new(code, Provider: refusal?.Provider), + _ => new(code) + }; + } + + /// + /// A 200 body is a receipt only when it is whole and answers this request: its moveId (and reversesMoveId) equal the request's, + /// a forward move names a destination proof tier and a reversal does not. Anything else is not trusted as a move. + /// + private static async Task ReadReceiptAsync(HttpResponseMessage response, HeimdallMoveRequest request, CancellationToken cancellationToken) + { + using var document = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(cancellationToken), cancellationToken: cancellationToken); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object + || Text(root, "moveId") != request.MoveId + || Text(root, "reversesMoveId") != request.ReversesMoveId + || Text(root, "accountId") is not { Length: > 0 } account + || !root.TryGetProperty("movedIdentityIds", out var moved) + || moved.ValueKind != JsonValueKind.Array + || moved.GetArrayLength() is 0 or > MaxMovedIdentities + || !root.TryGetProperty("proof", out var proof) + || proof.ValueKind != JsonValueKind.Object + || Tier(proof, "from") is not { } from) + { + return null; + } + + var ids = new List(); + foreach (var item in moved.EnumerateArray()) + { + if (item.ValueKind != JsonValueKind.String || !Guid.TryParse(item.GetString(), out _)) + { + return null; + } + + ids.Add(item.GetString()!); + } + + HeimdallProofTier? to = null; + if (request.ReversesMoveId is null) + { + to = Tier(proof, "to"); + if (to is null) + { + return null; + } + } + else if (!proof.TryGetProperty("to", out var none) || none.ValueKind != JsonValueKind.Null) + { + return null; + } + + return new HeimdallMoveReceipt(request.MoveId, account, ids, from, to, request.ReversesMoveId); + } + + private static HeimdallProofTier? Tier(JsonElement proof, string name) => Text(proof, name) switch + { + "strong" => HeimdallProofTier.Strong, + "weak" => HeimdallProofTier.Weak, + _ => null + }; + + private static string? Text(JsonElement item, string name) => + item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; + + /// The contract's closed body, or ArgumentException before any I/O when the request breaks it. + private static string Serialize(HeimdallMoveRequest request) + { + if (request.MoveId is null || !MoveIdShape().IsMatch(request.MoveId)) + { + throw new ArgumentException("moveId must match ^[A-Za-z0-9_-]{16,64}$", nameof(request)); + } + + if (request.FromProofs is not { Count: >= 1 and <= 8 } || request.FromProofs.Any(string.IsNullOrWhiteSpace)) + { + throw new ArgumentException("fromProofs must hold 1 to 8 proofs", nameof(request)); + } + + if ((request.ToProof is null) == (request.ReversesMoveId is null)) + { + throw new ArgumentException("exactly one of toProof and reversesMoveId is required", nameof(request)); + } + + if (request.ToProof is not null && string.IsNullOrWhiteSpace(request.ToProof)) + { + throw new ArgumentException("toProof is empty", nameof(request)); + } + + if (request.ReversesMoveId is not null && !MoveIdShape().IsMatch(request.ReversesMoveId)) + { + throw new ArgumentException("reversesMoveId must match the moveId shape", nameof(request)); + } + + if (request.IdentityIds is not null + && (request.ToProof is null || request.IdentityIds.Count is < 1 or > 32 || request.IdentityIds.Any(string.IsNullOrWhiteSpace))) + { + throw new ArgumentException("identityIds are 1 to 32 and only with toProof", nameof(request)); + } + + var body = new Dictionary { ["moveId"] = request.MoveId, ["fromProofs"] = request.FromProofs }; + if (request.ToProof is not null) + { + body["toProof"] = request.ToProof; + } + + if (request.IdentityIds is not null) + { + body["identityIds"] = request.IdentityIds; + } + + if (request.ReversesMoveId is not null) + { + body["reversesMoveId"] = request.ReversesMoveId; + } + + return JsonSerializer.Serialize(body); + } +} diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs index fea10aa..c6bd638 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallRefusal.cs @@ -11,7 +11,14 @@ public static class HeimdallRefusal /// The error code in the first 4 KiB of a body when it is a short snake_case token, else null. A body that cannot be /// read or parsed yields null: a refusal never becomes a 500, and free text or tokens never reach a log or a page. /// - public static async Task CodeAsync(HttpResponseMessage response, CancellationToken cancellationToken) + public static async Task CodeAsync(HttpResponseMessage response, CancellationToken cancellationToken) => + (await ReadAsync(response, cancellationToken))?.Code; + + /// + /// The error code plus the two qualifiers a move refusal carries (the contract's `proof`, only "from" or "to", and `provider`, a + /// short snake_case token), each kept only when it is that safe shape. Nothing else of the body is read. Null when no code reads. + /// + public static async Task ReadAsync(HttpResponseMessage response, CancellationToken cancellationToken) { try { @@ -24,13 +31,10 @@ public static class HeimdallRefusal } using var body = JsonDocument.Parse(head.AsMemory(0, length)); - if (body.RootElement.ValueKind == JsonValueKind.Object - && body.RootElement.TryGetProperty("error", out var error) - && error.ValueKind == JsonValueKind.String - && error.GetString() is { Length: > 0 and <= 64 } code - && code.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_')) + if (body.RootElement.ValueKind == JsonValueKind.Object && Token(body.RootElement, "error", 64) is { } code) { - return code; + var proof = body.RootElement.TryGetProperty("proof", out var side) && side.ValueKind == JsonValueKind.String ? side.GetString() : null; + return new HeimdallRefusalBody(code, proof is "from" or "to" ? proof : null, Token(body.RootElement, "provider", 32)); } } catch (Exception) when (!cancellationToken.IsCancellationRequested) @@ -39,4 +43,16 @@ public static class HeimdallRefusal return null; } + + private static string? Token(JsonElement root, string name, int maxLength) => + root.TryGetProperty(name, out var value) + && value.ValueKind == JsonValueKind.String + && value.GetString() is { Length: > 0 } text + && text.Length <= maxLength + && text.All(c => c is (>= 'a' and <= 'z') or (>= '0' and <= '9') or '_') + ? text + : null; } + +/// A Heimdall refusal's safe fields: the code, the proof side ("from"/"to") and the provider, when present and well formed. +public sealed record HeimdallRefusalBody(string Code, string? Proof, string? Provider); diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs index 48c0f74..2590f77 100644 --- a/src/Bifrost.Web/Program.cs +++ b/src/Bifrost.Web/Program.cs @@ -158,6 +158,13 @@ builder.Services.AddHttpClient((serviceProvider, client) => builder.Services.AddHttpClient((serviceProvider, client) => HeimdallMemberClient.ConfigureClient(client, serviceProvider.GetRequiredService>().Value)) .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader); +// The mover route is an app-secret call like HeimdallAuthService's: same ConfigureClient, same header redaction. +builder.Services.AddHttpClient((serviceProvider, client) => + { + HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value); + client.Timeout = HeimdallIdentityMoveClient.Timeout; + }) + .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); From fbb5853b1d76cd5185242e0395352dfca2da6366 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sat, 14 Nov 2026 02:27:38 +0000 Subject: [PATCH 2/6] Fake Heimdall mover and consumer-side move client tests FakeHeimdall.Moves owns per-account logins, a bearer registry, revoked sessions and stored moves, and answers the identity-moves route in decideMove's order (4fe367a): replay before proofs, strict passkey coverage, freshness windows, first-receipt replay. Fault switches for status, apply-then-fail and down. Co-Authored-By: Claude Sonnet 5.5 --- .../HeimdallIdentityMoveClientTests.cs | 442 ++++++++++++++++++ tests/Bifrost.Web.Tests/Support/FakeMoves.cs | 304 ++++++++++++ .../Support/HeimdallTestKit.cs | 11 + 3 files changed, 757 insertions(+) create mode 100644 tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs create mode 100644 tests/Bifrost.Web.Tests/Support/FakeMoves.cs diff --git a/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs b/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs new file mode 100644 index 0000000..8b312ba --- /dev/null +++ b/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs @@ -0,0 +1,442 @@ +using System.Net; +using System.Text; +using System.Text.Json; +using Bifrost.Web.Configuration; +using Bifrost.Web.Features.Heimdall; +using Bifrost.Web.Tests.Support; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Moved = Bifrost.Web.Features.Heimdall.HeimdallMoveOutcome.Moved; +using Refused = Bifrost.Web.Features.Heimdall.HeimdallMoveOutcome.Refused; +using Unknown = Bifrost.Web.Features.Heimdall.HeimdallMoveOutcome.Unknown; + +namespace Bifrost.Web.Tests; + +/// +/// Bifrost's client for Heimdall's identity-move route, from the caller's side, against the fake Heimdall's account model, which answers +/// as Heimdall 4fe367a's service contract does. Moved and Refused are definitive; anything else is Unknown and is healed by replaying the same moveId. +/// +public sealed class HeimdallIdentityMoveClientTests +{ + private const string Passkey = "bifrost-passkey"; + private const string EmailCode = "bifrost-email-code"; + + private static string NewMoveId() => "move-" + Guid.NewGuid().ToString("N"); + + private static string NewAccount() => HeimdallShapes.NewAccountId(); + + private static HeimdallIdentityMoveClient ClientOf(HeimdallHost host) => host.Services.GetRequiredService(); + + private static Task Move(HeimdallHost host, HeimdallMoveRequest request) => + ClientOf(host).MoveAsync(request, CancellationToken.None); + + private static HeimdallMoveReceipt Receipt(HeimdallMoveOutcome outcome) => Assert.IsType(outcome).Receipt; + + /// An account holding these providers, one login each, in order. + private static (string Account, string[] Ids) AccountWith(FakeMoves moves, params string[] providers) + { + var account = NewAccount(); + return (account, providers.Select(p => moves.AddLogin(account, p)).ToArray()); + } + + /// The usual forward move of everything: a passkey proof of the source and a weak proof of the destination. + private static HeimdallMoveRequest Forward(FakeMoves moves, string source, string destination, string? destinationLogin = null, string[]? ids = null) => + new(NewMoveId(), [moves.Issue(source, stepUpMethod: Passkey)], moves.Issue(destination, destinationLogin), ids); + + // ---- the forward move and its receipt ---- + + [Fact] + public async Task A_forward_move_with_one_weak_proof_per_login_answers_the_receipt_under_the_app_secret_and_names_no_account() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (source, ids) = AccountWith(moves, "discord", "patreon"); + var (destination, destinationIds) = AccountWith(moves, "twitch"); + var request = new HeimdallMoveRequest( + NewMoveId(), [moves.Issue(source, ids[0]), moves.Issue(source, ids[1])], moves.Issue(destination, destinationIds[0])); + + var receipt = Receipt(await Move(host, request)); + + Assert.Equal(new HeimdallMoveReceipt(request.MoveId, destination, ids, HeimdallProofTier.Weak, HeimdallProofTier.Weak, null), receipt with { MovedIdentityIds = ids }); + Assert.Equal(ids, receipt.MovedIdentityIds); + Assert.Equal(["twitch", "discord", "patreon"], moves.Logins[destination].Select(x => x.Provider)); + Assert.Empty(moves.Logins[source]); + var sent = Assert.Single(moves.Requests); + Assert.Equal(HeimdallHost.AppSecret, sent.Secret); + Assert.Null(sent.Authorization); + Assert.DoesNotContain(source, sent.Body); + Assert.DoesNotContain(destination, sent.Body); + var names = JsonDocument.Parse(sent.Body).RootElement.EnumerateObject().Select(x => x.Name).Order().ToArray(); + Assert.Equal(["fromProofs", "moveId", "toProof"], names); + } + + [Fact] + public async Task A_proof_through_one_login_moves_only_that_login_and_only_an_asserted_passkey_speaks_for_the_account() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (destination, _) = AccountWith(moves, "twitch"); + + // Discord proves Discord; Patreon, and so the whole account, is not proved by it. + var (a, aIds) = AccountWith(moves, "discord", "patreon"); + Assert.Equal(new Refused(HeimdallMoveRefusal.IdentityNotProved), + await Move(host, new(NewMoveId(), [moves.Issue(a, aIds[0])], moves.Issue(destination), aIds[1..]))); + Assert.Equal(new Refused(HeimdallMoveRefusal.IdentityNotProved), + await Move(host, new(NewMoveId(), [moves.Issue(a, aIds[0])], moves.Issue(destination)))); + Assert.Equal(2, moves.Logins[a].Count); + + // An email code proves an inbox: strong, fresh, and still only its own login. + Assert.Equal(new Refused(HeimdallMoveRefusal.IdentityNotProved), + await Move(host, new(NewMoveId(), [moves.Issue(a, aIds[0], EmailCode)], moves.Issue(destination)))); + Assert.Equal(new Refused(HeimdallMoveRefusal.IdentityNotProved), + await Move(host, new(NewMoveId(), [moves.Issue(a, aIds[0], EmailCode)], moves.Issue(destination), aIds[1..]))); + Assert.Equal(2, moves.Logins[a].Count); + + // The same proof does move the one login it came through. + Assert.Equal([aIds[0]], Receipt(await Move(host, new(NewMoveId(), [moves.Issue(a, aIds[0], EmailCode)], moves.Issue(destination), aIds[..1]))).MovedIdentityIds); + (destination, _) = AccountWith(moves, "twitch"); + + // An asserted passkey moves everything. + var (b, bIds) = AccountWith(moves, "discord", "patreon", "google"); + var all = Receipt(await Move(host, Forward(moves, b, destination))); + Assert.Equal(bIds, all.MovedIdentityIds); + Assert.Equal(HeimdallProofTier.Strong, all.ProofFrom); + } + + [Fact] + public async Task A_proof_by_a_stale_weak_sign_in_or_step_up_is_refused_with_its_side_at_the_window_edge() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (destination, _) = AccountWith(moves, "twitch"); + + HeimdallMoveRequest Weak(string source, string login, int ago, int toAgo = 0) => + new(NewMoveId(), [moves.Issue(source, login, authAgo: ago)], moves.Issue(destination, authAgo: toAgo)); + + var (a, a1) = AccountWith(moves, "discord"); + Assert.Equal(new Refused(HeimdallMoveRefusal.ProofStale, HeimdallProofSide.From), await Move(host, Weak(a, a1[0], 301))); + Assert.Equal(new Refused(HeimdallMoveRefusal.ProofStale, HeimdallProofSide.To), await Move(host, Weak(a, a1[0], 0, 301))); + Assert.Equal(HeimdallProofTier.Weak, Receipt(await Move(host, Weak(a, a1[0], 300))).ProofFrom); + + var (b, _) = AccountWith(moves, "patreon"); + Assert.Equal(new Refused(HeimdallMoveRefusal.ProofStale, HeimdallProofSide.From), + await Move(host, new(NewMoveId(), [moves.Issue(b, stepUpMethod: Passkey, authAgo: 601, stepUpAgo: 601)], moves.Issue(destination)))); + Assert.Equal(HeimdallProofTier.Strong, + Receipt(await Move(host, new(NewMoveId(), [moves.Issue(b, stepUpMethod: Passkey, authAgo: 600, stepUpAgo: 600)], moves.Issue(destination)))).ProofFrom); + } + + // ---- replay ---- + + [Fact] + public async Task A_replayed_move_id_answers_the_first_receipt_after_the_sources_sessions_were_revoked_and_the_tokens_expired() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (source, ids) = AccountWith(moves, "discord", "patreon"); + var (destination, _) = AccountWith(moves, "twitch"); + var request = Forward(moves, source, destination); + var first = Receipt(await Move(host, request)); + Assert.True(moves.IsRevoked(request.FromProofs[0])); + host.Clock.Advance(TimeSpan.FromHours(2)); + + var again = Receipt(await Move(host, request)); + + Assert.Equal(first.AccountId, again.AccountId); + Assert.Equal(ids, again.MovedIdentityIds); + Assert.Equal(first.ProofFrom, again.ProofFrom); + Assert.Single(moves.Stored); + Assert.Equal(2, moves.Requests.Count); + } + + [Fact] + public async Task A_replay_with_different_identity_ids_answers_the_first_receipt_and_moves_nothing_more() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (source, ids) = AccountWith(moves, "discord", "patreon"); + var (destination, _) = AccountWith(moves, "twitch"); + var proofs = new[] { moves.Issue(source, stepUpMethod: Passkey) }; + var toProof = moves.Issue(destination); + var moveId = NewMoveId(); + + var first = Receipt(await Move(host, new(moveId, proofs, toProof, ids[..1]))); + var again = Receipt(await Move(host, new(moveId, proofs, toProof, ids))); + + Assert.Equal([ids[0]], first.MovedIdentityIds); + Assert.Equal([ids[0]], again.MovedIdentityIds); + Assert.Equal([ids[1]], moves.Logins[source].Select(x => x.Id)); + } + + [Fact] + public async Task A_move_whose_answer_was_lost_heals_by_replaying_the_same_request() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (source, ids) = AccountWith(moves, "discord"); + var (destination, _) = AccountWith(moves, "twitch"); + var request = Forward(moves, source, destination); + + moves.MoveApplyThenFail = HttpStatusCode.InternalServerError; + Assert.IsType(await Move(host, request)); + Assert.Single(moves.Stored); + moves.MoveApplyThenFail = HttpStatusCode.OK; + Assert.IsType(await Move(host, request)); + + moves.MoveApplyThenFail = null; + var healed = Receipt(await Move(host, request)); + Assert.Equal(destination, healed.AccountId); + Assert.Equal(ids, healed.MovedIdentityIds); + Assert.Single(moves.Stored); + } + + // ---- reversal ---- + + [Fact] + public async Task A_reversal_moves_back_exactly_the_logins_the_forward_move_carried_once() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (source, ids) = AccountWith(moves, "discord", "patreon"); + var (destination, destinationIds) = AccountWith(moves, "twitch"); + var forward = Forward(moves, source, destination, ids: ids[..1]); + Receipt(await Move(host, forward)); + Assert.Equal(["twitch", "discord"], moves.Logins[destination].Select(x => x.Provider)); + + // The destination's bearer proves a login it holds; the carried one is proved by its own sign-in. + var undo = new HeimdallMoveRequest(NewMoveId(), [moves.Issue(destination, ids[0])], ReversesMoveId: forward.MoveId); + var receipt = Receipt(await Move(host, undo)); + + Assert.Equal(source, receipt.AccountId); + Assert.Equal([ids[0]], receipt.MovedIdentityIds); + Assert.Equal(forward.MoveId, receipt.ReversesMoveId); + Assert.Null(receipt.ProofTo); + Assert.Equal([destinationIds[0]], moves.Logins[destination].Select(x => x.Id)); + Assert.Equal(ids.Order(), moves.Logins[source].Select(x => x.Id).Order()); + + Assert.Equal(new Refused(HeimdallMoveRefusal.NotReversible), + await Move(host, new(NewMoveId(), [moves.Issue(destination, destinationIds[0], Passkey)], ReversesMoveId: forward.MoveId))); + Assert.Equal(new Refused(HeimdallMoveRefusal.NotReversible), + await Move(host, new(NewMoveId(), [moves.Issue(source, ids[0], Passkey)], ReversesMoveId: undo.MoveId))); + } + + // ---- refusals ---- + + [Fact] + public async Task Each_contract_refusal_code_maps_to_its_member_and_only_provider_conflict_carries_a_provider() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + + // not_allowed_for_app + var (s0, _) = AccountWith(moves, "discord"); + var (d0, _) = AccountWith(moves, "twitch"); + moves.Granted = false; + Assert.Equal(new Refused(HeimdallMoveRefusal.NotAllowedForApp), await Move(host, Forward(moves, s0, d0))); + moves.Granted = true; + + // proof_invalid: unknown, revoked, foreign audience (from side); a lapsed destination proof (to side) + Assert.Equal(new Refused(HeimdallMoveRefusal.ProofInvalid, HeimdallProofSide.From), + await Move(host, new(NewMoveId(), ["no-such-bearer"], moves.Issue(d0)))); + Assert.Equal(new Refused(HeimdallMoveRefusal.ProofInvalid, HeimdallProofSide.From), + await Move(host, new(NewMoveId(), [moves.Issue(s0, stepUpMethod: Passkey, aud: "someone-else")], moves.Issue(d0)))); + Assert.Equal(new Refused(HeimdallMoveRefusal.ProofInvalid, HeimdallProofSide.To), + await Move(host, new(NewMoveId(), [moves.Issue(s0, stepUpMethod: Passkey)], "no-such-bearer"))); + var (other, _) = AccountWith(moves, "google"); + Assert.Equal(new Refused(HeimdallMoveRefusal.ProofInvalid, HeimdallProofSide.From), + await Move(host, new(NewMoveId(), [moves.Issue(s0, stepUpMethod: Passkey), moves.Issue(other, stepUpMethod: Passkey)], moves.Issue(d0)))); + + // same_account + Assert.Equal(new Refused(HeimdallMoveRefusal.SameAccount), + await Move(host, new(NewMoveId(), [moves.Issue(s0, stepUpMethod: Passkey)], moves.Issue(s0)))); + + // identity_not_found: the proof is a passkey, the login is nobody's + Assert.Equal(new Refused(HeimdallMoveRefusal.IdentityNotFound), + await Move(host, Forward(moves, s0, d0, ids: [Guid.NewGuid().ToString()]))); + + // provider_conflict: the destination already holds a Discord login + var (s1, _) = AccountWith(moves, "discord"); + var (d1, _) = AccountWith(moves, "discord"); + Assert.Equal(new Refused(HeimdallMoveRefusal.ProviderConflict, Provider: "discord"), await Move(host, Forward(moves, s1, d1))); + + // move_id_conflict: a used id under other accounts + var (s2, _) = AccountWith(moves, "patreon"); + var (d2, _) = AccountWith(moves, "twitch"); + var used = Forward(moves, s2, d2); + Receipt(await Move(host, used)); + var (s3, _) = AccountWith(moves, "patreon"); + Assert.Equal(new Refused(HeimdallMoveRefusal.MoveIdConflict), + await Move(host, new(used.MoveId, [moves.Issue(s3, stepUpMethod: Passkey)], moves.Issue(d2)))); + + // already_moved: s2 now holds nothing and an unreversed move left it + Assert.Equal(new Refused(HeimdallMoveRefusal.AlreadyMoved), await Move(host, Forward(moves, s2, d0))); + Assert.Equal(new Refused(HeimdallMoveRefusal.AlreadyMoved), await Move(host, Forward(moves, s3, s2))); + + // not_reversible: a move that never happened + Assert.Equal(new Refused(HeimdallMoveRefusal.NotReversible), + await Move(host, new(NewMoveId(), [moves.Issue(d2, stepUpMethod: Passkey)], ReversesMoveId: NewMoveId()))); + } + + [Fact] + public async Task A_wrong_app_secret_is_refused_as_app_auth_required() + { + using var host = new HeimdallHost(appSecret: "not-the-secret"); + var moves = host.Heimdall.Moves; + var (source, _) = AccountWith(moves, "discord"); + var (destination, _) = AccountWith(moves, "twitch"); + + Assert.Equal(new Refused(HeimdallMoveRefusal.AppAuthRequired), await Move(host, Forward(moves, source, destination))); + Assert.Empty(moves.Stored); + } + + [Fact] + public async Task A_missing_route_is_Unrecognized_and_a_400_is_RequestInvalid_both_definitive_refusals() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (source, _) = AccountWith(moves, "discord"); + var (destination, _) = AccountWith(moves, "twitch"); + var request = Forward(moves, source, destination); + + moves.MoveStatus = HttpStatusCode.NotFound; + Assert.Equal(new Refused(HeimdallMoveRefusal.Unrecognized), await Move(host, request)); + moves.MoveStatus = HttpStatusCode.BadRequest; + Assert.Equal(new Refused(HeimdallMoveRefusal.RequestInvalid), await Move(host, request)); + moves.MoveStatus = (HttpStatusCode)418; + Assert.Equal(new Refused(HeimdallMoveRefusal.Unrecognized), await Move(host, request)); + Assert.Empty(moves.Stored); + } + + // ---- unknown outcomes ---- + + [Theory] + [InlineData(HttpStatusCode.InternalServerError)] + [InlineData(HttpStatusCode.ServiceUnavailable)] + [InlineData(HttpStatusCode.TooManyRequests)] + [InlineData(HttpStatusCode.Found)] + public async Task A_5xx_a_429_or_any_other_status_is_Unknown_never_a_refusal(HttpStatusCode status) + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (source, _) = AccountWith(moves, "discord"); + var (destination, _) = AccountWith(moves, "twitch"); + moves.MoveStatus = status; + + Assert.IsType(await Move(host, Forward(moves, source, destination))); + } + + [Fact] + public async Task A_timeout_a_transport_error_and_garbage_with_a_200_are_Unknown_while_the_callers_own_cancellation_propagates() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (source, _) = AccountWith(moves, "discord"); + var (destination, _) = AccountWith(moves, "twitch"); + var request = Forward(moves, source, destination); + + moves.MoveDown = new TaskCanceledException("the client timed out"); + Assert.IsType(await Move(host, request)); + moves.MoveDown = new HttpRequestException("Heimdall is down"); + Assert.IsType(await Move(host, request)); + moves.MoveDown = null; + moves.MoveApplyThenFail = HttpStatusCode.OK; + Assert.IsType(await Move(host, request)); + moves.MoveApplyThenFail = null; + + using var cancelled = new CancellationTokenSource(); + await cancelled.CancelAsync(); + await Assert.ThrowsAnyAsync(() => ClientOf(host).MoveAsync(request, cancelled.Token)); + } + + private sealed class Stub(string json) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }); + } + + private static Task Answered(string json, HeimdallMoveRequest request) => + new HeimdallIdentityMoveClient( + new HttpClient(new Stub(json)) { BaseAddress = new Uri("https://heimdall.test") }, + Options.Create(new HeimdallOptions()), NullLogger.Instance).MoveAsync(request, CancellationToken.None); + + [Fact] + public async Task A_200_that_is_not_a_whole_receipt_for_this_request_is_Unknown() + { + var id = Guid.NewGuid().ToString(); + var forward = new HeimdallMoveRequest("move-0123456789abcdef", ["p"], "q"); + var reversal = new HeimdallMoveRequest("move-0123456789abcdef", ["p"], ReversesMoveId: "move-fedcba9876543210"); + string Body(string moveId = "move-0123456789abcdef", string? reverses = null, string proof = """{"from":"weak","to":"weak"}""", string ids = "\"" + "ID" + "\"") => + $$"""{"moveId":"{{moveId}}","accountId":"acct","movedIdentityIds":[{{ids.Replace("ID", id)}}],"proof":{{proof}}{{(reverses is null ? "" : $",\"reversesMoveId\":\"{reverses}\"")}}}"""; + + // The well formed shapes are accepted, so each refusal below is about its one flaw. + Assert.IsType(await Answered(Body(), forward)); + Assert.IsType(await Answered(Body("move-0123456789abcdef", "move-fedcba9876543210", """{"from":"strong","to":null}"""), reversal)); + + Assert.IsType(await Answered(Body("move-someoneelse12345"), forward)); + Assert.IsType(await Answered(Body(reverses: "move-fedcba9876543210"), forward)); + Assert.IsType(await Answered(Body(), reversal)); + Assert.IsType(await Answered(Body("move-0123456789abcdef", "move-other0123456789", """{"from":"strong","to":null}"""), reversal)); + Assert.IsType(await Answered(Body("move-0123456789abcdef", "move-fedcba9876543210", """{"from":"strong","to":"weak"}"""), reversal)); + Assert.IsType(await Answered(Body(proof: """{"from":"strong","to":null}"""), forward)); + Assert.IsType(await Answered(Body(proof: """{"from":"maybe","to":"weak"}"""), forward)); + Assert.IsType(await Answered(Body(ids: ""), forward)); + Assert.IsType(await Answered(Body(ids: "\"not-a-guid\""), forward)); + Assert.IsType(await Answered("""{"moveId":"move-0123456789abcdef"}""", forward)); + Assert.IsType(await Answered("[]", forward)); + } + + // ---- the closed body ---- + + [Fact] + public async Task A_request_that_breaks_the_contracts_body_throws_before_any_request_reaches_Heimdall() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var good = NewMoveId(); + var proofs = new[] { "p" }; + var broken = new HeimdallMoveRequest[] + { + new(good, proofs, "t", ReversesMoveId: NewMoveId()), + new(good, proofs), + new(good, Enumerable.Repeat("p", 9).ToArray(), "t"), + new(good, [], "t"), + new("short", proofs, "t"), + new("bad move id with spaces", proofs, "t"), + new(good, proofs, ReversesMoveId: "short"), + new(good, proofs, IdentityIds: ["i"], ReversesMoveId: NewMoveId()), + new(good, proofs, "t", []), + new(good, proofs, "t", Enumerable.Repeat("i", 33).ToArray()), + new(good, [""], "t") + }; + + foreach (var request in broken) + { + await Assert.ThrowsAsync(() => Move(host, request)); + } + + Assert.Empty(moves.Requests); + } + + // ---- what the logs hold ---- + + [Fact] + public async Task With_http_trace_logging_on_no_log_line_holds_a_bearer_the_secret_an_identity_id_or_an_account_id() + { + using var host = new HeimdallHost(traceHttp: true); + var moves = host.Heimdall.Moves; + var (source, ids) = AccountWith(moves, "discord", "patreon"); + var (destination, _) = AccountWith(moves, "twitch"); + var request = Forward(moves, source, destination); + Receipt(await Move(host, request)); + Assert.IsType(await Move(host, Forward(moves, source, destination))); + + var logs = string.Join('\n', host.Logs.Lines); + Assert.Contains("Heimdall identity move: Moved", logs); + Assert.Contains("Heimdall identity move: Refused", logs); + Assert.Contains("identity-moves", logs); + foreach (var secret in new[] { HeimdallHost.AppSecret, source, destination, request.FromProofs[0], request.ToProof!, request.MoveId }.Concat(ids)) + { + Assert.DoesNotContain(secret, logs); + } + } +} diff --git a/tests/Bifrost.Web.Tests/Support/FakeMoves.cs b/tests/Bifrost.Web.Tests/Support/FakeMoves.cs new file mode 100644 index 0000000..b28a0c7 --- /dev/null +++ b/tests/Bifrost.Web.Tests/Support/FakeMoves.cs @@ -0,0 +1,304 @@ +using System.Net; +using System.Text; +using System.Text.Json; + +namespace Bifrost.Web.Tests.Support; + +/// One login of a fake account. +public sealed record MoveLogin(string Id, string Provider); + +/// A move Heimdall stored: the forward move or its reversal, with the receipt it answered byte for byte. +public sealed class StoredMove(string moveId, string from, string to, string? reversesMoveId, IReadOnlyList carried, string receipt) +{ + public string MoveId { get; } = moveId; + + public string From { get; } = from; + + public string To { get; } = to; + + public string? ReversesMoveId { get; } = reversesMoveId; + + public IReadOnlyList Carried { get; } = carried; + + public string Receipt { get; } = receipt; + + public bool Reversed { get; set; } +} + +/// +/// The fake Heimdall's account model for identity moves, and the route over it: POST /v1/apps/bifrost/identity-moves as Heimdall's +/// moveIdentitiesRoute and decideMove answer it (docs/service-contract.md at 4fe367a). It owns per-account logins, a registry of the +/// bearers it issued (token to claims), revoked sessions and stored moves. Nothing else of the fake reads these yet; the linked +/// accounts list can read later so one model answers both routes. +/// +public sealed class FakeMoves(Func now) +{ + private const string App = "bifrost"; + private const int WeakSeconds = 300; + private const int StrongSeconds = 600; + private const int Lifetime = 900; + + private sealed record Claims(string Account, string Sid, string Aud, long AuthAt, string? AuthIdentityId, long? StepUpAt, string? StepUpMethod, long Exp); + + private readonly Dictionary _tokens = new(StringComparer.Ordinal); + private readonly HashSet _revoked = new(StringComparer.Ordinal); + private readonly Dictionary _moves = new(StringComparer.Ordinal); + + public Dictionary> Logins { get; } = new(StringComparer.Ordinal); + + public IReadOnlyCollection Stored => _moves.Values; + + /// Every request that reached the route: the app secret header, the Authorization header and the raw body. + public List<(string? Secret, string? Authorization, string Body)> Requests { get; } = []; + + /// When false the app's profile lacks identityMoves, so the route answers 403 not_allowed_for_app. + public bool Granted { get; set; } = true; + + /// When set, the route answers this status after the schema check, bypassing the fake's own rules (nothing is applied). + public HttpStatusCode? MoveStatus { get; set; } + + /// When set, a move that passes every rule is applied and then answered with this status (200 answers a body that is not JSON): a lost answer. + public HttpStatusCode? MoveApplyThenFail { get; set; } + + /// When set, the route throws it instead of answering, as an unreachable or timed-out Heimdall does. + public Exception? MoveDown { get; set; } + + public string AddLogin(string account, string provider, string? id = null) + { + id ??= Guid.NewGuid().ToString(); + if (!Logins.TryGetValue(account, out var list)) + { + Logins[account] = list = []; + } + + list.Add(new MoveLogin(id, provider)); + return id; + } + + /// + /// Issues a live bearer of for the bifrost app. A weak proof is a sign-in through + /// at before now; a step-up () adds step_up_at at before now. + /// + public string Issue(string account, string? authIdentityId = null, string? stepUpMethod = null, int authAgo = 0, int? stepUpAgo = null, string aud = App) + { + var at = now().ToUnixTimeSeconds(); + var token = "bearer-" + Guid.NewGuid().ToString("N"); + _tokens[token] = new Claims( + account, Guid.NewGuid().ToString(), aud, at - authAgo, authIdentityId, + stepUpMethod is null ? null : at - (stepUpAgo ?? 0), stepUpMethod, at + Lifetime); + return token; + } + + public bool IsRevoked(string token) => _revoked.Contains(_tokens[token].Sid); + + public HttpResponseMessage Route(HttpRequestMessage request, string body, string? requiredSecret) + { + var secret = request.Headers.TryGetValues("x-heimdall-app-secret", out var values) ? values.Single() : null; + Requests.Add((secret, request.Headers.Authorization?.ToString(), body)); + if (MoveDown is not null) + { + throw MoveDown; + } + + if (Parse(body) is not { } move) + { + return Json(HttpStatusCode.BadRequest, """{"statusCode":400,"error":"Bad Request","message":"body does not match the schema"}"""); + } + + if (MoveStatus is { } forced) + { + return forced == HttpStatusCode.NotFound + ? new HttpResponseMessage(forced) + : Json(forced, forced == HttpStatusCode.BadRequest + ? """{"statusCode":400,"error":"Bad Request"}""" + : """{"error":"server_error","detail":"HEIMDALL FREE TEXT"}"""); + } + + if (secret != requiredSecret) + { + return Refuse(HttpStatusCode.Unauthorized, "app_auth_required"); + } + + if (!Granted) + { + return Refuse(HttpStatusCode.Forbidden, "not_allowed_for_app"); + } + + var applied = Decide(move); + if (applied.Refusal is { } refusal || MoveApplyThenFail is not { } lost) + { + return applied.Refusal ?? Ok(applied.Receipt!); + } + + return lost == HttpStatusCode.OK ? Json(HttpStatusCode.OK, "not json {") : Json(lost, """{"error":"server_error","detail":"HEIMDALL FREE TEXT"}"""); + } + + private sealed record Move(string MoveId, string[] FromProofs, string? ToProof, string[]? IdentityIds, string? ReversesMoveId); + + private static readonly System.Text.RegularExpressions.Regex MoveIdShape = new("^[A-Za-z0-9_-]{16,64}$"); + + private static Move? Parse(string body) + { + try + { + var root = JsonDocument.Parse(body).RootElement; + string? Text(string name) => root.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; + string[]? List(string name) => root.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Array + ? v.EnumerateArray().Select(x => x.ValueKind == JsonValueKind.String ? x.GetString()! : null!).ToArray() + : null; + var from = List("fromProofs"); + var ids = List("identityIds"); + if (Text("moveId") is not { } id || !MoveIdShape.IsMatch(id) + || from is not { Length: >= 1 and <= 8 } || from.Any(x => x is null) + || ids is { Length: 0 or > 32 } || (ids is not null && ids.Any(x => x is null))) + { + return null; + } + + return new Move(id, from, Text("toProof"), ids, Text("reversesMoveId")); + } + catch (JsonException) + { + return null; + } + } + + private (HttpResponseMessage? Refusal, string? Receipt) Decide(Move move) + { + var at = now().ToUnixTimeSeconds(); + var reversal = move.ReversesMoveId is not null; + + // Replay: registry match of app and accounts, liveness not checked. + var known = move.FromProofs.Select(Known).ToArray(); + if (_moves.TryGetValue(move.MoveId, out var stored)) + { + if (known.Any(x => x is null) || known.Select(x => x!.Account).Distinct().Count() != 1) + { + return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "from"), null); + } + + var toKnown = move.ToProof is null ? null : Known(move.ToProof); + if (move.ToProof is not null && toKnown is null) + { + return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "to"), null); + } + + return known[0]!.Account == stored.From && toKnown?.Account == (reversal ? null : stored.To) && move.ReversesMoveId == stored.ReversesMoveId + ? (null, stored.Receipt) + : (Refuse(HttpStatusCode.Conflict, "move_id_conflict"), null); + } + + StoredMove? forward = null; + if (reversal && !(_moves.TryGetValue(move.ReversesMoveId!, out forward) && forward.ReversesMoveId is null && !forward.Reversed + && (known[0] is not { } holder || holder.Account == forward.To))) + { + return (Refuse(HttpStatusCode.Conflict, "not_reversible"), null); + } + + // proof_invalid: not a live bearer of this app, or fromProofs naming two accounts. + var from = move.FromProofs.Select(Live).ToArray(); + if (from.Any(x => x is null) || from.Select(x => x!.Account).Distinct().Count() != 1) + { + return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "from"), null); + } + + var to = move.ToProof is null ? null : Live(move.ToProof); + if (move.ToProof is not null && to is null) + { + return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "to"), null); + } + + var source = from[0]!.Account; + if (to is not null && to.Account == source) + { + return (Refuse(HttpStatusCode.Conflict, "same_account"), null); + } + + // proof_stale: weak 300 s by auth_at, strong 600 s by step_up_at, the host clock. + if (from.Any(x => Tier(x!, at) is null)) + { + return (Refuse(HttpStatusCode.Forbidden, "proof_stale", proof: "from"), null); + } + + if (to is not null && Tier(to, at) is null) + { + return (Refuse(HttpStatusCode.Forbidden, "proof_stale", proof: "to"), null); + } + + var held = Logins.GetValueOrDefault(source) ?? []; + var carried = reversal ? forward!.Carried.ToArray() : move.IdentityIds ?? held.Select(x => x.Id).ToArray(); + var whole = from.Any(x => Tier(x!, at) == "strong" && x!.StepUpMethod == "bifrost-passkey"); + if (!whole && carried.Any(id => from.All(x => x!.AuthIdentityId != id))) + { + return (Refuse(HttpStatusCode.Forbidden, "identity_not_proved"), null); + } + + var destination = reversal ? forward!.From : to!.Account; + if (!reversal && (IsAlias(source) || IsAlias(destination))) + { + return (Refuse(HttpStatusCode.Conflict, "already_moved"), null); + } + + if (carried.Any(id => held.All(x => x.Id != id))) + { + return (Refuse(HttpStatusCode.NotFound, "identity_not_found"), null); + } + + var moving = held.Where(x => carried.Contains(x.Id)).ToList(); + var there = Logins.GetValueOrDefault(destination) ?? []; + if (moving.FirstOrDefault(x => there.Any(y => y.Provider == x.Provider)) is { } clash) + { + return (Refuse(HttpStatusCode.Conflict, "provider_conflict", provider: clash.Provider), null); + } + + // The move: re-home, revoke the source's sessions, store the receipt. + held.RemoveAll(moving.Contains); + Logins[destination] = [.. there, .. moving]; + foreach (var claims in _tokens.Values.Where(x => x.Account == source)) + { + _revoked.Add(claims.Sid); + } + + var strong = from.Any(x => Tier(x!, at) == "strong"); + var receipt = JsonSerializer.Serialize(new Dictionary + { + ["moveId"] = move.MoveId, + ["accountId"] = destination, + ["movedIdentityIds"] = moving.Select(x => x.Id).ToArray(), + ["proof"] = new Dictionary { ["from"] = strong ? "strong" : "weak", ["to"] = to is null ? null : Tier(to, at) }, + ["reversesMoveId"] = move.ReversesMoveId + }.Where(x => x.Key != "reversesMoveId" || x.Value is not null).ToDictionary()); + _moves[move.MoveId] = new StoredMove(move.MoveId, source, destination, move.ReversesMoveId, moving.Select(x => x.Id).ToArray(), receipt); + if (forward is not null) + { + forward.Reversed = true; + } + + return (null, receipt); + } + + private bool IsAlias(string account) => + (Logins.GetValueOrDefault(account)?.Count ?? 0) == 0 && _moves.Values.Any(x => x.From == account && x.ReversesMoveId is null && !x.Reversed); + + private Claims? Known(string token) => _tokens.TryGetValue(token, out var claims) && claims.Aud == App ? claims : null; + + private Claims? Live(string token) => + Known(token) is { } claims && !_revoked.Contains(claims.Sid) && claims.Exp > now().ToUnixTimeSeconds() ? claims : null; + + private static string? Tier(Claims claims, long at) => + claims.StepUpAt is { } stepUp && at - stepUp <= StrongSeconds ? "strong" : at - claims.AuthAt <= WeakSeconds ? "weak" : null; + + private static HttpResponseMessage Json(HttpStatusCode status, string json) => + new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + + private static HttpResponseMessage Ok(string receipt) + { + var response = Json(HttpStatusCode.OK, receipt); + response.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue { NoStore = true }; + return response; + } + + private static HttpResponseMessage Refuse(HttpStatusCode status, string error, string? proof = null, string? provider = null) => + Json(status, JsonSerializer.Serialize(new Dictionary { ["error"] = error, ["proof"] = proof, ["provider"] = provider } + .Where(x => x.Value is not null).ToDictionary())); +} diff --git a/tests/Bifrost.Web.Tests/Support/HeimdallTestKit.cs b/tests/Bifrost.Web.Tests/Support/HeimdallTestKit.cs index 6ef98a3..688676c 100644 --- a/tests/Bifrost.Web.Tests/Support/HeimdallTestKit.cs +++ b/tests/Bifrost.Web.Tests/Support/HeimdallTestKit.cs @@ -200,6 +200,11 @@ public sealed class FakeHeimdall : HttpMessageHandler public Exception? JwksFailure { get; set; } + /// The account model and route of POST /v1/apps/bifrost/identity-moves (the host's clock is ). + public FakeMoves Moves { get; } + + public FakeHeimdall() => Moves = new FakeMoves(() => Now()); + public List StartBodies { get; } = []; public List StartSecrets { get; } = []; @@ -606,6 +611,11 @@ public sealed class FakeHeimdall : HttpMessageHandler return StepUpRoute(request, await request.Content!.ReadAsStringAsync(cancellationToken)); } + if (request.Method == HttpMethod.Post && path == "/v1/apps/bifrost/identity-moves") + { + return Moves.Route(request, await request.Content!.ReadAsStringAsync(cancellationToken), RequiredAppSecret); + } + if (path.StartsWith("/v1/me/identities", StringComparison.Ordinal)) { return MemberRoute(request, path); @@ -807,6 +817,7 @@ public sealed class HeimdallHost : TestWebApplicationFactory services.AddHttpClient(HeimdallTokenVerifier.ClientName).ConfigurePrimaryHttpMessageHandler(() => Heimdall); services.AddHttpClient().ConfigurePrimaryHttpMessageHandler(() => Heimdall); services.AddHttpClient().ConfigurePrimaryHttpMessageHandler(() => Heimdall); + services.AddHttpClient().ConfigurePrimaryHttpMessageHandler(() => Heimdall); }); } From 13ab2e3be7ced98e25d2345da0f14db77822f153 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sat, 14 Nov 2026 03:13:14 +0000 Subject: [PATCH 3/6] Fake mover: port Heimdall 4fe367a's route schema and decision order 400 for every body the route schema rejects (oneOf toProof/reversesMoveId, duplicate or empty identityIds, proof bounds), 404 identity_not_found for a source holding nothing, coverage-all-null 403 before the store, store order not_reversible/already_moved/not_found/not_proved/provider_conflict, replay by signature without liveness (409 move_id_conflict for unsigned proofs), future-dated proofs stale. Soul's P1-P4 are committed as FakeHeimdallMoverTests. Co-Authored-By: Claude Sonnet 5.5 --- .../FakeHeimdallMoverTests.cs | 165 +++++++++++++++++ tests/Bifrost.Web.Tests/Support/FakeMoves.cs | 174 ++++++++++++------ 2 files changed, 286 insertions(+), 53 deletions(-) create mode 100644 tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs diff --git a/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs b/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs new file mode 100644 index 0000000..b1311a5 --- /dev/null +++ b/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs @@ -0,0 +1,165 @@ +using System.Net; +using System.Text; +using Bifrost.Web.Tests.Support; + +namespace Bifrost.Web.Tests; + +/// +/// The fake mover is the spec the client is tested against, so it must refuse what Heimdall 4fe367a refuses, with the same status and code, in the +/// same order (app.ts moveIdentitiesRoute and its schema, identity-move.ts decideMove). Each case sends a raw body to the fake. +/// +public sealed class FakeHeimdallMoverTests +{ + private static string Id() => "move-" + Guid.NewGuid().ToString("N"); + + private static string Account() => HeimdallShapes.NewAccountId(); + + private static async Task<(HttpStatusCode Status, string Error)> Post(HeimdallHost host, string json) + { + using var client = new HttpClient(host.Heimdall, disposeHandler: false) { BaseAddress = new Uri("https://heimdall.test") }; + client.DefaultRequestHeaders.Add("x-heimdall-app-secret", HeimdallHost.AppSecret); + using var response = await client.PostAsync("/v1/apps/bifrost/identity-moves", new StringContent(json, Encoding.UTF8, "application/json")); + var body = await response.Content.ReadAsStringAsync(); + var error = System.Text.Json.JsonDocument.Parse(body).RootElement.TryGetProperty("error", out var e) ? e.GetString()! : ""; + return (response.StatusCode, error); + } + + private static string Move(string moveId, string[] from, string? to = null, string[]? ids = null, string? reverses = null) => + System.Text.Json.JsonSerializer.Serialize(new Dictionary + { + ["moveId"] = moveId, + ["fromProofs"] = from, + ["toProof"] = to, + ["identityIds"] = ids, + ["reversesMoveId"] = reverses + }.Where(x => x.Value is not null).ToDictionary()); + + [Fact] + public async Task A_body_the_routes_schema_rejects_is_a_400_and_moves_nothing() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (s, d) = (Account(), Account()); + var login = moves.AddLogin(s, "discord"); + moves.AddLogin(d, "twitch"); + var forward = Id(); + Assert.Equal(HttpStatusCode.OK, (await Post(host, Move(forward, [moves.Issue(s, login, "bifrost-passkey")], moves.Issue(d)))).Status); + var (s2, d2) = (Account(), Account()); + var login2 = moves.AddLogin(s2, "patreon"); + moves.AddLogin(d2, "twitch"); + var strong = () => moves.Issue(s2, login2, "bifrost-passkey"); + + var bad = new[] + { + Move(Id(), [moves.Issue(d)], moves.Issue(s), reverses: forward), + Move(Id(), [strong()]), + Move(Id(), [strong()], reverses: "x"), + Move(Id(), [strong()], moves.Issue(d2), [login2, login2]), + Move(Id(), [""], "x"), + Move(Id(), [strong()], "x", [""]), + Move(Id(), [strong()], "x", []), + Move(Id(), [moves.Issue(d)], ids: [login], reverses: forward), + Move(Id(), [], "x"), + Move(Id(), Enumerable.Repeat("p", 9).ToArray(), "x"), + Move(Id(), [new string('p', 8193)], "x"), + Move("short", [strong()], "x"), + """{"moveId":"move-0123456789abcdef","fromProofs":"p","toProof":"x"}""", + "[]" + }; + foreach (var json in bad) + { + Assert.Equal(HttpStatusCode.BadRequest, (await Post(host, json)).Status); + } + + Assert.Single(moves.Stored); + Assert.Single(moves.Logins[s2]); + } + + [Fact] + public async Task A_source_holding_no_login_is_404_identity_not_found_not_an_empty_receipt() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (s, d) = (Account(), Account()); + moves.AddLogin(d, "twitch"); + + var answer = await Post(host, Move(Id(), [moves.Issue(s, Guid.NewGuid().ToString(), "bifrost-passkey")], moves.Issue(d))); + + Assert.Equal((HttpStatusCode.NotFound, "identity_not_found"), answer); + } + + [Fact] + public async Task An_unheld_login_is_404_before_coverage_is_judged() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (s, d) = (Account(), Account()); + var login = moves.AddLogin(s, "discord"); + moves.AddLogin(d, "twitch"); + + var answer = await Post(host, Move(Id(), [moves.Issue(s, login)], moves.Issue(d), [login, Guid.NewGuid().ToString()])); + + Assert.Equal((HttpStatusCode.NotFound, "identity_not_found"), answer); + } + + [Fact] + public async Task A_proof_that_covers_no_login_at_all_is_403_identity_not_proved_before_the_store_looks() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (s, d) = (Account(), Account()); + moves.AddLogin(d, "twitch"); + + // No auth_identity_id and no passkey: nothing is covered, even though the source holds no login either. + Assert.Equal((HttpStatusCode.Forbidden, "identity_not_proved"), await Post(host, Move(Id(), [moves.Issue(s)], moves.Issue(d)))); + } + + [Fact] + public async Task A_future_dated_proof_proves_nothing() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (s, d) = (Account(), Account()); + var login = moves.AddLogin(s, "discord"); + moves.AddLogin(d, "twitch"); + + Assert.Equal((HttpStatusCode.Forbidden, "proof_stale"), await Post(host, Move(Id(), [moves.Issue(s, login, authAgo: -60)], moves.Issue(d)))); + } + + [Fact] + public async Task A_replay_whose_proofs_are_not_signed_for_the_stored_accounts_is_409_move_id_conflict_not_proof_invalid() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (s, d) = (Account(), Account()); + var login = moves.AddLogin(s, "discord"); + moves.AddLogin(d, "twitch"); + var id = Id(); + var to = moves.Issue(d); + Assert.Equal(HttpStatusCode.OK, (await Post(host, Move(id, [moves.Issue(s, login)], to))).Status); + + Assert.Equal((HttpStatusCode.Conflict, "move_id_conflict"), await Post(host, Move(id, ["forged-bearer"], to))); + Assert.Equal((HttpStatusCode.Conflict, "move_id_conflict"), await Post(host, Move(id, [moves.Issue(d)], to))); + Assert.Equal((HttpStatusCode.Conflict, "move_id_conflict"), await Post(host, Move(id, [moves.Issue(s)], reverses: Id()))); + Assert.Equal(HttpStatusCode.OK, (await Post(host, Move(id, [moves.Issue(s)], to))).Status); + } + + [Fact] + public async Task A_reversal_by_the_wrong_account_or_of_a_reversed_move_is_409_not_reversible_in_Heimdalls_order() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (s, d, other) = (Account(), Account(), Account()); + var login = moves.AddLogin(s, "discord"); + moves.AddLogin(d, "twitch"); + moves.AddLogin(other, "google"); + var forward = Id(); + await Post(host, Move(forward, [moves.Issue(s, login, "bifrost-passkey")], moves.Issue(d))); + + // The wrong account proves the reversal: not_reversible only after its proof was judged live. + Assert.Equal((HttpStatusCode.Forbidden, "proof_invalid"), await Post(host, Move(Id(), ["unknown"], reverses: forward))); + Assert.Equal((HttpStatusCode.Conflict, "not_reversible"), await Post(host, Move(Id(), [moves.Issue(other, stepUpMethod: "bifrost-passkey")], reverses: forward))); + Assert.Equal((HttpStatusCode.OK, ""), await Post(host, Move(Id(), [moves.Issue(d, login, "bifrost-passkey")], reverses: forward))); + Assert.Equal((HttpStatusCode.Conflict, "not_reversible"), await Post(host, Move(Id(), [moves.Issue(d, stepUpMethod: "bifrost-passkey")], reverses: forward))); + } +} diff --git a/tests/Bifrost.Web.Tests/Support/FakeMoves.cs b/tests/Bifrost.Web.Tests/Support/FakeMoves.cs index b28a0c7..e1df159 100644 --- a/tests/Bifrost.Web.Tests/Support/FakeMoves.cs +++ b/tests/Bifrost.Web.Tests/Support/FakeMoves.cs @@ -137,25 +137,65 @@ public sealed class FakeMoves(Func now) private static readonly System.Text.RegularExpressions.Regex MoveIdShape = new("^[A-Za-z0-9_-]{16,64}$"); + /// + /// Heimdall's route schema (app.ts, the identity-moves route): moveId pattern, 1 to 8 fromProofs of 1 to 8192 chars, toProof, 1 to 32 + /// unique non-empty identityIds, reversesMoveId pattern; and oneOf: a forward move has toProof and no reversesMoveId, a reversal has + /// reversesMoveId and neither toProof nor identityIds. Unknown properties are stripped. Anything else is a 400. + /// private static Move? Parse(string body) { try { var root = JsonDocument.Parse(body).RootElement; - string? Text(string name) => root.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() : null; - string[]? List(string name) => root.TryGetProperty(name, out var v) && v.ValueKind == JsonValueKind.Array - ? v.EnumerateArray().Select(x => x.ValueKind == JsonValueKind.String ? x.GetString()! : null!).ToArray() - : null; - var from = List("fromProofs"); - var ids = List("identityIds"); - if (Text("moveId") is not { } id || !MoveIdShape.IsMatch(id) - || from is not { Length: >= 1 and <= 8 } || from.Any(x => x is null) - || ids is { Length: 0 or > 32 } || (ids is not null && ids.Any(x => x is null))) + if (root.ValueKind != JsonValueKind.Object) { return null; } - return new Move(id, from, Text("toProof"), ids, Text("reversesMoveId")); + var bad = false; + string? Text(string name, int min, int max, bool pattern) + { + if (!root.TryGetProperty(name, out var v)) + { + return null; + } + + if (v.ValueKind != JsonValueKind.String || v.GetString() is not { } t || t.Length < min || t.Length > max || (pattern && !MoveIdShape.IsMatch(t))) + { + bad = true; + return null; + } + + return t; + } + + string[]? List(string name, int max, int maxLength, bool unique) + { + if (!root.TryGetProperty(name, out var v)) + { + return null; + } + + if (v.ValueKind != JsonValueKind.Array || v.GetArrayLength() is 0 || v.GetArrayLength() > max + || v.EnumerateArray().Any(x => x.ValueKind != JsonValueKind.String || x.GetString() is not { Length: > 0 } t || t.Length > maxLength)) + { + bad = true; + return null; + } + + var items = v.EnumerateArray().Select(x => x.GetString()!).ToArray(); + bad |= unique && items.Distinct().Count() != items.Length; + return items; + } + + var id = Text("moveId", 16, 64, true); + var from = List("fromProofs", 8, 8192, false); + var to = Text("toProof", 1, 8192, false); + var ids = List("identityIds", 32, int.MaxValue, true); + var reverses = Text("reversesMoveId", 16, 64, true); + var forward = to is not null && reverses is null; + var reversal = reverses is not null && to is null && ids is null; + return bad || id is null || from is null || !(forward || reversal) ? null : new Move(id, from, to, ids, reverses); } catch (JsonException) { @@ -163,59 +203,62 @@ public sealed class FakeMoves(Func now) } } + /// moveIdentitiesRoute then decideMove at 4fe367a, in their order; each comment names the check. private (HttpResponseMessage? Refusal, string? Receipt) Decide(Move move) { var at = now().ToUnixTimeSeconds(); var reversal = move.ReversesMoveId is not null; - // Replay: registry match of app and accounts, liveness not checked. - var known = move.FromProofs.Select(Known).ToArray(); + // Replay: the stored move answers before any proof is judged live; proofs need only be signed for the stored accounts. if (_moves.TryGetValue(move.MoveId, out var stored)) { - if (known.Any(x => x is null) || known.Select(x => x!.Account).Distinct().Count() != 1) - { - return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "from"), null); - } - - var toKnown = move.ToProof is null ? null : Known(move.ToProof); - if (move.ToProof is not null && toKnown is null) - { - return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "to"), null); - } - - return known[0]!.Account == stored.From && toKnown?.Account == (reversal ? null : stored.To) && move.ReversesMoveId == stored.ReversesMoveId - ? (null, stored.Receipt) - : (Refuse(HttpStatusCode.Conflict, "move_id_conflict"), null); + var same = move.ReversesMoveId == stored.ReversesMoveId + && move.FromProofs.All(x => Known(x)?.Account == stored.From) + && (reversal ? move.ToProof is null : Known(move.ToProof!)?.Account == stored.To); + return same ? (null, stored.Receipt) : (Refuse(HttpStatusCode.Conflict, "move_id_conflict"), null); } StoredMove? forward = null; - if (reversal && !(_moves.TryGetValue(move.ReversesMoveId!, out forward) && forward.ReversesMoveId is null && !forward.Reversed - && (known[0] is not { } holder || holder.Account == forward.To))) + if (reversal && !(_moves.TryGetValue(move.ReversesMoveId!, out forward) && forward.ReversesMoveId is null)) { return (Refuse(HttpStatusCode.Conflict, "not_reversible"), null); } - // proof_invalid: not a live bearer of this app, or fromProofs naming two accounts. - var from = move.FromProofs.Select(Live).ToArray(); - if (from.Any(x => x is null) || from.Select(x => x!.Account).Distinct().Count() != 1) + var from = new List(); + foreach (var token in move.FromProofs) + { + if (Live(token) is not { } claims) + { + return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "from"), null); + } + + from.Add(claims); + } + + var source = from[0].Account; + if (from.Any(x => x.Account != source)) { return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "from"), null); } - var to = move.ToProof is null ? null : Live(move.ToProof); - if (move.ToProof is not null && to is null) + Claims? to = null; + if (!reversal && (to = Live(move.ToProof!)) is null) { return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "to"), null); } - var source = from[0]!.Account; - if (to is not null && to.Account == source) + if (reversal && source != forward!.To) + { + return (Refuse(HttpStatusCode.Conflict, "not_reversible"), null); + } + + var destination = to?.Account ?? forward!.From; + if (source == destination) { return (Refuse(HttpStatusCode.Conflict, "same_account"), null); } - // proof_stale: weak 300 s by auth_at, strong 600 s by step_up_at, the host clock. - if (from.Any(x => Tier(x!, at) is null)) + if (from.Any(x => Tier(x, at) is null)) { return (Refuse(HttpStatusCode.Forbidden, "proof_stale", proof: "from"), null); } @@ -225,26 +268,44 @@ public sealed class FakeMoves(Func now) return (Refuse(HttpStatusCode.Forbidden, "proof_stale", proof: "to"), null); } - var held = Logins.GetValueOrDefault(source) ?? []; - var carried = reversal ? forward!.Carried.ToArray() : move.IdentityIds ?? held.Select(x => x.Id).ToArray(); - var whole = from.Any(x => Tier(x!, at) == "strong" && x!.StepUpMethod == "bifrost-passkey"); - if (!whole && carried.Any(id => from.All(x => x!.AuthIdentityId != id))) + // proofCovers: a strong passkey proof speaks for the account, else the login the sign-in came through, else nothing. + var coverage = from.Select(x => Tier(x, at) == "strong" && x.StepUpMethod == "bifrost-passkey" ? "account" : x.AuthIdentityId).ToArray(); + if (coverage.All(x => x is null)) { return (Refuse(HttpStatusCode.Forbidden, "identity_not_proved"), null); } - var destination = reversal ? forward!.From : to!.Account; - if (!reversal && (IsAlias(source) || IsAlias(destination))) + // decideMove: reversal or alias, the logins chosen (held ones only), coverage of them, then the destination's providers. + var held = Logins.GetValueOrDefault(source) ?? []; + if (reversal) + { + if (forward!.Reversed || forward.Carried.Any(id => held.All(x => x.Id != id))) + { + return (Refuse(HttpStatusCode.Conflict, "not_reversible"), null); + } + } + else if (IsAlias(source) || IsAlias(destination)) { return (Refuse(HttpStatusCode.Conflict, "already_moved"), null); } - if (carried.Any(id => held.All(x => x.Id != id))) + var wanted = reversal ? forward!.Carried : move.IdentityIds; + if (wanted is not null && wanted.Any(id => held.All(x => x.Id != id))) { return (Refuse(HttpStatusCode.NotFound, "identity_not_found"), null); } - var moving = held.Where(x => carried.Contains(x.Id)).ToList(); + var moving = held.Where(x => wanted is null || wanted.Contains(x.Id)).ToList(); + if (moving.Count == 0) + { + return (Refuse(HttpStatusCode.NotFound, "identity_not_found"), null); + } + + if (!coverage.Contains("account") && moving.Any(x => !coverage.Contains(x.Id))) + { + return (Refuse(HttpStatusCode.Forbidden, "identity_not_proved"), null); + } + var there = Logins.GetValueOrDefault(destination) ?? []; if (moving.FirstOrDefault(x => there.Any(y => y.Provider == x.Provider)) is { } clash) { @@ -259,22 +320,27 @@ public sealed class FakeMoves(Func now) _revoked.Add(claims.Sid); } - var strong = from.Any(x => Tier(x!, at) == "strong"); - var receipt = JsonSerializer.Serialize(new Dictionary + var strong = from.Any(x => Tier(x, at) == "strong"); + var receipt = new Dictionary { ["moveId"] = move.MoveId, ["accountId"] = destination, ["movedIdentityIds"] = moving.Select(x => x.Id).ToArray(), - ["proof"] = new Dictionary { ["from"] = strong ? "strong" : "weak", ["to"] = to is null ? null : Tier(to, at) }, - ["reversesMoveId"] = move.ReversesMoveId - }.Where(x => x.Key != "reversesMoveId" || x.Value is not null).ToDictionary()); - _moves[move.MoveId] = new StoredMove(move.MoveId, source, destination, move.ReversesMoveId, moving.Select(x => x.Id).ToArray(), receipt); + ["proof"] = new Dictionary { ["from"] = strong ? "strong" : "weak", ["to"] = to is null ? null : Tier(to, at) } + }; + if (move.ReversesMoveId is not null) + { + receipt["reversesMoveId"] = move.ReversesMoveId; + } + + var json = JsonSerializer.Serialize(receipt); + _moves[move.MoveId] = new StoredMove(move.MoveId, source, destination, move.ReversesMoveId, moving.Select(x => x.Id).ToArray(), json); if (forward is not null) { forward.Reversed = true; } - return (null, receipt); + return (null, json); } private bool IsAlias(string account) => @@ -285,8 +351,10 @@ public sealed class FakeMoves(Func now) private Claims? Live(string token) => Known(token) is { } claims && !_revoked.Contains(claims.Sid) && claims.Exp > now().ToUnixTimeSeconds() ? claims : null; + /// proofTier: strong inside 600 s of step_up_at, else weak inside 300 s of auth_at; a future-dated claim proves nothing. private static string? Tier(Claims claims, long at) => - claims.StepUpAt is { } stepUp && at - stepUp <= StrongSeconds ? "strong" : at - claims.AuthAt <= WeakSeconds ? "weak" : null; + claims.StepUpAt is { } stepUp && stepUp <= at && at - stepUp <= StrongSeconds ? "strong" + : claims.AuthAt <= at && at - claims.AuthAt <= WeakSeconds ? "weak" : null; private static HttpResponseMessage Json(HttpStatusCode status, string json) => new(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; From baa70bcef08ddaf659cde3c10f85229e85e294d4 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sat, 14 Nov 2026 03:13:14 +0000 Subject: [PATCH 4/6] Move client: no redirects, one deadline over body reads, 64 KiB receipt cap, 409 move_id_conflict is Unknown A 3xx is Unknown and never carries the secret or proofs off origin (registration owns the handler); the HttpClient timeout now bounds the body read and any IOException or stall is Unknown; receipts over 64 KiB are Unknown; the request's ToString hides its proofs; move_id_conflict is Unknown because a committed move answers it when its proofs no longer verify, which keeps the sealed proofs resumable; identity ids need not be GUIDs, proofs are bounded to 8192 and identityIds unique. Co-Authored-By: Claude Sonnet 5.5 --- .../Heimdall/HeimdallIdentityMoveClient.cs | 89 +++++-- src/Bifrost.Web/Program.cs | 9 +- .../HeimdallIdentityMoveClientTests.cs | 239 +++++++++++++++++- 3 files changed, 303 insertions(+), 34 deletions(-) diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs index b670aee..94b7853 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs @@ -13,7 +13,15 @@ namespace Bifrost.Web.Features.Heimdall; /// never names an account: the proofs, live Heimdall access tokens, say which accounts are meant. /// public sealed record HeimdallMoveRequest( - string MoveId, IReadOnlyList FromProofs, string? ToProof = null, IReadOnlyList? IdentityIds = null, string? ReversesMoveId = null); + string MoveId, IReadOnlyList FromProofs, string? ToProof = null, IReadOnlyList? IdentityIds = null, string? ReversesMoveId = null) +{ + // The proofs are live bearers: the generated ToString would print them into any log or exception that holds the request. + private bool PrintMembers(StringBuilder builder) + { + builder.Append($"MoveId = {MoveId}, FromProofs = {FromProofs?.Count}, ToProof = {(ToProof is null ? "none" : "present")}, ReversesMoveId = {ReversesMoveId}"); + return true; + } +} public enum HeimdallProofTier { @@ -37,7 +45,6 @@ public enum HeimdallMoveRefusal IdentityNotProved, AlreadyMoved, ProviderConflict, - MoveIdConflict, IdentityNotFound, RequestInvalid, Unrecognized @@ -51,7 +58,8 @@ public enum HeimdallProofSide /// /// The closed answer to a move. Moved: the receipt. Refused: Heimdall answered a 4xx before applying anything, so nothing changed. -/// Unknown: anything else (a 5xx may follow a committed move, a timeout may hide one): the caller replays the same request. +/// Unknown: anything else (a 5xx may follow a committed move, a timeout may hide one, and so may a 409 move_id_conflict: Heimdall +/// answers it to a replay of a committed move whose proofs no longer verify): the caller keeps its proofs and replays the same request. /// public abstract record HeimdallMoveOutcome { @@ -74,9 +82,13 @@ public abstract record HeimdallMoveOutcome public sealed partial class HeimdallIdentityMoveClient( HttpClient httpClient, IOptions heimdallOptions, ILogger logger) { + /// The deadline of one call, headers and body together, set on the HttpClient by . public static readonly TimeSpan Timeout = TimeSpan.FromSeconds(15); private const int MaxMovedIdentities = 256; + private const int MaxIdentityIdLength = 128; + private const int MaxReceiptBytes = 64 * 1024; + private const int MaxProofLength = 8192; [GeneratedRegex("^[A-Za-z0-9_-]{16,64}$")] private static partial Regex MoveIdShape(); @@ -91,6 +103,10 @@ public sealed partial class HeimdallIdentityMoveClient( private async Task SendAsync(HeimdallMoveRequest request, string body, CancellationToken cancellationToken) { + // One deadline over the whole call: HttpClient.Timeout ends at the headers, and a stalled body must not outlive it. + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(httpClient.Timeout); + var token = deadline.Token; try { using var message = new HttpRequestMessage( @@ -98,11 +114,11 @@ public sealed partial class HeimdallIdentityMoveClient( { Content = new StringContent(body, Encoding.UTF8, "application/json") }; - using var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, cancellationToken); + using var response = await httpClient.SendAsync(message, HttpCompletionOption.ResponseHeadersRead, token); var status = (int)response.StatusCode; if (response.StatusCode == HttpStatusCode.OK) { - return await ReadReceiptAsync(response, request, cancellationToken) is { } receipt + return await ReadReceiptAsync(response, request, token) is { } receipt ? new HeimdallMoveOutcome.Moved(receipt) : new HeimdallMoveOutcome.Unknown("malformed or mismatched receipt"); } @@ -112,18 +128,24 @@ public sealed partial class HeimdallIdentityMoveClient( return new HeimdallMoveOutcome.Unknown($"HTTP {status}"); } - var refusal = await HeimdallRefusal.ReadAsync(response, cancellationToken); + var refusal = await HeimdallRefusal.ReadAsync(response, token); return status == 400 ? new HeimdallMoveOutcome.Refused(HeimdallMoveRefusal.RequestInvalid) : Refused(refusal); } - catch (Exception error) when (error is HttpRequestException or JsonException or NotSupportedException or TaskCanceledException + catch (Exception error) when (error is HttpRequestException or IOException or JsonException or NotSupportedException or OperationCanceledException && !cancellationToken.IsCancellationRequested) { return new HeimdallMoveOutcome.Unknown("transport"); } } - private static HeimdallMoveOutcome.Refused Refused(HeimdallRefusalBody? refusal) + private static HeimdallMoveOutcome Refused(HeimdallRefusalBody? refusal) { + // Not a refusal: a committed move answers 409 move_id_conflict when its proofs no longer verify, so it proves nothing about the move. + if (refusal?.Code == "move_id_conflict") + { + return new HeimdallMoveOutcome.Unknown("move_id_conflict"); + } + var code = refusal?.Code switch { "app_auth_required" => HeimdallMoveRefusal.AppAuthRequired, @@ -135,20 +157,19 @@ public sealed partial class HeimdallIdentityMoveClient( "identity_not_proved" => HeimdallMoveRefusal.IdentityNotProved, "already_moved" => HeimdallMoveRefusal.AlreadyMoved, "provider_conflict" => HeimdallMoveRefusal.ProviderConflict, - "move_id_conflict" => HeimdallMoveRefusal.MoveIdConflict, "identity_not_found" => HeimdallMoveRefusal.IdentityNotFound, _ => HeimdallMoveRefusal.Unrecognized }; return code switch { - HeimdallMoveRefusal.ProofInvalid or HeimdallMoveRefusal.ProofStale => new(code, Side: refusal?.Proof switch + HeimdallMoveRefusal.ProofInvalid or HeimdallMoveRefusal.ProofStale => new HeimdallMoveOutcome.Refused(code, Side: refusal?.Proof switch { "from" => HeimdallProofSide.From, "to" => HeimdallProofSide.To, _ => null }), - HeimdallMoveRefusal.ProviderConflict => new(code, Provider: refusal?.Provider), - _ => new(code) + HeimdallMoveRefusal.ProviderConflict => new HeimdallMoveOutcome.Refused(code, Provider: refusal?.Provider), + _ => new HeimdallMoveOutcome.Refused(code) }; } @@ -158,7 +179,20 @@ public sealed partial class HeimdallIdentityMoveClient( /// private static async Task ReadReceiptAsync(HttpResponseMessage response, HeimdallMoveRequest request, CancellationToken cancellationToken) { - using var document = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(cancellationToken), cancellationToken: cancellationToken); + await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken); + using var buffer = new MemoryStream(); + var chunk = new byte[4096]; + while (await stream.ReadAsync(chunk, cancellationToken) is > 0 and var read) + { + if (buffer.Length + read > MaxReceiptBytes) + { + return null; + } + + buffer.Write(chunk, 0, read); + } + + using var document = JsonDocument.Parse(buffer.ToArray()); var root = document.RootElement; if (root.ValueKind != JsonValueKind.Object || Text(root, "moveId") != request.MoveId @@ -177,7 +211,7 @@ public sealed partial class HeimdallIdentityMoveClient( var ids = new List(); foreach (var item in moved.EnumerateArray()) { - if (item.ValueKind != JsonValueKind.String || !Guid.TryParse(item.GetString(), out _)) + if (item.ValueKind != JsonValueKind.String || item.GetString() is not { Length: > 0 and <= MaxIdentityIdLength }) { return null; } @@ -212,6 +246,8 @@ public sealed partial class HeimdallIdentityMoveClient( private static string? Text(JsonElement item, string name) => item.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; + private static bool IsBadProof(string? proof) => string.IsNullOrEmpty(proof) || proof.Length > MaxProofLength; + /// The contract's closed body, or ArgumentException before any I/O when the request breaks it. private static string Serialize(HeimdallMoveRequest request) { @@ -220,7 +256,7 @@ public sealed partial class HeimdallIdentityMoveClient( throw new ArgumentException("moveId must match ^[A-Za-z0-9_-]{16,64}$", nameof(request)); } - if (request.FromProofs is not { Count: >= 1 and <= 8 } || request.FromProofs.Any(string.IsNullOrWhiteSpace)) + if (request.FromProofs is not { Count: >= 1 and <= 8 } || request.FromProofs.Any(IsBadProof)) { throw new ArgumentException("fromProofs must hold 1 to 8 proofs", nameof(request)); } @@ -230,7 +266,7 @@ public sealed partial class HeimdallIdentityMoveClient( throw new ArgumentException("exactly one of toProof and reversesMoveId is required", nameof(request)); } - if (request.ToProof is not null && string.IsNullOrWhiteSpace(request.ToProof)) + if (request.ToProof is not null && IsBadProof(request.ToProof)) { throw new ArgumentException("toProof is empty", nameof(request)); } @@ -241,9 +277,10 @@ public sealed partial class HeimdallIdentityMoveClient( } if (request.IdentityIds is not null - && (request.ToProof is null || request.IdentityIds.Count is < 1 or > 32 || request.IdentityIds.Any(string.IsNullOrWhiteSpace))) + && (request.ToProof is null || request.IdentityIds.Count is < 1 or > 32 || request.IdentityIds.Any(string.IsNullOrEmpty) + || request.IdentityIds.Distinct().Count() != request.IdentityIds.Count)) { - throw new ArgumentException("identityIds are 1 to 32 and only with toProof", nameof(request)); + throw new ArgumentException("identityIds are 1 to 32 unique ids and only with toProof", nameof(request)); } var body = new Dictionary { ["moveId"] = request.MoveId, ["fromProofs"] = request.FromProofs }; @@ -265,3 +302,19 @@ public sealed partial class HeimdallIdentityMoveClient( return JsonSerializer.Serialize(body); } } + +public static class HeimdallIdentityMoveClientServices +{ + /// + /// The mover's HttpClient: Heimdall's base address and app secret from HeimdallAuthService.ConfigureClient (the one secret path), the + /// call deadline, no redirects (a 3xx must never carry the secret or the proofs to another origin), and the shared header redaction. + /// + public static IHttpClientBuilder AddHeimdallIdentityMoveClient(this IServiceCollection services) => + services.AddHttpClient((serviceProvider, client) => + { + HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value); + client.Timeout = HeimdallIdentityMoveClient.Timeout; + }) + .ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { AllowAutoRedirect = false, PooledConnectionLifetime = TimeSpan.FromMinutes(2) }) + .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader); +} diff --git a/src/Bifrost.Web/Program.cs b/src/Bifrost.Web/Program.cs index 2590f77..38f73cc 100644 --- a/src/Bifrost.Web/Program.cs +++ b/src/Bifrost.Web/Program.cs @@ -158,13 +158,8 @@ builder.Services.AddHttpClient((serviceProvider, client) => builder.Services.AddHttpClient((serviceProvider, client) => HeimdallMemberClient.ConfigureClient(client, serviceProvider.GetRequiredService>().Value)) .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader); -// The mover route is an app-secret call like HeimdallAuthService's: same ConfigureClient, same header redaction. -builder.Services.AddHttpClient((serviceProvider, client) => - { - HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService>().Value); - client.Timeout = HeimdallIdentityMoveClient.Timeout; - }) - .RedactLoggedHeaders(HeimdallAuthService.RedactsHeader); +// The mover route is an app-secret call like HeimdallAuthService's: same ConfigureClient, same header redaction, no redirects. +builder.Services.AddHeimdallIdentityMoveClient(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs b/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs index 8b312ba..8157cd1 100644 --- a/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs +++ b/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs @@ -259,14 +259,16 @@ public sealed class HeimdallIdentityMoveClientTests var (d1, _) = AccountWith(moves, "discord"); Assert.Equal(new Refused(HeimdallMoveRefusal.ProviderConflict, Provider: "discord"), await Move(host, Forward(moves, s1, d1))); - // move_id_conflict: a used id under other accounts + // move_id_conflict is not a refusal: a committed move answers it when its proofs no longer verify, so the caller keeps its proofs. var (s2, _) = AccountWith(moves, "patreon"); var (d2, _) = AccountWith(moves, "twitch"); var used = Forward(moves, s2, d2); Receipt(await Move(host, used)); var (s3, _) = AccountWith(moves, "patreon"); - Assert.Equal(new Refused(HeimdallMoveRefusal.MoveIdConflict), + Assert.Equal(new Unknown("move_id_conflict"), await Move(host, new(used.MoveId, [moves.Issue(s3, stepUpMethod: Passkey)], moves.Issue(d2)))); + Assert.Equal(new Unknown("move_id_conflict"), + await Move(host, new(used.MoveId, ["forged-bearer"], used.ToProof))); // already_moved: s2 now holds nothing and an unreversed move left it Assert.Equal(new Refused(HeimdallMoveRefusal.AlreadyMoved), await Move(host, Forward(moves, s2, d0))); @@ -348,16 +350,82 @@ public sealed class HeimdallIdentityMoveClientTests await Assert.ThrowsAnyAsync(() => ClientOf(host).MoveAsync(request, cancelled.Token)); } - private sealed class Stub(string json) : HttpMessageHandler + private sealed class Stub(Func content, HttpStatusCode status = HttpStatusCode.OK) : HttpMessageHandler { + public Stub(string json, HttpStatusCode status = HttpStatusCode.OK) + : this(() => new StringContent(json, Encoding.UTF8, "application/json"), status) + { + } + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => - Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }); + Task.FromResult(new HttpResponseMessage(status) { Content = content() }); } - private static Task Answered(string json, HeimdallMoveRequest request) => - new HeimdallIdentityMoveClient( - new HttpClient(new Stub(json)) { BaseAddress = new Uri("https://heimdall.test") }, - Options.Create(new HeimdallOptions()), NullLogger.Instance).MoveAsync(request, CancellationToken.None); + /// A body that serves a prefix and then stalls, resets, or streams endless filler. + private sealed class Body(string prefix, bool reset = false, long endless = 0) : Stream + { + private readonly byte[] _prefix = Encoding.UTF8.GetBytes(prefix); + + public long Served { get; private set; } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position { get => Served; set => throw new NotSupportedException(); } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (Served < _prefix.Length) + { + var n = (int)Math.Min(buffer.Length, _prefix.Length - Served); + _prefix.AsMemory((int)Served, n).CopyTo(buffer); + Served += n; + return n; + } + + if (endless > 0 && Served < _prefix.Length + endless) + { + var n = (int)Math.Min(buffer.Length, _prefix.Length + endless - Served); + buffer.Span[..n].Fill((byte)'a'); + Served += n; + return n; + } + + if (reset) + { + throw new IOException("connection reset mid-body"); + } + + await Task.Delay(Timeout.Infinite, cancellationToken); + return 0; + } + } + + private static HeimdallIdentityMoveClient Client(HttpMessageHandler handler, TimeSpan? timeout = null) => + new(new HttpClient(handler) { BaseAddress = new Uri("https://heimdall.test"), Timeout = timeout ?? TimeSpan.FromSeconds(30) }, + Options.Create(new HeimdallOptions()), NullLogger.Instance); + + private static Task Answered(string json, HeimdallMoveRequest request, HttpStatusCode status = HttpStatusCode.OK) => + Client(new Stub(json, status)).MoveAsync(request, CancellationToken.None); + + private static readonly HeimdallMoveRequest Plain = new("move-0123456789abcdef", ["p"], "q"); [Fact] public async Task A_200_that_is_not_a_whole_receipt_for_this_request_is_Unknown() @@ -370,6 +438,7 @@ public sealed class HeimdallIdentityMoveClientTests // The well formed shapes are accepted, so each refusal below is about its one flaw. Assert.IsType(await Answered(Body(), forward)); + Assert.IsType(await Answered(Body(ids: "\"not-a-guid-but-an-id\""), forward)); Assert.IsType(await Answered(Body("move-0123456789abcdef", "move-fedcba9876543210", """{"from":"strong","to":null}"""), reversal)); Assert.IsType(await Answered(Body("move-someoneelse12345"), forward)); @@ -380,7 +449,7 @@ public sealed class HeimdallIdentityMoveClientTests Assert.IsType(await Answered(Body(proof: """{"from":"strong","to":null}"""), forward)); Assert.IsType(await Answered(Body(proof: """{"from":"maybe","to":"weak"}"""), forward)); Assert.IsType(await Answered(Body(ids: ""), forward)); - Assert.IsType(await Answered(Body(ids: "\"not-a-guid\""), forward)); + Assert.IsType(await Answered(Body(ids: "123"), forward)); Assert.IsType(await Answered("""{"moveId":"move-0123456789abcdef"}""", forward)); Assert.IsType(await Answered("[]", forward)); } @@ -417,6 +486,156 @@ public sealed class HeimdallIdentityMoveClientTests Assert.Empty(moves.Requests); } + // ---- the wire: bounds, deadline, redirects, secrets ---- + + [Fact] + public async Task A_body_that_stalls_after_the_headers_is_Unknown_within_the_clients_deadline_for_a_receipt_and_a_refusal() + { + foreach (var (status, prefix) in new[] { (HttpStatusCode.OK, """{"moveId":"move-0123456789abcdef","""), (HttpStatusCode.Conflict, """{"error":"pro""") }) + { + var client = Client(new Stub(() => new StreamContent(new Body(prefix)), status), TimeSpan.FromMilliseconds(500)); + var task = client.MoveAsync(Plain, CancellationToken.None); + Assert.Same(task, await Task.WhenAny(task, Task.Delay(TimeSpan.FromSeconds(10)))); + Assert.IsType(await task); + } + } + + [Fact] + public async Task A_connection_reset_while_reading_the_body_is_Unknown_not_an_exception() + { + var client = Client(new Stub(() => new StreamContent(new Body("""{"moveId":"move-0123456789abcdef",""", reset: true)))); + + Assert.IsType(await client.MoveAsync(Plain, CancellationToken.None)); + } + + [Fact] + public async Task A_receipt_body_past_64_KiB_is_refused_unread_as_Unknown() + { + var body = new Body("""{"moveId":"move-0123456789abcdef","accountId":" """, endless: 64L * 1024 * 1024); + var client = Client(new Stub(() => new StreamContent(body))); + + Assert.IsType(await client.MoveAsync(Plain, CancellationToken.None)); + Assert.True(body.Served < 1024 * 1024, $"read {body.Served} bytes"); + } + + [Fact] + public async Task Refusal_qualifiers_are_kept_only_for_the_codes_that_carry_them() + { + Assert.Equal(new Refused(HeimdallMoveRefusal.SameAccount), + await Answered("""{"error":"same_account","proof":"from","provider":"discord"}""", Plain, HttpStatusCode.Conflict)); + Assert.Equal(new Refused(HeimdallMoveRefusal.AlreadyMoved), + await Answered("""{"error":"already_moved","proof":"to"}""", Plain, HttpStatusCode.Conflict)); + Assert.Equal(new Refused(HeimdallMoveRefusal.ProviderConflict, Provider: "discord"), + await Answered("""{"error":"provider_conflict","proof":"to","provider":"discord"}""", Plain, HttpStatusCode.Conflict)); + Assert.Equal(new Refused(HeimdallMoveRefusal.ProofStale, HeimdallProofSide.To), + await Answered("""{"error":"proof_stale","proof":"to","provider":"discord"}""", Plain, HttpStatusCode.Forbidden)); + Assert.Equal(new Refused(HeimdallMoveRefusal.ProofInvalid), + await Answered("""{"error":"proof_invalid","proof":"sideways"}""", Plain, HttpStatusCode.Forbidden)); + } + + [Fact] + public async Task The_largest_legal_request_is_sent_and_moves_what_it_names() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var source = NewAccount(); + var ids = Enumerable.Range(0, 32).Select(_ => moves.AddLogin(source, "discord")).ToArray(); + var (destination, _) = AccountWith(moves, "twitch"); + var proofs = Enumerable.Range(0, 8).Select(_ => moves.Issue(source, stepUpMethod: Passkey)).ToArray(); + + var receipt = Receipt(await Move(host, new(NewMoveId(), proofs, moves.Issue(destination), ids))); + + Assert.Equal(ids, receipt.MovedIdentityIds); + Assert.Equal(8, JsonDocument.Parse(moves.Requests[0].Body).RootElement.GetProperty("fromProofs").GetArrayLength()); + } + + [Fact] + public void A_request_does_not_print_its_proofs() + { + var request = new HeimdallMoveRequest("move-0123456789abcdef", ["FROM-BEARER-SECRET"], "TO-BEARER-SECRET"); + + Assert.DoesNotContain("BEARER-SECRET", request.ToString()); + Assert.Contains("move-0123456789abcdef", request.ToString()); + } + + private static ServiceProvider RealRegistration(string baseUrl) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddSingleton(Options.Create(new HeimdallOptions { BaseUrl = baseUrl, AppSecret = "APP-SECRET-VALUE" })); + services.AddHeimdallIdentityMoveClient(); + return services.BuildServiceProvider(); + } + + [Fact] + public void The_registered_client_carries_the_app_secret_and_the_15_second_deadline() + { + using var provider = RealRegistration("https://heimdall.test"); + var http = provider.GetRequiredService().CreateClient(nameof(HeimdallIdentityMoveClient)); + + Assert.Equal(TimeSpan.FromSeconds(15), http.Timeout); + Assert.Equal(new Uri("https://heimdall.test"), http.BaseAddress); + Assert.Equal("APP-SECRET-VALUE", Assert.Single(http.DefaultRequestHeaders.GetValues(HeimdallAuthService.AppSecretHeader))); + } + + [Theory] + [InlineData(307)] + [InlineData(302)] + public async Task A_redirect_is_Unknown_and_nothing_reaches_the_other_origin(int code) + { + static int FreePort() + { + var listener = new System.Net.Sockets.TcpListener(IPAddress.Loopback, 0); + listener.Start(); + var port = ((IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + return port; + } + + int first = FreePort(), second = FreePort(); + using var origin = new HttpListener(); + origin.Prefixes.Add($"http://127.0.0.1:{first}/"); + origin.Start(); + using var other = new HttpListener(); + other.Prefixes.Add($"http://127.0.0.1:{second}/"); + other.Start(); + var redirected = Task.Run(async () => + { + var context = await origin.GetContextAsync(); + context.Response.StatusCode = code; + context.Response.RedirectLocation = $"http://127.0.0.1:{second}/steal"; + context.Response.Close(); + }); + var stolen = new List(); + _ = Task.Run(async () => + { + try + { + var context = await other.GetContextAsync(); + stolen.Add(context.Request.Headers["x-heimdall-app-secret"] + new StreamReader(context.Request.InputStream).ReadToEnd()); + var forged = Encoding.UTF8.GetBytes($$$"""{"moveId":"move-0123456789abcdef","accountId":"attacker","movedIdentityIds":["{{{Guid.NewGuid()}}}"],"proof":{"from":"weak","to":"weak"}}"""); + context.Response.StatusCode = 200; + await context.Response.OutputStream.WriteAsync(forged); + context.Response.Close(); + } + catch (HttpListenerException) + { + } + catch (ObjectDisposedException) + { + } + }); + using var provider = RealRegistration($"http://127.0.0.1:{first}"); + + var outcome = await provider.GetRequiredService() + .MoveAsync(new("move-0123456789abcdef", ["FROM-BEARER"], "TO-BEARER"), CancellationToken.None); + await redirected; + await Task.Delay(300); + + Assert.IsType(outcome); + Assert.Empty(stolen); + } + // ---- what the logs hold ---- [Fact] @@ -434,6 +653,8 @@ public sealed class HeimdallIdentityMoveClientTests Assert.Contains("Heimdall identity move: Moved", logs); Assert.Contains("Heimdall identity move: Refused", logs); Assert.Contains("identity-moves", logs); + // Only the secret and bearer headers are redacted: an ordinary header's value is logged, so the shared redaction is what is in force. + Assert.Contains("application/json", logs); foreach (var secret in new[] { HeimdallHost.AppSecret, source, destination, request.FromProofs[0], request.ToProof!, request.MoveId }.Concat(ids)) { Assert.DoesNotContain(secret, logs); From 1ffb8886c07074305a9cd143bd82e61a51189bc4 Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sat, 14 Nov 2026 03:50:42 +0000 Subject: [PATCH 5/6] Move client: Refused only for Heimdall's coded move refusals, any pipeline exception is Unknown, ids end at \z An uncoded 4xx (gateway 404, 408, 410, unknown code) is Unknown: Refused wipes sealed proofs. Unrecognized leaves the refusal enum. The catch lists no types: only the caller's cancellation propagates. moveId and reversesMoveId patterns use \z in client and fake, so a trailing line feed is refused as Heimdall's ajv refuses it; 64, 65 and newline are pinned. Co-Authored-By: Claude Sonnet 5.5 --- .../Heimdall/HeimdallIdentityMoveClient.cs | 44 +++++++---- .../FakeHeimdallMoverTests.cs | 3 + .../HeimdallIdentityMoveClientTests.cs | 75 ++++++++++++++++--- tests/Bifrost.Web.Tests/Support/FakeMoves.cs | 2 +- 4 files changed, 98 insertions(+), 26 deletions(-) diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs index 94b7853..e485b37 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs @@ -33,7 +33,7 @@ public enum HeimdallProofTier public sealed record HeimdallMoveReceipt( string MoveId, string AccountId, IReadOnlyList MovedIdentityIds, HeimdallProofTier ProofFrom, HeimdallProofTier? ProofTo, string? ReversesMoveId); -/// Heimdall's fixed refusal codes for a move, plus the two local classes: a 400, and a 4xx this client does not know. +/// Heimdall's fixed refusal codes for a move, plus the one local class: Heimdall's schema 400. public enum HeimdallMoveRefusal { AppAuthRequired, @@ -46,8 +46,7 @@ public enum HeimdallMoveRefusal AlreadyMoved, ProviderConflict, IdentityNotFound, - RequestInvalid, - Unrecognized + RequestInvalid } public enum HeimdallProofSide @@ -90,7 +89,8 @@ public sealed partial class HeimdallIdentityMoveClient( private const int MaxReceiptBytes = 64 * 1024; private const int MaxProofLength = 8192; - [GeneratedRegex("^[A-Za-z0-9_-]{16,64}$")] + // \z, not $: $ also matches before a final line feed, which Heimdall's schema pattern refuses with a 400. + [GeneratedRegex("^[A-Za-z0-9_-]{16,64}\\z")] private static partial Regex MoveIdShape(); public async Task MoveAsync(HeimdallMoveRequest request, CancellationToken cancellationToken) @@ -128,19 +128,28 @@ public sealed partial class HeimdallIdentityMoveClient( return new HeimdallMoveOutcome.Unknown($"HTTP {status}"); } - var refusal = await HeimdallRefusal.ReadAsync(response, token); - return status == 400 ? new HeimdallMoveOutcome.Refused(HeimdallMoveRefusal.RequestInvalid) : Refused(refusal); + // Fastify's schema 400 answers before the route runs, so it carries no Heimdall code and applied nothing. + if (status == 400) + { + return new HeimdallMoveOutcome.Refused(HeimdallMoveRefusal.RequestInvalid); + } + + return Refused(await HeimdallRefusal.ReadAsync(response, token), status); } - catch (Exception error) when (error is HttpRequestException or IOException or JsonException or NotSupportedException or OperationCanceledException - && !cancellationToken.IsCancellationRequested) + catch (Exception) when (!cancellationToken.IsCancellationRequested) { + // Whatever the pipeline throws after the request may have gone out is not a refusal; only the caller's own cancellation propagates. return new HeimdallMoveOutcome.Unknown("transport"); } } - private static HeimdallMoveOutcome Refused(HeimdallRefusalBody? refusal) + /// + /// Refused only for the coded refusals Heimdall's move route emits (4fe367a moveIdentitiesRoute). A 4xx without one of those codes + /// (a gateway's HTML 404, a 408, a code a later Heimdall adds) proves nothing was applied, so it is Unknown. move_id_conflict is + /// Unknown too: a committed move answers it when its proofs no longer verify. + /// + private static HeimdallMoveOutcome Refused(HeimdallRefusalBody? refusal, int status) { - // Not a refusal: a committed move answers 409 move_id_conflict when its proofs no longer verify, so it proves nothing about the move. if (refusal?.Code == "move_id_conflict") { return new HeimdallMoveOutcome.Unknown("move_id_conflict"); @@ -158,18 +167,23 @@ public sealed partial class HeimdallIdentityMoveClient( "already_moved" => HeimdallMoveRefusal.AlreadyMoved, "provider_conflict" => HeimdallMoveRefusal.ProviderConflict, "identity_not_found" => HeimdallMoveRefusal.IdentityNotFound, - _ => HeimdallMoveRefusal.Unrecognized + _ => (HeimdallMoveRefusal?)null }; - return code switch + if (code is not { } known) { - HeimdallMoveRefusal.ProofInvalid or HeimdallMoveRefusal.ProofStale => new HeimdallMoveOutcome.Refused(code, Side: refusal?.Proof switch + return new HeimdallMoveOutcome.Unknown($"HTTP {status} without a Heimdall refusal code"); + } + + return known switch + { + HeimdallMoveRefusal.ProofInvalid or HeimdallMoveRefusal.ProofStale => new HeimdallMoveOutcome.Refused(known, Side: refusal?.Proof switch { "from" => HeimdallProofSide.From, "to" => HeimdallProofSide.To, _ => null }), - HeimdallMoveRefusal.ProviderConflict => new HeimdallMoveOutcome.Refused(code, Provider: refusal?.Provider), - _ => new HeimdallMoveOutcome.Refused(code) + HeimdallMoveRefusal.ProviderConflict => new HeimdallMoveOutcome.Refused(known, Provider: refusal?.Provider), + _ => new HeimdallMoveOutcome.Refused(known) }; } diff --git a/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs b/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs index b1311a5..b49c8be 100644 --- a/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs +++ b/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs @@ -63,6 +63,9 @@ public sealed class FakeHeimdallMoverTests Move(Id(), Enumerable.Repeat("p", 9).ToArray(), "x"), Move(Id(), [new string('p', 8193)], "x"), Move("short", [strong()], "x"), + Move(Id() + "\n", [strong()], "x"), + Move(new string('a', 65), [strong()], "x"), + Move(Id(), [strong()], reverses: Id() + "\n"), """{"moveId":"move-0123456789abcdef","fromProofs":"p","toProof":"x"}""", "[]" }; diff --git a/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs b/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs index 8157cd1..8055c6d 100644 --- a/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs +++ b/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs @@ -292,23 +292,70 @@ public sealed class HeimdallIdentityMoveClientTests } [Fact] - public async Task A_missing_route_is_Unrecognized_and_a_400_is_RequestInvalid_both_definitive_refusals() + public async Task A_400_is_RequestInvalid_a_definitive_refusal_that_moves_nothing() { using var host = new HeimdallHost(); var moves = host.Heimdall.Moves; var (source, _) = AccountWith(moves, "discord"); var (destination, _) = AccountWith(moves, "twitch"); - var request = Forward(moves, source, destination); - - moves.MoveStatus = HttpStatusCode.NotFound; - Assert.Equal(new Refused(HeimdallMoveRefusal.Unrecognized), await Move(host, request)); moves.MoveStatus = HttpStatusCode.BadRequest; - Assert.Equal(new Refused(HeimdallMoveRefusal.RequestInvalid), await Move(host, request)); - moves.MoveStatus = (HttpStatusCode)418; - Assert.Equal(new Refused(HeimdallMoveRefusal.Unrecognized), await Move(host, request)); + + Assert.Equal(new Refused(HeimdallMoveRefusal.RequestInvalid), await Move(host, Forward(moves, source, destination))); Assert.Empty(moves.Stored); } + [Theory] + [InlineData(HttpStatusCode.NotFound, "404 Not Found")] + [InlineData(HttpStatusCode.NotFound, "")] + [InlineData(HttpStatusCode.RequestTimeout, "")] + [InlineData(HttpStatusCode.RequestTimeout, """{"error":"request_timeout"}""")] + [InlineData(HttpStatusCode.Gone, "")] + [InlineData(HttpStatusCode.UnavailableForLegalReasons, "")] + [InlineData(HttpStatusCode.Unauthorized, """{"error":"weird_code"}""")] + [InlineData(HttpStatusCode.Forbidden, """{"message":"no error field"}""")] + [InlineData((HttpStatusCode)418, """{"error":"app_auth_required_sort_of"}""")] + public async Task A_4xx_without_one_of_Heimdalls_move_codes_is_Unknown_because_it_proves_nothing_was_applied_no_more_than_a_gateway_does( + HttpStatusCode status, string body) + { + Assert.IsType(await Answered(body, Plain, status)); + } + + [Fact] + public async Task A_404_with_no_body_from_the_route_is_Unknown_not_identity_not_found() + { + using var host = new HeimdallHost(); + var moves = host.Heimdall.Moves; + var (source, _) = AccountWith(moves, "discord"); + var (destination, _) = AccountWith(moves, "twitch"); + moves.MoveStatus = HttpStatusCode.NotFound; + + Assert.IsType(await Move(host, Forward(moves, source, destination))); + } + + [Fact] + public async Task An_exception_of_any_kind_from_the_pipeline_is_Unknown_and_only_the_callers_cancellation_propagates() + { + Exception[] thrown = + [ + new InvalidOperationException("handler"), new ObjectDisposedException("connection"), + new System.Security.Authentication.AuthenticationException("tls"), new InvalidDataException("zip"), new UriFormatException("uri"), + new HttpRequestException("down"), new IOException("reset"), new TaskCanceledException("deadline") + ]; + foreach (var error in thrown) + { + var client = new HeimdallIdentityMoveClient( + new HttpClient(new Throwing(error)) { BaseAddress = new Uri("https://heimdall.test") }, + Options.Create(new HeimdallOptions()), NullLogger.Instance); + + Assert.IsType(await client.MoveAsync(Plain, CancellationToken.None)); + } + } + + private sealed class Throwing(Exception error) : HttpMessageHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => throw error; + } + // ---- unknown outcomes ---- [Theory] @@ -475,7 +522,13 @@ public sealed class HeimdallIdentityMoveClientTests new(good, proofs, IdentityIds: ["i"], ReversesMoveId: NewMoveId()), new(good, proofs, "t", []), new(good, proofs, "t", Enumerable.Repeat("i", 33).ToArray()), - new(good, [""], "t") + new(good, [""], "t"), + new(good + "\n", proofs, "t"), + new(good, proofs, ReversesMoveId: good + "\n"), + new("move-0123456789abcdef\n", proofs, "t"), + new(new string('a', 65), proofs, "t"), + new(new string('a', 15), proofs, "t"), + new(good, proofs, ReversesMoveId: new string('a', 65)) }; foreach (var request in broken) @@ -543,7 +596,9 @@ public sealed class HeimdallIdentityMoveClientTests var (destination, _) = AccountWith(moves, "twitch"); var proofs = Enumerable.Range(0, 8).Select(_ => moves.Issue(source, stepUpMethod: Passkey)).ToArray(); - var receipt = Receipt(await Move(host, new(NewMoveId(), proofs, moves.Issue(destination), ids))); + var longest = new string('m', 64); + var receipt = Receipt(await Move(host, new(longest, proofs, moves.Issue(destination), ids))); + Assert.Equal(longest, receipt.MoveId); Assert.Equal(ids, receipt.MovedIdentityIds); Assert.Equal(8, JsonDocument.Parse(moves.Requests[0].Body).RootElement.GetProperty("fromProofs").GetArrayLength()); diff --git a/tests/Bifrost.Web.Tests/Support/FakeMoves.cs b/tests/Bifrost.Web.Tests/Support/FakeMoves.cs index e1df159..ef3eb35 100644 --- a/tests/Bifrost.Web.Tests/Support/FakeMoves.cs +++ b/tests/Bifrost.Web.Tests/Support/FakeMoves.cs @@ -135,7 +135,7 @@ public sealed class FakeMoves(Func now) private sealed record Move(string MoveId, string[] FromProofs, string? ToProof, string[]? IdentityIds, string? ReversesMoveId); - private static readonly System.Text.RegularExpressions.Regex MoveIdShape = new("^[A-Za-z0-9_-]{16,64}$"); + private static readonly System.Text.RegularExpressions.Regex MoveIdShape = new(@"^[A-Za-z0-9_-]{16,64}\z"); /// /// Heimdall's route schema (app.ts, the identity-moves route): moveId pattern, 1 to 8 fromProofs of 1 to 8192 chars, toProof, 1 to 32 From b7b33bc5db1f104488f966f7b4d8308dd1e9990d Mon Sep 17 00:00:00 2001 From: Heimdall Date: Sat, 14 Nov 2026 04:14:38 +0000 Subject: [PATCH 6/6] Move client: a 400 is RequestInvalid only with Heimdall's invalid_request body An nginx HTML 400, an empty 400 or any other 400 is Unknown. The fake answers its schema 400 with Heimdall's error handler body. Co-Authored-By: Claude Sonnet 5.5 --- .../Features/Heimdall/HeimdallIdentityMoveClient.cs | 12 ++++-------- tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs | 2 +- .../HeimdallIdentityMoveClientTests.cs | 7 ++++++- tests/Bifrost.Web.Tests/Support/FakeMoves.cs | 4 ++-- 4 files changed, 13 insertions(+), 12 deletions(-) diff --git a/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs index e485b37..f285ae2 100644 --- a/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs +++ b/src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs @@ -33,7 +33,7 @@ public enum HeimdallProofTier public sealed record HeimdallMoveReceipt( string MoveId, string AccountId, IReadOnlyList MovedIdentityIds, HeimdallProofTier ProofFrom, HeimdallProofTier? ProofTo, string? ReversesMoveId); -/// Heimdall's fixed refusal codes for a move, plus the one local class: Heimdall's schema 400. +/// Heimdall's fixed refusal codes for a move, plus invalid_request, Heimdall's own schema 400. public enum HeimdallMoveRefusal { AppAuthRequired, @@ -128,12 +128,6 @@ public sealed partial class HeimdallIdentityMoveClient( return new HeimdallMoveOutcome.Unknown($"HTTP {status}"); } - // Fastify's schema 400 answers before the route runs, so it carries no Heimdall code and applied nothing. - if (status == 400) - { - return new HeimdallMoveOutcome.Refused(HeimdallMoveRefusal.RequestInvalid); - } - return Refused(await HeimdallRefusal.ReadAsync(response, token), status); } catch (Exception) when (!cancellationToken.IsCancellationRequested) @@ -144,7 +138,7 @@ public sealed partial class HeimdallIdentityMoveClient( } /// - /// Refused only for the coded refusals Heimdall's move route emits (4fe367a moveIdentitiesRoute). A 4xx without one of those codes + /// Refused only for the coded refusals Heimdall's move route emits (4fe367a moveIdentitiesRoute, and its error handler's invalid_request 400). A 4xx without one of those codes /// (a gateway's HTML 404, a 408, a code a later Heimdall adds) proves nothing was applied, so it is Unknown. move_id_conflict is /// Unknown too: a committed move answers it when its proofs no longer verify. /// @@ -167,6 +161,8 @@ public sealed partial class HeimdallIdentityMoveClient( "already_moved" => HeimdallMoveRefusal.AlreadyMoved, "provider_conflict" => HeimdallMoveRefusal.ProviderConflict, "identity_not_found" => HeimdallMoveRefusal.IdentityNotFound, + // Heimdall's error handler gives its own 400 this code; an nginx or other edge 400 has none, so it is not Heimdall's refusal. + "invalid_request" when status == 400 => HeimdallMoveRefusal.RequestInvalid, _ => (HeimdallMoveRefusal?)null }; if (code is not { } known) diff --git a/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs b/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs index b49c8be..c856c8f 100644 --- a/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs +++ b/tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs @@ -71,7 +71,7 @@ public sealed class FakeHeimdallMoverTests }; foreach (var json in bad) { - Assert.Equal(HttpStatusCode.BadRequest, (await Post(host, json)).Status); + Assert.Equal((HttpStatusCode.BadRequest, "invalid_request"), await Post(host, json)); } Assert.Single(moves.Stored); diff --git a/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs b/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs index 8055c6d..a2cc873 100644 --- a/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs +++ b/tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs @@ -292,7 +292,7 @@ public sealed class HeimdallIdentityMoveClientTests } [Fact] - public async Task A_400_is_RequestInvalid_a_definitive_refusal_that_moves_nothing() + public async Task A_400_carrying_Heimdalls_invalid_request_code_is_RequestInvalid_a_definitive_refusal_that_moves_nothing() { using var host = new HeimdallHost(); var moves = host.Heimdall.Moves; @@ -307,6 +307,11 @@ public sealed class HeimdallIdentityMoveClientTests [Theory] [InlineData(HttpStatusCode.NotFound, "404 Not Found")] [InlineData(HttpStatusCode.NotFound, "")] + [InlineData(HttpStatusCode.BadRequest, "400 Bad Requestnginx")] + [InlineData(HttpStatusCode.BadRequest, "")] + [InlineData(HttpStatusCode.BadRequest, """{"statusCode":400,"error":"Bad Request","message":"x"}""")] + [InlineData(HttpStatusCode.BadRequest, """{"message":"no error field"}""")] + [InlineData(HttpStatusCode.Conflict, """{"error":"invalid_request"}""")] [InlineData(HttpStatusCode.RequestTimeout, "")] [InlineData(HttpStatusCode.RequestTimeout, """{"error":"request_timeout"}""")] [InlineData(HttpStatusCode.Gone, "")] diff --git a/tests/Bifrost.Web.Tests/Support/FakeMoves.cs b/tests/Bifrost.Web.Tests/Support/FakeMoves.cs index ef3eb35..1a87171 100644 --- a/tests/Bifrost.Web.Tests/Support/FakeMoves.cs +++ b/tests/Bifrost.Web.Tests/Support/FakeMoves.cs @@ -102,7 +102,7 @@ public sealed class FakeMoves(Func now) if (Parse(body) is not { } move) { - return Json(HttpStatusCode.BadRequest, """{"statusCode":400,"error":"Bad Request","message":"body does not match the schema"}"""); + return Json(HttpStatusCode.BadRequest, """{"error":"invalid_request","detail":"body: must match the schema"}"""); } if (MoveStatus is { } forced) @@ -110,7 +110,7 @@ public sealed class FakeMoves(Func now) return forced == HttpStatusCode.NotFound ? new HttpResponseMessage(forced) : Json(forced, forced == HttpStatusCode.BadRequest - ? """{"statusCode":400,"error":"Bad Request"}""" + ? """{"error":"invalid_request","detail":"body: must match the schema"}""" : """{"error":"server_error","detail":"HEIMDALL FREE TEXT"}"""); }