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 <noreply@anthropic.com>
This commit is contained in:
parent
b54cf27101
commit
fbb5853b1d
3 changed files with 757 additions and 0 deletions
442
tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs
Normal file
442
tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<HeimdallIdentityMoveClient>();
|
||||
|
||||
private static Task<HeimdallMoveOutcome> Move(HeimdallHost host, HeimdallMoveRequest request) =>
|
||||
ClientOf(host).MoveAsync(request, CancellationToken.None);
|
||||
|
||||
private static HeimdallMoveReceipt Receipt(HeimdallMoveOutcome outcome) => Assert.IsType<Moved>(outcome).Receipt;
|
||||
|
||||
/// <summary>An account holding these providers, one login each, in order.</summary>
|
||||
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());
|
||||
}
|
||||
|
||||
/// <summary>The usual forward move of everything: a passkey proof of the source and a weak proof of the destination.</summary>
|
||||
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<Unknown>(await Move(host, request));
|
||||
Assert.Single(moves.Stored);
|
||||
moves.MoveApplyThenFail = HttpStatusCode.OK;
|
||||
Assert.IsType<Unknown>(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<Unknown>(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<Unknown>(await Move(host, request));
|
||||
moves.MoveDown = new HttpRequestException("Heimdall is down");
|
||||
Assert.IsType<Unknown>(await Move(host, request));
|
||||
moves.MoveDown = null;
|
||||
moves.MoveApplyThenFail = HttpStatusCode.OK;
|
||||
Assert.IsType<Unknown>(await Move(host, request));
|
||||
moves.MoveApplyThenFail = null;
|
||||
|
||||
using var cancelled = new CancellationTokenSource();
|
||||
await cancelled.CancelAsync();
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => ClientOf(host).MoveAsync(request, cancelled.Token));
|
||||
}
|
||||
|
||||
private sealed class Stub(string json) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") });
|
||||
}
|
||||
|
||||
private static Task<HeimdallMoveOutcome> Answered(string json, HeimdallMoveRequest request) =>
|
||||
new HeimdallIdentityMoveClient(
|
||||
new HttpClient(new Stub(json)) { BaseAddress = new Uri("https://heimdall.test") },
|
||||
Options.Create(new HeimdallOptions()), NullLogger<HeimdallIdentityMoveClient>.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<Moved>(await Answered(Body(), forward));
|
||||
Assert.IsType<Moved>(await Answered(Body("move-0123456789abcdef", "move-fedcba9876543210", """{"from":"strong","to":null}"""), reversal));
|
||||
|
||||
Assert.IsType<Unknown>(await Answered(Body("move-someoneelse12345"), forward));
|
||||
Assert.IsType<Unknown>(await Answered(Body(reverses: "move-fedcba9876543210"), forward));
|
||||
Assert.IsType<Unknown>(await Answered(Body(), reversal));
|
||||
Assert.IsType<Unknown>(await Answered(Body("move-0123456789abcdef", "move-other0123456789", """{"from":"strong","to":null}"""), reversal));
|
||||
Assert.IsType<Unknown>(await Answered(Body("move-0123456789abcdef", "move-fedcba9876543210", """{"from":"strong","to":"weak"}"""), reversal));
|
||||
Assert.IsType<Unknown>(await Answered(Body(proof: """{"from":"strong","to":null}"""), forward));
|
||||
Assert.IsType<Unknown>(await Answered(Body(proof: """{"from":"maybe","to":"weak"}"""), forward));
|
||||
Assert.IsType<Unknown>(await Answered(Body(ids: ""), forward));
|
||||
Assert.IsType<Unknown>(await Answered(Body(ids: "\"not-a-guid\""), forward));
|
||||
Assert.IsType<Unknown>(await Answered("""{"moveId":"move-0123456789abcdef"}""", forward));
|
||||
Assert.IsType<Unknown>(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<ArgumentException>(() => 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<Refused>(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);
|
||||
}
|
||||
}
|
||||
}
|
||||
304
tests/Bifrost.Web.Tests/Support/FakeMoves.cs
Normal file
304
tests/Bifrost.Web.Tests/Support/FakeMoves.cs
Normal file
|
|
@ -0,0 +1,304 @@
|
|||
using System.Net;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Bifrost.Web.Tests.Support;
|
||||
|
||||
/// <summary>One login of a fake account.</summary>
|
||||
public sealed record MoveLogin(string Id, string Provider);
|
||||
|
||||
/// <summary>A move Heimdall stored: the forward move or its reversal, with the receipt it answered byte for byte.</summary>
|
||||
public sealed class StoredMove(string moveId, string from, string to, string? reversesMoveId, IReadOnlyList<string> 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<string> Carried { get; } = carried;
|
||||
|
||||
public string Receipt { get; } = receipt;
|
||||
|
||||
public bool Reversed { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="Logins"/> later so one model answers both routes.
|
||||
/// </summary>
|
||||
public sealed class FakeMoves(Func<DateTimeOffset> 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<string, Claims> _tokens = new(StringComparer.Ordinal);
|
||||
private readonly HashSet<string> _revoked = new(StringComparer.Ordinal);
|
||||
private readonly Dictionary<string, StoredMove> _moves = new(StringComparer.Ordinal);
|
||||
|
||||
public Dictionary<string, List<MoveLogin>> Logins { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public IReadOnlyCollection<StoredMove> Stored => _moves.Values;
|
||||
|
||||
/// <summary>Every request that reached the route: the app secret header, the Authorization header and the raw body.</summary>
|
||||
public List<(string? Secret, string? Authorization, string Body)> Requests { get; } = [];
|
||||
|
||||
/// <summary>When false the app's profile lacks identityMoves, so the route answers 403 not_allowed_for_app.</summary>
|
||||
public bool Granted { get; set; } = true;
|
||||
|
||||
/// <summary>When set, the route answers this status after the schema check, bypassing the fake's own rules (nothing is applied).</summary>
|
||||
public HttpStatusCode? MoveStatus { get; set; }
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public HttpStatusCode? MoveApplyThenFail { get; set; }
|
||||
|
||||
/// <summary>When set, the route throws it instead of answering, as an unreachable or timed-out Heimdall does.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Issues a live bearer of <paramref name="account"/> for the bifrost app. A weak proof is a sign-in through <paramref name="authIdentityId"/>
|
||||
/// at <paramref name="authAgo"/> before now; a step-up (<paramref name="stepUpMethod"/>) adds step_up_at at <paramref name="stepUpAgo"/> before now.
|
||||
/// </summary>
|
||||
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<string, object?>
|
||||
{
|
||||
["moveId"] = move.MoveId,
|
||||
["accountId"] = destination,
|
||||
["movedIdentityIds"] = moving.Select(x => x.Id).ToArray(),
|
||||
["proof"] = new Dictionary<string, object?> { ["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<string, object?> { ["error"] = error, ["proof"] = proof, ["provider"] = provider }
|
||||
.Where(x => x.Value is not null).ToDictionary()));
|
||||
}
|
||||
|
|
@ -200,6 +200,11 @@ public sealed class FakeHeimdall : HttpMessageHandler
|
|||
|
||||
public Exception? JwksFailure { get; set; }
|
||||
|
||||
/// <summary>The account model and route of POST /v1/apps/bifrost/identity-moves (the host's clock is <see cref="Now"/>).</summary>
|
||||
public FakeMoves Moves { get; }
|
||||
|
||||
public FakeHeimdall() => Moves = new FakeMoves(() => Now());
|
||||
|
||||
public List<string> StartBodies { get; } = [];
|
||||
|
||||
public List<string?> 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<HeimdallAuthService>().ConfigurePrimaryHttpMessageHandler(() => Heimdall);
|
||||
services.AddHttpClient<HeimdallMemberClient>().ConfigurePrimaryHttpMessageHandler(() => Heimdall);
|
||||
services.AddHttpClient<HeimdallIdentityMoveClient>().ConfigurePrimaryHttpMessageHandler(() => Heimdall);
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue