From 95d8bf575813b98a454acbc44ccb5e7a8e2db0ae Mon Sep 17 00:00:00 2001 From: endercodezz Date: Sun, 22 Nov 2026 04:09:34 +0200 Subject: [PATCH] Keep Fake TLS read scratch separate from the write buffer The bridge reads and writes the client stream concurrently. Skipping a ChangeCipherSpec payload reused the record buffer of a pending write, so the client could receive an ApplicationData record carrying the CCS bytes. Use a dedicated read-side buffer and add a regression test that parks a write while the reader skips a CCS. Closes #509 --- src/Bydlo.Engines/TgWsProxy/FakeTls.cs | 14 ++-- tests/Bydlo.Tests/FakeTlsConcurrencyTests.cs | 68 ++++++++++++++++++++ 2 files changed, 76 insertions(+), 6 deletions(-) create mode 100644 tests/Bydlo.Tests/FakeTlsConcurrencyTests.cs diff --git a/src/Bydlo.Engines/TgWsProxy/FakeTls.cs b/src/Bydlo.Engines/TgWsProxy/FakeTls.cs index 36e0a081..c91a6566 100644 --- a/src/Bydlo.Engines/TgWsProxy/FakeTls.cs +++ b/src/Bydlo.Engines/TgWsProxy/FakeTls.cs @@ -348,7 +348,12 @@ public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationTo internal sealed class FakeTlsStream(Stream inner) : Stream { private readonly byte[] _header = new byte[5]; + /// Write-side record buffer; only touches it. private byte[]? _record; + + /// Read-side scratch for skipped ChangeCipherSpec payloads (a record length is at most 65535). + private byte[]? _discard; + private int _recordLeft; public override bool CanRead => true; @@ -381,12 +386,9 @@ public override async ValueTask ReadAsync(Memory buffer, Cancellation { if (length > 0) { - _record ??= new byte[5 + FakeTls.MaxRecordPayload]; - await inner.ReadExactlyAsync(_record.AsMemory(0, Math.Min(length, _record.Length)), cancellationToken).ConfigureAwait(false); - if (length > _record.Length) - { - await inner.ReadExactlyAsync(new byte[length - _record.Length], cancellationToken).ConfigureAwait(false); - } + // Reads and writes run concurrently, so the discarded CCS payload never uses the write buffer. + _discard ??= new byte[ushort.MaxValue]; + await inner.ReadExactlyAsync(_discard.AsMemory(0, length), cancellationToken).ConfigureAwait(false); } continue; diff --git a/tests/Bydlo.Tests/FakeTlsConcurrencyTests.cs b/tests/Bydlo.Tests/FakeTlsConcurrencyTests.cs new file mode 100644 index 00000000..8f0741f7 --- /dev/null +++ b/tests/Bydlo.Tests/FakeTlsConcurrencyTests.cs @@ -0,0 +1,68 @@ +using Bydlo.Engines.TgWsProxy; + +namespace Bydlo.Tests; + +/// FakeTlsStream is read and written by two bridge workers at the same time. +public sealed class FakeTlsConcurrencyTests +{ + /// Serves scripted bytes to reads; holds every write until released and records it. + private sealed class GatedStream(byte[] incoming) : Stream + { + private int _offset; + public TaskCompletionSource WriteEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public TaskCompletionSource ReleaseWrite { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public MemoryStream Written { get; } = new(); + public override bool CanRead => true; + public override bool CanSeek => false; + public override bool CanWrite => true; + public override long Length => throw new NotSupportedException(); + public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var n = Math.Min(buffer.Length, incoming.Length - _offset); + incoming.AsSpan(_offset, n).CopyTo(buffer.Span); + _offset += n; + return ValueTask.FromResult(n); + } + + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + WriteEntered.TrySetResult(); + await ReleaseWrite.Task.WaitAsync(cancellationToken); + // Copy only now: a buffer reused by a concurrent read would show up here. + Written.Write(buffer.Span); + } + + public override int Read(byte[] buffer, int offset, int count) => ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(); + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + public override void Flush() { } + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + public override void SetLength(long value) => throw new NotSupportedException(); + } + + [Fact] + public async Task Skipping_a_change_cipher_spec_does_not_corrupt_a_pending_write() + { + // Incoming: a 200-byte CCS record (0xEE), then an ApplicationData record "ok". + var ccs = new byte[200]; + ccs.AsSpan().Fill(0xEE); + byte[] incoming = [0x14, 0x03, 0x03, 0x00, 200, .. ccs, 0x17, 0x03, 0x03, 0x00, 0x02, (byte)'o', (byte)'k']; + var inner = new GatedStream(incoming); + var tls = new FakeTlsStream(inner); + + var payload = new byte[300]; + Random.Shared.NextBytes(payload); + var write = tls.WriteAsync(payload.AsMemory()).AsTask(); + await inner.WriteEntered.Task.WaitAsync(TimeSpan.FromSeconds(10)); + + // The write is parked inside the inner stream while the reader skips the CCS payload. + var buffer = new byte[16]; + var read = await tls.ReadAsync(buffer.AsMemory()).AsTask().WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal("ok"u8.ToArray(), buffer[..read]); + + inner.ReleaseWrite.SetResult(); + await write.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal(FakeTlsStream.Wrap(payload), inner.Written.ToArray()); + } +}