StellaOps.Router.Transport.Tls
Router TLS transport, client side: connects a microservice to a gateway over TLS, with client certificates.
| Package | StellaOps.Router.Transport.Tls |
| Component | Router |
| Licence | Apache-2.0 |
| Package kind | Library |
| Target framework | net10.0 |
To add the package to a project, see Installing Stella Ops packages.
Namespaces
| Namespace | Types |
|---|---|
StellaOps.Router.Transport.Tls | 12 |
StellaOps.Router.Transport.Tls namespace
| Type | Kind | Description |
|---|---|---|
CertificateLoader | class | Utility class for loading certificates from various sources. |
CertificatePinningOptions | class | Certificate pinning configuration. |
CertificateWatcher | class | Watches certificate files for changes and triggers hot-reload. |
TlsCertificateValidator | class | Strict TLS certificate validator. |
TlsCertificateValidator.Reasons | class | Reason codes used in log messages and the rejection counter. |
TlsConnection | class | Represents a TLS-secured connection to a microservice. |
TlsTransportClient | class | TLS transport client implementation for microservices. |
TlsTransportClientServiceCollectionExtensions | class | Extension methods for registering TLS transport services. |
TlsTransportOptions | class | Options for TLS transport configuration. |
TlsTransportPlugin | class | Plugin for the client side of the TLS transport, which a microservice connects with. |
TlsValidationDecision | enum | Decision returned by TlsCertificateValidator.Validate(X509Certificate, X509Chain, SslPolicyErrors, TlsTransportOptions, bool, string, ILogger). |
TlsValidationResult | struct | Result of running the validator: an TlsValidationDecisionplus a machine-readable rejection reason for logging and the router_tls_validate_rejected_total{reason} counter. |
CertificateLoader class
public static class CertificateLoader
Utility class for loading certificates from various sources.
LoadCertificateFromPath(string, string, string) method
public static X509Certificate2 LoadCertificateFromPath(string certPath, string? keyPath = null, string? password = null)
Loads a certificate from a file path.
Parameters
certPath: The certificate path (PEM or PFX).keyPath: The private key path (optional, for PEM).password: The password (optional, for PFX).
Returns
The loaded certificate.
LoadClientCertificate(TlsTransportOptions) method
public static X509Certificate2? LoadClientCertificate(TlsTransportOptions options)
Loads a client certificate from the options.
Parameters
options: The TLS transport options.
Returns
The loaded certificate, or null if not configured.
LoadServerCertificate(TlsTransportOptions) method
public static X509Certificate2 LoadServerCertificate(TlsTransportOptions options)
Loads a server certificate from the options.
Parameters
options: The TLS transport options.
Returns
The loaded certificate.
Exceptions
InvalidOperationException: Thrown when no certificate is configured.
CertificatePinningOptions class
public sealed class CertificatePinningOptions
Certificate pinning configuration. Required when TlsTransportOptions.AllowSelfSignedis true — otherwise the validator would accept any self-signed certificate.
At least one of the three pin sets must be non-empty when self-signed acceptance is enabled. Pin matching is any-of: a presented certificate is acceptable when its SHA-256 thumbprint OR its subject DN OR any of its SAN DNS entries matches an entry in the corresponding allowlist.
Recommended posture, in tightening order: 1. CertificatePinningOptions.ThumbprintsSha256only (leaf-pinning; rotates require config update) 2. Subject pinning to a private CA (leaf rotation without re-pinning) 3. SAN allowlist (loosest; relies on operator-issued cert names)
CertificatePinningOptions() constructor
public CertificatePinningOptions()
Creates an instance of CertificatePinningOptions.
AllowedSans property
public IReadOnlyList<string> AllowedSans { get; init; }
Allowed Subject Alternative Name DNS entries. Compared via StringComparer.Ordinal against entries extracted from the cert’s SAN extension. Wildcard entries are not expanded — provide the exact value.
AllowedSubjects property
public IReadOnlyList<string> AllowedSubjects { get; init; }
Allowed subject distinguished names. Compared via StringComparer.Ordinal against X509Certificate.Subject. Use the exact RFC-2253 form emitted by .NET (e.g. CN=service-a, O=stellaops).
IsEmpty property
public bool IsEmpty { get; }
Returns true when no pin entries are configured at all.
ThumbprintsSha256 property
public IReadOnlyList<string> ThumbprintsSha256 { get; init; }
Allowed certificate SHA-256 thumbprints, hex-encoded (case-insensitive on input, normalised to upper-case for matching). Matching uses StringComparer.Ordinal after normalisation. An empty/whitespace string is ignored.
CertificateWatcher class
public sealed class CertificateWatcher : IDisposable
Watches certificate files for changes and triggers hot-reload.
CertificateWatcher(TlsTransportOptions, ILogger) constructor
public CertificateWatcher(TlsTransportOptions options, ILogger logger)
Initializes a new instance of the CertificateWatcherclass.
ClientCertificate property
public X509Certificate2? ClientCertificate { get; }
Gets the current client certificate.
ServerCertificate property
public X509Certificate2? ServerCertificate { get; }
Gets the current server certificate.
OnClientCertificateReloaded event
public event Action<X509Certificate2>? OnClientCertificateReloaded
Event raised when the client certificate is reloaded.
OnServerCertificateReloaded event
public event Action<X509Certificate2>? OnServerCertificateReloaded
Event raised when the server certificate is reloaded.
Dispose() method
public void Dispose()
See IDisposable.Dispose().
TlsCertificateValidator class
public static class TlsCertificateValidator
Strict TLS certificate validator.
Rules, in order: 1. Errors include SslPolicyErrors.RemoteCertificateNotAvailable -> reject. 2. Errors include SslPolicyErrors.RemoteCertificateNameMismatch -> reject unconditionally, regardless of AllowSelfSigned. 3. Errors include SslPolicyErrors.RemoteCertificateChainErrors: - When AllowSelfSigned=false: reject. - When AllowSelfSigned=true: accept only if the chain status is exactly X509ChainStatusFlags.UntrustedRoot or X509ChainStatusFlags.PartialChain (no other status flags) AND the certificate matches the configured pin set. 4. No errors -> accept.
Both sides of the TLS transport apply it: the client to the gateway’s server certificate and the server (StellaOps.Router.Transport.Tls.Server) to a microservice’s client certificate.
MeterName constant
public const string MeterName = "StellaOps.Router.Transport.Tls"
Meter name for OpenTelemetry exporters.
Validate(X509Certificate, X509Chain, SslPolicyErrors, TlsTransportOptions, bool, string, ILogger) method
public static TlsValidationResult Validate(X509Certificate? certificate, X509Chain? chain, SslPolicyErrors errors, TlsTransportOptions options, bool requireCertificate, string role, ILogger logger)
Runs the validator and emits structured-log + counter side effects on rejection.
Parameters
certificate: The presented peer certificate, ornull.chain: The chain object built bySslStream.errors: The errors raised by the platform validator.options: The transport options carrying pinning / self-signed config.requireCertificate: Whether absence of a certificate is itself a rejection (server side: mTLS required; client side: always required since the gateway always presents one).role: Either"client_certificate"or"server_certificate"; emitted on the counter and in log messages so server-side and client-side rejections can be distinguished in metrics.logger: Logger for warning-level rejection messages.
TlsCertificateValidator.Reasons class
public static class Reasons
Reason codes used in log messages and the rejection counter.
CertificateRequiredButMissing constant
public const string CertificateRequiredButMissing = "certificate_required_but_missing"
A certificate is required and the peer presented none.
ChainErrorAndSelfSignedDisallowed constant
public const string ChainErrorAndSelfSignedDisallowed = "chain_error_and_self_signed_disallowed"
The chain does not validate and self-signed certificates are not allowed.
ChainStatusNotPermitted constant
public const string ChainStatusNotPermitted = "chain_status_not_permitted"
The chain status is other than an untrusted root or a partial chain.
NameMismatch constant
public const string NameMismatch = "name_mismatch"
The certificate name does not match the peer.
OtherSslPolicyError constant
public const string OtherSslPolicyError = "other_ssl_policy_error"
Another TLS policy error.
PinMismatch constant
public const string PinMismatch = "pin_mismatch"
The certificate matches no configured pin.
PinSetEmpty constant
public const string PinSetEmpty = "pin_set_empty"
Self-signed certificates are allowed but no pin is configured.
RemoteCertificateNotAvailable constant
public const string RemoteCertificateNotAvailable = "remote_certificate_not_available"
The platform reported that the remote certificate is not available.
TlsConnection class
public sealed class TlsConnection : IAsyncDisposable
Represents a TLS-secured connection to a microservice.
TlsConnection(string, TcpClient, SslStream, TlsTransportOptions, ILogger) constructor
public TlsConnection(string connectionId, TcpClient client, SslStream sslStream, TlsTransportOptions options, ILogger logger)
Initializes a new instance of the TlsConnectionclass.
ConnectionId property
public string ConnectionId { get; }
Gets the connection ID.
ConnectionToken property
public CancellationToken ConnectionToken { get; }
Gets the cancellation token for this connection.
IsConnected property
public bool IsConnected { get; }
Gets a value indicating whether the connection is active.
PeerIdentity property
public string? PeerIdentity { get; }
Gets the peer identity extracted from the certificate.
RemoteCertificate property
public X509Certificate? RemoteCertificate { get; }
Gets the remote certificate (if mTLS).
RemoteEndpoint property
public string RemoteEndpoint { get; }
Gets the remote endpoint as a string.
State property
public ConnectionState? State { get; set; }
Gets the connection state.
OnDisconnected event
public event Action<TlsConnection, Exception?>? OnDisconnected
Event raised when the connection is closed.
OnFrameReceived event
public event Action<TlsConnection, Frame>? OnFrameReceived
Event raised when a frame is received.
Close() method
public void Close()
Closes the connection.
DisposeAsync() method
public ValueTask DisposeAsync()
See IAsyncDisposable.DisposeAsync().
ReadLoopAsync(CancellationToken) method
public Task ReadLoopAsync(CancellationToken cancellationToken)
Starts the read loop to receive frames.
Parameters
cancellationToken: Cancellation token.
WriteFrameAsync(Frame, CancellationToken) method
public Task WriteFrameAsync(Frame frame, CancellationToken cancellationToken = default)
Writes a frame to the connection.
Parameters
frame: The frame to write.cancellationToken: Cancellation token.
TlsTransportClient class
public sealed class TlsTransportClient : ITransportClient, IMicroserviceTransport, IAsyncDisposable
TLS transport client implementation for microservices.
TlsTransportClient(IOptions<TlsTransportOptions>, ILogger<TlsTransportClient>) constructor
public TlsTransportClient(IOptions<TlsTransportOptions> options, ILogger<TlsTransportClient> logger)
Initializes a new instance of the TlsTransportClientclass.
OnCancelReceived event
public event Func<Guid, string?, Task>? OnCancelReceived
Event raised when a CANCEL frame is received.
OnRequestReceived event
public event Func<Frame, CancellationToken, Task<Frame>>? OnRequestReceived
Event raised when a REQUEST frame is received.
TransportDied event
public event Action? TransportDied
Raised once when the connection is lost and TlsTransportOptions.MaxReconnectAttemptsreconnects have failed. The service’s connection manager then connects again with its own back-off until the gateway answers or the service stops.
CancelAllInflight(string) method
public void CancelAllInflight(string reason)
Cancels all in-flight handlers.
ConnectAsync(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, CancellationToken) method
public Task ConnectAsync(InstanceDescriptor instance, IReadOnlyList<EndpointDescriptor> endpoints, CancellationToken cancellationToken)
Connects to the gateway.
Parameters
instance: The instance descriptor.endpoints: The endpoints to register.cancellationToken: Cancellation token.
ConnectAsync(InstanceDescriptor, IReadOnlyList<EndpointDescriptor>, IReadOnlyDictionary<string, SchemaDefinition>, ServiceOpenApiInfo, CancellationToken) method
public Task ConnectAsync(InstanceDescriptor instance, IReadOnlyList<EndpointDescriptor> endpoints, IReadOnlyDictionary<string, SchemaDefinition>? schemas, ServiceOpenApiInfo? openApiInfo, CancellationToken cancellationToken)
Connects to the gateway and registers the instance, its endpoints, schemas and OpenAPI metadata in the HELLO frame.
Parameters
instance: The instance descriptor.endpoints: The endpoints to register.schemas: Schema definitions referenced by the endpoints.openApiInfo: OpenAPI metadata for the service.cancellationToken: Cancellation token.
DisconnectAsync() method
public Task DisconnectAsync()
Disconnects from the gateway.
DisposeAsync() method
public ValueTask DisposeAsync()
See IAsyncDisposable.DisposeAsync().
SendCancelAsync(ConnectionState, Guid, string) method
public Task SendCancelAsync(ConnectionState connection, Guid correlationId, string? reason = null)
Sends a cancellation request.
Parameters
connection: The connection to use.correlationId: The correlation ID of the request to cancel.reason: Optional reason for cancellation.
SendHeartbeatAsync(HeartbeatPayload, CancellationToken) method
public Task SendHeartbeatAsync(HeartbeatPayload heartbeat, CancellationToken cancellationToken)
Sends a heartbeat.
SendRequestAsync(ConnectionState, Frame, TimeSpan, CancellationToken) method
public Task<Frame> SendRequestAsync(ConnectionState connection, Frame requestFrame, TimeSpan timeout, CancellationToken cancellationToken)
Sends a request and waits for a response.
Parameters
connection: The connection to use.requestFrame: The request frame.timeout: The timeout for the request.cancellationToken: Cancellation token.
Returns
The response frame.
SendStreamingAsync(ConnectionState, Frame, Stream, Func<ResponseFrame, Stream, Task>, PayloadLimits, CancellationToken) method
public Task SendStreamingAsync(ConnectionState connection, Frame requestHeader, Stream requestBody, Func<ResponseFrame, Stream, Task> readResponse, PayloadLimits limits, CancellationToken cancellationToken)
Sends a request whose body is read from a stream and hands the microservice’s response to readResponse. TransportStreamingDispatch.SendBufferedAsync(ITransportClient, ConnectionState, Frame, Stream, Func<ResponseFrame, Stream, Task>, PayloadLimits, CancellationToken)implements it for transports whose microservice side answers a request with one response frame.
Parameters
connection: The connection to use.requestHeader: The request header frame.requestBody: The request body stream.readResponse: Callback that receives the response head (the status code and headers of the microservice’s response; itsResponseFrame.Payloadis empty) and the response body stream.limits: Payload limits to enforce.cancellationToken: Cancellation token.
Remarks
Sends the request body in one request frame (TransportStreamingDispatch.SendBufferedAsync(ITransportClient, ConnectionState, Frame, Stream, Func<ResponseFrame, Stream, Task>, PayloadLimits, CancellationToken)).
TlsTransportClientServiceCollectionExtensions class
public static class TlsTransportClientServiceCollectionExtensions
Extension methods for registering TLS transport services.
AddTlsTransportClient(IServiceCollection, Action<TlsTransportOptions>) extension method
public static IServiceCollection AddTlsTransportClient(this IServiceCollection services, Action<TlsTransportOptions>? configure = null)
Adds the TLS transport client to the service collection.
Parameters
services: The service collection.configure: Configuration action.
Returns
The service collection.
TlsTransportOptions class
public sealed class TlsTransportOptions
Options for TLS transport configuration.
TlsTransportOptions() constructor
public TlsTransportOptions()
Creates an instance of TlsTransportOptions.
AllowSelfSigned property
public bool AllowSelfSigned { get; set; }
Gets or sets whether to allow self-signed certificates (dev only).
BindAddress property
public IPAddress BindAddress { get; set; }
Gets or sets the bind address for the server.
CertificatePinning property
public CertificatePinningOptions CertificatePinning { get; set; }
Certificate pinning configuration. Required when TlsTransportOptions.AllowSelfSignedis true: without a pin set, that validator would accept any self-signed certificate, so startup fails with a descriptive error when self-signed acceptance has no pin set.
When TlsTransportOptions.AllowSelfSignedis false, pinning is optional but still applied as a defence-in-depth check on top of standard chain validation.
CheckCertificateRevocation property
public bool CheckCertificateRevocation { get; set; }
Gets or sets whether to check certificate revocation.
ClientCertificate property
public X509Certificate2? ClientCertificate { get; set; }
Gets or sets the client certificate object.
ClientCertificateKeyPath property
public string? ClientCertificateKeyPath { get; set; }
Gets or sets the client certificate key path (PEM private key).
ClientCertificatePassword property
public string? ClientCertificatePassword { get; set; }
Gets or sets the client certificate password (for PFX).
ClientCertificatePath property
public string? ClientCertificatePath { get; set; }
Gets or sets the client certificate path (PEM or PFX).
ConnectTimeout property
public TimeSpan ConnectTimeout { get; set; }
Gets or sets the connection timeout.
EnableCertificateHotReload property
public bool EnableCertificateHotReload { get; set; }
Gets or sets whether to enable certificate hot-reload.
EnabledProtocols property
public SslProtocols EnabledProtocols { get; set; }
Gets or sets the enabled SSL/TLS protocols.
ExpectedServerHostname property
public string? ExpectedServerHostname { get; set; }
Gets or sets the expected server hostname (for SNI).
Host property
public string? Host { get; set; }
Gets or sets the host to connect to (client only).
KeepAliveInterval property
public TimeSpan KeepAliveInterval { get; set; }
Gets or sets the TCP keep-alive interval of the connection’s socket, on the service and on the gateway: after this long without traffic the operating system probes the peer, probes again every interval and closes the connection after three unanswered probes, so a peer that vanished without closing the connection is noticed. Zero or a negative value turns keep-alive off. Whole seconds, rounded up. Default: 30 seconds.
MaxFrameSize property
public int MaxFrameSize { get; set; }
Gets or sets the maximum frame size.
MaxReconnectAttempts property
public int MaxReconnectAttempts { get; set; }
Gets or sets the number of reconnection attempts after a lost connection, with the capped back-off of TlsTransportOptions.MaxReconnectBackoff. When they all fail, the client raises TlsTransportClient.TransportDiedand the service’s connection manager connects again with its own back-off until the gateway answers or the service stops; the service is never left disconnected. Default: 10.
MaxReconnectBackoff property
public TimeSpan MaxReconnectBackoff { get; set; }
Gets or sets the maximum reconnection backoff.
Port property
public int Port { get; set; }
Gets or sets the port to listen on, or the gateway port a client connects to. Default: TransportDefaultPorts.Tls(9443), the gateway options’ default.
ReceiveBufferSize property
public int ReceiveBufferSize { get; set; }
Gets or sets the receive buffer size.
RequireClientCertificate property
public bool RequireClientCertificate { get; set; }
Gets or sets whether to require client certificates (mTLS).
SendBufferSize property
public int SendBufferSize { get; set; }
Gets or sets the send buffer size.
ServerCertificate property
public X509Certificate2? ServerCertificate { get; set; }
Gets or sets the server certificate object.
ServerCertificateKeyPath property
public string? ServerCertificateKeyPath { get; set; }
Gets or sets the server certificate key path (PEM private key).
ServerCertificatePassword property
public string? ServerCertificatePassword { get; set; }
Gets or sets the server certificate password (for PFX).
ServerCertificatePath property
public string? ServerCertificatePath { get; set; }
Gets or sets the server certificate path (PEM or PFX).
Validate() method
public void Validate()
Validates the option combination and throws InvalidOperationException if the configuration would accept any self-signed certificate (self-signed acceptance without a pin set). Called by TlsTransportServer (StellaOps.Router.Transport.Tls.Server) and TlsTransportClientat startup.
TlsTransportPlugin class
public sealed class TlsTransportPlugin : IRouterTransportPlugin
Plugin for the client side of the TLS transport, which a microservice connects with. The server side is TlsTransportServerPlugin in StellaOps.Router.Transport.Tls.Server; both carry the transport name tls.
TlsTransportPlugin() constructor
public TlsTransportPlugin()
Creates an instance of TlsTransportPlugin.
DisplayName property
public string DisplayName { get; }
Gets the human-readable display name for this transport.
Mode property
public RouterTransportMode Mode { get; }
Gets the side of the transport this plugin registers: RouterTransportMode.Client, RouterTransportMode.Server, or RouterTransportMode.Both. IRouterTransportPlugin.Register(RouterTransportRegistrationContext)refuses a context that asks for a side outside this value (RouterTransportRegistrationContext.EnsureSupportedBy(IRouterTransportPlugin)).
TransportName property
public string TransportName { get; }
Gets the transport name (e.g., “tcp”, “tls”, “udp”, “rabbitmq”, “inmemory”, “messaging”), shared by the client and the server plugin of one transport.
Register(RouterTransportRegistrationContext) method
public void Register(RouterTransportRegistrationContext context)
Registers transport services into the DI container for the side the context asks for.
Parameters
context: The registration context containing services, configuration, and transport mode.
Exceptions
InvalidOperationException: The context asks for a side this plugin does not provide.
RegisterShared(RouterTransportRegistrationContext) method
public static void RegisterShared(RouterTransportRegistrationContext context)
The registration the client and the server plugin of the TLS transport share: the TlsTransportOptionsbinding of the context’s configuration section (Router:Transport:Tls when the context names none). Both plugins call it from TlsTransportPlugin.Register(RouterTransportRegistrationContext); a plugin for either side of the transport calls it the same way.
Parameters
context: The registration context of the plugin.
TlsValidationDecision enum
public enum TlsValidationDecision
Decision returned by TlsCertificateValidator.Validate(X509Certificate, X509Chain, SslPolicyErrors, TlsTransportOptions, bool, string, ILogger).
| Value | Description |
|---|---|
Accept = 0 | Validation passed; the certificate is trusted. |
Reject = 1 | Validation failed; the certificate must be rejected. |
TlsValidationResult struct
public readonly struct TlsValidationResult : IEquatable<TlsValidationResult>
Result of running the validator: an TlsValidationDecisionplus a machine-readable rejection reason for logging and the router_tls_validate_rejected_total{reason} counter.
Parameters
Decision: Whether the certificate is accepted.Reason: The rejection reason, one ofTlsCertificateValidator.Reasons; not set on acceptance.
TlsValidationResult(TlsValidationDecision, string) constructor
public TlsValidationResult(TlsValidationDecision Decision, string? Reason)
Result of running the validator: an TlsValidationDecisionplus a machine-readable rejection reason for logging and the router_tls_validate_rejected_total{reason} counter.
Parameters
Decision: Whether the certificate is accepted.Reason: The rejection reason, one ofTlsCertificateValidator.Reasons; not set on acceptance.
Decision property
public TlsValidationDecision Decision { get; init; }
Whether the certificate is accepted.
Reason property
public string? Reason { get; init; }
The rejection reason, one of TlsCertificateValidator.Reasons; not set on acceptance.
