cultnet-cs: refuse a peer raw put whose storedAt is no stamp (raw-put-refuse-cs)
Exact-shape stamp check (stored-at-stamp vector); judged after the write authority and before any shard or forward; message_invalid field document, nothing stored or minted. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
47ae4796be
commit
c751cb1326
4 changed files with 164 additions and 0 deletions
|
|
@ -1055,6 +1055,13 @@ namespace GameCult.Networking
|
|||
var key = new CultRecordKey(message.Document.RecordKey);
|
||||
var descriptor = _documents.ResolveDescriptorForRawDocument(message.Document);
|
||||
authorize?.Invoke(descriptor.SchemaId, key);
|
||||
// A peer's put is judged for its stamp after its authority and before any shard is asked (so it is never forwarded):
|
||||
// the cache would mint a stamp for one that is no stamp, and a refused put stores and mints nothing.
|
||||
if (authorize != null && !CultNetStoredAtStamp.IsStamp(message.Document.StoredAt))
|
||||
{
|
||||
throw new CultNetStoredAtStampException();
|
||||
}
|
||||
|
||||
var shard = ResolveShardInternal(descriptor, key);
|
||||
EnsurePrimary(shard, descriptor.SchemaId, key, message.ShardEpoch);
|
||||
var document = _documents.DeserializeRawDocument(message.Document);
|
||||
|
|
|
|||
|
|
@ -475,6 +475,11 @@ namespace GameCult.Networking
|
|||
_server.Logger.LogWarning($"CultNet raw put refused: {ex.Message}");
|
||||
Refuse(peer, write, CultNetErrorMessage.ForRemoteWriteRefused(ex.Request, ex.Reason));
|
||||
}
|
||||
catch (CultNetStoredAtStampException ex)
|
||||
{
|
||||
_server.Logger.LogWarning($"CultNet raw put refused: {ex.Message}");
|
||||
Refuse(peer, write, CultNetErrorMessage.ForMessageInvalid("document", "document.storedAt is not a stamp"));
|
||||
}
|
||||
catch (CultNetShardAuthorityException ex)
|
||||
{
|
||||
bool forwarded;
|
||||
|
|
|
|||
58
src/GameCult.Networking/CultNetStoredAtStamp.cs
Normal file
58
src/GameCult.Networking/CultNetStoredAtStamp.cs
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
#nullable enable
|
||||
using System;
|
||||
|
||||
namespace GameCult.Networking
|
||||
{
|
||||
// The one shape a peer's storedAt must have: RFC 3339 date-time, YYYY-MM-DDThh:mm:ss, an optional fraction of 1 to 9 digits,
|
||||
// then Z or +hh:mm / -hh:mm. Uppercase T and Z, ASCII digits, no whitespace, a real calendar date, seconds 00-59, years
|
||||
// 0001-9999, offset hours 00-23 and minutes 00-59. Checked by shape and range, never by DateTimeOffset.TryParse, which is
|
||||
// culture-aware and takes far more than this (tests/vectors/stored-at-stamp, variants:ruling:raw-put-without-stamp-refused).
|
||||
internal static class CultNetStoredAtStamp
|
||||
{
|
||||
public static bool IsStamp(string? text)
|
||||
{
|
||||
if (text == null || text.Length < 20) return false;
|
||||
if (!Digits(text, 0, 4, out var year) || text[4] != '-' || !Digits(text, 5, 2, out var month) || text[7] != '-'
|
||||
|| !Digits(text, 8, 2, out var day) || text[10] != 'T' || !Digits(text, 11, 2, out var hour) || text[13] != ':'
|
||||
|| !Digits(text, 14, 2, out var minute) || text[16] != ':' || !Digits(text, 17, 2, out var second))
|
||||
return false;
|
||||
if (year < 1 || month is < 1 or > 12 || day < 1 || day > DateTime.DaysInMonth(year, month)
|
||||
|| hour > 23 || minute > 59 || second > 59)
|
||||
return false;
|
||||
|
||||
var i = 19;
|
||||
if (text[i] == '.')
|
||||
{
|
||||
var start = ++i;
|
||||
while (i < text.Length && IsDigit(text[i])) i++;
|
||||
if (i - start is < 1 or > 9) return false;
|
||||
}
|
||||
|
||||
if (i >= text.Length) return false;
|
||||
if (text[i] == 'Z') return i == text.Length - 1;
|
||||
return text.Length - i == 6 && (text[i] == '+' || text[i] == '-')
|
||||
&& Digits(text, i + 1, 2, out var offsetHour) && text[i + 3] == ':' && Digits(text, i + 4, 2, out var offsetMinute)
|
||||
&& offsetHour <= 23 && offsetMinute <= 59;
|
||||
}
|
||||
|
||||
private static bool IsDigit(char c) => c is >= '0' and <= '9';
|
||||
|
||||
private static bool Digits(string text, int start, int count, out int value)
|
||||
{
|
||||
value = 0;
|
||||
for (var i = start; i < start + count; i++)
|
||||
{
|
||||
if (i >= text.Length || !IsDigit(text[i])) return false;
|
||||
value = value * 10 + (text[i] - '0');
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// A peer's raw put whose storedAt is no stamp: refused message_invalid, field document, nothing stored or minted.
|
||||
internal sealed class CultNetStoredAtStampException : Exception
|
||||
{
|
||||
public CultNetStoredAtStampException() : base("a raw put document must carry a storedAt stamp") { }
|
||||
}
|
||||
}
|
||||
|
|
@ -405,6 +405,100 @@ namespace GameCult.Networking.Tests
|
|||
Assert.That(rig.Logger.Errors, Is.Empty, "a null decision is a refusal, not a fault");
|
||||
}
|
||||
|
||||
// ---- a peer's storedAt must be a stamp (tests/vectors/stored-at-stamp, variants:ruling:raw-put-without-stamp-refused) ----
|
||||
|
||||
private static (string Text, bool Parses)[] StampVectors()
|
||||
{
|
||||
var dir = new System.IO.DirectoryInfo(TestContext.CurrentContext.TestDirectory);
|
||||
while (dir != null && !System.IO.Directory.Exists(System.IO.Path.Combine(dir.FullName, "tests", "vectors"))) dir = dir.Parent;
|
||||
var bytes = System.IO.File.ReadAllBytes(System.IO.Path.Combine(dir!.FullName, "tests", "vectors", "stored-at-stamp", "stamps.msgpack"));
|
||||
return MessagePack.MessagePackSerializer.Deserialize<object[]>(bytes)
|
||||
.Select(row => (Row: (object[])row, 0)).Select(r => ((string)r.Row[0], (bool)r.Row[1])).ToArray();
|
||||
}
|
||||
|
||||
// A blank stamp is a frame that does not read (write-receipt.md, vector blankFields: field "message"); any other text
|
||||
// that is no stamp is message_invalid on field "document". Both are refused before the store is asked.
|
||||
private static bool IsBlankText(string text) => text.All(c => char.IsWhiteSpace(c));
|
||||
|
||||
[Test]
|
||||
public async Task EveryStampVectorRowIsJudgedThroughTheRealServerHandler()
|
||||
{
|
||||
using var wire = new WirePair();
|
||||
var rig = Build(new RecordingAuthority(_ => CultNetRemoteWriteDecision.Grant()), peer: wire.Peer);
|
||||
var rows = StampVectors();
|
||||
Assert.That(rows, Has.Length.GreaterThan(30));
|
||||
var n = 0;
|
||||
foreach (var (text, parses) in rows)
|
||||
{
|
||||
var key = new CultRecordKey($"tests:stamp:{n++}");
|
||||
var put = rig.PutOf(key, "peer");
|
||||
put.Document.StoredAt = text;
|
||||
var publishedBefore = rig.Published.Count;
|
||||
var logBefore = rig.LogLength;
|
||||
|
||||
await rig.Put(put);
|
||||
|
||||
if (parses)
|
||||
{
|
||||
Assert.That(rig.TextOf(key), Is.EqualTo("peer"), $"stamp '{text}' is admitted");
|
||||
Assert.That(wire.Errors, Is.Empty, $"stamp '{text}' is not answered with an error");
|
||||
continue;
|
||||
}
|
||||
|
||||
var reply = await wire.NextErrorAsync();
|
||||
Assert.That(reply.Code, Is.EqualTo("message_invalid"), $"'{text}'");
|
||||
Assert.That(reply.Details!.Field, Is.EqualTo(IsBlankText(text) ? "message" : "document"), $"'{text}'");
|
||||
Assert.That(rig.TextOf(key), Is.Null, $"'{text}' stored nothing");
|
||||
Assert.That(rig.Cache.Get<NetworkSchemaNote>(key), Is.Null, $"'{text}' minted nothing");
|
||||
Assert.That(rig.Published, Has.Count.EqualTo(publishedBefore), $"'{text}' published nothing");
|
||||
Assert.That(rig.LogLength, Is.EqualTo(logBefore), $"'{text}' logged nothing");
|
||||
Assert.That(wire.Errors, Is.Empty, "one reply per refused write");
|
||||
}
|
||||
|
||||
var fresh = new CultRecordKey("tests:stamp:after");
|
||||
await rig.Put(rig.PutOf(fresh, "after"));
|
||||
Assert.That(rig.TextOf(fresh), Is.EqualTo("after"), "the store stays writable after the refusals");
|
||||
Assert.That(wire.Errors, Is.Empty);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AnUngrantedPeerIsToldItIsNotAuthorizedBeforeItsStampIsJudgedAndAnAliasAsksTheCanonicalId()
|
||||
{
|
||||
using var wire = new WirePair();
|
||||
var authority = new RecordingAuthority(_ => CultNetRemoteWriteDecision.Refuse("no"));
|
||||
var rig = Build(authority, peer: wire.Peer);
|
||||
var put = rig.PutOf(KeyA, "peer");
|
||||
put.Document.StoredAt = "yesterday";
|
||||
put.Document.SchemaId = "runtime.generated.network-note.ui.42";
|
||||
|
||||
await rig.Put(put);
|
||||
var reply = await wire.NextErrorAsync();
|
||||
|
||||
Assert.That(reply.Code, Is.EqualTo("write_not_authorized"), "authority first, the stamp is not judged");
|
||||
Assert.That(authority.Requests.Single().SchemaId, Is.EqualTo(rig.SchemaId));
|
||||
Assert.That(rig.TextOf(KeyA), Is.Null);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AGarbageStampIsNeverForwardedToThePrimary()
|
||||
{
|
||||
using var wire = new WirePair();
|
||||
var forwarder = new CountingForwarder();
|
||||
var rig = Build(new RecordingAuthority(_ => CultNetRemoteWriteDecision.Grant()), primary: false, forwarder, wire.Peer);
|
||||
var put = rig.PutOf(KeyA, "peer");
|
||||
put.Document.StoredAt = "2026-06-25T00:00:00";
|
||||
|
||||
await rig.Put(put);
|
||||
var reply = await wire.NextErrorAsync();
|
||||
|
||||
Assert.That(reply.Code, Is.EqualTo("message_invalid"));
|
||||
Assert.That(reply.Details!.Field, Is.EqualTo("document"));
|
||||
Assert.That(forwarder.Puts, Is.EqualTo(0));
|
||||
|
||||
await rig.Put(rig.PutOf(KeyA, "peer"));
|
||||
Assert.That(forwarder.Puts, Is.EqualTo(1), "a stamped put still forwards");
|
||||
}
|
||||
|
||||
private sealed class RecordingAuthority : ICultNetRemoteWriteAuthority
|
||||
{
|
||||
private readonly Func<CultNetRemoteWriteRequest, CultNetRemoteWriteDecision> _decide;
|
||||
|
|
|
|||
Loading…
Reference in a new issue