Merge mover client (heimdall/account-merge-mover-client b7b33bc) into account merge ledger
This commit is contained in:
commit
41189e14d3
7 changed files with 1629 additions and 7 deletions
330
src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs
Normal file
330
src/Bifrost.Web/Features/Heimdall/HeimdallIdentityMoveClient.cs
Normal file
|
|
@ -0,0 +1,330 @@
|
|||
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;
|
||||
|
||||
/// <summary>
|
||||
/// What Bifrost asks Heimdall to move (docs/service-contract.md, POST /v1/apps/{app}/identity-moves). Exactly one of
|
||||
/// <see cref="ToProof"/> (a forward move, optionally of <see cref="IdentityIds"/>) and <see cref="ReversesMoveId"/> (the undo). The body
|
||||
/// never names an account: the proofs, live Heimdall access tokens, say which accounts are meant.
|
||||
/// </summary>
|
||||
public sealed record HeimdallMoveRequest(
|
||||
string MoveId, IReadOnlyList<string> FromProofs, string? ToProof = null, IReadOnlyList<string>? 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
|
||||
{
|
||||
Strong,
|
||||
Weak
|
||||
}
|
||||
|
||||
/// <summary>The receipt of a move: the destination account, the logins that moved and the tier of the proofs that carried it.</summary>
|
||||
public sealed record HeimdallMoveReceipt(
|
||||
string MoveId, string AccountId, IReadOnlyList<string> MovedIdentityIds, HeimdallProofTier ProofFrom, HeimdallProofTier? ProofTo, string? ReversesMoveId);
|
||||
|
||||
/// <summary>Heimdall's fixed refusal codes for a move, plus invalid_request, Heimdall's own schema 400.</summary>
|
||||
public enum HeimdallMoveRefusal
|
||||
{
|
||||
AppAuthRequired,
|
||||
NotAllowedForApp,
|
||||
NotReversible,
|
||||
ProofInvalid,
|
||||
SameAccount,
|
||||
ProofStale,
|
||||
IdentityNotProved,
|
||||
AlreadyMoved,
|
||||
ProviderConflict,
|
||||
IdentityNotFound,
|
||||
RequestInvalid
|
||||
}
|
||||
|
||||
public enum HeimdallProofSide
|
||||
{
|
||||
From,
|
||||
To
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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, 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <see cref="HeimdallMoveRequest.MoveId"/> is the caller's, and Heimdall answers it with the stored
|
||||
/// receipt. Logs name the outcome class and refusal code only.
|
||||
/// </summary>
|
||||
public sealed partial class HeimdallIdentityMoveClient(
|
||||
HttpClient httpClient, IOptions<HeimdallOptions> heimdallOptions, ILogger<HeimdallIdentityMoveClient> logger)
|
||||
{
|
||||
/// <summary>The deadline of one call, headers and body together, set on the HttpClient by <see cref="HeimdallIdentityMoveClientServices"/>.</summary>
|
||||
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;
|
||||
|
||||
// \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<HeimdallMoveOutcome> 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<HeimdallMoveOutcome> 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(
|
||||
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, token);
|
||||
var status = (int)response.StatusCode;
|
||||
if (response.StatusCode == HttpStatusCode.OK)
|
||||
{
|
||||
return await ReadReceiptAsync(response, request, token) 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}");
|
||||
}
|
||||
|
||||
return Refused(await HeimdallRefusal.ReadAsync(response, token), status);
|
||||
}
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static HeimdallMoveOutcome Refused(HeimdallRefusalBody? refusal, int status)
|
||||
{
|
||||
if (refusal?.Code == "move_id_conflict")
|
||||
{
|
||||
return new HeimdallMoveOutcome.Unknown("move_id_conflict");
|
||||
}
|
||||
|
||||
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,
|
||||
"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)
|
||||
{
|
||||
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(known, Provider: refusal?.Provider),
|
||||
_ => new HeimdallMoveOutcome.Refused(known)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static async Task<HeimdallMoveReceipt?> ReadReceiptAsync(HttpResponseMessage response, HeimdallMoveRequest request, 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
|
||||
|| 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<string>();
|
||||
foreach (var item in moved.EnumerateArray())
|
||||
{
|
||||
if (item.ValueKind != JsonValueKind.String || item.GetString() is not { Length: > 0 and <= MaxIdentityIdLength })
|
||||
{
|
||||
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;
|
||||
|
||||
private static bool IsBadProof(string? proof) => string.IsNullOrEmpty(proof) || proof.Length > MaxProofLength;
|
||||
|
||||
/// <summary>The contract's closed body, or ArgumentException before any I/O when the request breaks it.</summary>
|
||||
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(IsBadProof))
|
||||
{
|
||||
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 && IsBadProof(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.IsNullOrEmpty)
|
||||
|| request.IdentityIds.Distinct().Count() != request.IdentityIds.Count))
|
||||
{
|
||||
throw new ArgumentException("identityIds are 1 to 32 unique ids and only with toProof", nameof(request));
|
||||
}
|
||||
|
||||
var body = new Dictionary<string, object?> { ["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);
|
||||
}
|
||||
}
|
||||
|
||||
public static class HeimdallIdentityMoveClientServices
|
||||
{
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static IHttpClientBuilder AddHeimdallIdentityMoveClient(this IServiceCollection services) =>
|
||||
services.AddHttpClient<HeimdallIdentityMoveClient>((serviceProvider, client) =>
|
||||
{
|
||||
HeimdallAuthService.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value);
|
||||
client.Timeout = HeimdallIdentityMoveClient.Timeout;
|
||||
})
|
||||
.ConfigurePrimaryHttpMessageHandler(() => new SocketsHttpHandler { AllowAutoRedirect = false, PooledConnectionLifetime = TimeSpan.FromMinutes(2) })
|
||||
.RedactLoggedHeaders(HeimdallAuthService.RedactsHeader);
|
||||
}
|
||||
|
|
@ -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.
|
||||
/// </summary>
|
||||
public static async Task<string?> CodeAsync(HttpResponseMessage response, CancellationToken cancellationToken)
|
||||
public static async Task<string?> CodeAsync(HttpResponseMessage response, CancellationToken cancellationToken) =>
|
||||
(await ReadAsync(response, cancellationToken))?.Code;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static async Task<HeimdallRefusalBody?> 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;
|
||||
}
|
||||
|
||||
/// <summary>A Heimdall refusal's safe fields: the code, the proof side ("from"/"to") and the provider, when present and well formed.</summary>
|
||||
public sealed record HeimdallRefusalBody(string Code, string? Proof, string? Provider);
|
||||
|
|
|
|||
|
|
@ -160,6 +160,8 @@ builder.Services.AddHttpClient<HeimdallAuthService>((serviceProvider, client) =>
|
|||
builder.Services.AddHttpClient<HeimdallMemberClient>((serviceProvider, client) =>
|
||||
HeimdallMemberClient.ConfigureClient(client, serviceProvider.GetRequiredService<IOptions<HeimdallOptions>>().Value))
|
||||
.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<LinkedAccountsSnapshots>();
|
||||
builder.Services.AddSingleton<Bifrost.Web.Features.Passkeys.PasskeyRelyingParty>();
|
||||
builder.Services.AddSingleton<Bifrost.Web.Features.Passkeys.PasskeyCeremonies>();
|
||||
|
|
|
|||
168
tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs
Normal file
168
tests/Bifrost.Web.Tests/FakeHeimdallMoverTests.cs
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
using System.Net;
|
||||
using System.Text;
|
||||
using Bifrost.Web.Tests.Support;
|
||||
|
||||
namespace Bifrost.Web.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<string, object?>
|
||||
{
|
||||
["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"),
|
||||
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"}""",
|
||||
"[]"
|
||||
};
|
||||
foreach (var json in bad)
|
||||
{
|
||||
Assert.Equal((HttpStatusCode.BadRequest, "invalid_request"), await Post(host, json));
|
||||
}
|
||||
|
||||
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)));
|
||||
}
|
||||
}
|
||||
723
tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs
Normal file
723
tests/Bifrost.Web.Tests/HeimdallIdentityMoveClientTests.cs
Normal file
|
|
@ -0,0 +1,723 @@
|
|||
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 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 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)));
|
||||
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_400_carrying_Heimdalls_invalid_request_code_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");
|
||||
moves.MoveStatus = HttpStatusCode.BadRequest;
|
||||
|
||||
Assert.Equal(new Refused(HeimdallMoveRefusal.RequestInvalid), await Move(host, Forward(moves, source, destination)));
|
||||
Assert.Empty(moves.Stored);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(HttpStatusCode.NotFound, "<html><body>404 Not Found</body></html>")]
|
||||
[InlineData(HttpStatusCode.NotFound, "")]
|
||||
[InlineData(HttpStatusCode.BadRequest, "<html><head><title>400 Bad Request</title></head><body>nginx</body></html>")]
|
||||
[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, "")]
|
||||
[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<Unknown>(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<Unknown>(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<HeimdallIdentityMoveClient>.Instance);
|
||||
|
||||
Assert.IsType<Unknown>(await client.MoveAsync(Plain, CancellationToken.None));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Throwing(Exception error) : HttpMessageHandler
|
||||
{
|
||||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => throw error;
|
||||
}
|
||||
|
||||
// ---- 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(Func<HttpContent> 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<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) =>
|
||||
Task.FromResult(new HttpResponseMessage(status) { Content = content() });
|
||||
}
|
||||
|
||||
/// <summary>A body that serves a prefix and then stalls, resets, or streams endless filler.</summary>
|
||||
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<int> ReadAsync(Memory<byte> 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<HeimdallIdentityMoveClient>.Instance);
|
||||
|
||||
private static Task<HeimdallMoveOutcome> 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()
|
||||
{
|
||||
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(ids: "\"not-a-guid-but-an-id\""), 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: "123"), 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"),
|
||||
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)
|
||||
{
|
||||
await Assert.ThrowsAsync<ArgumentException>(() => Move(host, request));
|
||||
}
|
||||
|
||||
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<Unknown>(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<Unknown>(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<Unknown>(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 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());
|
||||
}
|
||||
|
||||
[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<IHttpClientFactory>().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<string>();
|
||||
_ = 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<HeimdallIdentityMoveClient>()
|
||||
.MoveAsync(new("move-0123456789abcdef", ["FROM-BEARER"], "TO-BEARER"), CancellationToken.None);
|
||||
await redirected;
|
||||
await Task.Delay(300);
|
||||
|
||||
Assert.IsType<Unknown>(outcome);
|
||||
Assert.Empty(stolen);
|
||||
}
|
||||
|
||||
// ---- 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);
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
372
tests/Bifrost.Web.Tests/Support/FakeMoves.cs
Normal file
372
tests/Bifrost.Web.Tests/Support/FakeMoves.cs
Normal file
|
|
@ -0,0 +1,372 @@
|
|||
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, """{"error":"invalid_request","detail":"body: must match the schema"}""");
|
||||
}
|
||||
|
||||
if (MoveStatus is { } forced)
|
||||
{
|
||||
return forced == HttpStatusCode.NotFound
|
||||
? new HttpResponseMessage(forced)
|
||||
: Json(forced, forced == HttpStatusCode.BadRequest
|
||||
? """{"error":"invalid_request","detail":"body: must match the schema"}"""
|
||||
: """{"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}\z");
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static Move? Parse(string body)
|
||||
{
|
||||
try
|
||||
{
|
||||
var root = JsonDocument.Parse(body).RootElement;
|
||||
if (root.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>moveIdentitiesRoute then decideMove at 4fe367a, in their order; each comment names the check.</summary>
|
||||
private (HttpResponseMessage? Refusal, string? Receipt) Decide(Move move)
|
||||
{
|
||||
var at = now().ToUnixTimeSeconds();
|
||||
var reversal = move.ReversesMoveId is not null;
|
||||
|
||||
// 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))
|
||||
{
|
||||
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))
|
||||
{
|
||||
return (Refuse(HttpStatusCode.Conflict, "not_reversible"), null);
|
||||
}
|
||||
|
||||
var from = new List<Claims>();
|
||||
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);
|
||||
}
|
||||
|
||||
Claims? to = null;
|
||||
if (!reversal && (to = Live(move.ToProof!)) is null)
|
||||
{
|
||||
return (Refuse(HttpStatusCode.Forbidden, "proof_invalid", proof: "to"), null);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
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 => 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)
|
||||
{
|
||||
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 = 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) }
|
||||
};
|
||||
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, json);
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
/// <summary>proofTier: strong inside 600 s of step_up_at, else weak inside 300 s of auth_at; a future-dated claim proves nothing.</summary>
|
||||
private static string? Tier(Claims claims, long at) =>
|
||||
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") };
|
||||
|
||||
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