diff --git a/src/Bifrost.Web/Features/Desk/DeskDocuments.cs b/src/Bifrost.Web/Features/Desk/DeskDocuments.cs index 1c17490..deb6c1d 100644 --- a/src/Bifrost.Web/Features/Desk/DeskDocuments.cs +++ b/src/Bifrost.Web/Features/Desk/DeskDocuments.cs @@ -110,6 +110,15 @@ public sealed record ForkEntry( [property: JsonPropertyName("card")] ForkCard Card, [property: JsonPropertyName("record")] ForkRecord Record); +public sealed record ForkList( + [property: JsonPropertyName("schemaVersion")] string SchemaVersion, + [property: JsonPropertyName("mind")] string Mind, + [property: JsonPropertyName("stamp")] string Stamp, + [property: JsonPropertyName("open_count")] int OpenCount, + [property: JsonPropertyName("recorded_count")] int RecordedCount, + [property: JsonPropertyName("forks")] ForkEntry[] Forks, + [property: JsonPropertyName("next_cursor")] string? NextCursor); + public sealed record AnswerResult( [property: JsonPropertyName("schemaVersion")] string SchemaVersion, [property: JsonPropertyName("answer")] DeskAnswerDocument Answer, diff --git a/src/Bifrost.Web/Features/Desk/DeskEndpoints.cs b/src/Bifrost.Web/Features/Desk/DeskEndpoints.cs index 127f50f..1d88e18 100644 --- a/src/Bifrost.Web/Features/Desk/DeskEndpoints.cs +++ b/src/Bifrost.Web/Features/Desk/DeskEndpoints.cs @@ -95,8 +95,10 @@ public static class DeskEndpoints return; } - // 6. The body's shape. The bytes read are the bytes forwarded. + // 6. The request's shape. An answer's bytes are the bytes forwarded; list and read judge their query. byte[] body = []; + DeskListRequest? listRequest = null; + var forkId = string.Empty; if (route.Kind == DeskRouteKind.Answer) { var read = await ReadBodyAsync(http.Request, desk.MaxBodyBytes, cancellationToken); @@ -111,6 +113,13 @@ public static class DeskEndpoints body = read!; } + else if (route.Kind == DeskRouteKind.Read + ? !DeskQuery.TryRead(route.RawQuery, route.RawFork!, out forkId) + : !DeskQuery.TryList(route.RawQuery, string.Empty, out listRequest)) + { + await WriteRefusalAsync(http, DeskRefusals.RequestInvalid); + return; + } // 7. The {mind} lookup: a miss is the same document as an unknown fork. var mind = minds.Resolve(route.RawMind); @@ -125,29 +134,42 @@ public static class DeskEndpoints var context = new DeskDoorContext(subject, desk.Attribution.AuthorityOf(subject), mind.Deciders); try { - var outcome = await door.AnswerAsync(mind.Socket, context, body, cancellationToken); - switch (outcome) + switch (route.Kind) { - case DeskAnswerOutcome.NotStored(var code) when DoorMayRefuse(code): - await WriteRefusalAsync(http, code); - return; - case DeskAnswerOutcome.Answered(var result) when DeskStatus.Of(result) is { } status: - if (string.Equals(result.Answer.Code, DeskStatus.StaleFork, StringComparison.Ordinal)) + case DeskRouteKind.List: + var listed = await door.ListAsync(mind.Socket, context, listRequest! with { Mind = mind.Id }, cancellationToken); + if (listed is DeskListOutcome.Listed(var list)) { - var current = await door.ReadAsync(mind.Socket, context, result.Answer.ForkId, cancellationToken); - if (current is not DeskReadOutcome.Found(var entry)) - { - await WriteUnavailableAsync(http, desk); - return; - } - - result = result with { Card = entry.Card }; + await WriteJsonAsync(http, 200, list); + } + else if (listed is DeskListOutcome.NotListed(var listCode) && DoorMayRefuse(listCode)) + { + await WriteRefusalAsync(http, listCode); + } + else + { + await WriteUnavailableAsync(http, desk); + } + + return; + case DeskRouteKind.Read: + var found = await door.ReadAsync(mind.Socket, context, forkId, cancellationToken); + if (found is DeskReadOutcome.Found(var entry)) + { + await WriteJsonAsync(http, 200, entry); + } + else if (found is DeskReadOutcome.NotFound(var readCode) && DoorMayRefuse(readCode)) + { + await WriteRefusalAsync(http, readCode); + } + else + { + await WriteUnavailableAsync(http, desk); } - await WriteJsonAsync(http, status, result); return; default: - await WriteUnavailableAsync(http, desk); + await AnswerAsync(http, door, mind, context, body, desk); return; } } @@ -157,6 +179,38 @@ public static class DeskEndpoints } } + private static async Task AnswerAsync( + HttpContext http, IDeskDoor door, DeskMindOptions mind, DeskDoorContext context, byte[] body, DeskOptions desk) + { + var cancellationToken = http.RequestAborted; + var outcome = await door.AnswerAsync(mind.Socket, context, body, cancellationToken); + switch (outcome) + { + case DeskAnswerOutcome.NotStored(var code) when DoorMayRefuse(code): + await WriteRefusalAsync(http, code); + return; + case DeskAnswerOutcome.Answered(var result) when DeskStatus.Of(result) is { } status: + // A stale_fork answer, fresh or replayed, carries the CURRENT card: nothing is stored for it. + if (string.Equals(result.Answer.Code, DeskStatus.StaleFork, StringComparison.Ordinal)) + { + var current = await door.ReadAsync(mind.Socket, context, result.Answer.ForkId, cancellationToken); + if (current is not DeskReadOutcome.Found(var entry)) + { + await WriteUnavailableAsync(http, desk); + return; + } + + result = result with { Card = entry.Card }; + } + + await WriteJsonAsync(http, status, result); + return; + default: + await WriteUnavailableAsync(http, desk); + return; + } + } + // Codes the door may hand back for nothing stored. The three the edge alone judges are never the door's. private static bool DoorMayRefuse(string code) => code is not (DeskRefusals.Unauthenticated or DeskRefusals.InsufficientScope or DeskRefusals.Forbidden) && @@ -231,20 +285,24 @@ public static class DeskStatus public enum DeskRouteKind { + List, + Read, Answer, } -public sealed record DeskRoute(DeskRouteKind Kind, string RawMind) +public sealed record DeskRoute(DeskRouteKind Kind, string RawMind, string? RawFork, string RawQuery) { // The raw request target against the three routes. Segments stay percent-encoded: {mind} is decoded once, by // the resolver, and nothing here normalises a dot segment. Any other shape is not a desk route. public static DeskRoute? Parse(string method, string rawTarget) { var path = rawTarget; - var query = path.IndexOf('?'); - if (query >= 0) + var query = string.Empty; + var split = path.IndexOf('?'); + if (split >= 0) { - path = path[..query]; + query = path[(split + 1)..]; + path = path[..split]; } if (!path.StartsWith(DeskEndpoints.RoutePrefix + "/", StringComparison.Ordinal)) @@ -253,10 +311,91 @@ public sealed record DeskRoute(DeskRouteKind Kind, string RawMind) } var segments = path[(DeskEndpoints.RoutePrefix.Length + 1)..].Split('/'); - return method switch + return (method, segments) switch { - "POST" when segments is [var mind, "answers"] => new DeskRoute(DeskRouteKind.Answer, mind), + ("GET", [var mind, "forks"]) => new DeskRoute(DeskRouteKind.List, mind, null, query), + ("GET", [var mind, "forks", var fork]) => new DeskRoute(DeskRouteKind.Read, mind, fork, query), + ("POST", [var mind, "answers"]) => new DeskRoute(DeskRouteKind.Answer, mind, null, query), _ => null, }; } } + +// The list and read requests the query string and path stand for (fork-card.md, List and Read). Nothing in a +// query sets a decider, an answerer or a Mind; an unknown key, a repeated key or a bad value is request_invalid. +public static class DeskQuery +{ + public const int MaxLimit = 50; + + public static bool TryList(string rawQuery, string mind, out DeskListRequest request) + { + request = new DeskListRequest(mind, null, null, MaxLimit); + if (!TryPairs(rawQuery, out var pairs)) + { + return false; + } + + string? status = null, cursor = null; + var limit = MaxLimit; + foreach (var (key, value) in pairs) + { + switch (key) + { + case "status" when value is "open" or "recorded": + status = value; + break; + case "status" when value.Length == 0: + break; + case "cursor" when IsCursor(value): + cursor = value; + break; + case "cursor" when value.Length == 0: + break; + case "limit" when int.TryParse(value, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var n) && n <= MaxLimit: + limit = n; + break; + default: + return false; + } + } + + request = new DeskListRequest(mind, status, cursor, limit); + return true; + } + + // The read request has no query at all. + public static bool TryRead(string rawQuery, string rawFork, out string forkId) + { + forkId = string.Empty; + return rawQuery.Length == 0 && DeskMindRoutes.TryDecode(rawFork, out forkId) && forkId.Length > 0; + } + + // c, N a positive integer without a leading zero. + private static bool IsCursor(string value) => + value.Length > 1 && value[0] == 'c' && value[1] is >= '1' and <= '9' && value.Skip(2).All(char.IsAsciiDigit); + + private static bool TryPairs(string rawQuery, out List<(string Key, string Value)> pairs) + { + pairs = []; + var seen = new HashSet(StringComparer.Ordinal); + if (rawQuery.Length == 0) + { + return true; + } + + foreach (var part in rawQuery.Split('&')) + { + var eq = part.IndexOf('='); + var rawKey = eq < 0 ? part : part[..eq]; + var rawValue = eq < 0 ? string.Empty : part[(eq + 1)..]; + if (!DeskMindRoutes.TryDecode(rawKey, out var key) || !DeskMindRoutes.TryDecode(rawValue, out var value) || !seen.Add(key)) + { + return false; + } + + pairs.Add((key, value)); + } + + return true; + } +} diff --git a/src/Bifrost.Web/Features/Desk/DeskPorts.cs b/src/Bifrost.Web/Features/Desk/DeskPorts.cs index aa439b4..b36a687 100644 --- a/src/Bifrost.Web/Features/Desk/DeskPorts.cs +++ b/src/Bifrost.Web/Features/Desk/DeskPorts.cs @@ -35,12 +35,27 @@ public abstract record DeskReadOutcome public sealed record NotFound(string Code) : DeskReadOutcome; } +// The list request the desk's query string stands for. Mind is the route's, resolved against the configured list. +public sealed record DeskListRequest(string Mind, string? Status, string? Cursor, int Limit); + +public abstract record DeskListOutcome +{ + public sealed record Listed(ForkList List) : DeskListOutcome; + + public sealed record NotListed(string Code) : DeskListOutcome; +} + public interface IDeskDoor { // The body is exactly the bytes the client sent. Any exception means the outcome is not confirmed. Task AnswerAsync( string socket, DeskDoorContext context, ReadOnlyMemory body, CancellationToken cancellationToken); + // The entry for one fork, its card built and hashed by Huginn. Task ReadAsync( string socket, DeskDoorContext context, string forkId, CancellationToken cancellationToken); + + // A page of entries, the counts and the stamp, as Huginn projects them for this viewer. + Task ListAsync( + string socket, DeskDoorContext context, DeskListRequest request, CancellationToken cancellationToken); } diff --git a/tests/Bifrost.Web.Tests/DeskAuthCaseTests.cs b/tests/Bifrost.Web.Tests/DeskAuthCaseTests.cs index c52a131..bedbbfc 100644 --- a/tests/Bifrost.Web.Tests/DeskAuthCaseTests.cs +++ b/tests/Bifrost.Web.Tests/DeskAuthCaseTests.cs @@ -12,16 +12,17 @@ public sealed class DeskAuthCaseTests var cases = DeskVectors.Rows("transport", "authCases").ToList(); Assert.Equal(22, cases.Count); - foreach (var row in cases.Where(r => (string)r["route"]! == "answer")) + foreach (var row in cases) { using var factory = new DeskWebApplicationFactory(); DeskReplay.HoldVectorForks(factory.Door); factory.Door.Down = (bool)row["huginn_down"]!; var token = await DeskReplay.TokenAsync(factory, row["token"]); + var route = (string)row["route"]!; var reply = await factory.SendAsync( - "POST", DeskReplay.Target("answer", "gamecult-chat", DeskReplay.ChatFork), - DeskReplay.AnswerBody(DeskReplay.ChatFork), token); + route == "answer" ? "POST" : "GET", DeskReplay.Target(route, "gamecult-chat", DeskReplay.ChatFork), + route == "answer" ? DeskReplay.AnswerBody(DeskReplay.ChatFork) : null, token); var name = (string)row["name"]!; var expect = (string)row["expect"]!; diff --git a/tests/Bifrost.Web.Tests/DeskMindRouteTests.cs b/tests/Bifrost.Web.Tests/DeskMindRouteTests.cs index 8198530..86b1835 100644 --- a/tests/Bifrost.Web.Tests/DeskMindRouteTests.cs +++ b/tests/Bifrost.Web.Tests/DeskMindRouteTests.cs @@ -28,7 +28,7 @@ public sealed class DeskMindRouteTests var cases = DeskVectors.Rows("transport", "mindRoutes", "cases").ToList(); Assert.Equal(57, cases.Count); - foreach (var row in cases.Where(r => (string)r["route"]! == "answer")) + foreach (var row in cases) { var name = (string)row["name"]!; var (reply, factory) = await RunAsync(row); @@ -78,11 +78,6 @@ public sealed class DeskMindRouteTests { var first = cases[(string)pair![0]!]; var second = cases[(string)pair[1]!]; - if ((string)first["route"]! != "answer" || (string)second["route"]! != "answer") - { - continue; - } - var (a, fa) = await RunAsync(first); var (b, fb) = await RunAsync(second); using (fa) diff --git a/tests/Bifrost.Web.Tests/DeskReadTests.cs b/tests/Bifrost.Web.Tests/DeskReadTests.cs new file mode 100644 index 0000000..9cf0f05 --- /dev/null +++ b/tests/Bifrost.Web.Tests/DeskReadTests.cs @@ -0,0 +1,169 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using Bifrost.Web.Features.Desk; +using Bifrost.Web.Tests.Support; + +namespace Bifrost.Web.Tests; + +public sealed class DeskReadTests +{ + private static string ReadToken(DeskWebApplicationFactory f) => + f.Token(DeskWebApplicationFactory.Alice, "bifrost-desk", "desk.read"); + + private static Uri Unused => new("http://unused"); + + // A list_request invalid row names the query that cannot express it; the others are the shapes a query cannot hold. + private static readonly Dictionary InvalidListQueries = new() + { + ["limit_51"] = "?limit=51", + ["limit_negative"] = "?limit=-1", + ["status_all"] = "?status=all", + ["cursor_malformed"] = "?cursor=next", + ["cursor_zero"] = "?cursor=c0", + ["unknown_key"] = "?sort=oldest", + }; + + [Fact] + public async Task List_and_read_request_invalid_vectors() + { + using var factory = new DeskWebApplicationFactory(); + DeskReplay.HoldVectorForks(factory.Door); + await factory.EnsureAccountAsync(DeskWebApplicationFactory.Alice, true); + var token = ReadToken(factory); + + var invalid = DeskVectors.Rows("transport", "listRequest", "invalid").Select(r => (string)r["name"]!).ToList(); + foreach (var name in invalid.Where(n => n != "mind_empty")) + { + var reply = await factory.SendAsync("GET", "/api/desk/gamecult-chat/forks" + InvalidListQueries[name], null, token); + Assert.True(reply.Status == 400, $"{name}: {reply.Status}"); + Assert.Equal("request_invalid", (string?)JsonNode.Parse(reply.Body)!["code"]); + } + + // Also: repeated key, bad escape, query on a read, empty fork id. + foreach (var target in new[] + { + "/api/desk/gamecult-chat/forks?limit=1&limit=2", "/api/desk/gamecult-chat/forks?limit=%zz", "/api/desk/gamecult-chat/forks?limit=", + "/api/desk/gamecult-chat/forks?limit=+1", "/api/desk/gamecult-chat/forks?limit=1.0", + "/api/desk/gamecult-chat/forks/gamecult-chat%3Aquestion%3Aq1?x=1", "/api/desk/gamecult-chat/forks/", "/api/desk/gamecult-chat/forks/%ff", + }) + { + var reply = await factory.SendAsync("GET", target, null, token); + Assert.True(reply.Status == 400, $"{target}: {reply.Status}"); + } + + // The invalid request is judged before the Mind: an unknown Mind with a bad query is the query's refusal. + var order = await factory.SendAsync("GET", "/api/desk/ghost/forks?limit=99", null, token); + Assert.Equal("request_invalid", (string?)JsonNode.Parse(order.Body)!["code"]); + Assert.Empty(factory.Door.Calls); + } + + [Fact] + public async Task Valid_list_queries_reach_the_door_as_typed_requests() + { + using var factory = new DeskWebApplicationFactory(); + await factory.EnsureAccountAsync(DeskWebApplicationFactory.Alice, true); + + foreach (var row in DeskVectors.Rows("transport", "listRequest", "valid")) + { + var m = row["message"]!; + var query = $"?status={(string?)m["status"]}&cursor={(string?)m["cursor"]}&limit={(int)m["limit"]!}"; + var reply = await factory.SendAsync("GET", "/api/desk/gamecult-chat/forks" + query, null, ReadToken(factory)); + Assert.Equal(200, reply.Status); + var call = factory.Door.Calls[^1]; + Assert.Equal(new DeskListRequest("gamecult-chat", (string?)m["status"], (string?)m["cursor"], (int)m["limit"]!), call.List); + } + + var bare = await factory.SendAsync("GET", "/api/desk/nibu/forks", null, ReadToken(factory)); + Assert.Equal(new DeskListRequest("nibu", null, null, 50), factory.Door.Calls[^1].List); + 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(7, steps); + } + + [Fact] + public async Task Read_returns_the_entry_unchanged_and_an_unknown_fork_is_refused() + { + using var factory = new DeskWebApplicationFactory(); + DeskReplay.HoldVectorForks(factory.Door); + await factory.EnsureAccountAsync(DeskWebApplicationFactory.Alice, true); + + var ok = await factory.SendAsync("GET", DeskReplay.Target("read", "gamecult-chat", DeskReplay.ChatFork), null, ReadToken(factory)); + var entry = JsonSerializer.SerializeToNode(DeskReplay.Entry(DeskReplay.Card(DeskReplay.ChatFork)), DeskJson.Options); + var missing = await factory.SendAsync("GET", DeskReplay.Target("read", "gamecult-chat", "gamecult-chat:question:ghost"), null, ReadToken(factory)); + + Assert.Equal(200, ok.Status); + Assert.True(DeskVectors.SameShape(JsonNode.Parse(ok.Body), entry)); + Assert.Equal(DeskReplay.ChatFork, Assert.IsType(factory.Door.Calls[0].ForkId)); + Assert.Equal(404, missing.Status); + } + + [Fact] + public async Task Door_failure_on_list_and_read_is_unavailable() + { + using var factory = new DeskWebApplicationFactory(); + await factory.EnsureAccountAsync(DeskWebApplicationFactory.Alice, true); + factory.Door.Down = true; + + foreach (var target in new[] { "/api/desk/nibu/forks", DeskReplay.Target("read", "nibu", "nibu:question:glow-order") }) + { + var reply = await factory.SendAsync("GET", target, null, ReadToken(factory)); + Assert.Equal(503, reply.Status); + Assert.Equal(30, (int?)JsonNode.Parse(reply.Body)!["retryAfterSeconds"]); + } + } + + [Fact] + public async Task Every_door_call_carries_the_configured_deciders_and_nothing_in_the_request_can_change_them() + { + using var factory = new DeskWebApplicationFactory(); + DeskReplay.HoldVectorForks(factory.Door); + await factory.EnsureAccountAsync(DeskWebApplicationFactory.Alice, true); + var hostile = "deciders=" + DeskWebApplicationFactory.Member; + Action headers = http => + { + http.Request.Headers["X-Deciders"] = DeskWebApplicationFactory.Member; + http.Request.Headers["Deciders"] = DeskWebApplicationFactory.Member; + }; + var read = ReadToken(factory); + var answer = factory.Token(DeskWebApplicationFactory.Alice, "bifrost-desk", "desk.answer"); + + await factory.SendAsync("GET", "/api/desk/nibu/forks", null, read, configure: headers); + var hostileList = await factory.SendAsync("GET", "/api/desk/nibu/forks?" + hostile, null, read, configure: headers); + Assert.Equal(400, hostileList.Status); + await factory.SendAsync("GET", DeskReplay.Target("read", "nibu", "nibu:question:glow-order"), null, read, configure: headers); + await factory.SendAsync("POST", DeskReplay.Target("answer", "nibu", null) + "?" + hostile, DeskReplay.AnswerBody("nibu:question:glow-order"), answer, configure: headers); + // A body naming deciders never reaches the door. + var body = JsonNode.Parse(DeskReplay.AnswerBody("nibu:question:glow-order"))!.AsObject(); + body["deciders"] = new JsonArray(DeskWebApplicationFactory.Member); + var named = await factory.SendAsync("POST", DeskReplay.Target("answer", "nibu", null), DeskVectors.Bytes(body), answer); + + Assert.Equal("body_unknown_field", (string?)JsonNode.Parse(named.Body)!["code"]); + Assert.Equal(["list", "read", "answer"], factory.Door.Calls.Select(c => c.Kind).ToArray()); + Assert.All(factory.Door.Calls, c => Assert.Equal([DeskWebApplicationFactory.Alice, DeskWebApplicationFactory.Steward], c.Context.Deciders)); + } +} diff --git a/tests/Bifrost.Web.Tests/Support/FakeDeskDoor.cs b/tests/Bifrost.Web.Tests/Support/FakeDeskDoor.cs index 524ca20..2e8af51 100644 --- a/tests/Bifrost.Web.Tests/Support/FakeDeskDoor.cs +++ b/tests/Bifrost.Web.Tests/Support/FakeDeskDoor.cs @@ -3,7 +3,7 @@ using Bifrost.Web.Features.Desk; namespace Bifrost.Web.Tests.Support; -public sealed record DeskDoorCall(string Kind, string Socket, DeskDoorContext Context, byte[]? Body, string? ForkId); +public sealed record DeskDoorCall(string Kind, string Socket, DeskDoorContext Context, byte[]? Body, string? ForkId, DeskListRequest? List = null); // The door as a test double: it records every call, holds the forks each socket's Mind holds, and by default stores // an answer to a held fork as Counted. A test may script the outcome or make the door fail before or after storing. @@ -27,6 +27,25 @@ public sealed class FakeDeskDoor : IDeskDoor public bool ThrowOnRead { get; set; } + public Func? ListScript { get; set; } + + public Task ListAsync( + string socket, DeskDoorContext context, DeskListRequest request, CancellationToken cancellationToken) + { + lock (gate) + { + Calls.Add(new DeskDoorCall("list", socket, context, null, null, request)); + } + + if (Down) + { + throw new IOException("huginn is down"); + } + + return Task.FromResult(ListScript?.Invoke(socket, request) + ?? new DeskListOutcome.Listed(new ForkList("gamecult.fork.list.v0", request.Mind, "s1", 0, 0, [], null))); + } + public Task AnswerAsync( string socket, DeskDoorContext context, ReadOnlyMemory body, CancellationToken cancellationToken) {