No manifest exemption: one entry decides one value (ruling trailing-bytes-refuse); mesh reads through the production binding; per-path tail tests; TS decodeManifest refuses tails

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Libby 2026-11-12 02:06:56 +00:00
commit 2dbb41dee7
13 changed files with 216 additions and 69 deletions

View file

@ -99,16 +99,6 @@ namespace GameCult.Caching.Tests
}
}
[Test]
public void TheBoundedEntryKeepsTheDepthBoundAndToleratesATail()
{
foreach (var (file, _) in Cases())
Assert.That(CultDocumentMessagePackSerialization.DeserializeBoundedUntyped(typeof(UnionSurface), VectorFiles.Committed(Vector, file), Registry), Is.TypeOf<UnionSurface>(), file);
var deep = VectorFiles.Committed(Vector, "depth-past-limit.msgpack");
Assert.That(Message(() => CultDocumentMessagePackSerialization.DeserializeBoundedUntyped(typeof(UnionSurface), deep, Registry)), Does.Contain($"the limit is {Limit}"));
}
[Test]
public void StoreLoadRefuses()
{
@ -117,7 +107,7 @@ namespace GameCult.Caching.Tests
try
{
var snapshot = CultDocumentMessagePackSerialization.DeserializeSnapshot(VectorFiles.Committed(Vector, "union-surface.cc"));
snapshot.Records[0].Payload = VectorFiles.Committed(Vector, "bytes-after-nil.msgpack");
snapshot.Records[0].Payload = Base.Concat(new byte[] { 0xc0 }).ToArray();
var scratch = Path.Combine(work, "tail.cc");
File.WriteAllBytes(scratch, CultDocumentMessagePackSerialization.SerializeSnapshot(snapshot));
var load = Message(() => CultCacheMessagePack.Create(scratch, new CultCacheOpenOptions { Registry = Registry }).Dispose());
@ -129,6 +119,57 @@ namespace GameCult.Caching.Tests
}
}
// A directory store names a page by the SHA-256 of its bytes and its manifest commits to that hash: the page holding the
// payload is rewritten with a tail, renamed, and the manifest told its new hash, so the store is well formed and only the payload is wrong.
[Test]
public async System.Threading.Tasks.Task DirectoryLoadPageRefuses()
{
var folder = Path.Combine(Path.GetTempPath(), $"cultlib-bytesafter-dir-{Guid.NewGuid():N}");
Directory.CreateDirectory(folder);
try
{
var path = Path.Combine(folder, "tail.cc");
var options = new CultCacheOpenOptions { Registry = Registry, UseDirectoryStore = true, StoreFlushOnDispose = true };
using (var writer = CultCacheMessagePack.Create(path, options))
{
var value = CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(UnionSurface), Base, Registry);
await writer.UpsertAsync(typeof(UnionSurface), value, new CultRecordKey("surface"));
await writer.FlushAsync();
}
var rehashed = new System.Collections.Generic.List<(byte[] Old, byte[] New)>();
foreach (var file in Directory.EnumerateFiles(folder, "*.msgpack", SearchOption.AllDirectories).ToArray())
{
var bytes = File.ReadAllBytes(file);
if (bytes.AsSpan().IndexOf(Base) < 0) continue;
var page = CultDocumentMessagePackSerialization.DeserializePersistedRecord(bytes);
page.Payload = Base.Concat(new byte[] { 0xc0 }).ToArray();
var forged = CultDocumentMessagePackSerialization.SerializePersistedRecord(page);
File.Delete(file);
File.WriteAllBytes(Path.Combine(Path.GetDirectoryName(file)!, Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(forged)).ToLowerInvariant() + ".msgpack"), forged);
rehashed.Add((System.Security.Cryptography.SHA256.HashData(bytes), System.Security.Cryptography.SHA256.HashData(forged)));
}
Assert.That(rehashed, Is.Not.Empty, "the record page was found");
foreach (var file in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).Where(f => !f.EndsWith(".msgpack", StringComparison.Ordinal)).ToArray())
{
var bytes = File.ReadAllBytes(file);
foreach (var (old, @new) in rehashed)
for (var at = bytes.AsSpan().IndexOf(old); at >= 0; at = bytes.AsSpan().IndexOf(old)) @new.CopyTo(bytes, at);
File.WriteAllBytes(file, bytes);
}
var thrown = Assert.CatchAsync(async () => { using var cache = await CultCacheMessagePack.OpenAsync(path, new CultCacheOpenOptions { Registry = Registry, UseDirectoryStore = true, ReadOnly = true }); });
var chain = "";
for (var e = thrown; e != null; e = e.InnerException) chain += e.Message + "\n";
Assert.That(chain, Does.Contain($"1 {Clause}"));
}
finally
{
Directory.Delete(folder, recursive: true);
}
}
public sealed class TwoValueFormatter : global::MessagePack.Formatters.IMessagePackFormatter<TwoValues>
{
public void Serialize(ref MessagePackWriter writer, TwoValues value, MessagePackSerializerOptions options)

View file

@ -0,0 +1,61 @@
using System;
using System.Linq;
using System.Reflection;
using FluentAssertions;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using GameCult.Networking;
using NUnit.Framework;
namespace GameCult.Mesh.Tests;
// The mesh's typed reads of a raw record decode the payload through the one-value rule: a tail is refused, never ignored.
public class BytesAfterPathTests
{
private const string Clause = "bytes after its first MessagePack value";
private static CultNetRawDocumentRecord WithTail(CultMeshCdnArtifactManifest manifest)
{
var payload = CultDocumentMessagePackSerialization.SerializeUntyped(manifest, typeof(CultMeshCdnArtifactManifest)).Concat(new byte[] { 0xc0 }).ToArray();
return new CultNetRawDocumentRecord
{
SchemaId = CultDocumentRegistry.Shared.GetRequired<CultMeshCdnArtifactManifest>().SchemaId,
RecordKey = "k",
StoredAt = "1970-01-01T00:00:00.000Z",
Payload = payload,
};
}
private static CultMeshCdnArtifactManifest Manifest() => new() { ArtifactId = "a", Version = "1", ContentHash = "h" };
private static string Refusal(Action read)
{
var thrown = Assert.Catch(read)!;
return thrown is TargetInvocationException { InnerException: { } inner } ? inner.ToString() : thrown.ToString();
}
[Test]
public void ASnapshotDecodeThroughABindingRefusesATail()
{
var registry = CultMeshCdn.CreateDocumentRegistry();
var snapshot = new CultNetSnapshotResponseRawMessage { Documents = new[] { WithTail(Manifest()) } };
Refusal(() => CultMesh.DecodeSnapshotDocuments<CultMeshCdnArtifactManifest>(snapshot, registry)).Should().Contain(Clause);
}
[Test]
public void ASnapshotDecodeWithNoBindingRefusesATail()
{
var snapshot = new CultNetSnapshotResponseRawMessage { Documents = new[] { WithTail(Manifest()) } };
Refusal(() => CultMesh.DecodeSnapshotDocuments<CultMeshCdnArtifactManifest>(snapshot, new CultNetDocumentRegistry())).Should().Contain(Clause);
}
[Test]
public void ATypedReadOfOneSnapshotRecordRefusesATail()
{
var record = WithTail(Manifest());
var snapshot = new CultNetSnapshotResponseRawMessage { MessageId = "m", Documents = new[] { record } };
var read = typeof(CultMesh).GetMethod("ReadDocumentFromSnapshotResponse", BindingFlags.NonPublic | BindingFlags.Static)!
.MakeGenericMethod(typeof(CultMeshCdnArtifactManifest));
Refusal(() => read.Invoke(null, new object[] { snapshot, record.SchemaId, record.RecordKey })).Should().Contain(Clause);
}
}

View file

@ -462,12 +462,12 @@ public sealed class CultMeshContentVectorTests
private static byte[] Reencode(CultMeshContentChunkResponseMessage message) =>
CultNetSchemaMessageSerialization.Serialize(message);
/// <summary>The one reader of manifest bytes: the bounded document reader (CultPayloadDepth 256 included): the CDN manifest contract tolerates bytes after the value, a record payload does not.</summary>
/// <summary>The one reader of manifest bytes: the production CultNet binding of the manifest (CultPayloadDepth 256 and the one-value rule included).</summary>
private static CultMeshCdnArtifactManifest ReadManifest(byte[] bytes) =>
(CultMeshCdnArtifactManifest)CultDocumentMessagePackSerialization.DeserializeBoundedUntyped(typeof(CultMeshCdnArtifactManifest), bytes, CultDocumentRegistry.Shared);
(CultMeshCdnArtifactManifest)CultMeshCdn.CreateDocumentRegistry().GetByDocumentType(typeof(CultMeshCdnArtifactManifest))!.PayloadDeserializer(bytes);
private static byte[] Reencode(CultMeshCdnArtifactManifest manifest) =>
CultDocumentMessagePackSerialization.SerializeUntyped(manifest, typeof(CultMeshCdnArtifactManifest));
CultMeshCdn.CreateDocumentRegistry().GetByDocumentType(typeof(CultMeshCdnArtifactManifest))!.PayloadSerializer(manifest);
private static CultMeshContentChunkRequestMessage Request(string id, string hash, string key, int size) => new()
{

View file

@ -0,0 +1,62 @@
using System;
using System.Linq;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using MessagePack;
using NUnit.Framework;
namespace GameCult.Networking.Tests
{
// A record's payload is one MessagePack value: each CultNet path that decodes a payload refuses a tail, by the one rule in
// CultPayloadDepth.Check. One test per path family, so that pointing a path at a tolerant reader turns it red.
public class BytesAfterPathTests
{
private const string Clause = "1 bytes after its first MessagePack value";
[CultDocument("tests.bytes_after_net", "tests.bytes_after_net.v1")]
[MessagePackObject]
public sealed class TailDoc
{
[Key(0)] [CultName] public string Id = "a";
[Key(1)] public int N = 3;
}
private static readonly CultDocumentRegistry Documents = CultDocumentRegistry.ForTypes(new[] { typeof(TailDoc) });
private static byte[] WithTail() =>
CultDocumentMessagePackSerialization.SerializeUntyped(new TailDoc(), typeof(TailDoc), Documents).Concat(new byte[] { 0xc0 }).ToArray();
private static CultNetRawDocumentRecord Raw(CultNetDocumentRegistry registry, byte[] payload) => new()
{
SchemaId = Documents.GetRequired(typeof(TailDoc)).SchemaId,
RecordKey = "a",
StoredAt = "1970-01-01T00:00:00.000Z",
Payload = payload,
};
private static void Refuses(TestDelegate read) =>
Assert.That(Assert.Catch(read)!.ToString(), Does.Contain(Clause));
[Test]
public void TheGenericBindingRefusesATail() =>
Refuses(() => CultNetDocumentBinding.ForDocument<TailDoc>(Documents).PayloadDeserializer(WithTail()));
[Test]
public void TheRuntimeTypeBindingRefusesATail() =>
Refuses(() => CultNetDocumentBinding.ForDocument(typeof(TailDoc), Documents).PayloadDeserializer(WithTail()));
[Test]
public void ARawEnvelopeThroughARegisteredBindingRefusesATail()
{
var registry = new CultNetDocumentRegistry(Documents).Register(CultNetDocumentBinding.ForDocument<TailDoc>(Documents));
Refuses(() => registry.DeserializeRawDocument(Raw(registry, WithTail())));
}
[Test]
public void ARawEnvelopeWithNoBindingRefusesATail()
{
var registry = new CultNetDocumentRegistry(Documents);
Refuses(() => registry.DeserializeRawDocument(Raw(registry, WithTail())));
}
}
}

View file

@ -188,4 +188,4 @@ Must: refuse on read, naming the type and the count of bytes after the first val
What a runtime walks: only the first value of the payload, to find where it ends (a leaf counts as complete at its own length, a container when its last child completes). It compares that end with the payload length; a payload that ends early is not bytes after the value and stays the decoder's to refuse. It never walks the tail, so the tail's own shape (a stray `c1`, 300 levels) is never judged.
The CultMesh CDN manifest is not covered by these vectors: its contract (`contracts/cultmesh/content-acceptance-vectors.json`) accepts bytes after the value, and its reader keeps the depth bound through `DeserializeBoundedUntyped`.
A CDN manifest read as a record follows the same rule; its vectors are `contracts/cultmesh/content-acceptance-vectors.json` (`trailing_*` are refusals).