diff --git a/packages/cultnet-rs/src/contracts.rs b/packages/cultnet-rs/src/contracts.rs index 6cca92ee..e99c60e0 100644 --- a/packages/cultnet-rs/src/contracts.rs +++ b/packages/cultnet-rs/src/contracts.rs @@ -1857,10 +1857,17 @@ fn encode_gamecult_networking_message(message: &CultNetMessage) -> Result vec![ + } => { + // The legacy union's request has no such field: a request that asks for members is refused, never sent without the ask. + if include_members.unwrap_or(false) { + return Err(anyhow!( + "includeMembers is not part of gamecult.networking.v0; send cultnet.schema.v0" + )); + } + vec![ rmpv::Value::from(7), rmpv::Value::Array(vec![ message_id.as_str().into(), @@ -1868,7 +1875,8 @@ fn encode_gamecult_networking_message(message: &CultNetMessage) -> Result { + const request = { schemaVersion: "cultnet.schema_catalog_request.v0", messageId: "m", includeMembers: true } as const; + assert.throws(() => encodeCultNetMessageForWire(request, "gamecult.networking.v0"), /includeMembers/); + assert.doesNotThrow(() => encodeCultNetMessageForWire({ ...request, includeMembers: undefined }, "gamecult.networking.v0")); +}); diff --git a/packages/cultnet-ts/test/first-call.test.ts b/packages/cultnet-ts/test/first-call.test.ts index 977a6e5b..6c3c37a4 100644 --- a/packages/cultnet-ts/test/first-call.test.ts +++ b/packages/cultnet-ts/test/first-call.test.ts @@ -68,7 +68,7 @@ test("send a typed document over loopback and receive it into a second cache", a test("docs show the tested snippet", async () => { // Compiled to dist-test/test/first-call.test.js, so the package root is two levels up. - const source = await readFile(join(__dirname, "..", "..", "test", "first-call.test.ts"), "utf8"); + const source = (await readFile(join(__dirname, "..", "..", "test", "first-call.test.ts"), "utf8")).replace(/\r\n/g, "\n"); const snippet = source .split("// snippet:begin\n")[1] .split("// snippet:end\n")[0] diff --git a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs index 91e5fb94..6cebde27 100644 --- a/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs +++ b/src/GameCult.Networking/CultNetDatabaseSubscriptionServer.cs @@ -124,14 +124,21 @@ namespace GameCult.Networking // Answers a catalog request with the document types this database's cache registers: kind document_payload, contentHash the // schemaContentHash its records carry. The cache's descriptor owns the member rows and the hash; nothing is kept here, and // schemaJson stays the contract-schema field, never filled with cache schema JSON. Members leave only for a request that asked. + // A type is listed only for a peer the subscribe authorization admits to subscribe to it (the same authorizeRequest, asked with + // that schema alone), and schemaIds match as a subscription's schemas do (id, name, version or alias; none listed: every type). private Task HandleCatalogAsync(CultNetSchemaCatalogRequestMessage request, ICultNetSchemaServerPeer peer) { - var schemaIds = request.SchemaIds != null ? new HashSet(request.SchemaIds, StringComparer.Ordinal) : null; var kinds = request.Kinds != null ? new HashSet(request.Kinds, StringComparer.Ordinal) : null; var schemas = _database.Cache.Registry.AllDescriptors .Where(descriptor => - (schemaIds == null || schemaIds.Contains(descriptor.SchemaId)) && - (kinds == null || kinds.Contains("document_payload"))) + (kinds == null || kinds.Contains("document_payload")) && + (request.SchemaIds == null || CultNetSchemaAliasMatching.MatchesAny(request.SchemaIds, descriptor)) && + (_authorizeRequest == null || _authorizeRequest(new CultNetDatabaseSubscribeMessage + { + MessageId = request.MessageId, + SubscriptionId = request.MessageId, + SchemaIds = new[] { descriptor.SchemaId } + }, peer))) .Select(descriptor => new CultNetSchemaDescriptor { SchemaId = descriptor.SchemaId, diff --git a/tests/GameCult.Networking.Tests/CultNetSchemaCatalogMembersTests.cs b/tests/GameCult.Networking.Tests/CultNetSchemaCatalogMembersTests.cs index a3194acd..2a93e20c 100644 --- a/tests/GameCult.Networking.Tests/CultNetSchemaCatalogMembersTests.cs +++ b/tests/GameCult.Networking.Tests/CultNetSchemaCatalogMembersTests.cs @@ -5,6 +5,8 @@ using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; +using System.Reflection; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; using GameCult.Caching; @@ -61,13 +63,13 @@ namespace GameCult.Networking.Tests public ConcurrentQueue Catalogs { get; } = new(); public ConcurrentQueue Snapshots { get; } = new(); - public Wire(CultNetDatabase database) + public Wire(CultNetDatabase database, Func? authorizeRequest = null) { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.ReceiveTimeout = 20; _server = new RudpCultNetSchemaServer(new RudpCultNetSchemaServerOptions { RuntimeId = "catalog-server", Socket = socket }); - _subscriptions = new CultNetDatabaseSubscriptionServer(_server, database); + _subscriptions = new CultNetDatabaseSubscriptionServer(_server, database, authorizeRequest); _thread = new Thread(() => { while (!_cancellation.IsCancellationRequested) @@ -189,6 +191,91 @@ namespace GameCult.Networking.Tests Is.EqualTo(MessagePackSerializer.Serialize(legacy, CultNetSchemaMessageSerialization.Options))); } + [Test] + public async Task SchemaCatalogListsOnlyTheTypesThePeerMaySubscribeTo() + { + var cache = new CultCache(); + var note = cache.Registry.GetRequired(); + var mesh = cache.Registry.GetRequired(); + var database = new CultNetDatabase(cache); + using var wire = new Wire(database, (request, _) => request.SchemaIds!.All(id => id == note.SchemaId)); + + var response = await wire.AskAsync(new CultNetSchemaCatalogRequestMessage { MessageId = "denied", IncludeMembers = true }); + + var served = response.Schemas.Single(); + Assert.That(served.SchemaId, Is.EqualTo(note.SchemaId)); + Assert.That(served.Members, Is.Not.Empty); + Assert.That(response.Schemas.Select(s => s.SchemaId), Does.Not.Contain(mesh.SchemaId)); + + using var closed = new Wire(database, (_, _) => false); + var none = await closed.AskAsync(new CultNetSchemaCatalogRequestMessage { MessageId = "closed", IncludeMembers = true }); + Assert.That(none.Schemas, Is.Empty, "a peer denied every subscription learns no member rows"); + } + + [Test] + public async Task SchemaCatalogSchemaIdsMatchAsASubscriptionsSchemasDo() + { + var database = DatabaseWithANote(out var descriptor); + using var wire = new Wire(database); + + var byName = await wire.AskAsync(new CultNetSchemaCatalogRequestMessage + { + MessageId = "by-name", SchemaIds = new[] { descriptor.SchemaName } + }); + Assert.That(byName.Schemas.Single().SchemaId, Is.EqualTo(descriptor.SchemaId)); + + var unknown = await wire.AskAsync(new CultNetSchemaCatalogRequestMessage { MessageId = "unknown", SchemaIds = new[] { "no.such.schema" } }); + Assert.That(unknown.Schemas, Is.Empty); + } + + // The two types with a hand formatter: every [Key] member must be written by its formatter and read back, so a key added to + // the contract type without the formatter fails here instead of vanishing from the wire. + private static object Populated(Type type, string name) + { + if (type == typeof(string)) return "v-" + name; + if (type == typeof(bool)) return true; + if (type == typeof(int)) return 7; + if (type == typeof(string[])) return new[] { "a-" + name, "b-" + name }; + if (type == typeof(CultNetSchemaMember[])) + return new[] { (CultNetSchemaMember)PopulatedInstance(typeof(CultNetSchemaMember)) }; + Assert.Fail($"{name}: the test cannot populate {type}; teach Populated about it"); + return null!; + } + + private static object PopulatedInstance(Type type) + { + var instance = Activator.CreateInstance(type)!; + foreach (var property in KeyedProperties(type)) + property.SetValue(instance, Populated(property.PropertyType, property.Name)); + return instance; + } + + private static PropertyInfo[] KeyedProperties(Type type) => + type.GetProperties().Where(p => p.GetCustomAttribute() != null).ToArray(); + + [TestCase(typeof(CultNetSchemaCatalogRequestMessage))] + [TestCase(typeof(CultNetSchemaDescriptor))] + public void EveryKeyOfAHandFormattedTypeIsWrittenAndReadBack(Type type) + { + var instance = PopulatedInstance(type); + var bytes = MessagePackSerializer.Serialize(type, instance, CultNetSchemaMessageSerialization.Options); + + var reader = new MessagePackReader(bytes); + var written = Enumerable.Range(0, reader.ReadMapHeader()).Select(_ => + { + var key = reader.ReadString()!; + reader.Skip(); + return key; + }).ToArray(); + var declared = KeyedProperties(type).Select(p => p.GetCustomAttribute()!.StringKey!).ToArray(); + Assert.That(written, Is.EquivalentTo(declared), $"{type.Name}: its formatter must write exactly the [Key] members"); + + var back = MessagePackSerializer.Deserialize(type, bytes, CultNetSchemaMessageSerialization.Options); + foreach (var property in KeyedProperties(type)) + Assert.That(JsonSerializer.Serialize(property.GetValue(back)), Is.EqualTo(JsonSerializer.Serialize(property.GetValue(instance))), + $"{type.Name}.{property.Name} was not read back by its formatter"); + } + private static CultNetSchemaCatalogResponseMessage VectorResponse() => new() { MessageId = "catalog-members-vector",