Path: redb-route/redb.Route.RabbitMQ/RabbitMQConnectionFactory.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.RabbitMQ/RabbitMQConnectionFactory.cs ---- using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using global::RabbitMQ.Client; using Microsoft.Extensions.Logging; using redb.Route.Core; namespace redb.Route.RabbitMQ; /// /// Connection factory configuration for RabbitMQ. Register in the route registry /// and reference by name in endpoint URIs (connectionFactory=myFactory). /// Supports cluster mode via comma-separated hosts. /// public sealed class RabbitMQConnectionFactory { /// Host name or comma-separated list for cluster mode. public string Host { get; set; } = "localhost"; /// AMQP port (default: 5672; the broker's TLS listener is usually 5671). public int Port { get; set; } = 5672; /// Username (default: guest). Not used with or OAuth2. public string Username { get; set; } = "guest"; /// Password (default: guest). Not used with or OAuth2. [Sensitive] public string Password { get; set; } = "guest"; /// Virtual host (default: /). public string VirtualHost { get; set; } = "/"; /// Enable automatic recovery (default: true). public bool AutomaticRecovery { get; set; } = true; /// Re-declare topology (exchanges, queues, bindings) after recovery (default: true). Critical for cluster. public bool TopologyRecoveryEnabled { get; set; } = true; /// Network recovery interval in seconds (default: 5). public int RecoveryInterval { get; set; } = 5; /// Requested heartbeat in seconds (default: 60). public int Heartbeat { get; set; } = 60; /// Connection timeout in seconds (default: 60). Prevents hangs on unreachable cluster nodes. public int ConnectionTimeout { get; set; } = 60; /// Socket read timeout in seconds (default: 30). Detects dead TCP connections faster than heartbeat alone. public int SocketReadTimeout { get; set; } = 30; /// Socket write timeout in seconds (default: 30). public int SocketWriteTimeout { get; set; } = 30; /// Timeout for AMQP protocol-level continuations in seconds (default: 30). Prevents indefinite hangs on declare/bind. public int ContinuationTimeout { get; set; } = 30; /// Concurrent dispatch limit per connection (default: 1). Controls how many messages the client dispatches concurrently. public ushort ConsumerDispatchConcurrency { get; set; } = 1; // ── TLS ── /// Enable TLS for the connection. public bool Ssl { get; set; } /// /// The name the broker certificate must carry. Unset, each host of the list is checked against its own name; set it /// when the certificate names a load balancer or an alias. /// public string? SslServerName { get; set; } /// Client certificate (PFX) presented for mutual TLS. Or give the certificate itself as . public string? SslCertPath { get; set; } /// Passphrase of . [Sensitive] public string? SslCertPassword { get; set; } /// /// Client certificate for mutual TLS, with its private key — from the Windows certificate store, a key vault or /// anywhere else. Checked for its validity period when the connection opens. /// public X509Certificate2? ClientCertificate { get; set; } /// PEM file with the root certificates the broker certificate must chain to, instead of the system trust store. public string? SslCaCertPath { get; set; } /// The root certificates the broker certificate must chain to, instead of the system trust store. public X509Certificate2Collection? SslCaCertificates { get; set; } /// Allowed TLS versions (Tls12, Tls13). (default): the operating system chooses. public SslProtocols SslProtocols { get; set; } /// /// Revocation check of the broker certificate: (default), /// or . /// public X509RevocationMode RevocationMode { get; set; } /// Accept a broker certificate whose revocation status cannot be determined. Default false: refused. public bool RevocationSoftFail { get; set; } // ── Authentication ── /// /// (default) or : the TLS client /// certificate is the login. /// public RabbitMQAuthMechanism AuthMechanism { get; set; } /// /// OAuth 2.0 token endpoint (client credentials grant). Set with and /// , the connection logs in with an access token instead of a password and renews /// it on the open connection before it expires. HTTPS, except on the loopback address. Needs the broker's /// rabbitmq_auth_backend_oauth2 plugin. /// public string? OAuth2TokenEndpoint { get; set; } /// OAuth 2.0 client id. public string? OAuth2ClientId { get; set; } /// OAuth 2.0 client secret. [Sensitive] public string? OAuth2ClientSecret { get; set; } /// Requested scopes, space-separated (optional; for RabbitMQ usually rabbitmq.read:*/* ...). public string? OAuth2Scope { get; set; } /// /// Your own source of credentials (), in place of and /// — a secret store, a token of another identity provider. Not combined with OAuth2. /// public ICredentialsProvider? CredentialsProvider { get; set; } /// Client-provided connection name for management UI. public string ClientName { get; set; } = "redb.Route"; internal bool UsesOAuth2 => !string.IsNullOrEmpty(OAuth2TokenEndpoint); /// Throws when the factory's settings contradict each other; called when a connection is opened with it. /// The factory's registry name, for the error text. public void Validate(string name) { var owner = $"RabbitMQ connection factory '{name}'"; RabbitMQTls.Validate(new RabbitMQTls.TlsRules( Ssl, SslServerName, SslCertPath, SslCertPassword, ClientCertificate is not null, SslCaCertPath, SslCaCertificates is not null, SslProtocols, RevocationMode, RevocationSoftFail, AuthMechanism), owner); var oauthSet = new[] { OAuth2TokenEndpoint, OAuth2ClientId, OAuth2ClientSecret }.Count(v => !string.IsNullOrEmpty(v)); if (oauthSet is > 0 and < 3) throw new ArgumentException($"{owner}: OAuth2 needs OAuth2TokenEndpoint, OAuth2ClientId and OAuth2ClientSecret together."); if (!string.IsNullOrEmpty(OAuth2Scope) && !UsesOAuth2) throw new ArgumentException($"{owner}: OAuth2Scope is given without OAuth2TokenEndpoint."); var logins = new List(); if (UsesOAuth2) logins.Add("OAuth2"); if (CredentialsProvider is not null) logins.Add("CredentialsProvider"); if (AuthMechanism == RabbitMQAuthMechanism.External) logins.Add("AuthMechanism=External"); if (logins.Count > 1) throw new ArgumentException($"{owner}: {string.Join(" and ", logins)} are two ways to log in; choose one."); if (UsesOAuth2) { if (!Uri.TryCreate(OAuth2TokenEndpoint, UriKind.Absolute, out var endpoint) || (endpoint.Scheme != Uri.UriSchemeHttps && !(endpoint.Scheme == Uri.UriSchemeHttp && endpoint.IsLoopback))) throw new ArgumentException( $"{owner}: OAuth2TokenEndpoint '{OAuth2TokenEndpoint}' must be an absolute https URI (http only on the loopback " + "address): the client secret is sent to it."); } } /// /// Creates a configured pointed at the first host. Open the connection with /// CreateConnectionAsync() to fail over across every host of the cluster. /// OAuth2 credentials are set up by the component when it opens the connection (the token is fetched asynchronously /// and renewed on the open connection). /// public ConnectionFactory Build() => Build(GetEndpoints()); internal ConnectionFactory Build(IReadOnlyList endpoints) { var factory = new ConnectionFactory { UserName = Username, Password = Password, VirtualHost = VirtualHost, AutomaticRecoveryEnabled = AutomaticRecovery, TopologyRecoveryEnabled = TopologyRecoveryEnabled, NetworkRecoveryInterval = TimeSpan.FromSeconds(RecoveryInterval), RequestedHeartbeat = TimeSpan.FromSeconds(Heartbeat), RequestedConnectionTimeout = TimeSpan.FromSeconds(ConnectionTimeout), SocketReadTimeout = TimeSpan.FromSeconds(SocketReadTimeout), SocketWriteTimeout = TimeSpan.FromSeconds(SocketWriteTimeout), ContinuationTimeout = TimeSpan.FromSeconds(ContinuationTimeout), ConsumerDispatchConcurrency = ConsumerDispatchConcurrency, ClientProvidedName = ClientName, }; if (AuthMechanism == RabbitMQAuthMechanism.External) factory.AuthMechanisms = [new ExternalMechanismFactory()]; if (CredentialsProvider is not null) factory.CredentialsProvider = CredentialsProvider; // The Endpoint setter also replaces factory.Ssl with the endpoint's own TLS settings, // so TLS travels with the endpoint and is never set on the factory separately. factory.Endpoint = endpoints[0]; return factory; } /// /// Parses the host list into AMQP endpoints, each carrying the TLS settings: a connection opened over an /// endpoint list takes TLS from the endpoints, not from the . /// public List GetEndpoints() => GetEndpoints("RabbitMQ connection factory", null); internal List GetEndpoints(string owner, ILogger? logger) => BuildEndpoints(Host, Port, ResolveTls(owner), logger); /// The TLS settings of this factory, loading the certificate files it names. internal RabbitMQTlsSettings ResolveTls(string owner) { if (!Ssl) return RabbitMQTlsSettings.Off; var client = ClientCertificate; if (client is not null) RabbitMQTls.EnsureClientCertificateUsable(client, owner); else if (!string.IsNullOrEmpty(SslCertPath)) client = RabbitMQTls.LoadClientCertificate(SslCertPath, SslCertPassword, owner); var roots = SslCaCertificates ?? (string.IsNullOrEmpty(SslCaCertPath) ? null : RabbitMQTls.LoadCaCertificates(SslCaCertPath, owner)); return new RabbitMQTlsSettings(true, SslServerName, client, SslProtocols, roots, RevocationMode, RevocationSoftFail); } /// /// The AMQP endpoints of a comma-separated host list, each with the TLS settings. Without an explicit server name /// each endpoint checks the broker certificate against its own host. /// internal static List BuildEndpoints(string hostList, int port, RabbitMQTlsSettings tls, ILogger? logger) { var hosts = hostList.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); if (hosts.Length == 0) throw new InvalidOperationException("RabbitMQ: no host is configured; set host (a name or a comma-separated list)."); return hosts.Select(h => new AmqpTcpEndpoint(h, port, RabbitMQTls.OptionFor(h, tls, logger))).ToList(); } }