Merge origin/main into hands/variants-c2a-main (main-into-c2a)
Sixteen conflicted files resolved by the spec's rule: main owns payload ownership, bounds and the Clock seam; C2a owns persistence semantics and exact binding. MintStoredAt is internal static (previous, now); the cache and the store pass their cache's Clock. Package versions are main's. The cultmesh-ts payload-parse acceptance and its test are deleted under retire-schema-alias; peer snapshot reads take the schema's own id, else an id the definition lists as compatible. The held firstRecordAtKey fallback is removed: main's handles take definitions only, so nothing could reach it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
3b83cb6c08
287 changed files with 55077 additions and 1820 deletions
|
|
@ -56,9 +56,12 @@ public static class CultDocumentMessagePackSerialization
|
|||
|
||||
private static MessagePackSerializerOptions Compose(IFormatterResolver[] consumerResolvers)
|
||||
{
|
||||
// The guard goes first and wraps whatever formatter the rest of the composite would hand out, so a consumer
|
||||
// resolver still encodes an arm while the key check runs.
|
||||
var inner = CompositeResolver.Create(
|
||||
consumerResolvers.Append(CultDocumentResolver.Instance).Append(CultMathResolver.Instance).Append(StandardResolver.Instance).ToArray());
|
||||
return MessagePackSerializerOptions.Standard
|
||||
.WithResolver(CompositeResolver.Create(
|
||||
consumerResolvers.Append(CultDocumentResolver.Instance).Append(CultMathResolver.Instance).Append(StandardResolver.Instance).ToArray()))
|
||||
.WithResolver(CompositeResolver.Create(new CultUnionGuard(inner), inner))
|
||||
.WithSecurity(CultMessagePackSecurity.Instance);
|
||||
}
|
||||
|
||||
|
|
@ -81,7 +84,9 @@ public static class CultDocumentMessagePackSerialization
|
|||
{
|
||||
if (registry == null) throw new ArgumentNullException(nameof(registry));
|
||||
if (value != null) registry.GetRequired(type);
|
||||
return MessagePackSerializer.Serialize(type, value, OptionsFor(type.Assembly));
|
||||
var payload = MessagePackSerializer.Serialize(type, value, OptionsFor(type.Assembly));
|
||||
CultPayloadDepth.Check(payload, type, PayloadDirection.Write);
|
||||
return payload;
|
||||
}
|
||||
|
||||
public static object DeserializeUntyped(Type type, byte[] payload)
|
||||
|
|
@ -93,6 +98,7 @@ public static class CultDocumentMessagePackSerialization
|
|||
{
|
||||
if (registry == null) throw new ArgumentNullException(nameof(registry));
|
||||
registry.GetRequired(type);
|
||||
CultPayloadDepth.Check(payload, type, PayloadDirection.Read);
|
||||
return MessagePackSerializer.Deserialize(type, payload, OptionsFor(type.Assembly))
|
||||
?? throw new InvalidOperationException($"MessagePack returned null for Cult document type {type.FullName}.");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,15 @@ namespace GameCult.Caching.MessagePack;
|
|||
// UntrustedData, plus a collision-resistant comparer for CultRecordRef<T> dictionary keys over the key string.
|
||||
public sealed class CultMessagePackSecurity : MessagePackSecurity
|
||||
{
|
||||
public static readonly CultMessagePackSecurity Instance = new(UntrustedData);
|
||||
/// <summary>
|
||||
/// The deepest a document payload may nest, on read and on write, in every CultCache runtime: every MessagePack array and
|
||||
/// map counts, read by a formatter or skipped past it, and the outermost array is depth 1. A payload of this depth is
|
||||
/// accepted and one container deeper is refused. MessagePack's own object-graph counter is set to the same value as a
|
||||
/// backstop; the rule itself is <c>CultPayloadDepth.Check</c>, run by the document serialization entry points.
|
||||
/// </summary>
|
||||
public const int MaximumPayloadDepth = 256;
|
||||
|
||||
public static readonly CultMessagePackSecurity Instance = new(UntrustedData.WithMaximumObjectGraphDepth(MaximumPayloadDepth));
|
||||
|
||||
private CultMessagePackSecurity(MessagePackSecurity copyFrom) : base(copyFrom) { }
|
||||
|
||||
|
|
|
|||
94
src/GameCult.Caching.MessagePack/CultPayloadDepth.cs
Normal file
94
src/GameCult.Caching.MessagePack/CultPayloadDepth.cs
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using MessagePack;
|
||||
|
||||
namespace GameCult.Caching.MessagePack;
|
||||
|
||||
internal enum PayloadDirection { Read, Write }
|
||||
|
||||
/// <summary>
|
||||
/// The one payload nesting count. Walks the MessagePack headers of a document payload iteratively, counting every array and
|
||||
/// map (read by a formatter or skipped past it; the outermost array is depth 1) and refusing the first container past
|
||||
/// <see cref="CultMessagePackSecurity.MaximumPayloadDepth"/>. Scalars are skipped by length, nothing is allocated per
|
||||
/// element, and the count stack is bounded by the limit. A refusal names the type, the depth reached and the limit,
|
||||
/// never payload bytes. A payload that ends early is the deserializer's to refuse.
|
||||
/// </summary>
|
||||
internal static class CultPayloadDepth
|
||||
{
|
||||
public static void Check(ReadOnlySpan<byte> bytes, Type type, PayloadDirection direction)
|
||||
{
|
||||
const int limit = CultMessagePackSecurity.MaximumPayloadDepth;
|
||||
Span<long> remaining = stackalloc long[limit];
|
||||
var depth = 0;
|
||||
long position = 0;
|
||||
while (position < bytes.Length)
|
||||
{
|
||||
var code = bytes[(int)position];
|
||||
long children = 0;
|
||||
long header = 0;
|
||||
long skip = 0;
|
||||
var container = false;
|
||||
switch (code)
|
||||
{
|
||||
case <= 0x7f or >= 0xe0 or 0xc0 or 0xc1 or 0xc2 or 0xc3: skip = 1; break;
|
||||
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 0xca or 0xce or 0xd2: skip = 5; break;
|
||||
case 0xcb or 0xcf or 0xd3: skip = 9; break;
|
||||
case 0xcc or 0xd0: skip = 2; break;
|
||||
case 0xcd or 0xd1 or 0xd4: skip = 3; break;
|
||||
case 0xd5: skip = 4; break;
|
||||
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;
|
||||
}
|
||||
|
||||
if (container)
|
||||
{
|
||||
if (depth == limit)
|
||||
throw new MessagePackSerializationException(
|
||||
$"{type.FullName} payload nests {limit + 1} MessagePack containers deep; the limit is {limit} (refused on {(direction == PayloadDirection.Read ? "read" : "write")}).");
|
||||
position += header;
|
||||
if (children > 0)
|
||||
{
|
||||
remaining[depth++] = children;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
position += skip;
|
||||
}
|
||||
|
||||
// One element is complete; close every container it was the last element of.
|
||||
while (depth > 0 && --remaining[depth - 1] == 0) depth--;
|
||||
if (depth == 0) return;
|
||||
}
|
||||
}
|
||||
|
||||
// The big-endian length that follows the code byte, when the payload is long enough to hold it.
|
||||
private static bool Length(ReadOnlySpan<byte> bytes, long position, int width, out long length)
|
||||
{
|
||||
length = 0;
|
||||
if (position + 1 + width > bytes.Length) return false;
|
||||
var field = bytes.Slice((int)position + 1, width);
|
||||
length = width switch
|
||||
{
|
||||
1 => field[0],
|
||||
2 => BinaryPrimitives.ReadUInt16BigEndian(field),
|
||||
_ => BinaryPrimitives.ReadUInt32BigEndian(field)
|
||||
};
|
||||
return true;
|
||||
}
|
||||
}
|
||||
74
src/GameCult.Caching.MessagePack/CultUnionGuard.cs
Normal file
74
src/GameCult.Caching.MessagePack/CultUnionGuard.cs
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using MessagePack;
|
||||
using MessagePack.Formatters;
|
||||
|
||||
namespace GameCult.Caching.MessagePack;
|
||||
|
||||
/// <summary>
|
||||
/// The one place an unknown union arm or an unnamed subtype is decided. A union is an abstract class or interface carrying
|
||||
/// its own [Union] attributes (never inherited: a union whose arms are also a union has its own key set). MessagePack-CSharp
|
||||
/// still encodes the [key, armSlots] shape; this wraps its formatter so that a key the union does not declare is refused on
|
||||
/// read, and a value whose runtime type is not a declared arm is refused on write, where MessagePack alone yields null and nil.
|
||||
/// </summary>
|
||||
internal sealed class CultUnionGuard(IFormatterResolver inner) : IFormatterResolver
|
||||
{
|
||||
public IMessagePackFormatter<T>? GetFormatter<T>()
|
||||
{
|
||||
var arms = typeof(T).GetCustomAttributes<UnionAttribute>(inherit: false).ToArray();
|
||||
return arms.Length == 0 || inner.GetFormatter<T>() is not { } formatter ? null : new Formatter<T>(formatter, arms);
|
||||
}
|
||||
|
||||
private sealed class Formatter<T>(IMessagePackFormatter<T> inner, UnionAttribute[] arms) : IMessagePackFormatter<T>
|
||||
{
|
||||
private readonly HashSet<int> keys = arms.Select(arm => arm.Key).ToHashSet();
|
||||
private readonly HashSet<Type> types = arms.Select(arm => arm.SubType).ToHashSet();
|
||||
|
||||
public void Serialize(ref MessagePackWriter writer, T value, MessagePackSerializerOptions options)
|
||||
{
|
||||
if (value != null && !types.Contains(value.GetType()))
|
||||
throw new MessagePackSerializationException($"{value.GetType().FullName} is not an arm of union {typeof(T).FullName}; it would be written as nil.");
|
||||
inner.Serialize(ref writer, value, options);
|
||||
}
|
||||
|
||||
public T Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
|
||||
{
|
||||
// Peek only the arm's first two tokens; any other shape is the inner formatter's to refuse.
|
||||
var peek = reader.CreatePeekReader();
|
||||
if (!peek.TryReadNil() && peek.NextMessagePackType == MessagePackType.Array && peek.ReadArrayHeader() == 2)
|
||||
{
|
||||
var declared = string.Join(", ", keys.OrderBy(k => k));
|
||||
if (peek.NextMessagePackType != MessagePackType.Integer)
|
||||
throw new MessagePackSerializationException($"Union {typeof(T).FullName} has a non-integer arm key (slot 0 of the arm); declared keys: {declared}.");
|
||||
if (!TryReadKey(ref peek, out var key))
|
||||
throw new MessagePackSerializationException($"Union {typeof(T).FullName} has an arm key outside Int32 (slot 0 of the arm); declared keys: {declared}.");
|
||||
if (!keys.Contains(key))
|
||||
throw new MessagePackSerializationException($"Union {typeof(T).FullName} has no arm for key {key} (slot 0 of the arm); declared keys: {declared}.");
|
||||
if (peek.TryReadNil())
|
||||
throw new MessagePackSerializationException($"Union {typeof(T).FullName} arm {key} has nil slots (slot 1 of the arm); declared keys: {declared}.");
|
||||
}
|
||||
|
||||
return inner.Deserialize(ref reader, options);
|
||||
}
|
||||
|
||||
// An arm key is an Int32; a wider or unsigned-64 integer is out of range, never an OverflowException.
|
||||
private static bool TryReadKey(ref MessagePackReader reader, out int key)
|
||||
{
|
||||
key = 0;
|
||||
if (reader.NextCode == MessagePackCode.UInt64)
|
||||
{
|
||||
var wide = reader.ReadUInt64();
|
||||
if (wide > int.MaxValue) return false;
|
||||
key = (int)wide;
|
||||
return true;
|
||||
}
|
||||
|
||||
var value = reader.ReadInt64();
|
||||
if (value < int.MinValue || value > int.MaxValue) return false;
|
||||
key = (int)value;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue