Keep the CDN manifest contract: DeserializeBoundedUntyped reads under the depth bound alone; Check stays the record-payload owner

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Libby 2026-11-12 01:39:58 +00:00
commit 1ef05106ae
7 changed files with 56 additions and 21 deletions

View file

@ -227,6 +227,20 @@ public static class CultDocumentMessagePackSerialization
return new CultDecoded(document, scope.Finding());
}
/// <summary>
/// Reads a document payload that is not a stored record under the nesting bound alone: bytes after the first value are
/// ignored, as the CultMesh CDN manifest contract has them (contracts/cultmesh/content-acceptance-vectors.json). A record
/// payload goes through <see cref="DeserializeUntyped(Type, byte[], CultDocumentRegistry)"/>, which refuses them.
/// </summary>
public static object DeserializeBoundedUntyped(Type type, byte[] payload, CultDocumentRegistry registry)
{
if (registry == null) throw new ArgumentNullException(nameof(registry));
registry.GetRequired(type);
CultPayloadDepth.CheckDepth(payload, type, PayloadDirection.Read);
return MessagePackSerializer.Deserialize(type, payload, OptionsForDocument(type))
?? throw new InvalidOperationException($"MessagePack returned null for Cult document type {type.FullName}.");
}
/// <summary>
/// Replaces slots of a serialized document payload (a MessagePack array indexed by slot) with already-encoded member
/// values, leaving every other slot byte for byte as it was. A slot past the end extends the array with nil.

View file

@ -16,7 +16,20 @@ internal enum PayloadDirection { Read, Write }
/// </summary>
internal static class CultPayloadDepth
{
/// <summary>A record's payload: the depth bound, and exactly one value. Bytes after the first value are refused, never walked.</summary>
public static void Check(ReadOnlySpan<byte> bytes, Type type, PayloadDirection direction)
{
var end = Walk(bytes, type, direction);
if (end < bytes.Length)
throw new MessagePackSerializationException(
$"{type.FullName} payload has {bytes.Length - end} bytes after its first MessagePack value (refused on {(direction == PayloadDirection.Read ? "read" : "write")}).");
}
/// <summary>The depth bound alone, for a reader whose contract tolerates bytes after the value (the CDN manifest vectors).</summary>
public static void CheckDepth(ReadOnlySpan<byte> bytes, Type type, PayloadDirection direction) => Walk(bytes, type, direction);
// The one walk: refuses past the depth limit and returns where the first value ends (the payload's length when it ends early).
private static long Walk(ReadOnlySpan<byte> bytes, Type type, PayloadDirection direction)
{
const int limit = CultMessagePackSecurity.MaximumPayloadDepth;
Span<long> remaining = stackalloc long[limit];
@ -35,12 +48,12 @@ internal static class CultPayloadDepth
case <= 0x8f: container = true; header = 1; children = 2L * (code & 0x0f); break;
case <= 0x9f: container = true; header = 1; children = code & 0x0f; break;
case <= 0xbf: skip = 1 + (code & 0x1f); break;
case 0xc4 or 0xd9: if (!Length(bytes, position, 1, out var l8)) return; skip = 2 + l8; break;
case 0xc5 or 0xda: if (!Length(bytes, position, 2, out var l16)) return; skip = 3 + l16; break;
case 0xc6 or 0xdb: if (!Length(bytes, position, 4, out var l32)) return; skip = 5 + l32; break;
case 0xc7: if (!Length(bytes, position, 1, out var e8)) return; skip = 3 + e8; break;
case 0xc8: if (!Length(bytes, position, 2, out var e16)) return; skip = 4 + e16; break;
case 0xc9: if (!Length(bytes, position, 4, out var e32)) return; skip = 6 + e32; break;
case 0xc4 or 0xd9: if (!Length(bytes, position, 1, out var l8)) return bytes.Length; skip = 2 + l8; break;
case 0xc5 or 0xda: if (!Length(bytes, position, 2, out var l16)) return bytes.Length; skip = 3 + l16; break;
case 0xc6 or 0xdb: if (!Length(bytes, position, 4, out var l32)) return bytes.Length; skip = 5 + l32; break;
case 0xc7: if (!Length(bytes, position, 1, out var e8)) return bytes.Length; skip = 3 + e8; break;
case 0xc8: if (!Length(bytes, position, 2, out var e16)) return bytes.Length; skip = 4 + e16; break;
case 0xc9: if (!Length(bytes, position, 4, out var e32)) return bytes.Length; skip = 6 + e32; break;
case 0xca or 0xce or 0xd2: skip = 5; break;
case 0xcb or 0xcf or 0xd3: skip = 9; break;
case 0xcc or 0xd0: skip = 2; break;
@ -49,10 +62,10 @@ internal static class CultPayloadDepth
case 0xd6: skip = 6; break;
case 0xd7: skip = 10; break;
case 0xd8: skip = 18; break;
case 0xdc: if (!Length(bytes, position, 2, out var a16)) return; container = true; header = 3; children = a16; break;
case 0xdd: if (!Length(bytes, position, 4, out var a32)) return; container = true; header = 5; children = a32; break;
case 0xde: if (!Length(bytes, position, 2, out var m16)) return; container = true; header = 3; children = 2 * m16; break;
default: if (!Length(bytes, position, 4, out var m32)) return; container = true; header = 5; children = 2 * m32; break;
case 0xdc: if (!Length(bytes, position, 2, out var a16)) return bytes.Length; container = true; header = 3; children = a16; break;
case 0xdd: if (!Length(bytes, position, 4, out var a32)) return bytes.Length; container = true; header = 5; children = a32; break;
case 0xde: if (!Length(bytes, position, 2, out var m16)) return bytes.Length; container = true; header = 3; children = 2 * m16; break;
default: if (!Length(bytes, position, 4, out var m32)) return bytes.Length; container = true; header = 5; children = 2 * m32; break;
}
if (container)
@ -74,14 +87,10 @@ internal static class CultPayloadDepth
// One element is complete; close every container it was the last element of.
while (depth > 0 && --remaining[depth - 1] == 0) depth--;
if (depth == 0)
{
if (position < bytes.Length)
throw new MessagePackSerializationException(
$"{type.FullName} payload has {bytes.Length - position} bytes after its first MessagePack value (refused on {(direction == PayloadDirection.Read ? "read" : "write")}).");
return;
}
if (depth == 0) return position;
}
return bytes.Length;
}
// The big-endian length that follows the code byte, when the payload is long enough to hold it.

