Harden CultLib for local production use

This commit is contained in:
Meta Vens 2026-05-09 11:45:46 +01:00
commit 3f1cb8b36e
12 changed files with 1376 additions and 47 deletions

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Concurrent;
using System.Security.Cryptography;
using GameCult.Logging;
using LiteNetLib;
using MessagePack;
@ -7,6 +8,27 @@ using R3;
namespace GameCult.Networking
{
/// <summary>
/// Describes the client's reconnect posture.
/// </summary>
public enum ClientReconnectState
{
/// <summary>
/// The client is connected or otherwise not trying to reconnect.
/// </summary>
Idle,
/// <summary>
/// The client is waiting for the next reconnect attempt.
/// </summary>
WaitingToReconnect,
/// <summary>
/// The client is actively attempting a reconnect.
/// </summary>
Reconnecting
}
/// <summary>
/// Provides client-side connection, authentication, and message dispatch logic.
/// </summary>
@ -16,6 +38,10 @@ namespace GameCult.Networking
/// Raised when the client encounters a user-visible error.
/// </summary>
public event Action<string>? OnError; // Hook for important user-facing feedback (e.g. via modal UI element)
/// <summary>
/// Raised when reconnect state changes.
/// </summary>
public event Action<ClientReconnectState>? OnReconnectStateChanged;
private NetManager? _client;
private NetPeer? _peer;
private IDisposable? _pollSubscription;
@ -23,6 +49,7 @@ namespace GameCult.Networking
private bool _disposed;
private bool _manualDisconnect;
private bool _isReconnecting;
private int _reconnectAttemptCount;
private readonly ConcurrentDictionary<Type, Delegate> _messageDelegates = new();
@ -31,7 +58,9 @@ namespace GameCult.Networking
private int _lastPort;
private readonly ClientSecurityOptions _security;
private ILogger _logger = new NullLogger();
private static readonly TimeSpan ReconnectDelay = TimeSpan.FromSeconds(1);
private static readonly TimeSpan BaseReconnectDelay = TimeSpan.FromSeconds(1);
private static readonly TimeSpan MaxReconnectDelay = TimeSpan.FromSeconds(30);
private static readonly TimeSpan MaxReconnectJitter = TimeSpan.FromMilliseconds(250);
/// <summary>
/// Gets or sets the logger used by the client.
@ -47,6 +76,16 @@ namespace GameCult.Networking
/// </summary>
public int Ping { get; private set; }
/// <summary>
/// Gets the current reconnect posture exposed to consumers.
/// </summary>
public ClientReconnectState ReconnectState { get; private set; } = ClientReconnectState.Idle;
/// <summary>
/// Gets or sets whether raw payload bodies may be logged for diagnostics.
/// </summary>
public bool LogSensitivePayloads { get; set; }
/// <summary>
/// Gets a value indicating whether the client currently has a verified session.
/// </summary>
@ -83,7 +122,14 @@ namespace GameCult.Networking
{
if (Verified || m is LoginMessage || m is RegisterMessage || m is VerifyMessage)
{
Logger.LogDebug($"Sending message {MessagePackSerializer.SerializeToJson(m)}");
if (LogSensitivePayloads)
{
Logger.LogDebug($"Sending message {MessagePackSerializer.SerializeToJson(m)}");
}
else
{
Logger.LogDebug($"Sending message {typeof(T).Name}");
}
_peer.Send(m);
}
else Logger.LogError("Cannot send, client is not verified!");
@ -192,6 +238,11 @@ namespace GameCult.Networking
/// <param name="host">The remote host name or IP address.</param>
/// <param name="port">The remote server port.</param>
public void Connect(string host = "localhost", int port = 3075)
{
ConnectCore(host, port, resetReconnectBackoff: true);
}
private void ConnectCore(string host, int port, bool resetReconnectBackoff)
{
if (_disposed)
{
@ -200,6 +251,11 @@ namespace GameCult.Networking
_manualDisconnect = false;
_isReconnecting = false;
if (resetReconnectBackoff)
{
_reconnectAttemptCount = 0;
}
SetReconnectState(ClientReconnectState.Idle);
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
_lastHost = host;
@ -221,8 +277,15 @@ namespace GameCult.Networking
try
{
var bytes = reader.GetRemainingBytes();
Logger.LogDebug($"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
var message = MessageSerialization.Deserialize<Message>(bytes);
if (LogSensitivePayloads)
{
Logger.LogDebug($"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
}
else
{
Logger.LogDebug($"Received message {message.GetType().Name}");
}
var type = message.GetType();
switch (message)
@ -252,6 +315,8 @@ namespace GameCult.Networking
{
Logger.LogInfo($"Peer {peer.Address}:{peer.Port} connected.");
_peer = peer;
_reconnectAttemptCount = 0;
SetReconnectState(ClientReconnectState.Idle);
if (Verified)
{
var nonce = Secret.NewNonce;
@ -282,6 +347,7 @@ namespace GameCult.Networking
_manualDisconnect = true;
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
SetReconnectState(ClientReconnectState.Idle);
DisposeTransport();
}
@ -297,6 +363,7 @@ namespace GameCult.Networking
_manualDisconnect = true;
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
SetReconnectState(ClientReconnectState.Idle);
DisposeTransport();
}
@ -308,15 +375,19 @@ namespace GameCult.Networking
}
_isReconnecting = true;
_reconnectSubscription = Observable.Timer(ReconnectDelay).Subscribe(_ =>
_reconnectAttemptCount++;
var delay = GetReconnectDelayForAttempt(_reconnectAttemptCount);
SetReconnectState(ClientReconnectState.WaitingToReconnect);
_reconnectSubscription = Observable.Timer(delay).Subscribe(_ =>
{
_isReconnecting = false;
_reconnectSubscription?.Dispose();
_reconnectSubscription = null;
SetReconnectState(ClientReconnectState.Reconnecting);
try
{
Connect(_lastHost, _lastPort);
ConnectCore(_lastHost, _lastPort, resetReconnectBackoff: false);
}
catch (Exception ex)
{
@ -326,6 +397,16 @@ namespace GameCult.Networking
});
}
internal static TimeSpan GetReconnectDelayForAttempt(int attempt)
{
var normalizedAttempt = Math.Max(1, attempt);
var exponentialSeconds = Math.Min(
MaxReconnectDelay.TotalSeconds,
BaseReconnectDelay.TotalSeconds * Math.Pow(2, normalizedAttempt - 1));
var jitterMilliseconds = RandomNumberGenerator.GetInt32((int)MaxReconnectJitter.TotalMilliseconds + 1);
return TimeSpan.FromSeconds(exponentialSeconds) + TimeSpan.FromMilliseconds(jitterMilliseconds);
}
private void DisposeTransport()
{
_pollSubscription?.Dispose();
@ -356,5 +437,16 @@ namespace GameCult.Networking
}
}
}
private void SetReconnectState(ClientReconnectState state)
{
if (ReconnectState == state)
{
return;
}
ReconnectState = state;
OnReconnectStateChanged?.Invoke(state);
}
}
}

View file

@ -7,7 +7,7 @@ namespace GameCult.Networking
/// <summary>
/// Basic player account document used by the sample networking stack.
/// </summary>
[CultDocument("gamecult.player_data", "gamecult.player_data.v1")]
[CultDocument("gamecult.player_data", "gamecult.player_data.v2")]
public class PlayerData
{
/// <summary>
@ -36,5 +36,11 @@ namespace GameCult.Networking
[Key(3)]
[CultName]
public string Username = string.Empty;
/// <summary>
/// Monotonic session version used to supersede older issued tokens.
/// </summary>
[Key(4)]
public long SessionVersion;
}
}

View file

@ -23,6 +23,11 @@ The library currently includes:
The library is focused on the built-in authentication and session flows in this repository.
Current readiness target:
- trusted local mesh / self-hosted swarm use: yes
- hostile public internet edge: not yet
Keep the distinction clean:
- auth/session semantics belong to the core library
@ -98,6 +103,9 @@ The built-in flow is:
5. server validates the token and re-establishes the session
The session token is signed and validated by the server.
Each newly issued session token also carries a monotonic session version so
older signed tokens can be superseded cleanly instead of haunting reconnect
paths forever.
## Runtime Secrets
@ -218,8 +226,9 @@ The client:
- disposes its prior polling subscription before reconnecting
- stops the prior `NetManager`
- schedules reconnect with a short delay
- schedules reconnect with bounded exponential backoff and jitter
- automatically re-verifies using the stored signed session token
- exposes reconnect state for UI/operator surfaces
## Important Constraints
@ -227,6 +236,10 @@ The client:
- Message authorization is based on the built-in verify/login/register flow.
- Transport is LiteNetLib, so this is not a drop-in substitute for HTTP or WebSocket stacks.
Sensitive payload logging is gated. Raw message JSON should only appear when a
caller explicitly opts into diagnostic logging instead of accidentally bleeding
live auth/session payloads into ordinary logs.
## Message Example
Messages derive from `Message` and are MessagePack-serializable:
@ -258,3 +271,10 @@ For the newer schema-v0 lane, the equivalent rule is:
- keep payload codecs in sync
- advertise supported contracts through schema discovery
- do not rely on implicit runtime magic to decide what a peer meant
## Future hostile-network work
The next hardening tranche is documented in
`production-hardening-checklist.md`. That ledger names the missing transport,
replay, abuse-handling, and adversarial-test organs directly instead of
pretending local-mesh readiness and internet readiness are the same rite.

View file

@ -193,14 +193,20 @@ namespace GameCult.Networking
/// <param name="expiresAtUtc">The UTC expiration time for the token.</param>
/// <returns>A tamper-evident session token.</returns>
public static string CreateSessionToken(Guid userId, DateTimeOffset expiresAtUtc) =>
CreateSessionToken(userId, expiresAtUtc, GetDefaultOptions());
CreateSessionToken(userId, expiresAtUtc, sessionVersion: 0, GetDefaultOptions());
/// <summary>
/// Creates a signed session token for the supplied user.
/// </summary>
public static string CreateSessionToken(Guid userId, DateTimeOffset expiresAtUtc, ServerSecurityOptions options)
public static string CreateSessionToken(Guid userId, DateTimeOffset expiresAtUtc, ServerSecurityOptions options) =>
CreateSessionToken(userId, expiresAtUtc, sessionVersion: 0, options);
/// <summary>
/// Creates a signed session token for the supplied user and session version.
/// </summary>
public static string CreateSessionToken(Guid userId, DateTimeOffset expiresAtUtc, long sessionVersion, ServerSecurityOptions options)
{
var payload = $"{userId:N}|{expiresAtUtc.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)}";
var payload = $"{userId:N}|{expiresAtUtc.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture)}|{sessionVersion.ToString(CultureInfo.InvariantCulture)}";
var payloadBytes = Encoding.UTF8.GetBytes(payload);
var signatureBytes = ComputeHmacSha256(options.GetSessionSigningKey(), payloadBytes);
return $"{ToBase64Url(payloadBytes)}.{ToBase64Url(signatureBytes)}";
@ -214,7 +220,17 @@ namespace GameCult.Networking
/// <param name="expiresAtUtc">The extracted UTC expiration time.</param>
/// <returns><c>true</c> when the token is valid and unexpired.</returns>
public static bool TryValidateSessionToken(string? token, out Guid userId, out DateTimeOffset expiresAtUtc) =>
TryValidateSessionToken(token, GetDefaultOptions(), out userId, out expiresAtUtc);
TryValidateSessionToken(token, GetDefaultOptions(), out userId, out expiresAtUtc, out _);
/// <summary>
/// Validates and parses a signed session token.
/// </summary>
public static bool TryValidateSessionToken(
string? token,
out Guid userId,
out DateTimeOffset expiresAtUtc,
out long sessionVersion) =>
TryValidateSessionToken(token, GetDefaultOptions(), out userId, out expiresAtUtc, out sessionVersion);
/// <summary>
/// Validates and parses a signed session token.
@ -224,9 +240,23 @@ namespace GameCult.Networking
ServerSecurityOptions options,
out Guid userId,
out DateTimeOffset expiresAtUtc)
{
return TryValidateSessionToken(token, options, out userId, out expiresAtUtc, out _);
}
/// <summary>
/// Validates and parses a signed session token.
/// </summary>
public static bool TryValidateSessionToken(
string? token,
ServerSecurityOptions options,
out Guid userId,
out DateTimeOffset expiresAtUtc,
out long sessionVersion)
{
userId = Guid.Empty;
expiresAtUtc = DateTimeOffset.MinValue;
sessionVersion = 0;
if (string.IsNullOrWhiteSpace(token))
return false;
@ -245,7 +275,7 @@ namespace GameCult.Networking
var payload = Encoding.UTF8.GetString(payloadBytes);
var payloadParts = payload.Split('|');
if (payloadParts.Length != 2 ||
if ((payloadParts.Length != 2 && payloadParts.Length != 3) ||
!Guid.TryParseExact(payloadParts[0], "N", out userId) ||
!long.TryParse(payloadParts[1], NumberStyles.None, CultureInfo.InvariantCulture, out var expiryUnixSeconds))
{
@ -253,6 +283,15 @@ namespace GameCult.Networking
return false;
}
if (payloadParts.Length == 3 &&
!long.TryParse(payloadParts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out sessionVersion))
{
userId = Guid.Empty;
expiresAtUtc = DateTimeOffset.MinValue;
sessionVersion = 0;
return false;
}
expiresAtUtc = DateTimeOffset.FromUnixTimeSeconds(expiryUnixSeconds);
return expiresAtUtc > DateTimeOffset.UtcNow;
}
@ -260,6 +299,7 @@ namespace GameCult.Networking
{
userId = Guid.Empty;
expiresAtUtc = DateTimeOffset.MinValue;
sessionVersion = 0;
return false;
}
}

View file

@ -25,12 +25,15 @@ namespace GameCult.Networking
private const int ServerPort = 3075;
private const float SessionTimeoutSeconds = 1800; // 30 minutes
private const float SessionRefreshThresholdSeconds = 300; // 5 minutes
private const int MaxConnectionAttemptsPerMinute = 30;
private const int MaxLoginAttemptsPerMinute = 5;
private readonly ConcurrentDictionary<Type, Delegate> _messageDelegates = new();
private readonly ConcurrentDictionary<long, User> _users = new();
private readonly ConcurrentDictionary<string, Queue<DateTimeOffset>> _loginAttempts = new();
private readonly ConcurrentDictionary<string, object> _loginAttemptLocks = new();
private readonly ConcurrentDictionary<string, Queue<DateTimeOffset>> _connectionAttempts = new();
private readonly ConcurrentDictionary<string, object> _connectionAttemptLocks = new();
private readonly ConcurrentDictionary<string, Queue<DateTimeOffset>> _authAttempts = new();
private readonly ConcurrentDictionary<string, object> _authAttemptLocks = new();
private readonly IDisposable _cleanupSubscription;
private readonly CultCache _database;
private readonly ServerSecurityOptions _security;
@ -48,6 +51,11 @@ namespace GameCult.Networking
set => _logger = value ?? new NullLogger();
}
/// <summary>
/// Gets or sets whether raw payload bodies may be logged for diagnostics.
/// </summary>
public bool LogSensitivePayloads { get; set; }
private float Time => (float)(_timer?.Elapsed.TotalSeconds ?? 0d);
/// <summary>
@ -59,6 +67,7 @@ namespace GameCult.Networking
{
_database = cache;
_security = security ?? ServerSecurityOptions.FromEnvironment();
LogSensitivePayloads = _security.IsDevelopment;
_cleanupSubscription = Observable.Timer(TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(60))
.Subscribe(_ => CleanupExpiredSessions());
}
@ -150,7 +159,7 @@ namespace GameCult.Networking
listener.ConnectionRequestEvent += request =>
{
if (CheckRateLimit(request.RemoteEndPoint.Address.ToString()))
if (CheckConnectionRateLimit(request.RemoteEndPoint.Address.ToString()))
{
request.AcceptIfKey(_security.ConnectionKey);
}
@ -186,7 +195,14 @@ namespace GameCult.Networking
{
var bytes = reader.GetRemainingBytes();
var message = MessageSerialization.Deserialize<Message>(bytes);
Logger.LogDebug($"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
if (LogSensitivePayloads)
{
Logger.LogDebug($"Received message: {MessagePackSerializer.ConvertToJson(new ReadOnlyMemory<byte>(bytes))}");
}
else
{
Logger.LogDebug($"Received message {message?.GetType().Name ?? "unknown"}");
}
if (message == null)
{
return;
@ -203,7 +219,7 @@ namespace GameCult.Networking
return;
}
if (message is LoginMessage or RegisterMessage && !CheckRateLimit(peer.Address.ToString()))
if (message is LoginMessage or RegisterMessage && !CheckAuthRateLimit(peer.Address.ToString()))
{
peer.Send(new ErrorMessage { Error = "Too Many Attempts" });
return;
@ -343,20 +359,27 @@ namespace GameCult.Networking
private void HandleVerify(NetPeer peer, User user, VerifyMessage verify)
{
var token = Secret.DecryptString(verify.Session, verify.Nonce, _security);
if (!Secret.TryValidateSessionToken(token, _security, out var playerId, out _))
if (!Secret.TryValidateSessionToken(token, _security, out var playerId, out _, out var sessionVersion))
{
peer.Send(new ErrorMessage { Error = "Session Invalid" });
return;
}
if (_database.GetByIndex<PlayerData>("PlayerId", playerId.ToString("D")) == null)
var player = _database.GetByIndex<PlayerData>("PlayerId", playerId.ToString("D"));
if (player == null)
{
peer.Send(new ErrorMessage { Error = "Session Not Found" });
return;
}
if (player.SessionVersion != sessionVersion)
{
peer.Send(new ErrorMessage { Error = "Session Superseded" });
return;
}
AttachUser(user, playerId);
SendSessionToken(peer, playerId);
SendSessionToken(peer, player);
}
private void HandleLogin(NetPeer peer, User user, LoginMessage login)
@ -387,7 +410,7 @@ namespace GameCult.Networking
}
AttachUser(user, userData.PlayerId);
SendSessionToken(peer, userData.PlayerId);
SendSessionToken(peer, userData);
}
private bool IsVerified(User? user) =>
@ -399,23 +422,14 @@ namespace GameCult.Networking
private PlayerData? SessionData(User user) =>
IsVerified(user) ? _database.GetByIndex<PlayerData>("PlayerId", user.PlayerId.ToString("D")) : null;
private bool CheckRateLimit(string ip)
internal bool CheckConnectionRateLimit(string ip)
{
var now = DateTimeOffset.UtcNow;
var windowStart = now.AddMinutes(-1);
var queue = _loginAttempts.GetOrAdd(ip, _ => new Queue<DateTimeOffset>());
var gate = _loginAttemptLocks.GetOrAdd(ip, _ => new object());
return CheckRateLimit(ip, MaxConnectionAttemptsPerMinute, _connectionAttempts, _connectionAttemptLocks);
}
lock (gate)
{
while (queue.Count > 0 && queue.Peek() < windowStart)
{
queue.Dequeue();
}
queue.Enqueue(now);
return queue.Count <= MaxLoginAttemptsPerMinute;
}
internal bool CheckAuthRateLimit(string ip)
{
return CheckRateLimit(ip, MaxLoginAttemptsPerMinute, _authAttempts, _authAttemptLocks);
}
private void CleanupExpiredSessions()
@ -439,14 +453,29 @@ namespace GameCult.Networking
}
private void SendSessionToken(NetPeer peer, Guid playerId)
{
var player = _database.GetByIndex<PlayerData>("PlayerId", playerId.ToString("D"));
if (player == null)
{
peer.Send(new ErrorMessage { Error = "Session Not Found" });
return;
}
SendSessionToken(peer, player);
}
private void SendSessionToken(NetPeer peer, PlayerData player)
{
var expiresAtUtc = DateTimeOffset.UtcNow.AddSeconds(SessionTimeoutSeconds);
var token = Secret.CreateSessionToken(playerId, expiresAtUtc, _security);
player.SessionVersion++;
var token = Secret.CreateSessionToken(player.PlayerId, expiresAtUtc, player.SessionVersion, _security);
_database.AddAsync(player).GetAwaiter().GetResult();
if (_users.TryGetValue(peer.Id, out var user))
{
user.PlayerId = playerId;
user.PlayerId = player.PlayerId;
user.SessionExpiresAt = expiresAtUtc;
user.SessionVersion = player.SessionVersion;
user.SessionToken = token;
}
@ -467,6 +496,29 @@ namespace GameCult.Networking
SendSessionToken(peer, user.PlayerId);
}
private static bool CheckRateLimit(
string ip,
int maxAttemptsPerMinute,
ConcurrentDictionary<string, Queue<DateTimeOffset>> attemptBuckets,
ConcurrentDictionary<string, object> attemptLocks)
{
var now = DateTimeOffset.UtcNow;
var windowStart = now.AddMinutes(-1);
var queue = attemptBuckets.GetOrAdd(ip, _ => new Queue<DateTimeOffset>());
var gate = attemptLocks.GetOrAdd(ip, _ => new object());
lock (gate)
{
while (queue.Count > 0 && queue.Peek() < windowStart)
{
queue.Dequeue();
}
queue.Enqueue(now);
return queue.Count <= maxAttemptsPerMinute;
}
}
}
/// <summary>
@ -514,5 +566,10 @@ namespace GameCult.Networking
/// The latest signed session token issued to the peer.
/// </summary>
public string SessionToken = string.Empty;
/// <summary>
/// The session version associated with the latest issued token.
/// </summary>
public long SessionVersion;
}
}

