Path: redb-route/redb.Route.Ldap/LdapEndpoint.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.Ldap/LdapEndpoint.cs
----
using System.Collections.Concurrent;
using System.Security.Cryptography.X509Certificates;
using Microsoft.Extensions.Logging;
using Novell.Directory.Ldap;
using redb.Route.Abstractions;
using redb.Route.Extensions;
using redb.Route.Core;
namespace redb.Route.Ldap;
///
/// LDAP endpoint. Parses the operation type and base DN from the URI path.
/// Manages a connection pool for LDAP operations.
///
/// URI path format: OPERATION:baseDn (e.g. SEARCH:dc=example,dc=com).
///
///
public sealed class LdapEndpoint : EndpointBase, IDisposable
{
private readonly ConcurrentBag _pool = new();
private readonly SemaphoreSlim _semaphore;
private bool _disposed;
/// Parsed LDAP operation type.
public LdapOperationType OperationType { get; }
/// Base DN or target DN parsed from the URI path.
public string BaseDn { get; }
/// Logger from the parent component.
internal ILogger? Logger { get; }
/// Typed options (exposed for producer/consumer).
internal LdapEndpointOptions EndpointOptions => Options;
/// Resolved connection factory from the registry (null if not configured).
internal LdapConnectionFactory? ResolvedFactory { get; }
/// Creates an LDAP endpoint.
public LdapEndpoint(EndpointUri uri, LdapComponent component, LdapEndpointOptions options)
: base(uri, component, options)
{
Logger = component.Logger;
// Resolve the named ConnectionFactory from the registry and fill in every option the
// URI did not set. This is what lets a route reference `connectionFactory=my-ldap`
// and keep the service-account credentials out of the URI entirely — so they can
// never surface in logs, telemetry, or the dashboard.
if (!string.IsNullOrEmpty(options.ConnectionFactory))
{
// A set-but-unknown name fails loud — never a silent fallback to URI params.
ResolvedFactory = component.Context.GetRequiredFromRegistry(options.ConnectionFactory);
ResolvedFactory.ApplyTo(options, uri);
// Re-validate: the merged values come from the factory, not the URI.
options.Validate();
Logger?.LogDebug("LDAP: using ConnectionFactory '{Name}' from registry",
options.ConnectionFactory);
}
_semaphore = new SemaphoreSlim(options.MaxConnections, options.MaxConnections);
(OperationType, BaseDn) = ParsePath(uri.Path);
}
///
public override IProducer CreateProducer() => new LdapProducer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor)
{
if (OperationType != LdapOperationType.WATCH)
throw new InvalidOperationException(
$"LDAP consumer is only supported for WATCH operation, got {OperationType}.");
return new LdapConsumer(this, processor, Options);
}
///
/// Acquires a bound LDAP connection from the pool.
/// If no idle connection is available, creates a new one.
///
internal async Task AcquireConnectionAsync(CancellationToken ct)
{
await _semaphore.WaitAsync(ct).ConfigureAwait(false);
try
{
// Service-account authenticated endpoints must never reuse a connection
// that is merely TCP-connected but no longer bound on the server side.
// AD can report "successful bind must be completed" in that state.
if (!string.IsNullOrEmpty(Options.BindDn))
return await CreateConnectionAsync(ct).ConfigureAwait(false);
// Try reuse a pooled connection
while (_pool.TryTake(out var conn))
{
if (conn.Connected)
return conn;
try { conn.Dispose(); } catch { /* discard broken */ }
}
// Create new connection
return await CreateConnectionAsync(ct).ConfigureAwait(false);
}
catch
{
_semaphore.Release();
throw;
}
}
///
/// Returns a connection to the pool for reuse.
/// Disposes the connection if it is no longer connected.
///
internal void ReleaseConnection(LdapConnection conn)
{
if (!string.IsNullOrEmpty(Options.BindDn))
{
try { conn.Dispose(); } catch { /* authenticated connection is not pooled */ }
_semaphore.Release();
return;
}
if (conn.Connected && !_disposed)
_pool.Add(conn);
else
try { conn.Dispose(); } catch { /* suppress */ }
_semaphore.Release();
}
///
public override Task Stop(CancellationToken ct = default)
{
Dispose();
Logger?.LogInformation("LDAP endpoint stopped: {Uri}", EndpointUri.ForLog(Uri.ToString(), Logger));
return Task.CompletedTask;
}
/// Disposes all pooled connections and the semaphore.
public void Dispose()
{
if (_disposed) return;
_disposed = true;
while (_pool.TryTake(out var conn))
{
try { conn.Dispose(); } catch { /* suppress cleanup errors */ }
}
_semaphore.Dispose();
}
private async Task CreateConnectionAsync(CancellationToken ct)
{
var connOptions = BuildConnectionOptions();
var conn = new LdapConnection(connOptions);
// Configure protocol version and referral following
conn.Constraints = new LdapSearchConstraints
{
ReferralFollowing = Options.FollowReferrals
};
// Connect
var host = Options.Server;
var port = Options.EffectivePort;
await conn.ConnectAsync(host, port, ct).ConfigureAwait(false);
// STARTTLS upgrade on plain connection (mutually exclusive with LDAPS)
if (Options.StartTls)
await conn.StartTlsAsync(ct).ConfigureAwait(false);
// Bind with service account if credentials provided
if (!string.IsNullOrEmpty(Options.BindDn))
{
ct.ThrowIfCancellationRequested();
await conn.BindAsync(Options.BindDn, Options.BindPassword ?? "", ct).ConfigureAwait(false);
}
return conn;
}
///
/// Builds Novell LdapConnectionOptions from our endpoint options,
/// wiring SSL, certificate validation, and client certificates.
///
internal LdapConnectionOptions BuildConnectionOptions()
{
var opts = new LdapConnectionOptions();
// LDAPS: enable SSL on the socket layer (port 636 by default)
if (Options.Ssl)
opts.UseSsl();
// Skip server certificate validation (development only!)
if (Options.TrustAllCertificates)
opts.ConfigureRemoteCertificateValidationCallback(
(sender, certificate, chain, sslPolicyErrors) => true);
// Client certificate for mutual TLS
if (!string.IsNullOrEmpty(Options.ClientCertPath))
{
var cert = string.IsNullOrEmpty(Options.ClientCertPassword)
? X509CertificateLoader.LoadCertificateFromFile(Options.ClientCertPath)
: X509CertificateLoader.LoadPkcs12FromFile(Options.ClientCertPath, Options.ClientCertPassword);
opts.ConfigureClientCertificates(new[] { cert });
}
return opts;
}
///
/// Parses the URI path into (OperationType, BaseDn).
/// Expected format: OPERATION:dn,segments
///
internal static (LdapOperationType Operation, string BaseDn) ParsePath(string? path)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentException("LDAP URI path cannot be empty. Expected format: OPERATION:baseDn");
// Find first colon — separates operation from base DN
var colonIndex = path.IndexOf(':');
if (colonIndex <= 0)
throw new ArgumentException(
$"Invalid LDAP URI path: '{path}'. Expected format: OPERATION:baseDn (e.g. SEARCH:dc=example,dc=com)");
var operationStr = path[..colonIndex];
var baseDn = path[(colonIndex + 1)..];
if (!Enum.TryParse(operationStr, ignoreCase: true, out var operation))
throw new ArgumentException(
$"Unknown LDAP operation: '{operationStr}'. Supported: {string.Join(", ", Enum.GetNames())}");
return (operation, baseDn);
}
}