View file

@ -403,7 +403,7 @@ runtime enforces the same bound on read and on write, and the refusal names the
the depth and the limit, never payload bytes. The vectors are in
`tests/vectors/union-parity` (`bounds-outcomes.msgpack`).
A record's payload is exactly one MessagePack value: every runtime refuses a payload with bytes after its first value wherever it reads a payload under the nesting bound, and on write where a write takes bytes the library did not encode itself (a C# type's own formatter, a Rust raw envelope), without walking those bytes, so a tail past the limit is refused as bytes after the value and not as depth; the refusal names the type and the count of bytes after the value, never the bytes (vectors: `tests/vectors/union-parity/bytes-after-outcomes.msgpack`).
A record's payload is exactly one MessagePack value: every runtime refuses a payload with bytes after its first value wherever it reads a payload under the nesting bound, and on write where a write takes bytes the library did not encode itself (a C# type's own formatter, a Rust raw envelope), without walking those bytes, so a tail past the limit is refused as bytes after the value and not as depth; the refusal names the type and the count of bytes after the value, never the bytes (vectors: `tests/vectors/union-parity/bytes-after-outcomes.msgpack`). The CultMesh CDN manifest is a different contract: its wire bytes may carry bytes after the value (`contracts/cultmesh/content-acceptance-vectors.json`), so its reader keeps the nesting bound through `DeserializeBoundedUntyped` and does not refuse them.
## Variant Records

View file

