Harden CultLib for local production use
This commit is contained in:
parent
1917bdb025
commit
3f1cb8b36e
12 changed files with 1376 additions and 47 deletions
|
|
@ -40,6 +40,88 @@ namespace GameCult.Caching.Tests
|
|||
|
||||
Assert.That(loaded, Is.Not.Null);
|
||||
Assert.That(loaded!.Value, Is.EqualTo("payload"));
|
||||
Assert.That(readStore.LastSchemaMigrationReports, Has.Count.EqualTo(1));
|
||||
Assert.That(readStore.LastSchemaMigrationReports[0].Kind, Is.EqualTo(CultSchemaMigrationKind.Exact));
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
File.Delete(filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CultCache_DirtyState_Tracks_Mutations_And_ExplicitFlush()
|
||||
{
|
||||
var filePath = Path.Combine(Path.GetTempPath(), $"cultlib-tests-{Guid.NewGuid():N}.msgpack");
|
||||
|
||||
try
|
||||
{
|
||||
var store = new SingleFileMessagePackBackingStore(filePath);
|
||||
var cache = new CultCache();
|
||||
cache.AddBackingStore(store);
|
||||
|
||||
Assert.That(cache.IsDirty, Is.False);
|
||||
Assert.That(store.IsDirty, Is.False);
|
||||
|
||||
await cache.AddAsync(new NamedTestEntry
|
||||
{
|
||||
Name = "dirty",
|
||||
Value = "pending"
|
||||
});
|
||||
|
||||
Assert.That(cache.IsDirty, Is.True);
|
||||
Assert.That(store.IsDirty, Is.True);
|
||||
Assert.That(cache.LastSuccessfulFlushAtUtc, Is.Null);
|
||||
|
||||
cache.FlushAllBackingStores();
|
||||
|
||||
Assert.That(cache.IsDirty, Is.False);
|
||||
Assert.That(store.IsDirty, Is.False);
|
||||
Assert.That(cache.LastSuccessfulFlushAtUtc, Is.Not.Null);
|
||||
Assert.That(store.LastSuccessfulFlushAtUtc, Is.Not.Null);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (File.Exists(filePath))
|
||||
{
|
||||
File.Delete(filePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task CultCache_FlushOnDispose_Persists_When_Enabled()
|
||||
{
|
||||
var filePath = Path.Combine(Path.GetTempPath(), $"cultlib-tests-{Guid.NewGuid():N}.msgpack");
|
||||
|
||||
try
|
||||
{
|
||||
var store = new SingleFileMessagePackBackingStore(filePath);
|
||||
var cache = new CultCache
|
||||
{
|
||||
FlushAttachedStoresOnDispose = true
|
||||
};
|
||||
cache.AddBackingStore(store);
|
||||
|
||||
var handle = await cache.AddAsync(new NamedTestEntry
|
||||
{
|
||||
Name = "dispose",
|
||||
Value = "flush"
|
||||
});
|
||||
|
||||
cache.Dispose();
|
||||
|
||||
var readStore = new SingleFileMessagePackBackingStore(filePath);
|
||||
var readCache = new CultCache();
|
||||
readCache.AddBackingStore(readStore);
|
||||
await readCache.PullAllBackingStoresAsync();
|
||||
|
||||
var loaded = readCache.Get<NamedTestEntry>(handle.Key);
|
||||
Assert.That(loaded, Is.Not.Null);
|
||||
Assert.That(loaded!.Value, Is.EqualTo("flush"));
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
|
@ -171,6 +253,66 @@ namespace GameCult.Caching.Tests
|
|||
Assert.That(descriptor.CanonicalSchemaJson, Does.Contain("\"isReference\":true"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Registry_CanonicalSchema_Fixtures_Are_Stable()
|
||||
{
|
||||
var named = CultDocumentRegistry.Shared.GetRequired<NamedTestEntry>();
|
||||
var referenceHolder = CultDocumentRegistry.Shared.GetRequired<ReferenceHolderEntry>();
|
||||
|
||||
Assert.That(named.CanonicalSchemaJson, Is.EqualTo(NamedFixtureCanonicalSchemaJson));
|
||||
Assert.That(named.SchemaId, Is.EqualTo(NamedFixtureSchemaId));
|
||||
Assert.That(named.ContentHash, Is.EqualTo(NamedFixtureContentHash));
|
||||
Assert.That(referenceHolder.SchemaId, Is.EqualTo(ReferenceFixtureSchemaId));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ResolvePersistedSchemaReport_Classifies_Compatible_And_Incompatible_Drift()
|
||||
{
|
||||
var registry = CultDocumentRegistry.Shared;
|
||||
var namedV1 = registry.GetRequired<NamedTestEntry>();
|
||||
var namedV2 = registry.GetRequired<NamedTestEntryAdditive>();
|
||||
var namedV3 = registry.GetRequired<NamedTestEntryRemoved>();
|
||||
var namedMismatch = registry.GetRequired<NamedTestEntryTypeMismatch>();
|
||||
var referenceV1 = registry.GetRequired<ReferenceHolderEntry>();
|
||||
var referenceRetargeted = registry.GetRequired<ReferenceHolderRetargetedEntry>();
|
||||
|
||||
var additiveCatalog = namedV1.ToCatalogEntry();
|
||||
additiveCatalog.SchemaId = "persisted.tests.named_entry.v1";
|
||||
additiveCatalog.CompatibleSchemaIds = new[] { namedV2.SchemaId };
|
||||
var additiveReport = registry.ResolvePersistedSchemaReport(additiveCatalog.SchemaId, new[] { additiveCatalog });
|
||||
Assert.That(additiveReport.Kind, Is.EqualTo(CultSchemaMigrationKind.CompatibleDrift));
|
||||
Assert.That(additiveReport.DefaultedMissingSlots, Is.EqualTo(new[] { 2 }));
|
||||
Assert.That(additiveReport.IgnoredExtraSlots, Is.Empty);
|
||||
|
||||
var removedCatalog = namedV2.ToCatalogEntry();
|
||||
removedCatalog.SchemaId = "persisted.tests.named_entry.v2";
|
||||
removedCatalog.CompatibleSchemaIds = new[] { namedV3.SchemaId };
|
||||
var removedReport = registry.ResolvePersistedSchemaReport(removedCatalog.SchemaId, new[] { removedCatalog });
|
||||
Assert.That(removedReport.Kind, Is.EqualTo(CultSchemaMigrationKind.CompatibleDrift));
|
||||
Assert.That(removedReport.DefaultedMissingSlots, Is.Empty);
|
||||
Assert.That(removedReport.IgnoredExtraSlots, Is.EqualTo(new[] { 1, 2 }));
|
||||
|
||||
var mismatchCatalog = namedV1.ToCatalogEntry();
|
||||
mismatchCatalog.SchemaId = "persisted.tests.named_entry.type_mismatch";
|
||||
mismatchCatalog.CompatibleSchemaIds = new[] { namedMismatch.SchemaId };
|
||||
Assert.That(
|
||||
() => registry.ResolvePersistedSchemaReport(mismatchCatalog.SchemaId, new[] { mismatchCatalog }),
|
||||
Throws.TypeOf<InvalidOperationException>().With.Message.Contains("changed type"));
|
||||
|
||||
var retargetedCatalog = referenceV1.ToCatalogEntry();
|
||||
retargetedCatalog.SchemaId = "persisted.tests.reference_holder.v1";
|
||||
retargetedCatalog.CompatibleSchemaIds = new[] { referenceRetargeted.SchemaId };
|
||||
Assert.That(
|
||||
() => registry.ResolvePersistedSchemaReport(retargetedCatalog.SchemaId, new[] { retargetedCatalog }),
|
||||
Throws.TypeOf<InvalidOperationException>().With.Message.Contains("changed target schema"));
|
||||
}
|
||||
|
||||
private const string NamedFixtureCanonicalSchemaJson =
|
||||
"{\"schemaName\":\"tests.named_entry\",\"schemaVersion\":\"tests.named_entry.v1\",\"members\":[{\"slot\":0,\"name\":\"Name\",\"type\":\"System.String\",\"isReference\":false,\"many\":false,\"targetSchemaName\":null,\"indexAlias\":null,\"isName\":true},{\"slot\":1,\"name\":\"Value\",\"type\":\"System.String\",\"isReference\":false,\"many\":false,\"targetSchemaName\":null,\"indexAlias\":null,\"isName\":false}]}";
|
||||
private const string NamedFixtureSchemaId = "sha256:e7b97801b94190f3159012ede45b0069bb09ebf7920f7432c971bc86a0e08de8";
|
||||
private const string NamedFixtureContentHash = "sha256:23150930afcc1d84f0cb3012ccc2debcb9b4685f62083033bbaab0083f1e832e";
|
||||
private const string ReferenceFixtureSchemaId = "sha256:bd85064961cc74565fb73e3ccbc4217cfba4dc4869e365a08bea4f704739bd8f";
|
||||
|
||||
[CultDocument("tests.named_entry", "tests.named_entry.v1")]
|
||||
internal sealed class NamedTestEntry
|
||||
{
|
||||
|
|
@ -192,5 +334,57 @@ namespace GameCult.Caching.Tests
|
|||
[Key(1)]
|
||||
public CultRecordRef<NamedTestEntry> Parent = new(new CultRecordKey("parent"));
|
||||
}
|
||||
|
||||
[CultDocument("tests.named_entry", "tests.named_entry.v2")]
|
||||
internal sealed class NamedTestEntryAdditive
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
public string Name = string.Empty;
|
||||
|
||||
[Key(1)]
|
||||
public string Value = string.Empty;
|
||||
|
||||
[Key(2)]
|
||||
public string Notes = string.Empty;
|
||||
}
|
||||
|
||||
[CultDocument("tests.named_entry", "tests.named_entry.v3")]
|
||||
internal sealed class NamedTestEntryRemoved
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
public string Name = string.Empty;
|
||||
}
|
||||
|
||||
[CultDocument("tests.named_entry", "tests.named_entry.v4")]
|
||||
internal sealed class NamedTestEntryTypeMismatch
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
public string Name = string.Empty;
|
||||
|
||||
[Key(1)]
|
||||
public int Value;
|
||||
}
|
||||
|
||||
[CultDocument("tests.alt_named_entry", "tests.alt_named_entry.v1")]
|
||||
internal sealed class AlternateNamedTestEntry
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
public string Name = string.Empty;
|
||||
}
|
||||
|
||||
[CultDocument("tests.reference_holder", "tests.reference_holder.v2")]
|
||||
internal sealed class ReferenceHolderRetargetedEntry
|
||||
{
|
||||
[Key(0)]
|
||||
[CultName]
|
||||
public string Name = string.Empty;
|
||||
|
||||
[Key(1)]
|
||||
public CultRecordRef<AlternateNamedTestEntry> Parent = new(new CultRecordKey("parent"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -38,6 +38,19 @@ namespace GameCult.Networking.Tests
|
|||
Assert.That(Secret.TryValidateSessionToken(tamperedToken, DevelopmentServerSecurity, out _, out _), Is.False);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SessionToken_Validates_SessionVersion()
|
||||
{
|
||||
var userId = Guid.NewGuid();
|
||||
var token = Secret.CreateSessionToken(userId, DateTimeOffset.UtcNow.AddMinutes(5), 42, DevelopmentServerSecurity);
|
||||
|
||||
Assert.That(
|
||||
Secret.TryValidateSessionToken(token, DevelopmentServerSecurity, out var parsedUserId, out _, out var sessionVersion),
|
||||
Is.True);
|
||||
Assert.That(parsedUserId, Is.EqualTo(userId));
|
||||
Assert.That(sessionVersion, Is.EqualTo(42));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SessionToken_RejectsExpiredTokens()
|
||||
{
|
||||
|
|
@ -267,6 +280,60 @@ namespace GameCult.Networking.Tests
|
|||
Assert.That(ghostlight.Kind, Is.EqualTo("document_payload"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Server_Separates_Connection_And_Auth_RateLimits()
|
||||
{
|
||||
var cache = new CultCache();
|
||||
var server = new Server(cache, DevelopmentServerSecurity);
|
||||
var serverType = typeof(Server);
|
||||
var connectionMethod = serverType.GetMethod("CheckConnectionRateLimit", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)!;
|
||||
var authMethod = serverType.GetMethod("CheckAuthRateLimit", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)!;
|
||||
|
||||
for (var index = 0; index < 5; index++)
|
||||
{
|
||||
Assert.That((bool)connectionMethod.Invoke(server, new object[] { "127.0.0.1" })!, Is.True);
|
||||
}
|
||||
|
||||
Assert.That((bool)authMethod.Invoke(server, new object[] { "127.0.0.1" })!, Is.True);
|
||||
|
||||
for (var index = 0; index < 5; index++)
|
||||
{
|
||||
_ = authMethod.Invoke(server, new object[] { "127.0.0.2" });
|
||||
}
|
||||
|
||||
Assert.That((bool)authMethod.Invoke(server, new object[] { "127.0.0.2" })!, Is.False);
|
||||
Assert.That((bool)connectionMethod.Invoke(server, new object[] { "127.0.0.2" })!, Is.True);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void Client_Reconnect_Backoff_Is_Bounded_And_Grows()
|
||||
{
|
||||
var method = typeof(Client).GetMethod("GetReconnectDelayForAttempt", BindingFlags.Static | BindingFlags.NonPublic)!;
|
||||
|
||||
var first = (TimeSpan)method.Invoke(null, new object[] { 1 })!;
|
||||
var third = (TimeSpan)method.Invoke(null, new object[] { 3 })!;
|
||||
var tenth = (TimeSpan)method.Invoke(null, new object[] { 10 })!;
|
||||
|
||||
Assert.That(first, Is.GreaterThanOrEqualTo(TimeSpan.FromSeconds(1)));
|
||||
Assert.That(first, Is.LessThanOrEqualTo(TimeSpan.FromSeconds(1.25)));
|
||||
Assert.That(third, Is.GreaterThanOrEqualTo(TimeSpan.FromSeconds(4)));
|
||||
Assert.That(third, Is.LessThanOrEqualTo(TimeSpan.FromSeconds(4.25)));
|
||||
Assert.That(tenth, Is.GreaterThanOrEqualTo(TimeSpan.FromSeconds(30)));
|
||||
Assert.That(tenth, Is.LessThanOrEqualTo(TimeSpan.FromSeconds(30.25)));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void SensitivePayloadLogging_Is_Gated_By_Default()
|
||||
{
|
||||
var client = new Client(DevelopmentClientSecurity);
|
||||
var productionServer = new Server(new CultCache(), new ServerSecurityOptions("prod-connection-key", "prod-session-signing-secret"));
|
||||
var developmentServer = new Server(new CultCache(), DevelopmentServerSecurity);
|
||||
|
||||
Assert.That(client.LogSensitivePayloads, Is.False);
|
||||
Assert.That(productionServer.LogSensitivePayloads, Is.False);
|
||||
Assert.That(developmentServer.LogSensitivePayloads, Is.True);
|
||||
}
|
||||
|
||||
private sealed class EnvironmentVariableScope : IDisposable
|
||||
{
|
||||
private readonly (string Name, string? Value)[] _originalValues;
|
||||
|
|
@ -297,6 +364,7 @@ namespace GameCult.Networking.Tests
|
|||
[MessagePack.Key(1)] public string Email { get; set; } = string.Empty;
|
||||
[MessagePack.Key(2)] public string PasswordHash { get; set; } = string.Empty;
|
||||
[MessagePack.Key(3)] public string Username { get; set; } = string.Empty;
|
||||
[MessagePack.Key(4)] public long SessionVersion { get; set; }
|
||||
}
|
||||
|
||||
private static byte[] SerializePlayerDataPayload(PlayerData entry)
|
||||
|
|
@ -306,7 +374,8 @@ namespace GameCult.Networking.Tests
|
|||
PlayerId = entry.PlayerId,
|
||||
Email = entry.Email,
|
||||
PasswordHash = entry.PasswordHash,
|
||||
Username = entry.Username
|
||||
Username = entry.Username,
|
||||
SessionVersion = entry.SessionVersion
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -318,7 +387,8 @@ namespace GameCult.Networking.Tests
|
|||
PlayerId = decoded.PlayerId,
|
||||
Email = decoded.Email,
|
||||
PasswordHash = decoded.PasswordHash,
|
||||
Username = decoded.Username
|
||||
Username = decoded.Username,
|
||||
SessionVersion = decoded.SessionVersion
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue