Bundle: redb-route / redb.Route.Ldap (redb.Route.Ldap.txt), 15 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.Ldap/Extensions/ServiceCollectionExtensions.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/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.Ldap;
///
/// Extension methods for registering the LDAP transport in a DI container.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the LdapComponent in the route context so that ldap: URIs are resolved.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.Services.AddRedbRouteLdap();
/// route.AddRouteBuilder<MyRoutes>();
/// });
///
///
///
public static IServiceCollection AddRedbRouteLdap(this IServiceCollection services)
{
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteComponent();
return services;
}
}
Path: redb-route/redb.Route.Ldap/Fluent/LdapDsl.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/Fluent/LdapDsl.cs
----
using System.Text;
using redb.Route.Abstractions;
namespace redb.Route.Ldap;
///
/// Fluent API for LDAP endpoints.
///
/// .To(LdapDsl.Search("dc=example,dc=com").Server("dc.company.com").Ssl().Filter("(objectClass=user)"))
/// .From(LdapDsl.Watch("ou=users,dc=example,dc=com").Server("dc.company.com").Ssl().PollInterval(60000))
///
///
public static class LdapDsl
{
// ── Read ──
/// Search entries by filter and base DN.
public static LdapBuilder Search(string baseDn) => new(LdapOperationType.SEARCH, baseDn);
/// Search entries by filter and dynamic base DN.
public static LdapBuilder Search(IExpression baseDn) => new(LdapOperationType.SEARCH, baseDn.ToTemplateString());
/// Compare an attribute value at a specific DN.
public static LdapBuilder Compare(string dn) => new(LdapOperationType.COMPARE, dn);
/// Compare an attribute value at a dynamic DN.
public static LdapBuilder Compare(IExpression dn) => new(LdapOperationType.COMPARE, dn.ToTemplateString());
// ── Write ──
/// Create a new entry under the specified parent DN.
public static LdapBuilder Add(string parentDn) => new(LdapOperationType.ADD, parentDn);
/// Create a new entry under a dynamic parent DN.
public static LdapBuilder Add(IExpression parentDn) => new(LdapOperationType.ADD, parentDn.ToTemplateString());
/// Modify attributes of an entry at the specified DN.
public static LdapBuilder Modify(string dn) => new(LdapOperationType.MODIFY, dn);
/// Modify attributes of an entry at a dynamic DN.
public static LdapBuilder Modify(IExpression dn) => new(LdapOperationType.MODIFY, dn.ToTemplateString());
/// Delete an entry at the specified DN.
public static LdapBuilder Delete(string dn) => new(LdapOperationType.DELETE, dn);
/// Delete an entry at a dynamic DN.
public static LdapBuilder Delete(IExpression dn) => new(LdapOperationType.DELETE, dn.ToTemplateString());
/// Rename/move an entry at the specified DN.
public static LdapBuilder Rename(string dn) => new(LdapOperationType.RENAME, dn);
/// Rename/move an entry at a dynamic DN.
public static LdapBuilder Rename(IExpression dn) => new(LdapOperationType.RENAME, dn.ToTemplateString());
// ── Auth ──
/// Verify user credentials via LDAP Bind.
public static LdapBuilder Bind(string baseDn) => new(LdapOperationType.BIND, baseDn);
/// Verify user credentials via LDAP Bind (dynamic).
public static LdapBuilder Bind(IExpression baseDn) => new(LdapOperationType.BIND, baseDn.ToTemplateString());
// ── Consumer ──
/// Poll directory for changes (consumer).
public static LdapBuilder Watch(string baseDn) => new(LdapOperationType.WATCH, baseDn);
/// Poll directory for changes (consumer, dynamic base DN).
public static LdapBuilder Watch(IExpression baseDn) => new(LdapOperationType.WATCH, baseDn.ToTemplateString());
}
///
/// Fluent builder for LDAP endpoint URIs.
///
public sealed class LdapBuilder
{
private readonly LdapOperationType _operation;
private readonly string _baseDn;
// Connection
private string? _server;
private string? _port;
private bool _ssl;
private bool _startTls;
private string? _connectionFactory;
private string? _connectTimeout;
private string? _operationTimeout;
// Auth
private string? _bindDn;
private string? _bindPassword;
// Search
private string? _filter;
private string? _scope;
private string? _attributes;
private string? _pageSize;
private string? _sizeLimit;
private string? _timeLimit;
// Consumer
private string? _pollInterval;
private string? _changeTrackingMode;
private bool _initialLoad;
private bool _detectDeletions;
private string? _fullSyncInterval;
// Protocol
private string? _protocolVersion;
private bool? _followReferrals;
// Pool
private string? _maxConnections;
// SSL
private bool _trustAllCertificates;
private string? _clientCertPath;
private string? _clientCertPassword;
internal LdapBuilder(LdapOperationType operation, string baseDn)
{
_operation = operation;
_baseDn = baseDn;
}
// ── Connection ──
/// Set the LDAP server hostname or IP.
public LdapBuilder Server(string host) { _server = host; return this; }
/// Set the LDAP server hostname dynamically.
public LdapBuilder Server(IExpression host) { _server = host.ToTemplateString(); return this; }
/// Set the LDAP port.
public LdapBuilder Port(int port) { _port = port.ToString(); return this; }
/// Set the LDAP port dynamically.
public LdapBuilder Port(IExpression port) { _port = port.ToTemplateString(); return this; }
/// Enable LDAPS (SSL/TLS, typically port 636).
public LdapBuilder Ssl() { _ssl = true; return this; }
/// Enable STARTTLS upgrade on the plain port.
public LdapBuilder StartTls() { _startTls = true; return this; }
/// Use a named connection factory from the registry.
public LdapBuilder ConnectionFactory(string name) { _connectionFactory = name; return this; }
/// Use a named connection factory dynamically.
public LdapBuilder ConnectionFactory(IExpression name) { _connectionFactory = name.ToTemplateString(); return this; }
/// Set connection timeout in milliseconds.
public LdapBuilder ConnectTimeout(int ms) { _connectTimeout = ms.ToString(); return this; }
/// Set operation timeout in milliseconds.
public LdapBuilder OperationTimeout(int ms) { _operationTimeout = ms.ToString(); return this; }
// ── Auth ──
/// Set the Bind DN for service account authentication.
public LdapBuilder BindDn(string dn) { _bindDn = dn; return this; }
/// Set the Bind DN dynamically.
public LdapBuilder BindDn(IExpression dn) { _bindDn = dn.ToTemplateString(); return this; }
/// Set the Bind password.
public LdapBuilder BindPassword(string password) { _bindPassword = password; return this; }
/// Set the Bind password dynamically.
public LdapBuilder BindPassword(IExpression password) { _bindPassword = password.ToTemplateString(); return this; }
// ── Search ──
/// Set the LDAP search filter.
public LdapBuilder Filter(string filter) { _filter = filter; return this; }
/// Set the LDAP search filter dynamically.
public LdapBuilder Filter(IExpression filter) { _filter = filter.ToTemplateString(); return this; }
/// Set the search scope.
public LdapBuilder Scope(LdapSearchScope scope) { _scope = scope.ToString().ToLowerInvariant(); return this; }
/// Set the attributes to return from search.
public LdapBuilder Attributes(params string[] attrs) { _attributes = string.Join(",", attrs); return this; }
/// Set the page size for paged search results.
public LdapBuilder PageSize(int size) { _pageSize = size.ToString(); return this; }
/// Set the page size dynamically.
public LdapBuilder PageSize(IExpression size) { _pageSize = size.ToTemplateString(); return this; }
/// Set the server-side maximum number of entries.
public LdapBuilder SizeLimit(int limit) { _sizeLimit = limit.ToString(); return this; }
/// Set the server-side time limit in seconds.
public LdapBuilder TimeLimit(int seconds) { _timeLimit = seconds.ToString(); return this; }
// ── Consumer ──
/// Set the poll interval in milliseconds for the Watch consumer.
public LdapBuilder PollInterval(int ms) { _pollInterval = ms.ToString(); return this; }
/// Set the poll interval dynamically.
public LdapBuilder PollInterval(IExpression ms) { _pollInterval = ms.ToTemplateString(); return this; }
/// Set the change tracking mode.
public LdapBuilder ChangeTracking(LdapChangeTrackingMode mode = LdapChangeTrackingMode.ModifyTimestamp)
{
_changeTrackingMode = mode.ToString().ToLowerInvariant();
return this;
}
/// Load all matching entries on consumer startup.
public LdapBuilder InitialLoad() { _initialLoad = true; return this; }
/// Enable deletion detection by comparing known DNs with current results.
public LdapBuilder DetectDeletions() { _detectDeletions = true; return this; }
/// Set the number of poll cycles between full synchronizations for deletion detection.
public LdapBuilder FullSyncInterval(int cycles) { _fullSyncInterval = cycles.ToString(); return this; }
// ── Protocol ──
/// Set the LDAP protocol version (2 or 3).
public LdapBuilder ProtocolVersion(int version) { _protocolVersion = version.ToString(); return this; }
/// Control referral following (default: true).
public LdapBuilder Referrals(bool follow) { _followReferrals = follow; return this; }
// ── Pool ──
/// Set the maximum number of pooled connections.
public LdapBuilder MaxConnections(int max) { _maxConnections = max.ToString(); return this; }
// ── SSL ──
/// Skip server certificate validation (development only!).
public LdapBuilder TrustAllCertificates() { _trustAllCertificates = true; return this; }
/// Set client certificate for mutual TLS.
public LdapBuilder ClientCert(string path, string? password = null)
{
_clientCertPath = path;
_clientCertPassword = password;
return this;
}
// ── Build ──
/// Builds the LDAP endpoint URI string.
public string Build()
{
var sb = new StringBuilder();
sb.Append("ldap:");
sb.Append(_operation.ToString());
sb.Append(':');
sb.Append(_baseDn);
var sep = '?';
void Append(string key, string value)
{
sb.Append(sep);
sb.Append(key);
sb.Append('=');
sb.Append(Uri.EscapeDataString(value));
sep = '&';
}
void AppendIf(string key, string? value) { if (value != null) Append(key, value); }
void AppendBool(string key, bool value) { if (value) Append(key, "true"); }
void AppendBoolExplicit(string key, bool? value) { if (value.HasValue) Append(key, value.Value ? "true" : "false"); }
// Connection
AppendIf("server", _server);
AppendIf("port", _port);
AppendBool("ssl", _ssl);
AppendBool("startTls", _startTls);
AppendIf("connectionFactory", _connectionFactory);
AppendIf("connectTimeout", _connectTimeout);
AppendIf("operationTimeout", _operationTimeout);
// Auth
AppendIf("bindDn", _bindDn);
AppendIf("bindPassword", _bindPassword);
// Search
AppendIf("filter", _filter);
AppendIf("scope", _scope);
AppendIf("attributes", _attributes);
AppendIf("pageSize", _pageSize);
AppendIf("sizeLimit", _sizeLimit);
AppendIf("timeLimit", _timeLimit);
// Consumer
AppendIf("pollInterval", _pollInterval);
AppendIf("changeTrackingMode", _changeTrackingMode);
AppendBool("initialLoad", _initialLoad);
AppendBool("detectDeletions", _detectDeletions);
AppendIf("fullSyncInterval", _fullSyncInterval);
// Protocol
AppendIf("protocolVersion", _protocolVersion);
AppendBoolExplicit("followReferrals", _followReferrals);
// Pool
AppendIf("maxConnections", _maxConnections);
// SSL
AppendBool("trustAllCertificates", _trustAllCertificates);
AppendIf("clientCertPath", _clientCertPath);
AppendIf("clientCertPassword", _clientCertPassword);
return sb.ToString();
}
/// Implicit conversion to URI string.
public static implicit operator string(LdapBuilder b) => b.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.Ldap/LdapChangeTrackingMode.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/LdapChangeTrackingMode.cs
----
namespace redb.Route.Ldap;
///
/// Change tracking mode for the LDAP consumer (WATCH operation).
///
public enum LdapChangeTrackingMode
{
/// Track changes via modifyTimestamp attribute. Works with any LDAP v3 server.
ModifyTimestamp,
/// Track changes via uSNChanged attribute. Active Directory only.
Usn,
/// Use LDAP Persistent Search control (RFC 2589). Supported by OpenLDAP, 389DS.
Persistent
}
Path: redb-route/redb.Route.Ldap/LdapComponent.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/LdapComponent.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Ldap;
///
/// LDAP transport component for redb.Route.
/// Scheme: ldap.
///
/// URI format: ldap:SEARCH:dc=example,dc=com?server=host&port=636&ssl=true&filter=(objectClass=user)
///
///
/// The first path segment is the .
/// The remaining segments form the base DN or target DN.
///
///
public sealed class LdapComponent : ComponentBase
{
///
public override string Scheme => "ldap";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new LdapEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
return new LdapEndpoint(uri, this, options);
}
}
Path: redb-route/redb.Route.Ldap/LdapConnectionFactory.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/LdapConnectionFactory.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Ldap;
///
/// Named connection factory for LDAP. Register it in the route registry and reference it
/// by name from the endpoint URI (connectionFactory=my-ldap) so that service-account
/// credentials never have to appear in the URI itself — and therefore can never reach logs,
/// telemetry, or the Tsak dashboard.
///
/// Example:
///
/// context.AddToRegistry("corp-ldap", new LdapConnectionFactory
/// {
/// Server = "ldap.corp.local",
/// Port = 636,
/// Ssl = true,
/// BindDn = "cn=svc-reader,dc=corp,dc=local",
/// BindPassword = Environment.GetEnvironmentVariable("LDAP_BIND_PASSWORD")
/// });
///
/// // route carries no credentials at all:
/// r.From("ldap://SEARCH:dc=corp,dc=local?connectionFactory=corp-ldap&filter=(objectClass=user)")
///
///
///
public sealed class LdapConnectionFactory
{
// ── Connection ──
/// LDAP server hostname or IP.
public string Server { get; set; } = "localhost";
/// LDAP port (389 for plain, 636 for LDAPS).
public int Port { get; set; } = 389;
/// Use LDAPS (SSL/TLS from the start, typically port 636).
public bool Ssl { get; set; }
/// Use STARTTLS upgrade on the plain port (389).
public bool StartTls { get; set; }
/// Connection timeout in milliseconds.
public int ConnectTimeout { get; set; } = 5000;
/// Operation timeout in milliseconds.
public int OperationTimeout { get; set; } = 30000;
// ── Auth (service account) ──
/// Bind DN for service account authentication.
public string? BindDn { get; set; }
/// Password for service account authentication.
[Sensitive]
public string? BindPassword { get; set; }
// ── Protocol / pool ──
/// LDAP protocol version (default 3).
public int ProtocolVersion { get; set; } = 3;
/// Follow LDAP referrals automatically.
public bool FollowReferrals { get; set; } = true;
/// Maximum number of connections in the pool.
public int MaxConnections { get; set; } = 10;
// ── TLS ──
/// Skip server certificate validation (development only!).
public bool TrustAllCertificates { get; set; }
/// Path to client certificate for mutual TLS.
public string? ClientCertPath { get; set; }
/// Password for client certificate.
[Sensitive]
public string? ClientCertPassword { get; set; }
///
/// Copies this factory's connection and credential settings onto the endpoint options,
/// but only for parameters the endpoint URI did not set explicitly — an inline URI value
/// always wins, so existing routes keep their behaviour.
///
/// Endpoint options already bound from the URI.
/// The parsed endpoint URI, used to detect explicitly-supplied parameters.
internal void ApplyTo(LdapEndpointOptions options, EndpointUri uri)
{
var supplied = uri.RawParameters;
if (!supplied.ContainsKey(nameof(options.Server))) options.Server = Server;
if (!supplied.ContainsKey(nameof(options.Port))) options.Port = Port;
if (!supplied.ContainsKey(nameof(options.Ssl))) options.Ssl = Ssl;
if (!supplied.ContainsKey(nameof(options.StartTls))) options.StartTls = StartTls;
if (!supplied.ContainsKey(nameof(options.ConnectTimeout))) options.ConnectTimeout = ConnectTimeout;
if (!supplied.ContainsKey(nameof(options.OperationTimeout))) options.OperationTimeout = OperationTimeout;
if (!supplied.ContainsKey(nameof(options.BindDn))) options.BindDn = BindDn;
if (!supplied.ContainsKey(nameof(options.BindPassword))) options.BindPassword = BindPassword;
if (!supplied.ContainsKey(nameof(options.ProtocolVersion))) options.ProtocolVersion = ProtocolVersion;
if (!supplied.ContainsKey(nameof(options.FollowReferrals))) options.FollowReferrals = FollowReferrals;
if (!supplied.ContainsKey(nameof(options.MaxConnections))) options.MaxConnections = MaxConnections;
if (!supplied.ContainsKey(nameof(options.TrustAllCertificates)))
options.TrustAllCertificates = TrustAllCertificates;
if (!supplied.ContainsKey(nameof(options.ClientCertPath))) options.ClientCertPath = ClientCertPath;
if (!supplied.ContainsKey(nameof(options.ClientCertPassword)))
options.ClientCertPassword = ClientCertPassword;
}
}
Path: redb-route/redb.Route.Ldap/LdapConsumer.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/LdapConsumer.cs
----
using System.Diagnostics;
using Microsoft.Extensions.Logging;
using Novell.Directory.Ldap;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
using NovellEntry = Novell.Directory.Ldap.LdapEntry;
namespace redb.Route.Ldap;
///
/// LDAP consumer. Polls the directory for changes using configurable change tracking.
/// Supports ModifyTimestamp (universal) and USN (Active Directory) modes.
/// Optionally detects deletions by comparing known DNs with current results.
///
internal sealed class LdapConsumer : DrainableConsumer
{
private readonly LdapEndpoint _endpoint;
private readonly LdapEndpointOptions _options;
private readonly HashSet _knownDns = new(StringComparer.OrdinalIgnoreCase);
private readonly string _baseFilter;
private int _pollsSinceFullSync;
///
protected override IEndpoint ConsumerEndpoint => _endpoint;
///
protected override string ConsumerName => $"ldap:WATCH:{_endpoint.BaseDn}";
/// Number of change events delivered.
public long ProcessedCount { get; private set; }
/// Creates an LDAP consumer.
public LdapConsumer(LdapEndpoint endpoint, IProcessor processor, LdapEndpointOptions options)
: base(processor)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
_baseFilter = _options.Filter?.Resolve(new Exchange()) ?? "(objectClass=*)";
}
///
protected override async Task RunAsync(CancellationToken pollCt, CancellationToken processingCt)
{
var mode = _options.ParseChangeTrackingMode();
if (mode == LdapChangeTrackingMode.Persistent)
throw new NotSupportedException(
"Persistent Search is not yet implemented. Use ModifyTimestamp or Usn mode.");
string? marker = _options.InitialLoad ? null : await GetInitialMarkerAsync(mode, processingCt).ConfigureAwait(false);
Logger?.LogInformation("LDAP consumer started: baseDn={BaseDn}, mode={Mode}, initialLoad={InitialLoad}, detectDeletions={DetectDeletions}",
_endpoint.BaseDn, mode, _options.InitialLoad, _options.DetectDeletions);
while (!pollCt.IsCancellationRequested)
{
try
{
var (entries, newMarker) = await PollChangesAsync(mode, marker, processingCt)
.ConfigureAwait(false);
foreach (var entry in entries)
{
var exchange = CreateExchange(entry);
await ProcessTracedAsync(exchange, processingCt).ConfigureAwait(false);
ProcessedCount++;
}
// Detect deletions if enabled
if (_options.DetectDeletions)
await DetectDeletionsAsync(entries, processingCt).ConfigureAwait(false);
if (newMarker != null)
marker = newMarker;
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
Logger?.LogError(ex, "LDAP poll failed for {BaseDn}", _endpoint.BaseDn);
_endpoint.RecordError(ex);
}
try
{
await Task.Delay(_options.PollInterval, pollCt).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
break;
}
}
Logger?.LogInformation("LDAP consumer stopped: baseDn={BaseDn}, processed={Count}",
_endpoint.BaseDn, ProcessedCount);
}
///
/// inside the span of the entry. A directory entry carries no
/// trace context, so the span is a root, never a child of the activity the poll loop holds. A failed route marks it,
/// whether the failure stays on the exchange or escapes the pipeline; our own stop does not.
///
private async Task ProcessTracedAsync(IExchange exchange, CancellationToken ct)
{
using var span = RouteTelemetryExtensions.StartConsumerSpan