Desk: the fork desk's Bifrost half (#40)
This commit is contained in:
parent
12a153f66f
commit
7e9ba5796b
28 changed files with 20775 additions and 6 deletions
68
src/Bifrost.Web/Configuration/DeskOptions.cs
Normal file
68
src/Bifrost.Web/Configuration/DeskOptions.cs
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
namespace Bifrost.Web.Configuration;
|
||||
|
||||
// The fork desk's configuration (CultLib fork-card.md, Transport; M1 and M5). Minds is an ARRAY, never a map keyed
|
||||
// by Mind id: configuration keys are case-insensitive, so a keyed section would let GAMECULT-CHAT reach
|
||||
// gamecult-chat. Account ids are lowercase D-format Guids. An empty Minds list means the desk is not configured.
|
||||
public sealed class DeskOptions
|
||||
{
|
||||
public const string SectionName = "Desk";
|
||||
|
||||
public List<DeskMindOptions> Minds { get; init; } = [];
|
||||
|
||||
public DeskAttributionOptions Attribution { get; init; } = new();
|
||||
|
||||
// The one origin allowed to call /api/desk from a browser (exactly this, no credentials).
|
||||
public string AllowedOrigin { get; init; } = string.Empty;
|
||||
|
||||
// The cap on an answer body, in bytes, judged before it is parsed.
|
||||
public int MaxBodyBytes { get; init; } = 16 * 1024;
|
||||
|
||||
// What an `unavailable` document tells the client to wait.
|
||||
public int RetryAfterSeconds { get; init; } = 30;
|
||||
|
||||
public bool IsConfigured => Minds.Count > 0;
|
||||
}
|
||||
|
||||
public sealed class DeskMindOptions
|
||||
{
|
||||
public string Id { get; init; } = string.Empty;
|
||||
|
||||
// The full path of this Mind's socket on the peer-checked door. Bifrost only connects to it.
|
||||
public string Socket { get; init; } = string.Empty;
|
||||
|
||||
// Accounts that may answer this Mind's forks. Sent to Huginn with every call; no request sets or extends it.
|
||||
public List<string> Deciders { get; init; } = [];
|
||||
|
||||
// Huginn's bound on the list a call carries (fork-card.md: one to 64 ids).
|
||||
public const int MaxDeciders = 64;
|
||||
|
||||
// One to 64 ids, none repeated. The startup validator and the request path both ask this one question.
|
||||
public static bool DecidersWithinBounds(IReadOnlyCollection<string> deciders) =>
|
||||
deciders.Count is >= 1 and <= MaxDeciders && deciders.Distinct(StringComparer.Ordinal).Count() == deciders.Count;
|
||||
}
|
||||
|
||||
// The authority a stamped answer carries (fork-card.md: Operator, Steward or Member), from configuration because
|
||||
// Bifrost has no such roles: Operator is one account, Stewards a list, everyone else a Member.
|
||||
public sealed class DeskAttributionOptions
|
||||
{
|
||||
public string? Operator { get; init; }
|
||||
|
||||
public List<string> Stewards { get; init; } = [];
|
||||
|
||||
public string AuthorityOf(string accountId)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(Operator) && string.Equals(accountId, Operator, StringComparison.Ordinal))
|
||||
{
|
||||
return DeskAuthority.Operator;
|
||||
}
|
||||
|
||||
return Stewards.Contains(accountId, StringComparer.Ordinal) ? DeskAuthority.Steward : DeskAuthority.Member;
|
||||
}
|
||||
}
|
||||
|
||||
public static class DeskAuthority
|
||||
{
|
||||
public const string Operator = "Operator";
|
||||
public const string Steward = "Steward";
|
||||
public const string Member = "Member";
|
||||
}
|
||||
270
src/Bifrost.Web/Features/Desk/DeskBodyShape.cs
Normal file
270
src/Bifrost.Web/Features/Desk/DeskBodyShape.cs
Normal file
|
|
@ -0,0 +1,270 @@
|
|||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace Bifrost.Web.Features.Desk;
|
||||
|
||||
// The edge's judgment of an answer body (fork-card.md, answer_request, steps 1 and 2). It checks the shape only:
|
||||
// whether the answer is legal (a retraction's target, the choice, the fork) is Huginn's. A body that passes is
|
||||
// forwarded as the bytes received; the parsed request is returned for the door's context and for tests.
|
||||
public sealed record DeskBodyVerdict(AnswerRequest? Request, string? RefusalCode)
|
||||
{
|
||||
public static DeskBodyVerdict Pass(AnswerRequest request) => new(request, null);
|
||||
|
||||
public static DeskBodyVerdict Refuse(string code) => new(null, code);
|
||||
}
|
||||
|
||||
public static partial class DeskBodyShape
|
||||
{
|
||||
public const int MaxNoteBytes = 4000;
|
||||
|
||||
// Two keys the receiver alone stamps. Refused whole at any depth, never stripped.
|
||||
private static readonly string[] ForbiddenKeys = ["answerer", "authority"];
|
||||
|
||||
private static readonly string[] TopKeys =
|
||||
["schemaVersion", "fork_id", "options_hash", "answer", "retracted", "retracts", "answered_at", "request_id"];
|
||||
|
||||
private static readonly string[] AnswerKeys = ["choice", "note"];
|
||||
|
||||
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
|
||||
|
||||
private static readonly JsonDocumentOptions ParseOptions = new() { MaxDepth = 32 };
|
||||
|
||||
public static DeskBodyVerdict Judge(ReadOnlySpan<byte> body, int maxBodyBytes)
|
||||
{
|
||||
if (body.Length > maxBodyBytes)
|
||||
{
|
||||
return DeskBodyVerdict.Refuse(DeskRefusals.BodyInvalid);
|
||||
}
|
||||
|
||||
JsonDocument document;
|
||||
try
|
||||
{
|
||||
document = JsonDocument.Parse(body.ToArray(), ParseOptions);
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
return DeskBodyVerdict.Refuse(DeskRefusals.BodyInvalid);
|
||||
}
|
||||
|
||||
using (document)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JudgeParsed(document.RootElement);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// A string the parser accepted but cannot decode: invalid UTF-8 or a lone surrogate.
|
||||
return DeskBodyVerdict.Refuse(DeskRefusals.BodyInvalid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static DeskBodyVerdict JudgeParsed(JsonElement root)
|
||||
{
|
||||
if (HasForbiddenKey(root))
|
||||
{
|
||||
return DeskBodyVerdict.Refuse(DeskRefusals.BodyForbiddenField);
|
||||
}
|
||||
|
||||
if (root.ValueKind != JsonValueKind.Object)
|
||||
{
|
||||
return DeskBodyVerdict.Refuse(DeskRefusals.BodyInvalid);
|
||||
}
|
||||
|
||||
var top = Members(root);
|
||||
if (top is null)
|
||||
{
|
||||
return DeskBodyVerdict.Refuse(DeskRefusals.BodyInvalid);
|
||||
}
|
||||
|
||||
// Unknown keys, including inside the answer object, before any value is judged.
|
||||
if (top.Keys.Any(key => !TopKeys.Contains(key, StringComparer.Ordinal)))
|
||||
{
|
||||
return DeskBodyVerdict.Refuse(DeskRefusals.BodyUnknownField);
|
||||
}
|
||||
|
||||
Dictionary<string, JsonElement>? answerMembers = null;
|
||||
if (top.TryGetValue("answer", out var answerElement) && answerElement.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
answerMembers = Members(answerElement);
|
||||
if (answerMembers is not null &&
|
||||
answerMembers.Keys.Any(key => !AnswerKeys.Contains(key, StringComparer.Ordinal)))
|
||||
{
|
||||
return DeskBodyVerdict.Refuse(DeskRefusals.BodyUnknownField);
|
||||
}
|
||||
}
|
||||
|
||||
return Shape(top, answerMembers);
|
||||
}
|
||||
|
||||
private static DeskBodyVerdict Shape(Dictionary<string, JsonElement> top, Dictionary<string, JsonElement>? answerMembers)
|
||||
{
|
||||
var invalid = DeskBodyVerdict.Refuse(DeskRefusals.BodyInvalid);
|
||||
|
||||
// Map-mode: every key is written.
|
||||
if (TopKeys.Any(key => !top.ContainsKey(key)))
|
||||
{
|
||||
return invalid;
|
||||
}
|
||||
|
||||
if (!IsString(top["schemaVersion"], out var schemaVersion) || schemaVersion != DeskSchemas.AnswerRequest ||
|
||||
!IsString(top["fork_id"], out var forkId) || forkId.Length == 0 ||
|
||||
!IsString(top["options_hash"], out var optionsHash) || !Hex64().IsMatch(optionsHash) ||
|
||||
!IsString(top["answered_at"], out var answeredAt) || !Instant().IsMatch(answeredAt) ||
|
||||
!IsString(top["request_id"], out var requestId) || !RequestId().IsMatch(requestId))
|
||||
{
|
||||
return invalid;
|
||||
}
|
||||
|
||||
var retractedElement = top["retracted"];
|
||||
if (retractedElement.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
|
||||
{
|
||||
return invalid;
|
||||
}
|
||||
|
||||
var retracted = retractedElement.ValueKind == JsonValueKind.True;
|
||||
|
||||
string? retracts = null;
|
||||
if (top["retracts"].ValueKind != JsonValueKind.Null)
|
||||
{
|
||||
if (!IsString(top["retracts"], out var target) || !AnswerId().IsMatch(target))
|
||||
{
|
||||
return invalid;
|
||||
}
|
||||
|
||||
retracts = target;
|
||||
}
|
||||
|
||||
AnswerObject? answer = null;
|
||||
if (top["answer"].ValueKind != JsonValueKind.Null)
|
||||
{
|
||||
if (answerMembers is null || AnswerKeys.Any(key => !answerMembers.ContainsKey(key)))
|
||||
{
|
||||
return invalid;
|
||||
}
|
||||
|
||||
string? choice = null;
|
||||
if (answerMembers["choice"].ValueKind != JsonValueKind.Null)
|
||||
{
|
||||
if (!IsString(answerMembers["choice"], out var picked) || picked.Length == 0)
|
||||
{
|
||||
return invalid;
|
||||
}
|
||||
|
||||
choice = picked;
|
||||
}
|
||||
|
||||
string? note = null;
|
||||
if (answerMembers["note"].ValueKind != JsonValueKind.Null)
|
||||
{
|
||||
if (!IsString(answerMembers["note"], out var words) || !IsWords(words))
|
||||
{
|
||||
return invalid;
|
||||
}
|
||||
|
||||
note = words;
|
||||
}
|
||||
|
||||
if (choice is null && note is null)
|
||||
{
|
||||
return invalid;
|
||||
}
|
||||
|
||||
answer = new AnswerObject(choice, note);
|
||||
}
|
||||
|
||||
// No answer and no retraction is no request. The illegal retraction forms (a target-less retraction, a
|
||||
// retraction carrying an answer, a target on a plain answer) pass here: Huginn stores them as bad_retraction.
|
||||
if (answer is null && !retracted)
|
||||
{
|
||||
return invalid;
|
||||
}
|
||||
|
||||
return DeskBodyVerdict.Pass(new AnswerRequest(
|
||||
schemaVersion, forkId, optionsHash, answer, retracted, retracts, answeredAt, requestId));
|
||||
}
|
||||
|
||||
// A note is 1 to 4000 UTF-8 bytes and not whitespace only. Bytes, not characters or UTF-16 units.
|
||||
private static bool IsWords(string value)
|
||||
{
|
||||
int bytes;
|
||||
try
|
||||
{
|
||||
bytes = StrictUtf8.GetByteCount(value);
|
||||
}
|
||||
catch (EncoderFallbackException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return bytes is >= 1 and <= MaxNoteBytes && !value.All(IsSchemaSpace);
|
||||
}
|
||||
|
||||
// The whitespace set of the schema's `words` pattern.
|
||||
private static bool IsSchemaSpace(char c) =>
|
||||
c is (>= (char)0x09 and <= (char)0x0d) or (char)0x20 or (char)0x85 or (char)0xa0 or (char)0x1680
|
||||
or (>= (char)0x2000 and <= (char)0x200a) or (char)0x2028 or (char)0x2029 or (char)0x202f or (char)0x205f or (char)0x3000;
|
||||
|
||||
private static bool IsString(JsonElement element, out string value)
|
||||
{
|
||||
value = string.Empty;
|
||||
if (element.ValueKind != JsonValueKind.String)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
value = element.GetString() ?? string.Empty;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Object members by unescaped name; null when a name repeats, because the forwarded bytes would then mean
|
||||
// different things to different parsers.
|
||||
private static Dictionary<string, JsonElement>? Members(JsonElement element)
|
||||
{
|
||||
var members = new Dictionary<string, JsonElement>(StringComparer.Ordinal);
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (!members.TryAdd(property.Name, property.Value))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return members;
|
||||
}
|
||||
|
||||
private static bool HasForbiddenKey(JsonElement element)
|
||||
{
|
||||
switch (element.ValueKind)
|
||||
{
|
||||
case JsonValueKind.Object:
|
||||
foreach (var property in element.EnumerateObject())
|
||||
{
|
||||
if (ForbiddenKeys.Contains(property.Name, StringComparer.Ordinal) || HasForbiddenKey(property.Value))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
case JsonValueKind.Array:
|
||||
return element.EnumerateArray().Any(HasForbiddenKey);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
[GeneratedRegex(@"^[0-9a-f]{64}\z")]
|
||||
private static partial Regex Hex64();
|
||||
|
||||
[GeneratedRegex(@"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{1,7})?Z\z")]
|
||||
private static partial Regex Instant();
|
||||
|
||||
[GeneratedRegex(@"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z")]
|
||||
private static partial Regex RequestId();
|
||||
|
||||
[GeneratedRegex(@"^n[1-9][0-9]*\z")]
|
||||
private static partial Regex AnswerId();
|
||||
}
|
||||
194
src/Bifrost.Web/Features/Desk/DeskDocuments.cs
Normal file
194
src/Bifrost.Web/Features/Desk/DeskDocuments.cs
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace Bifrost.Web.Features.Desk;
|
||||
|
||||
// The fork-desk documents Bifrost reads or writes, spelled as CultLib's contracts/cultnet/governance/fork-card.md
|
||||
// (commit 89755b08) spells them: snake_case keys, every key written (nil where absent), declared in the
|
||||
// contract's key order. Bifrost authors only DeskRefusal and DeskUnavailable. AnswerRequest is the client's body;
|
||||
// ForkCard, DeskAnswerDocument and AnswerResult are Huginn's documents, typed here so they pass through unchanged.
|
||||
|
||||
public static class DeskSchemas
|
||||
{
|
||||
public const string AnswerRequest = "gamecult.fork.answer_request.v0";
|
||||
public const string AnswerResult = "gamecult.fork.answer_result.v0";
|
||||
public const string Card = "gamecult.fork.card.v0";
|
||||
public const string DeskAnswer = "gamecult.desk_answer.v0";
|
||||
public const string Refusal = "gamecult.fork.refusal.v0";
|
||||
public const string Unavailable = "gamecult.fork.unavailable.v0";
|
||||
}
|
||||
|
||||
public static class DeskJson
|
||||
{
|
||||
// Defaults write nulls, which map-mode needs ("every key written").
|
||||
public static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
// The documents are not HTML: keep apostrophes and non-ASCII text as written.
|
||||
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||||
};
|
||||
}
|
||||
|
||||
public sealed record AnswerObject(
|
||||
[property: JsonPropertyName("choice")] string? Choice,
|
||||
[property: JsonPropertyName("note")] string? Note);
|
||||
|
||||
public sealed record AnswerRequest(
|
||||
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
||||
[property: JsonPropertyName("fork_id")] string ForkId,
|
||||
[property: JsonPropertyName("options_hash")] string OptionsHash,
|
||||
[property: JsonPropertyName("answer")] AnswerObject? Answer,
|
||||
[property: JsonPropertyName("retracted")] bool Retracted,
|
||||
[property: JsonPropertyName("retracts")] string? Retracts,
|
||||
[property: JsonPropertyName("answered_at")] string AnsweredAt,
|
||||
[property: JsonPropertyName("request_id")] string RequestId);
|
||||
|
||||
public sealed record DeskRefusal(
|
||||
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
||||
[property: JsonPropertyName("code")] string Code,
|
||||
[property: JsonPropertyName("error")] string Error);
|
||||
|
||||
public sealed record DeskUnavailable(
|
||||
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
||||
[property: JsonPropertyName("code")] string Code,
|
||||
[property: JsonPropertyName("error")] string Error,
|
||||
[property: JsonPropertyName("retryAfterSeconds")] int? RetryAfterSeconds);
|
||||
|
||||
public sealed record ForkOption(
|
||||
[property: JsonPropertyName("id")] string Id,
|
||||
[property: JsonPropertyName("text")] string Text);
|
||||
|
||||
public sealed record ForkRef(
|
||||
[property: JsonPropertyName("kind")] string Kind,
|
||||
[property: JsonPropertyName("id")] string Id);
|
||||
|
||||
public sealed record ForkCard(
|
||||
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
||||
[property: JsonPropertyName("fork_id")] string ForkId,
|
||||
[property: JsonPropertyName("title")] string Title,
|
||||
[property: JsonPropertyName("context")] string Context,
|
||||
[property: JsonPropertyName("options")] ForkOption[] Options,
|
||||
[property: JsonPropertyName("recommendation")] string Recommendation,
|
||||
[property: JsonPropertyName("depends")] string[] Depends,
|
||||
[property: JsonPropertyName("leans")] string? Leans,
|
||||
[property: JsonPropertyName("flag")] string? Flag,
|
||||
[property: JsonPropertyName("raised_in")] ForkRef? RaisedIn,
|
||||
[property: JsonPropertyName("deciders")] string[] Deciders,
|
||||
[property: JsonPropertyName("status")] string Status,
|
||||
[property: JsonPropertyName("ruling")] string? Ruling,
|
||||
[property: JsonPropertyName("ruled_from")] string[] RuledFrom,
|
||||
[property: JsonPropertyName("order")] long Order,
|
||||
[property: JsonPropertyName("options_hash")] string OptionsHash);
|
||||
|
||||
// One stored answer: Counted, Revision, Retraction or Refused, told apart by Outcome and Code.
|
||||
public sealed record DeskAnswerDocument(
|
||||
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
||||
[property: JsonPropertyName("answer_id")] string AnswerId,
|
||||
[property: JsonPropertyName("fork_id")] string ForkId,
|
||||
[property: JsonPropertyName("outcome")] string Outcome,
|
||||
[property: JsonPropertyName("of")] string? Of,
|
||||
[property: JsonPropertyName("retracts")] string? Retracts,
|
||||
[property: JsonPropertyName("code")] string? Code,
|
||||
[property: JsonPropertyName("options_hash")] string OptionsHash,
|
||||
[property: JsonPropertyName("choice")] string? Choice,
|
||||
[property: JsonPropertyName("note")] string? Note,
|
||||
[property: JsonPropertyName("answered_at")] string AnsweredAt,
|
||||
[property: JsonPropertyName("received_at")] string ReceivedAt,
|
||||
[property: JsonPropertyName("claim_in_future")] bool ClaimInFuture,
|
||||
[property: JsonPropertyName("answerer")] string Answerer,
|
||||
[property: JsonPropertyName("authority")] string Authority,
|
||||
[property: JsonPropertyName("request_id")] string RequestId);
|
||||
|
||||
public sealed record ForkRecord(
|
||||
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
||||
[property: JsonPropertyName("fork_id")] string ForkId,
|
||||
[property: JsonPropertyName("options_hash")] string OptionsHash,
|
||||
[property: JsonPropertyName("counted_answer_id")] string? CountedAnswerId,
|
||||
[property: JsonPropertyName("answers")] DeskAnswerDocument[] Answers);
|
||||
|
||||
public sealed record ForkEntry(
|
||||
[property: JsonPropertyName("schemaVersion")] string SchemaVersion,
|
||||
[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,
|
||||
[property: JsonPropertyName("card")] ForkCard? Card,
|
||||
[property: JsonPropertyName("counted_answer_id")] string? CountedAnswerId);
|
||||
|
||||
// The refusal codes Bifrost itself writes, each with its one status and message (vectors doorRefusals).
|
||||
public static class DeskRefusals
|
||||
{
|
||||
public const string Unauthenticated = "unauthenticated";
|
||||
public const string BodyForbiddenField = "body_forbidden_field";
|
||||
public const string BodyUnknownField = "body_unknown_field";
|
||||
public const string BodyInvalid = "body_invalid";
|
||||
public const string ForkUnknown = "fork_unknown";
|
||||
public const string InsufficientScope = "insufficient_scope";
|
||||
public const string Forbidden = "forbidden";
|
||||
public const string RequestInvalid = "request_invalid";
|
||||
public const string RequestIdConflict = "request_id_conflict";
|
||||
|
||||
private static readonly Dictionary<string, (int Status, string Error)> Table = new(StringComparer.Ordinal)
|
||||
{
|
||||
[Unauthenticated] = (401, "unauthenticated: a verified session is required"),
|
||||
[BodyForbiddenField] = (400, "body_forbidden_field: answerer and authority are set by the receiver"),
|
||||
[BodyUnknownField] = (400, "body_unknown_field: the body is a closed shape"),
|
||||
[BodyInvalid] = (400, "body_invalid: the body does not satisfy gamecult.fork.answer_request.v0"),
|
||||
[ForkUnknown] = (404, "fork_unknown: no such fork"),
|
||||
[InsufficientScope] = (403, "insufficient_scope: the token lacks the scope this route needs"),
|
||||
[Forbidden] = (403, "forbidden: only Active members may use the desk"),
|
||||
[RequestInvalid] = (400, "request_invalid: the request does not satisfy its document"),
|
||||
[RequestIdConflict] = (409, "request_id_conflict: this request_id was used for a different body"),
|
||||
};
|
||||
|
||||
// fork_too_large (Libby's ruling) is list-only and names its fork, so it is built here, not read from the table.
|
||||
// Not a literal const: the pinned vectors' doorRefusals do not name it yet, and the schema test pins literals to them.
|
||||
public static string ForkTooLarge => "fork_too_large";
|
||||
|
||||
public static int ForkTooLargeStatus => 422;
|
||||
|
||||
public static DeskRefusal ForkTooLargeDocument(string forkId, int order) => new(
|
||||
DeskSchemas.Refusal,
|
||||
ForkTooLarge,
|
||||
order > 0
|
||||
? $"fork_too_large: fork {forkId} (order {order}) is too large for a page; continue with cursor c{order}"
|
||||
: $"fork_too_large: fork {forkId} (order {order}) is too large for a page; the list has reached its end");
|
||||
|
||||
public static bool IsKnown(string code) => Table.ContainsKey(code);
|
||||
|
||||
public static int StatusOf(string code) => Table[code].Status;
|
||||
|
||||
public static DeskRefusal Document(string code) => new(DeskSchemas.Refusal, code, Table[code].Error);
|
||||
}
|
||||
|
||||
public static class DeskUnavailables
|
||||
{
|
||||
public const int Status = 503;
|
||||
|
||||
public static DeskUnavailable Document(int? retryAfterSeconds) => new(
|
||||
DeskSchemas.Unavailable,
|
||||
"unavailable",
|
||||
"unavailable: the outcome is not confirmed, try again with the same request_id",
|
||||
retryAfterSeconds);
|
||||
}
|
||||
|
||||
// Notes are returned only to deciders. For everyone else Bifrost nils every note at the door: the key stays written
|
||||
// (every key written, nil where absent), so the stripped body is still the contract's shape. Cards, outcomes, codes
|
||||
// and counts are untouched; Huginn returns the full record.
|
||||
public static class DeskNotes
|
||||
{
|
||||
public static ForkEntry Strip(ForkEntry entry) =>
|
||||
entry with { Record = entry.Record with { Answers = [.. entry.Record.Answers.Select(a => a with { Note = null })] } };
|
||||
|
||||
public static ForkList Strip(ForkList list) => list with { Forks = [.. list.Forks.Select(Strip)] };
|
||||
}
|
||||
445
src/Bifrost.Web/Features/Desk/DeskEndpoints.cs
Normal file
445
src/Bifrost.Web/Features/Desk/DeskEndpoints.cs
Normal file
|
|
@ -0,0 +1,445 @@
|
|||
using System.Text.Json;
|
||||
using Bifrost.Web.Configuration;
|
||||
using Bifrost.Web.Data;
|
||||
using Bifrost.Web.Features.Oidc;
|
||||
using Microsoft.AspNetCore.Cors.Infrastructure;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.Net.Http.Headers;
|
||||
|
||||
namespace Bifrost.Web.Features.Desk;
|
||||
|
||||
// The fork desk's HTTP edge (fork-card.md, Transport). One catch-all under /api/desk judges, in this order and no
|
||||
// other: the raw target, the bearer, its audience, its scope, Active membership (the body is unread), the body's
|
||||
// shape, the {mind} lookup, the door. Every refusal is a contract document. Bifrost holds no fork state: it passes
|
||||
// Huginn's outcome through, attaches the current card to a stale_fork answer, and says `unavailable` when the door
|
||||
// cannot confirm an outcome.
|
||||
public static class DeskEndpoints
|
||||
{
|
||||
public const string RoutePrefix = "/api/desk";
|
||||
public const string Audience = "bifrost-desk";
|
||||
public const string ReadScope = "desk.read";
|
||||
public const string AnswerScope = "desk.answer";
|
||||
public const string CorsPolicy = "DeskCors";
|
||||
|
||||
public static IServiceCollection AddBifrostDesk(this IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton(provider => new DeskMindRoutes(provider.GetRequiredService<IOptions<DeskOptions>>().Value.Minds));
|
||||
services.AddCors();
|
||||
// Exactly the configured origin, no credentials, and only on the routes that require this policy.
|
||||
services
|
||||
.AddOptions<CorsOptions>()
|
||||
.Configure<IOptions<DeskOptions>>((cors, desk) =>
|
||||
cors.AddPolicy(
|
||||
CorsPolicy,
|
||||
policy => policy
|
||||
.WithOrigins(desk.Value.AllowedOrigin)
|
||||
.WithMethods("GET", "POST")
|
||||
.WithHeaders(HeaderNames.Authorization, HeaderNames.ContentType)));
|
||||
return services;
|
||||
}
|
||||
|
||||
public static IEndpointConventionBuilder MapDesk(this IEndpointRouteBuilder app)
|
||||
{
|
||||
// A configured desk with no credential or door port would serve nothing true: stop startup instead.
|
||||
app.ServiceProvider.GetRequiredService<IDeskCredential>();
|
||||
app.ServiceProvider.GetRequiredService<IDeskDoor>();
|
||||
|
||||
return app.MapMethods(RoutePrefix + "/{**rest}", ["GET", "POST"], HandleAsync)
|
||||
.RequireCors(CorsPolicy)
|
||||
.AllowAnonymous();
|
||||
}
|
||||
|
||||
private static async Task HandleAsync(
|
||||
HttpContext http,
|
||||
IDeskCredential credential,
|
||||
IDeskDoor door,
|
||||
DeskMindRoutes minds,
|
||||
IOptions<DeskOptions> options,
|
||||
BifrostDbContext db)
|
||||
{
|
||||
var cancellationToken = http.RequestAborted;
|
||||
var desk = options.Value;
|
||||
http.Response.Headers.Append(HeaderNames.Vary, "Origin");
|
||||
http.Response.Headers.CacheControl = "no-store";
|
||||
|
||||
// 1. The raw target, never the decoded Request.Path.
|
||||
var rawTarget = http.Features.Get<Microsoft.AspNetCore.Http.Features.IHttpRequestFeature>()?.RawTarget ?? string.Empty;
|
||||
var route = DeskRoute.Parse(http.Request.Method, rawTarget);
|
||||
if (route is null)
|
||||
{
|
||||
await WriteRefusalAsync(http, DeskRefusals.ForkUnknown);
|
||||
return;
|
||||
}
|
||||
|
||||
// 2-4. Bearer, audience, scope.
|
||||
DeskToken? token;
|
||||
try
|
||||
{
|
||||
token = await credential.AuthenticateAsync(http, cancellationToken);
|
||||
}
|
||||
catch (Exception) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
// The bearer could not be judged: neither a pass nor a refusal of the caller.
|
||||
await WriteUnavailableAsync(http, desk);
|
||||
return;
|
||||
}
|
||||
|
||||
if (token is null || !string.Equals(token.Audience, Audience, StringComparison.Ordinal))
|
||||
{
|
||||
await WriteRefusalAsync(http, DeskRefusals.Unauthenticated);
|
||||
return;
|
||||
}
|
||||
|
||||
var scope = route.Kind == DeskRouteKind.Answer ? AnswerScope : ReadScope;
|
||||
if (!token.Scopes.Contains(scope, StringComparer.Ordinal))
|
||||
{
|
||||
await WriteRefusalAsync(http, DeskRefusals.InsufficientScope);
|
||||
return;
|
||||
}
|
||||
|
||||
// 5. Active membership, re-read now; the body has not been touched.
|
||||
Guid? accountId;
|
||||
try
|
||||
{
|
||||
accountId = await OidcEndpoints.ActiveMemberIdAsync(db, token.Subject, cancellationToken);
|
||||
}
|
||||
catch (Exception) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
await WriteUnavailableAsync(http, desk);
|
||||
return;
|
||||
}
|
||||
|
||||
if (accountId is null)
|
||||
{
|
||||
await WriteRefusalAsync(http, DeskRefusals.Forbidden);
|
||||
return;
|
||||
}
|
||||
|
||||
// 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);
|
||||
var verdict = read is null
|
||||
? DeskBodyVerdict.Refuse(DeskRefusals.BodyInvalid)
|
||||
: DeskBodyShape.Judge(read, desk.MaxBodyBytes);
|
||||
if (verdict.RefusalCode is not null)
|
||||
{
|
||||
await WriteRefusalAsync(http, verdict.RefusalCode);
|
||||
return;
|
||||
}
|
||||
|
||||
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);
|
||||
if (mind is null)
|
||||
{
|
||||
await WriteRefusalAsync(http, DeskRefusals.ForkUnknown);
|
||||
return;
|
||||
}
|
||||
|
||||
// 8-10. The door. A decider list outside 1..64 unique ids is a configuration fault: nothing is sent.
|
||||
if (!DeskMindOptions.DecidersWithinBounds(mind.Deciders))
|
||||
{
|
||||
await WriteUnavailableAsync(http, desk);
|
||||
return;
|
||||
}
|
||||
|
||||
var subject = accountId.Value.ToString("D");
|
||||
var context = new DeskDoorContext(mind.Id, desk.Attribution.AuthorityOf(subject), subject, mind.Deciders.ToArray());
|
||||
try
|
||||
{
|
||||
switch (route.Kind)
|
||||
{
|
||||
case DeskRouteKind.List:
|
||||
var listed = await door.ListAsync(mind.Socket, context, listRequest! with { Mind = mind.Id }, cancellationToken);
|
||||
if (listed is DeskListOutcome.Listed(var list))
|
||||
{
|
||||
await WriteJsonAsync(http, 200, IsDecider(context) ? list : DeskNotes.Strip(list));
|
||||
}
|
||||
else if (listed is DeskListOutcome.ForkTooLarge(var largeId, var largeOrder))
|
||||
{
|
||||
await WriteJsonAsync(http, DeskRefusals.ForkTooLargeStatus, DeskRefusals.ForkTooLargeDocument(largeId, largeOrder));
|
||||
}
|
||||
else if (listed is DeskListOutcome.NotListed(var listCode) && DoorMayRefuse(listCode) && listCode != DeskRefusals.RequestIdConflict)
|
||||
{
|
||||
await WriteRefusalAsync(http, ReadListCode(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, IsDecider(context) ? entry : DeskNotes.Strip(entry));
|
||||
}
|
||||
else if (found is DeskReadOutcome.NotFound(var readCode) && DoorMayRefuse(readCode) && readCode != DeskRefusals.RequestIdConflict)
|
||||
{
|
||||
await WriteRefusalAsync(http, ReadListCode(readCode));
|
||||
}
|
||||
else
|
||||
{
|
||||
await WriteUnavailableAsync(http, desk);
|
||||
}
|
||||
|
||||
return;
|
||||
default:
|
||||
await AnswerAsync(http, door, mind, context, body, desk);
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception) when (!cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
await WriteUnavailableAsync(http, desk);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// A note is a decider's own words: only a caller on the admin-set list reads them (visibility ruling c).
|
||||
private static bool IsDecider(DeskDoorContext context) =>
|
||||
context.Deciders.Contains(context.Subject, StringComparer.Ordinal);
|
||||
|
||||
// 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) &&
|
||||
DeskRefusals.IsKnown(code);
|
||||
|
||||
// request_id_conflict is the answer's alone (Libby): a read or list carries no request_id, so the door saying it
|
||||
// there is a door fault and the edge says `unavailable`.
|
||||
// A read or list sends no body. A door that refuses one for its body (an `authority` field among them) is
|
||||
// refusing the request, which is request_invalid; it is not an outage.
|
||||
private static string ReadListCode(string code) =>
|
||||
code is DeskRefusals.BodyForbiddenField or DeskRefusals.BodyUnknownField or DeskRefusals.BodyInvalid
|
||||
? DeskRefusals.RequestInvalid
|
||||
: code;
|
||||
|
||||
// At most `cap` bytes. Null when the body is longer, judged by Content-Length first and then while reading.
|
||||
private static async Task<byte[]?> ReadBodyAsync(HttpRequest request, int cap, CancellationToken cancellationToken)
|
||||
{
|
||||
if (request.ContentLength > cap)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using var buffer = new MemoryStream();
|
||||
var chunk = new byte[4096];
|
||||
int count;
|
||||
while ((count = await request.Body.ReadAsync(chunk, cancellationToken)) > 0)
|
||||
{
|
||||
if (buffer.Length + count > cap)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
buffer.Write(chunk, 0, count);
|
||||
}
|
||||
|
||||
return buffer.ToArray();
|
||||
}
|
||||
|
||||
private static Task WriteRefusalAsync(HttpContext http, string code) =>
|
||||
WriteJsonAsync(http, DeskRefusals.StatusOf(code), DeskRefusals.Document(code));
|
||||
|
||||
private static async Task WriteUnavailableAsync(HttpContext http, DeskOptions desk)
|
||||
{
|
||||
http.Response.Headers.RetryAfter = desk.RetryAfterSeconds.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
await WriteJsonAsync(http, DeskUnavailables.Status, DeskUnavailables.Document(desk.RetryAfterSeconds));
|
||||
}
|
||||
|
||||
private static async Task WriteJsonAsync<T>(HttpContext http, int status, T document)
|
||||
{
|
||||
http.Response.StatusCode = status;
|
||||
http.Response.ContentType = "application/json; charset=utf-8";
|
||||
await JsonSerializer.SerializeAsync(http.Response.Body, document, DeskJson.Options, http.RequestAborted);
|
||||
}
|
||||
}
|
||||
|
||||
// The one place a stored outcome becomes an HTTP status. fork-card.md prose says 200 for any stored outcome; the
|
||||
// vectors (results[].httpStatus) say a Refused answer carries its refusal's status, and the vectors are the check.
|
||||
public static class DeskStatus
|
||||
{
|
||||
public const string StaleFork = "stale_fork";
|
||||
|
||||
private static readonly Dictionary<string, int> RefusedStatus = new(StringComparer.Ordinal)
|
||||
{
|
||||
[StaleFork] = 409,
|
||||
["not_a_decider"] = 403,
|
||||
["fork_closed"] = 409,
|
||||
["choice_invalid"] = 400,
|
||||
["bad_retraction"] = 400,
|
||||
["already_retracted"] = 409,
|
||||
};
|
||||
|
||||
// Null when the door sent an outcome or a refusal code this contract does not name: Bifrost then cannot vouch
|
||||
// for it and says `unavailable`.
|
||||
public static int? Of(AnswerResult result) => result.Answer.Outcome switch
|
||||
{
|
||||
"Counted" or "Revision" or "Retraction" => 200,
|
||||
"Refused" when result.Answer.Code is { } code && RefusedStatus.TryGetValue(code, out var status) => status,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
public enum DeskRouteKind
|
||||
{
|
||||
List,
|
||||
Read,
|
||||
Answer,
|
||||
}
|
||||
|
||||
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 = string.Empty;
|
||||
var split = path.IndexOf('?');
|
||||
if (split >= 0)
|
||||
{
|
||||
query = path[(split + 1)..];
|
||||
path = path[..split];
|
||||
}
|
||||
|
||||
if (!path.StartsWith(DeskEndpoints.RoutePrefix + "/", StringComparison.Ordinal))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var segments = path[(DeskEndpoints.RoutePrefix.Length + 1)..].Split('/');
|
||||
return (method, segments) switch
|
||||
{
|
||||
("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>, 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<string>(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;
|
||||
}
|
||||
}
|
||||
84
src/Bifrost.Web/Features/Desk/DeskMindRoutes.cs
Normal file
84
src/Bifrost.Web/Features/Desk/DeskMindRoutes.cs
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
using System.Text;
|
||||
using Bifrost.Web.Configuration;
|
||||
|
||||
namespace Bifrost.Web.Features.Desk;
|
||||
|
||||
// The {mind} segment of a desk route (fork-card.md M1). The raw segment is percent-decoded once and compared,
|
||||
// ordinally, with the configured ids: no case folding, trimming or normalisation, and a decoding failure is a miss.
|
||||
// The segment is never joined into a path, a socket name or a query, so a value off the list opens nothing.
|
||||
public sealed class DeskMindRoutes
|
||||
{
|
||||
private static readonly UTF8Encoding StrictUtf8 = new(false, true);
|
||||
|
||||
private readonly Dictionary<string, DeskMindOptions> byId;
|
||||
|
||||
public DeskMindRoutes(IEnumerable<DeskMindOptions> minds)
|
||||
{
|
||||
byId = new Dictionary<string, DeskMindOptions>(StringComparer.Ordinal);
|
||||
foreach (var mind in minds)
|
||||
{
|
||||
byId.Add(mind.Id, mind);
|
||||
}
|
||||
}
|
||||
|
||||
public DeskMindOptions? Resolve(string rawSegment) =>
|
||||
TryDecode(rawSegment, out var id) && byId.TryGetValue(id, out var mind) ? mind : null;
|
||||
|
||||
// One pass of percent-decoding. Uri.UnescapeDataString is not used: it leaves a bad escape in place and turns
|
||||
// bytes that are not UTF-8 into U+FFFD instead of failing.
|
||||
internal static bool TryDecode(string raw, out string decoded)
|
||||
{
|
||||
decoded = string.Empty;
|
||||
var bytes = new List<byte>(raw.Length);
|
||||
for (var i = 0; i < raw.Length; i++)
|
||||
{
|
||||
var c = raw[i];
|
||||
if (c == '%')
|
||||
{
|
||||
if (i + 2 >= raw.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!TryHex(raw[i + 1], out var high) || !TryHex(raw[i + 2], out var low))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
bytes.Add((byte)((high << 4) | low));
|
||||
i += 2;
|
||||
}
|
||||
else if (c > 0x7f)
|
||||
{
|
||||
// A raw request target is ASCII; anything else is not a segment this desk issues.
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
bytes.Add((byte)c);
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
decoded = StrictUtf8.GetString(bytes.ToArray());
|
||||
return true;
|
||||
}
|
||||
catch (DecoderFallbackException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryHex(char c, out int value)
|
||||
{
|
||||
value = c switch
|
||||
{
|
||||
>= '0' and <= '9' => c - '0',
|
||||
>= 'a' and <= 'f' => c - 'a' + 10,
|
||||
>= 'A' and <= 'F' => c - 'A' + 10,
|
||||
_ => -1,
|
||||
};
|
||||
return value >= 0;
|
||||
}
|
||||
}
|
||||
67
src/Bifrost.Web/Features/Desk/DeskPorts.cs
Normal file
67
src/Bifrost.Web/Features/Desk/DeskPorts.cs
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
namespace Bifrost.Web.Features.Desk;
|
||||
|
||||
// The two ports the desk stands on. Bifrost owns the edge's order and judgments; these two own what is not
|
||||
// Bifrost's yet: validating a bearer token (the OIDC validation scheme) and speaking to a Mind's Huginn on the
|
||||
// peer-checked door. No production implementation is registered here: with the Desk section configured and a port
|
||||
// missing, startup fails (DeskEndpoints.MapDesk) instead of serving.
|
||||
|
||||
// What a validated bearer token claims. The credential port verifies the token; the desk judges audience, scope and
|
||||
// membership. A null Subject or Audience means the token did not carry one.
|
||||
public sealed record DeskToken(string? Subject, string? Audience, IReadOnlyCollection<string> Scopes);
|
||||
|
||||
public interface IDeskCredential
|
||||
{
|
||||
// Null when the request carries no valid bearer token.
|
||||
ValueTask<DeskToken?> AuthenticateAsync(HttpContext context, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
// The envelope sent with every answer, read and list call (fork-card.md M5), under the contract's names, built by
|
||||
// Bifrost alone: the route's configured Mind id, the verified account's authority (Operator, Steward or Member),
|
||||
// the account id, and the admin-set decider list of that Mind (1 to 64 unique ids). Nothing in the request sets any
|
||||
// of it, and Huginn keeps no copy of the list.
|
||||
public sealed record DeskDoorContext(string Mind, string Authority, string Subject, IReadOnlyList<string> Deciders);
|
||||
|
||||
public abstract record DeskAnswerOutcome
|
||||
{
|
||||
// Huginn stored an outcome (Counted, Revision, Retraction or Refused) and returned its document.
|
||||
public sealed record Answered(AnswerResult Result) : DeskAnswerOutcome;
|
||||
|
||||
// Nothing stored: Huginn refused with one of the contract's refusal codes.
|
||||
public sealed record NotStored(string Code) : DeskAnswerOutcome;
|
||||
}
|
||||
|
||||
public abstract record DeskReadOutcome
|
||||
{
|
||||
public sealed record Found(ForkEntry Entry) : 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;
|
||||
|
||||
// The next fork is too large for any page: the page holds nothing past the cursor. The client continues with
|
||||
// cursor c<Order>; at Order 0 it has reached the end. List only: no other call can be refused this way.
|
||||
public sealed record ForkTooLarge(string ForkId, int Order) : DeskListOutcome;
|
||||
}
|
||||
|
||||
public interface IDeskDoor
|
||||
{
|
||||
// The body is exactly the bytes the client sent. Any exception means the outcome is not confirmed.
|
||||
Task<DeskAnswerOutcome> AnswerAsync(
|
||||
string socket, DeskDoorContext context, ReadOnlyMemory<byte> body, CancellationToken cancellationToken);
|
||||
|
||||
// The entry for one fork, its card built and hashed by Huginn.
|
||||
Task<DeskReadOutcome> 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<DeskListOutcome> ListAsync(
|
||||
string socket, DeskDoorContext context, DeskListRequest request, CancellationToken cancellationToken);
|
||||
}
|
||||
|
|
@ -117,18 +117,22 @@ public static class OidcEndpoints
|
|||
return Results.Json(claims);
|
||||
}
|
||||
|
||||
/// <summary>The one reading of "this subject is still an Active member", shared by the token and userinfo endpoints and the logout reconciler.</summary>
|
||||
internal static async Task<bool> IsStillActiveMemberAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken)
|
||||
/// <summary>The one reading of "this subject is still an Active member", shared by the token and userinfo endpoints, the logout reconciler and the fork desk.</summary>
|
||||
internal static async Task<bool> IsStillActiveMemberAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken) =>
|
||||
await ActiveMemberIdAsync(db, subject, cancellationToken) is not null;
|
||||
|
||||
/// <summary>The account id of the subject when it is an Active member now, else null. Re-read on every call.</summary>
|
||||
internal static async Task<Guid?> ActiveMemberIdAsync(BifrostDbContext db, string? subject, CancellationToken cancellationToken)
|
||||
{
|
||||
if (!Guid.TryParse(subject, out var accountId))
|
||||
{
|
||||
return false;
|
||||
return null;
|
||||
}
|
||||
|
||||
var account = await db.UserAccounts.AsNoTracking()
|
||||
.Include(x => x.Membership)
|
||||
.SingleOrDefaultAsync(x => x.Id == accountId, cancellationToken);
|
||||
return new CurrentBifrostActor(true, account).IsActiveMember;
|
||||
return new CurrentBifrostActor(true, account).IsActiveMember ? accountId : null;
|
||||
}
|
||||
|
||||
private static IResult Deny(string error, string description) =>
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ public sealed class StartupConfigurationValidator(
|
|||
IOptions<HeimdallOptions> heimdallOptions,
|
||||
IOptions<StripeOptions> stripeOptions,
|
||||
IOptions<BifrostHostOptions> hostOptions,
|
||||
IOptions<ConceptVoteOptions> conceptVoteOptions)
|
||||
IOptions<ConceptVoteOptions> conceptVoteOptions,
|
||||
IOptions<DeskOptions> deskOptions)
|
||||
{
|
||||
public void Validate()
|
||||
{
|
||||
|
|
@ -45,6 +46,8 @@ public sealed class StartupConfigurationValidator(
|
|||
failures.Add("ConceptVotes:MaxTrackedKeys must be at least 1.");
|
||||
}
|
||||
|
||||
ValidateDesk(deskOptions.Value, failures);
|
||||
|
||||
if (hostEnvironment.IsDevelopment() || hostEnvironment.IsEnvironment("Testing"))
|
||||
{
|
||||
Refuse(failures);
|
||||
|
|
@ -116,6 +119,106 @@ public sealed class StartupConfigurationValidator(
|
|||
Refuse(failures);
|
||||
}
|
||||
|
||||
// Checked in every environment: a bad Mind list or decider id would otherwise pass startup and misroute or
|
||||
// mis-attribute answers. Account existence is a request-time question, not a startup one.
|
||||
private void ValidateDesk(DeskOptions desk, List<string> failures)
|
||||
{
|
||||
if (!desk.IsConfigured)
|
||||
{
|
||||
if (configuration.GetSection(DeskOptions.SectionName).Exists())
|
||||
{
|
||||
failures.Add("Desk:Minds must list at least one Mind when the Desk section exists.");
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Uri.TryCreate(desk.AllowedOrigin, UriKind.Absolute, out var origin) ||
|
||||
origin.Scheme is not ("http" or "https") ||
|
||||
!string.Equals(desk.AllowedOrigin, origin.GetLeftPart(UriPartial.Authority), StringComparison.Ordinal))
|
||||
{
|
||||
failures.Add("Desk:AllowedOrigin must be one http(s) origin: scheme, host and optional port, no path.");
|
||||
}
|
||||
|
||||
if (desk.MaxBodyBytes < 1)
|
||||
{
|
||||
failures.Add("Desk:MaxBodyBytes must be at least 1.");
|
||||
}
|
||||
|
||||
if (desk.RetryAfterSeconds < 1)
|
||||
{
|
||||
failures.Add("Desk:RetryAfterSeconds must be at least 1.");
|
||||
}
|
||||
|
||||
var ids = new HashSet<string>(StringComparer.Ordinal);
|
||||
var sockets = new HashSet<string>(StringComparer.Ordinal);
|
||||
for (var i = 0; i < desk.Minds.Count; i++)
|
||||
{
|
||||
var mind = desk.Minds[i];
|
||||
if (string.IsNullOrWhiteSpace(mind.Id))
|
||||
{
|
||||
failures.Add($"Desk:Minds:{i}:Id must not be blank.");
|
||||
}
|
||||
else if (!ids.Add(mind.Id))
|
||||
{
|
||||
failures.Add($"Desk:Minds:{i}:Id repeats an earlier Mind id.");
|
||||
}
|
||||
|
||||
if (!Path.IsPathFullyQualified(mind.Socket))
|
||||
{
|
||||
failures.Add($"Desk:Minds:{i}:Socket must be an absolute path.");
|
||||
}
|
||||
else if (!sockets.Add(mind.Socket))
|
||||
{
|
||||
failures.Add($"Desk:Minds:{i}:Socket repeats an earlier Mind's socket.");
|
||||
}
|
||||
|
||||
if (mind.Deciders.Count is < 1 or > DeskMindOptions.MaxDeciders)
|
||||
{
|
||||
failures.Add($"Desk:Minds:{i}:Deciders must hold 1 to {DeskMindOptions.MaxDeciders} account ids.");
|
||||
}
|
||||
|
||||
var deciders = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var decider in mind.Deciders)
|
||||
{
|
||||
if (!IsLowercaseGuid(decider))
|
||||
{
|
||||
failures.Add($"Desk:Minds:{i}:Deciders entries must be lowercase D-format account ids.");
|
||||
}
|
||||
else if (!deciders.Add(decider))
|
||||
{
|
||||
failures.Add($"Desk:Minds:{i}:Deciders repeats an account id.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var attribution = desk.Attribution;
|
||||
if (!string.IsNullOrEmpty(attribution.Operator) && !IsLowercaseGuid(attribution.Operator))
|
||||
{
|
||||
failures.Add("Desk:Attribution:Operator must be a lowercase D-format account id.");
|
||||
}
|
||||
|
||||
var stewards = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var steward in attribution.Stewards)
|
||||
{
|
||||
if (!IsLowercaseGuid(steward))
|
||||
{
|
||||
failures.Add("Desk:Attribution:Stewards entries must be lowercase D-format account ids.");
|
||||
}
|
||||
else if (!stewards.Add(steward))
|
||||
{
|
||||
failures.Add("Desk:Attribution:Stewards repeats an account id.");
|
||||
}
|
||||
else if (string.Equals(steward, attribution.Operator, StringComparison.Ordinal))
|
||||
{
|
||||
failures.Add("Desk:Attribution:Operator must not also be a steward.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsLowercaseGuid(string? value) =>
|
||||
Guid.TryParseExact(value, "D", out var guid) && string.Equals(value, guid.ToString("D"), StringComparison.Ordinal);
|
||||
|
||||
private static void Refuse(List<string> failures)
|
||||
{
|
||||
if (failures.Count > 0)
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ using Bifrost.Web.Data;
|
|||
using Bifrost.Web.Domain;
|
||||
using Bifrost.Web.Features.Bridge;
|
||||
using Bifrost.Web.Features.ConceptVotes;
|
||||
using Bifrost.Web.Features.Desk;
|
||||
using Bifrost.Web.Features.GitHub;
|
||||
using Bifrost.Web.Features.Heimdall;
|
||||
using Bifrost.Web.Features.Membership;
|
||||
|
|
@ -76,6 +77,10 @@ builder.Services
|
|||
.AddOptions<ConceptVoteOptions>()
|
||||
.BindConfiguration(ConceptVoteOptions.SectionName);
|
||||
|
||||
builder.Services
|
||||
.AddOptions<DeskOptions>()
|
||||
.BindConfiguration(DeskOptions.SectionName);
|
||||
|
||||
builder.Services.AddAntiforgery(options =>
|
||||
{
|
||||
options.Cookie.Name = BifrostCookies.Antiforgery;
|
||||
|
|
@ -252,6 +257,13 @@ if (oidcOptions is not null)
|
|||
builder.Services.AddBifrostOidc(oidcOptions);
|
||||
}
|
||||
|
||||
// The desk is mapped only when the Desk section exists, and a configured desk needs its credential and door ports.
|
||||
var deskConfigured = builder.Configuration.GetSection(DeskOptions.SectionName).Exists();
|
||||
if (deskConfigured)
|
||||
{
|
||||
builder.Services.AddBifrostDesk();
|
||||
}
|
||||
|
||||
var app = builder.Build();
|
||||
var appJsonSerializerOptions = CreateAppJsonSerializerOptions();
|
||||
|
||||
|
|
@ -300,6 +312,11 @@ if (oidcOptions is not null)
|
|||
app.MapBifrostOidc();
|
||||
}
|
||||
|
||||
if (deskConfigured)
|
||||
{
|
||||
app.MapDesk();
|
||||
}
|
||||
|
||||
app.MapPost("/github/webhooks", async (
|
||||
HttpRequest request,
|
||||
GitHubWebhookService gitHubWebhookService,
|
||||
|
|
|
|||
Loading…
Reference in a new issue