View file

@ -0,0 +1,76 @@
# GameCult.Networking Production Hardening Checklist
This library is readying itself for trusted local mesh use: localhost, LAN, or
controlled self-hosted runtime clusters such as Epiphany and Aquarium. It is
not yet claiming sainthood on the public internet.
## Local-mesh baseline now covered
- separate connection-attempt and auth-attempt throttles in `Server`
- versioned session tokens that supersede older issued tokens
- bounded reconnect backoff with jitter in `Client`
- raw payload logging gated behind explicit diagnostic opt-in
- schema-first raw document/snapshot lane with exact `schemaId` routing
## Missing hostile-network organs
### Transport posture
- LiteNetLib remains the transport substrate.
- There is no transport-level TLS story in this library today.
- Before internet exposure, decide whether LiteNetLib stays and gains a real
outer protection model, or whether another transport becomes the canonical
public edge.
### Credential and replay posture
- login/register payloads are AES-GCM encrypted with per-message nonces
- session tokens are signed and versioned
- replay resistance is still scoped to token expiry + supersession semantics,
not a broader anti-replay protocol
Before hostile exposure:
- define replay expectations explicitly
- add adversarial tests around token reuse, stale reconnects, and reordered
message delivery
### Session rotation and revocation
- superseded tokens are rejected once a newer session version is issued
- there is still no broader account-session management surface for:
- explicit logout-all
- administrative revocation
- multi-device policy
### Input abuse and malformed payload handling
- malformed MessagePack is rejected by the serializer path
- there is no explicit message-size policy or backpressure contract yet
Before hostile exposure:
- add payload-size ceilings
- add stress tests for oversized and malformed inputs
- decide what gets dropped, logged, or disconnected
### Replication abuse cases
- raw snapshot/document replication assumes peers already share payload schema
and trust boundaries
- there is not yet an adversarial policy for untrusted replication partners
Before hostile exposure:
- define peer authorization for raw snapshot/document lanes
- test unknown schema spam, snapshot flooding, and incompatible payload storms
### Missing tests
Still wanted before claiming internet-grade readiness:
- live client/server auth integration tests
- reconnect storm tests
- session supersession across multiple clients
- message-size and malformed-frame abuse tests
- load and soak tests for rate limiting and session refresh