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
12 changes: 2 additions & 10 deletions src/Orleans.Connections.Security/Hosting/HostingExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,7 @@ public static void UseServerTls(
}

var loggerFactory = builder.ApplicationServices.GetService(typeof(ILoggerFactory)) as ILoggerFactory ?? NullLoggerFactory.Instance;
builder.Use(next =>
{
var middleware = new TlsServerConnectionMiddleware(next, options, loggerFactory);
return middleware.OnConnectionAsync;
});
builder.UseMiddleware(new TlsServerConnectionMiddleware(options, loggerFactory));
}

public static void UseClientTls(
Expand All @@ -36,11 +32,7 @@ public static void UseClientTls(
}

var loggerFactory = builder.ApplicationServices.GetService(typeof(ILoggerFactory)) as ILoggerFactory ?? NullLoggerFactory.Instance;
builder.Use(next =>
{
var middleware = new TlsClientConnectionMiddleware(next, options, loggerFactory);
return middleware.OnConnectionAsync;
});
builder.UseMiddleware(new TlsClientConnectionMiddleware(options, loggerFactory));
}

internal static void ThrowNoPrivateKey(X509Certificate2 certificate, string parameterName)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,24 @@
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.Extensions.Logging;
using Orleans.Runtime.Messaging;

namespace Orleans.Connections.Security
{
internal partial class TlsClientConnectionMiddleware
internal partial class TlsClientConnectionMiddleware : IConnectionMiddleware
{
private readonly ConnectionDelegate _next;
private readonly TlsOptions _options;
private readonly ILogger? _logger;
private readonly X509Certificate2? _certificate;
private readonly Func<object, string, X509CertificateCollection, X509Certificate?, string[], X509Certificate2?>? _certificateSelector;

public TlsClientConnectionMiddleware(ConnectionDelegate next, TlsOptions options, ILoggerFactory? loggerFactory)
public TlsClientConnectionMiddleware(TlsOptions options, ILoggerFactory? loggerFactory)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}

_next = next;

// capture the certificate now so it can't be switched after validation
_certificate = ValidateCertificate(options.LocalCertificate, options.ClientCertificateMode);
_certificateSelector = options.LocalClientCertificateSelector;
Expand All @@ -37,12 +35,12 @@ public TlsClientConnectionMiddleware(ConnectionDelegate next, TlsOptions options
_logger = loggerFactory?.CreateLogger<TlsClientConnectionMiddleware>();
}

public Task OnConnectionAsync(ConnectionContext context)
public Task OnConnectionAsync(ConnectionContext context, ConnectionDelegate next)
{
return InnerOnConnectionAsync(context);
return InnerOnConnectionAsync(context, next);
}

private async Task InnerOnConnectionAsync(ConnectionContext context)
private async Task InnerOnConnectionAsync(ConnectionContext context, ConnectionDelegate next)
{
var feature = new TlsConnectionFeature();
context.Features.Set<ITlsConnectionFeature>(feature);
Expand Down Expand Up @@ -195,7 +193,7 @@ private async Task InnerOnConnectionAsync(ConnectionContext context)
await using (sslStream)
await using (tlsDuplexPipe)
{
await _next(context);
await next(context);
// Dispose the inner stream (tlsDuplexPipe) before disposing the SslStream
// as the duplex pipe can hit an ODE as it still may be writing.
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,24 @@
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Connections.Features;
using Microsoft.Extensions.Logging;
using Orleans.Runtime.Messaging;

namespace Orleans.Connections.Security
{
internal partial class TlsServerConnectionMiddleware
internal partial class TlsServerConnectionMiddleware : IConnectionMiddleware
{
private readonly ConnectionDelegate _next;
private readonly TlsOptions _options;
private readonly ILogger? _logger;
private readonly X509Certificate2? _certificate;
private readonly Func<ConnectionContext, string?, X509Certificate2>? _certificateSelector;

public TlsServerConnectionMiddleware(ConnectionDelegate next, TlsOptions options, ILoggerFactory? loggerFactory)
public TlsServerConnectionMiddleware(TlsOptions options, ILoggerFactory? loggerFactory)
{
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}

_next = next;

// capture the certificate now so it can't be switched after validation
_certificate = options.LocalCertificate;
_certificateSelector = options.LocalServerCertificateSelector;
Expand All @@ -50,12 +48,12 @@ public TlsServerConnectionMiddleware(ConnectionDelegate next, TlsOptions options
_logger = loggerFactory?.CreateLogger<TlsServerConnectionMiddleware>();
}

public Task OnConnectionAsync(ConnectionContext context)
public Task OnConnectionAsync(ConnectionContext context, ConnectionDelegate next)
{
return InnerOnConnectionAsync(context);
return InnerOnConnectionAsync(context, next);
}

private async Task InnerOnConnectionAsync(ConnectionContext context)
private async Task InnerOnConnectionAsync(ConnectionContext context, ConnectionDelegate next)
{
bool certificateRequired;
var feature = new TlsConnectionFeature();
Expand Down Expand Up @@ -222,7 +220,7 @@ private async Task InnerOnConnectionAsync(ConnectionContext context)
await using (sslStream)
await using (tlsDuplexPipe)
{
await _next(context);
await next(context);
// Dispose the inner stream (TlsDuplexPipe) before disposing the SslStream
// as the duplex pipe can hit an ODE as it still may be writing.
}
Expand Down
242 changes: 242 additions & 0 deletions src/Orleans.Core/Networking/ConnectionFrameHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.IO.Pipelines;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Connections;

namespace Orleans.Runtime.Messaging
{
/// <summary>
/// Provides framing utilities for connection middleware authors.
/// <para>
/// Wire format per frame: [4-byte LE length] [1-byte frame type] [payload].
/// The length field equals 1 + payload.Length.
/// </para>
/// <para>
/// Connection middlewares should follow the <see cref="ConnectionDelegate"/> pipeline pattern
/// (like TLS) and register via <c>SiloConnectionOptions</c> or <c>ClientConnectionOptions</c>.
/// Use these helpers for structured frame I/O within your middleware.
/// </para>
/// <para>
/// This helper is optional. Middleware authors who need custom protocols can read/write
/// directly from <c>context.Transport.Input</c> (PipeReader) and <c>context.Transport.Output</c>
/// (PipeWriter) without using this class.
/// </para>
/// </summary>
public static class ConnectionFrameHelper
{
/// <summary>
/// Default maximum frame length (1 MB).
/// </summary>
public const int DefaultMaxFrameLength = 1024 * 1024;

/// <summary>
/// Prefix size: 4 bytes (LE length) + 1 byte (frame type) = 5 bytes.
/// </summary>
public const int FramePrefixSize = 5;

/// <summary>
/// Reads a single frame from the connection.
/// </summary>
public static async ValueTask<(byte FrameType, byte[] Payload)> ReadFrameAsync(
ConnectionContext connection,
CancellationToken cancellationToken,
int maxFrameLength = DefaultMaxFrameLength)
{
var input = connection.Transport.Input;

var readResult = await input.ReadAsync(cancellationToken);
var buffer = readResult.Buffer;
CheckCompletionWithData(ref readResult, 4);

while (buffer.Length < 4)
{
input.AdvanceTo(buffer.Start, buffer.End);
readResult = await input.ReadAsync(cancellationToken);
buffer = readResult.Buffer;
CheckCompletionWithData(ref readResult, 4);
}

var lengthBytes = new byte[4];
buffer.Slice(0, 4).CopyTo(lengthBytes);
var frameLength = BinaryPrimitives.ReadInt32LittleEndian(lengthBytes);

if (frameLength < 1)
throw new InvalidOperationException($"Invalid frame length: {frameLength}. Minimum is 1 (frame type byte).");
if (frameLength > maxFrameLength)
throw new InvalidOperationException($"Frame length {frameLength} exceeds maximum allowed length of {maxFrameLength}.");

input.AdvanceTo(buffer.GetPosition(4));

var frameBytes = new byte[frameLength];
var bytesRead = 0;
while (bytesRead < frameLength)
{
readResult = await input.ReadAsync(cancellationToken);
buffer = readResult.Buffer;

if (readResult.IsCanceled)
{
input.AdvanceTo(buffer.Start, buffer.End);
throw new InvalidOperationException("Connection terminated during frame exchange.");
}

var bytesToCopy = (int)Math.Min(buffer.Length, frameLength - bytesRead);
buffer.Slice(0, bytesToCopy).CopyTo(frameBytes.AsSpan(bytesRead, bytesToCopy));
bytesRead += bytesToCopy;
input.AdvanceTo(buffer.GetPosition(bytesToCopy));

if (readResult.IsCompleted && bytesRead < frameLength)
{
throw new InvalidOperationException("Connection terminated during frame exchange.");
}
}

byte frameType = frameBytes[0];
byte[] payload;
if (frameLength > 1)
{
payload = new byte[frameLength - 1];
Array.Copy(frameBytes, 1, payload, 0, payload.Length);
}
else
{
payload = Array.Empty<byte>();
}

return (frameType, payload);
}

/// <summary>
/// Writes a frame with the given type and raw payload bytes.
/// </summary>
public static async ValueTask WriteFrameAsync(
ConnectionContext connection,
byte frameType,
byte[] payload,
CancellationToken cancellationToken)
{
WriteFrameToOutput(connection.Transport.Output, frameType, payload);
await FlushFrameAsync(connection.Transport.Output, cancellationToken);
}

/// <summary>
/// Writes a frame using zero-copy framing via <see cref="PrefixingBufferWriter"/>.
/// The <paramref name="writePayload"/> delegate writes payload directly into the transport pipe buffer.
/// </summary>
public static async ValueTask WriteFrameAsync(
ConnectionContext connection,
byte frameType,
Action<IBufferWriter<byte>> writePayload,
CancellationToken cancellationToken)
{
WriteFrameWithPrefixingWriter(connection.Transport.Output, frameType, writePayload, MemoryPool<byte>.Shared);
await FlushFrameAsync(connection.Transport.Output, cancellationToken);
}

private static async ValueTask FlushFrameAsync(PipeWriter output, CancellationToken cancellationToken)
{
var flushResult = await output.FlushAsync(cancellationToken);
if (flushResult.IsCanceled)
throw new OperationCanceledException("Flush canceled while writing frame.");
if (flushResult.IsCompleted)
throw new InvalidOperationException("Connection terminated while writing frame.");
}

/// <summary>
/// Writes a length-prefixed UTF-8 string (4-byte LE length + bytes) into a buffer.
/// </summary>
public static void WriteLengthPrefixedString(IBufferWriter<byte> writer, string value)
{
var bytes = Encoding.UTF8.GetBytes(value ?? string.Empty);

var lengthSpan = writer.GetSpan(4);
BinaryPrimitives.WriteInt32LittleEndian(lengthSpan, bytes.Length);
writer.Advance(4);

if (bytes.Length > 0)
{
var dataSpan = writer.GetSpan(bytes.Length);
bytes.CopyTo(dataSpan);
writer.Advance(bytes.Length);
}
}

/// <summary>
/// Reads a length-prefixed UTF-8 string from a payload byte array.
/// </summary>
public static string ReadLengthPrefixedString(byte[] data, ref int offset)
{
if ((uint)offset > (uint)data.Length || data.Length - offset < sizeof(int))
throw new InvalidOperationException("Not enough data to read string length.");

var length = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(offset, sizeof(int)));
offset += sizeof(int);

if (length < 0)
throw new InvalidOperationException($"Invalid string length: {length}.");
if (length == 0)
return string.Empty;
if (length > data.Length - offset)
throw new InvalidOperationException($"Not enough data to read string of length {length}. Available: {data.Length - offset}.");

var result = Encoding.UTF8.GetString(data, offset, length);
offset += length;
return result;
}

private static void WriteFrameToOutput(PipeWriter output, byte frameType, byte[] payload)
{
var payloadLength = payload?.Length ?? 0;
var frameLength = 1 + payloadLength;

Span<byte> prefix = stackalloc byte[FramePrefixSize];
BinaryPrimitives.WriteInt32LittleEndian(prefix, frameLength);
prefix[4] = frameType;
output.Write(prefix);

if (payloadLength > 0)
{
output.Write(payload);
}
}

private static void WriteFrameWithPrefixingWriter(
PipeWriter output,
byte frameType,
Action<IBufferWriter<byte>> writeBody,
MemoryPool<byte> memoryPool)
{
using var prefixWriter = new PrefixingBufferWriter(FramePrefixSize, 256, memoryPool);
prefixWriter.Init(output);

try
{
writeBody?.Invoke(prefixWriter);

var payloadLength = prefixWriter.CommittedBytes;
var frameLength = 1 + payloadLength;
Span<byte> prefix = stackalloc byte[FramePrefixSize];
BinaryPrimitives.WriteInt32LittleEndian(prefix, frameLength);
prefix[4] = frameType;

prefixWriter.Complete(prefix);
}
finally
{
prefixWriter.Reset();
}
}

private static void CheckCompletionWithData(ref ReadResult result, long required)
{
if (result.IsCanceled)
throw new InvalidOperationException("Connection terminated during frame exchange.");
if (result.IsCompleted && result.Buffer.Length < required)
throw new InvalidOperationException("Connection terminated during frame exchange.");
}
}
}
Loading
Loading