diff --git a/tests/Bifrost.Web.Tests/DeskReadTests.cs b/tests/Bifrost.Web.Tests/DeskReadTests.cs index fb163ad..70d849c 100644 --- a/tests/Bifrost.Web.Tests/DeskReadTests.cs +++ b/tests/Bifrost.Web.Tests/DeskReadTests.cs @@ -78,33 +78,6 @@ public sealed class DeskReadTests Assert.Equal(200, bare.Status); } - [Fact] - public async Task List_scenarios_pass_through() - { - var steps = 0; - foreach (var scenario in DeskVectors.Rows("transport", "listScenarios")) - { - using var factory = new DeskWebApplicationFactory(); - await factory.EnsureAccountAsync(DeskWebApplicationFactory.Alice, true); - foreach (var step in scenario["steps"]!.AsArray().Select(s => s!.AsObject())) - { - var request = step["request"]!; - var response = step["response"]!.AsObject(); - var list = response.Deserialize(DeskJson.Options)!; - factory.Door.ListScript = (_, _) => new DeskListOutcome.Listed(list); - var query = $"?status={(string?)request["status"]}&cursor={(string?)request["cursor"]}&limit={(int)request["limit"]!}"; - - var reply = await factory.SendAsync("GET", $"/api/desk/{(string)request["mind"]!}/forks" + query, null, ReadToken(factory)); - - Assert.Equal(200, reply.Status); - Assert.True(DeskVectors.SameShape(JsonNode.Parse(reply.Body), response), (string)scenario["name"]!); - steps++; - } - } - - Assert.Equal(12, steps); - } - [Fact] public async Task Read_returns_the_entry_unchanged_and_an_unknown_fork_is_refused() { diff --git a/tests/Bifrost.Web.Tests/DeskReaderViewTests.cs b/tests/Bifrost.Web.Tests/DeskReaderViewTests.cs index 88766c7..2d7d2d3 100644 --- a/tests/Bifrost.Web.Tests/DeskReaderViewTests.cs +++ b/tests/Bifrost.Web.Tests/DeskReaderViewTests.cs @@ -5,8 +5,9 @@ using Bifrost.Web.Tests.Support; namespace Bifrost.Web.Tests; -// CultLib d3025d3c's reader views (append-only on 3a51bbab), as Bifrost meets them: the 17-key card (raised_at, decider_count) stays opaque, -// the record is typed with answerer_count, and answerer is nil in a non-decider's view. +// CultLib d3025d3c's reader views (append-only on 3a51bbab), as Bifrost meets them: the 18-key card, DE0012 (raised_at, decider_count) stays opaque, +// the record is typed with answerer_count, and answerer is nil in a non-decider's view. Entries, records, list pages and +// stored answers are replayed from their wire bytes through the real door in DeskVectorWireTests. public sealed class DeskReaderViewTests { private static readonly string[] CardKeys = @@ -85,67 +86,4 @@ public sealed class DeskReaderViewTests Assert.Superset(new HashSet { "Counted", "Revision", "Retraction", "Refused" }, outcomes); } - - [Fact] - public void Entries_in_both_views_round_trip_and_the_shape_faults_Bifrost_can_see_are_refused() - { - var valid = DeskVectors.Rows("transport", "entry", "valid").ToList(); - Assert.Equal(8, valid.Count); - foreach (var row in valid) - { - var message = row["message"]!; - Assert.True(DeskVectors.SameShape(message, JsonSerializer.SerializeToNode(message.Deserialize(DeskJson.Options), DeskJson.Options)), (string)row["name"]!); - } - - // Missing or null answerer_count is not a count Bifrost may invent; the other invalid entries are rules of the - // contract's validators (CultLib) and Huginn's door, which Bifrost does not judge. - foreach (var name in new[] { "answerer_count_missing", "answerer_count_null" }) - { - var row = DeskVectors.Rows("transport", "entry", "invalid").First(r => (string)r["name"]! == name); - Assert.ThrowsAny(() => row["message"].Deserialize(DeskJson.Options)); - } - } - - [Fact] - public void Every_scenario_record_is_the_6_key_record_and_decodes_typed() - { - var count = 0; - foreach (var scenario in DeskVectors.Rows("scenarios")) - { - var record = scenario["record"]!; - Assert.StartsWith("86", (string)scenario["recordHex"]!, StringComparison.Ordinal); - Assert.True(DeskVectors.SameShape(record, JsonSerializer.SerializeToNode(record.Deserialize(DeskJson.Options), DeskJson.Options)), (string)scenario["name"]!); - count++; - } - - Assert.Equal(63, count); - } - - [Fact] - public async Task The_non_decider_page_leaves_the_edge_with_notes_nil_and_ids_withheld_untouched() - { - var scenario = DeskVectors.Rows("transport", "listScenarios").First(s => (string)s["name"]! == "non_decider_page"); - using var factory = new DeskWebApplicationFactory(); - await factory.EnsureAccountAsync(DeskWebApplicationFactory.Member, true); - var step = scenario["steps"]![0]!; - var response = step["response"]!.AsObject(); - factory.Door.ListScript = (_, _) => new DeskListOutcome.Listed(response.Deserialize(DeskJson.Options)!); - var request = step["request"]!; - - var reply = await factory.SendAsync( - "GET", $"/api/desk/{(string)request["mind"]!}/forks?status={(string?)request["status"]}&cursor={(string?)request["cursor"]}&limit={(int)request["limit"]!}", - null, factory.Token(DeskWebApplicationFactory.Member, "bifrost-desk", "desk.read")); - - Assert.Equal(200, reply.Status); - var expected = JsonNode.Parse(response.ToJsonString())!; - foreach (var fork in expected["forks"]!.AsArray()) - { - foreach (var answer in fork!["record"]!["answers"]!.AsArray()) - { - answer!["note"] = null; - } - } - - Assert.True(DeskVectors.SameShape(JsonNode.Parse(reply.Body), expected)); - } } diff --git a/tests/Bifrost.Web.Tests/DeskVectorWireTests.cs b/tests/Bifrost.Web.Tests/DeskVectorWireTests.cs new file mode 100644 index 0000000..cbcec25 --- /dev/null +++ b/tests/Bifrost.Web.Tests/DeskVectorWireTests.cs @@ -0,0 +1,211 @@ +using System.Text.Json.Nodes; +using Bifrost.Web.Features.Desk; +using Bifrost.Web.Tests.Support; + +namespace Bifrost.Web.Tests; + +// CultLib's vectors, replayed from their WIRE form (responseHex / messagePackHex) through the real UnixSocketDeskDoor on +// a socket double, then compared with the vector's `message`: same keys in the same order, integers unchanged +// (compared as JSON text; the vector side is parsed JSON, so an escaped apostrophe cannot differ). Only what Huginn +// sends is served here. The refusals, 503 documents and edge-authored results in the vectors are Bifrost's own +// output and are replayed on the edge (DeskReadTests, DeskAnswerTests, DeskDocumentTests). +// +// What the door judges of a reply (the single owner is the wire walker's Closed): every contract document is a closed +// map with every key present and typed; the card inside an entry is an opaque map. What it does not judge: every +// rule a schema cannot say (R-card, R-record, R-entry, R-list, R-answer-result, option and hash rules, ordering, +// the reader-view agreement between deciders and answerers). Those belong to CultLib's validators and to Huginn's door; +// Bifrost holds no audience rule and masks nothing it cannot read. +public sealed class DeskVectorWireTests +{ + private static string Mind(JsonNode request) => (string)request["mind"]!; + + private static IEnumerable<(string Name, JsonNode Request, JsonNode Response, string Hex)> ListSteps() + { + foreach (var scenario in DeskVectors.Rows("transport", "listScenarios").Concat(DeskVectors.Rows("transport", "listShortPages"))) + { + foreach (var step in scenario["steps"]!.AsArray().Select(s => s!.AsObject()).Where(s => s.ContainsKey("responseHex"))) + { + yield return ((string)scenario["name"]!, step["request"]!, step["response"]!, (string)step["responseHex"]!); + } + } + } + + [Fact] + public async Task Every_list_page_in_the_vectors_leaves_the_door_as_the_vectors_message() + { + var steps = 0; + foreach (var (name, request, response, hex) in ListSteps()) + { + var list = await DeskServe.ListAsync(Convert.FromHexString(hex), Mind(request)); + + Assert.True(DeskServe.Text(response) == DeskServe.Text(list), name); + steps++; + } + + Assert.Equal(16, steps); + } + + [Fact] + public async Task Every_list_page_in_the_vectors_leaves_the_edge_as_the_vectors_message_for_its_reader() + { + var steps = 0; + foreach (var (name, request, response, hex) in ListSteps()) + { + var scenario = DeskVectors.Rows("transport", "listScenarios").FirstOrDefault(s => (string)s["name"]! == name); + var nonDecider = scenario is not null && scenario.ContainsKey("twin"); + using var huginn = DeskServe.Socket(DeskServe.Forks(Convert.FromHexString(hex))); + using var factory = new DeskWebApplicationFactory(DeskServe.ConfigurationOn(Mind(request), huginn.Path), fakeDoor: false); + var reader = nonDecider ? DeskWebApplicationFactory.Member : DeskWebApplicationFactory.Alice; + await factory.EnsureAccountAsync(reader, true); + var query = $"?status={(string?)request["status"]}&cursor={(string?)request["cursor"]}&limit={(int)request["limit"]!}"; + + var reply = await factory.SendAsync("GET", $"/api/desk/{Mind(request)}/forks" + query, null, factory.Token(reader, "bifrost-desk", "desk.read")); + + // The edge's one change for a non-decider: every note nil, the key kept. + var expected = JsonNode.Parse(response.ToJsonString())!; + if (nonDecider) + { + foreach (var answer in expected["forks"]!.AsArray().SelectMany(f => f!["record"]!["answers"]!.AsArray())) + { + answer!["note"] = null; + } + } + + Assert.Equal(200, reply.Status); + Assert.True(DeskServe.Text(expected) == DeskServe.Text(JsonNode.Parse(reply.Body)!), name); + steps++; + } + + Assert.Equal(16, steps); + } + + [Fact] + public async Task Every_valid_entry_leaves_a_read_unchanged_in_both_views() + { + var rows = DeskVectors.Rows("transport", "entry", "valid").ToList(); + Assert.Equal(8, rows.Count); + foreach (var row in rows) + { + var entry = await DeskServe.ReadAsync(Convert.FromHexString((string)row["messagePackHex"]!)); + + Assert.True(DeskServe.Text(row["message"]!) == DeskServe.Text(entry), (string)row["name"]!); + } + } + + [Fact] + public async Task Every_valid_card_leaves_the_door_inside_an_entry_unchanged() + { + var rows = DeskVectors.Rows("card", "valid").ToList(); + Assert.Equal(7, rows.Count); + foreach (var row in rows) + { + var card = row["message"]!; + var record = DeskServe.FromJson(JsonNode.Parse($$"""{"schemaVersion":"gamecult.fork.record.v0","fork_id":"{{(string)card["fork_id"]!}}","options_hash":"{{(string)card["options_hash"]!}}","counted_answer_id":null,"answerer_count":0,"answers":[]}""")!); + + var entry = await DeskServe.ReadAsync(DeskServe.EntryOf(Convert.FromHexString((string)row["messagePackHex"]!), record)); + + Assert.True(DeskServe.Text(card) == DeskServe.Text(entry.Card), (string)row["name"]!); + } + } + + [Fact] + public async Task Every_scenario_record_leaves_the_door_unchanged_the_6_key_record() + { + var count = 0; + foreach (var scenario in DeskVectors.Rows("scenarios")) + { + var hex = (string)scenario["recordHex"]!; + Assert.StartsWith("86", hex, StringComparison.Ordinal); + + var entry = await DeskServe.ReadAsync(DeskServe.EntryOf(DeskServe.FromJson(scenario["card"]!), Convert.FromHexString(hex))); + + Assert.True(DeskServe.Text(scenario["record"]!) == DeskServe.Text(entry.Record), (string)scenario["name"]!); + count++; + } + + Assert.Equal(63, count); + } + + [Fact] + public async Task Every_valid_stored_answer_leaves_an_answered_reply_unchanged_the_withheld_variants_included() + { + var rows = DeskVectors.Rows("deskAnswer", "valid").ToList(); + Assert.Equal(8, rows.Count); + foreach (var row in rows) + { + var answer = await DeskServe.AnswerAsync(Convert.FromHexString((string)row["messagePackHex"]!)); + + Assert.True(DeskServe.Text(row["message"]!) == DeskServe.Text(answer), (string)row["name"]!); + } + + Assert.Contains(rows, r => (string)r["name"]! == "withheld_answerer_revision" && (string)r["message"]!["outcome"]! == "Revision" && r["message"]!["answerer"] is null); + Assert.Contains(rows, r => (string)r["name"]! == "withheld_answerer_retraction" && (string)r["message"]!["outcome"]! == "Retraction" && r["message"]!["answerer"] is null); + } + + // The entry negatives on the wire. The door refuses the four that break its closed-map typing: an entry without its + // record, and a missing, negative or nil answerer_count (never a count Bifrost may invent). The other fourteen are + // rules a schema cannot say (R-record, R-entry, the options-hash and derivation rules; the two new ones pin a + // withheld card beside a named Retraction and a count over the answers): CultLib's validators and Huginn's door + // judge them, Bifrost reads a closed map and passes it, and a change to either side shows here. + private static readonly HashSet EntryNegativesTheDoorRefuses = + ["entry_without_record", "answerer_count_missing", "answerer_count_negative", "answerer_count_null"]; + + [Fact] + public async Task The_door_refuses_the_entry_negatives_that_break_its_typing_and_judges_no_rule_of_the_contract() + { + var rows = DeskVectors.Rows("transport", "entry", "invalid").ToList(); + Assert.Equal(18, rows.Count); + Assert.Contains(rows, r => (string)r["name"]! == "withheld_revision_and_retraction_beside_a_named_retraction"); + Assert.Contains(rows, r => (string)r["name"]! == "withheld_revision_and_retraction_count_over_the_answers"); + foreach (var row in rows) + { + var name = (string)row["name"]!; + var served = Task.Run(() => DeskServe.ReadAsync(Convert.FromHexString((string)row["messagePackHex"]!))); + + if (EntryNegativesTheDoorRefuses.Contains(name)) + { + await Assert.ThrowsAsync(() => served); + } + else + { + var entry = await served; + Assert.True(DeskServe.Text(row["message"]!) == DeskServe.Text(entry), name); + } + } + } + + // The stored-answer negatives and the answer_result negatives. The door judges that an answer is a closed 16-key map with + // every key typed; all twelve deskAnswer negatives have the 16 keys, so none is refused here. They are rules (outcome + // and code pairing, targets, case, and "no_answerer": a nil answerer on a Counted answer is a withheld view only a + // reader can tell from a fault) that the contract's validators and Huginn's door own. A MISSING answerer key is the + // door's fault, pinned in UnixSocketDeskDoorWireTests. The three resultsInvalid vectors are R-answer-result (the + // sender's own answer carries their account, never nil): Huginn's rule; for Bifrost a nil answerer in an Answered + // reply is a string-or-nil key like any other. Whether the edge should add that check is not decided here. + [Fact] + public async Task The_door_judges_no_deskAnswer_rule_of_the_contract_only_its_closed_typed_shape() + { + var rows = DeskVectors.Rows("deskAnswer", "invalid").ToList(); + Assert.Equal(12, rows.Count); + foreach (var row in rows) + { + var answer = await DeskServe.AnswerAsync(Convert.FromHexString((string)row["messagePackHex"]!)); + + Assert.True(DeskServe.Text(row["message"]!) == DeskServe.Text(answer), (string)row["name"]!); + } + } + + [Fact] + public async Task The_three_answer_result_negatives_carry_an_answer_the_door_reads_as_any_answer() + { + var rows = DeskVectors.Rows("resultsInvalid").ToList(); + Assert.Equal(3, rows.Count); + foreach (var row in rows) + { + var answer = row["message"]!["answer"]!; + var served = await DeskServe.AnswerAsync(DeskServe.FromJson(answer)); + + Assert.Null(served.Answerer); + Assert.True(DeskServe.Text(answer) == DeskServe.Text(served), (string)row["name"]!); + } + } +} diff --git a/tests/Bifrost.Web.Tests/Support/DeskServe.cs b/tests/Bifrost.Web.Tests/Support/DeskServe.cs index d59aab9..64ec12e 100644 --- a/tests/Bifrost.Web.Tests/Support/DeskServe.cs +++ b/tests/Bifrost.Web.Tests/Support/DeskServe.cs @@ -79,4 +79,34 @@ public static class DeskServe public static string Text(T value) => JsonSerializer.SerializeToNode(value, DeskJson.Options)!.ToJsonString(DeskJson.Options); public static string Text(JsonNode node) => node.ToJsonString(DeskJson.Options); + + // The app's own configuration with one Mind on the socket double and every other Mind on a path no one listens on. + public static Dictionary ConfigurationOn(string mind, string socket) + { + var configuration = DeskWebApplicationFactory.DefaultConfiguration(); + foreach (var key in configuration.Keys.Where(k => k.EndsWith(":Id", StringComparison.Ordinal)).ToList()) + { + configuration[key[..^2] + "Socket"] = configuration[key] == mind ? socket : FakeHuginnSocket.Absent(); + } + + return configuration; + } + + // An entry map whose card and record bytes are the given ones, untouched. + public static byte[] EntryOf(byte[] card, byte[] record) + { + var buffer = new ArrayBufferWriter(); + var w = new MessagePackWriter(buffer); + w.WriteMapHeader(3); + w.Write("schemaVersion"); + w.Write("gamecult.fork.entry.v0"); + w.Write("card"); + w.WriteRaw(card); + w.Write("record"); + w.WriteRaw(record); + w.Flush(); + return buffer.WrittenSpan.ToArray(); + } + + public static byte[] FromJson(JsonNode node) => MessagePackSerializer.ConvertFromJson(node.ToJsonString(DeskJson.Options)); }