Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions src/Bydlo.Engines/TgWsProxy/FakeTls.cs
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,12 @@ public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationTo
internal sealed class FakeTlsStream(Stream inner) : Stream
{
private readonly byte[] _header = new byte[5];
/// <summary>Write-side record buffer; only <see cref="WriteAsync(ReadOnlyMemory{byte}, CancellationToken)"/> touches it.</summary>
private byte[]? _record;

/// <summary>Read-side scratch for skipped ChangeCipherSpec payloads (a record length is at most 65535).</summary>
private byte[]? _discard;

private int _recordLeft;

public override bool CanRead => true;
Expand Down Expand Up @@ -381,12 +386,9 @@ public override async ValueTask<int> ReadAsync(Memory<byte> 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;
Expand Down
68 changes: 68 additions & 0 deletions tests/Bydlo.Tests/FakeTlsConcurrencyTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
using Bydlo.Engines.TgWsProxy;

namespace Bydlo.Tests;

/// <summary>FakeTlsStream is read and written by two bridge workers at the same time.</summary>
public sealed class FakeTlsConcurrencyTests
{
/// <summary>Serves scripted bytes to reads; holds every write until released and records it.</summary>
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<int> ReadAsync(Memory<byte> 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<byte> 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());
}
}
Loading