@ -99,6 +99,16 @@ 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()
{

View file

@ -462,9 +462,9 @@ public sealed class CultMeshContentVectorTests
private static byte[] Reencode(CultMeshContentChunkResponseMessage message) =>
CultNetSchemaMessageSerialization.Serialize(message);
/// <summary>The one reader of manifest bytes: the document reader production stores and reads manifests with (CultPayloadDepth 256 included).</summary>
/// <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>
private static CultMeshCdnArtifactManifest ReadManifest(byte[] bytes) =>
(CultMeshCdnArtifactManifest)CultDocumentMessagePackSerialization.DeserializeUntyped(typeof(CultMeshCdnArtifactManifest), bytes);
(CultMeshCdnArtifactManifest)CultDocumentMessagePackSerialization.DeserializeBoundedUntyped(typeof(CultMeshCdnArtifactManifest), bytes, CultDocumentRegistry.Shared);
private static byte[] Reencode(CultMeshCdnArtifactManifest manifest) =>
CultDocumentMessagePackSerialization.SerializeUntyped(manifest, typeof(CultMeshCdnArtifactManifest));

View file

@ -187,3 +187,5 @@ A record's payload is exactly one MessagePack value. Each file is `union-surface
Must: refuse on read, naming the type and the count of bytes after the first value (`1`, `2`, the tail length) in a clause that says "bytes after its first MessagePack value"; never echo the canary; never report the depth refusal ("the limit is") for any of them, because the tail is not walked; and a single-file store holding `bytes-after-nil.msgpack` as a record payload refuses on open.
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`.

View file

@ -6,7 +6,7 @@ All notable changes to this package are documented in this file.
### Breaking
- A document payload with bytes after its first MessagePack value is refused on read and on write (`MessagePackSerializationException` naming the type and the count of bytes after the value, never the bytes); the tail is not walked, so a tail nested past the limit is refused as bytes after the value, not as depth. Before, the tail was ignored on read and dropped on the next write. A payload that ends early is still the deserializer's to refuse.
- A document payload with bytes after its first MessagePack value is refused on read and on write (`MessagePackSerializationException` naming the type and the count of bytes after the value, never the bytes); the tail is not walked, so a tail nested past the limit is refused as bytes after the value, not as depth. Before, the tail was ignored on read and dropped on the next write. A payload that ends early is still the deserializer's to refuse. The CultMesh CDN manifest contract still accepts bytes after the value; `CultDocumentMessagePackSerialization.DeserializeBoundedUntyped` (new) reads under the nesting bound alone for it.
- A single-file store holding two records under one key is unreadable: the reader refuses it with `CultStoreUnreadableException` naming the key (keys compare by ordinal code units, no case folding or normalisation), so a cache, `ReadStoreSnapshot` and a flush refuse the file and leave it as it is. Before, the later record silently replaced the earlier. A directory store reads its manifest through the same reader and refuses a duplicate key the same way. Repair the duplicate with the runtime that wrote it before reading the store here.
- A record whose payload carries a slot past the slots its reading type declares, at any depth (the record, a nested object, a list element, a union arm or a unit arm), is loaded read-only: it is served, and every staged write or removal of its key (`Upsert`, `UpsertVariant`, `Remove`, a batch, and `Flatten` of a variant) is refused with `CultSchemaConflictException` before anything is staged, and the store keeps the record byte for byte. Before, the extra slots were skipped on read and dropped on the next write. Declaring an id compatible consents only to depth-0 slots the schema comparison reports ignored under that id; any other extra slot keeps the record read-only whatever is declared, including under the reader's own id. A variant overriding a slot its type does not have is read-only too (it used to be shed on flush). Write such a record from the build that declares those slots. Missing trailing slots still default and stay writable.
- `Flatten` (and `FlattenAsync`) of a variant whose base chain holds a record its store does not own (a record held read-only for extra slots, or undeclared drift that drops slots) is refused with `CultSchemaConflictException` naming that base record, and the store is left as it was. Before, the flatten wrote the base's decoded view into a plain record and the base's unread data was lost for that variant. Writing and removing the variant itself are still accepted: they persist only its delta.