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( (_endpoint.Component as ComponentBase)?.Context, $"ldap {_endpoint.BaseDn} receive", ActivityKind.Consumer, "network.protocol.name", "ldap", _endpoint.Uri.NormalizedKey, null, static (_, _) => null, operation: "receive"); await ProcessWithTracking(exchange, span, ct).ConfigureAwait(false); } private IExchange CreateExchange(LdapEntry entry) { var exchange = Exchange.Create(new Message(entry), _endpoint.ScopeFactory); exchange.In.Headers[LdapHeaders.ChangeType] = entry.ChangeType ?? "modified"; exchange.In.Headers[LdapHeaders.Dn] = entry.Dn; exchange.In.Headers[LdapHeaders.BaseDn] = _endpoint.BaseDn; exchange.In.Headers[LdapHeaders.Timestamp] = DateTime.UtcNow.ToString("O"); return exchange; } private async Task<(List Entries, string? NewMarker)> PollChangesAsync( LdapChangeTrackingMode mode, string? marker, CancellationToken ct) { var conn = await _endpoint.AcquireConnectionAsync(ct).ConfigureAwait(false); try { return mode switch { LdapChangeTrackingMode.Usn => await PollUsnChangesAsync(conn, marker, ct).ConfigureAwait(false), _ => await PollModifyTimestampChangesAsync(conn, marker, ct).ConfigureAwait(false) }; } finally { _endpoint.ReleaseConnection(conn); } } private async Task<(List Entries, string? NewMarker)> PollModifyTimestampChangesAsync( LdapConnection conn, string? marker, CancellationToken ct) { var filter = marker != null ? $"(&{_baseFilter}(modifyTimestamp>={marker}))" : _baseFilter; var entries = await SearchEntriesAsync(conn, filter, ct).ConfigureAwait(false); // Derive next marker from the latest modifyTimestamp in results string? newMarker = marker; foreach (var entry in entries) { var ts = entry.GetString("modifyTimestamp"); if (ts != null && (newMarker == null || string.CompareOrdinal(ts, newMarker) > 0)) newMarker = ts; } // If no entries or no modifyTimestamp available, fall back to UTC if (newMarker == marker) newMarker = DateTime.UtcNow.ToString("yyyyMMddHHmmss") + "Z"; foreach (var entry in entries) entry.ChangeType = marker == null ? "added" : "modified"; return (entries, newMarker); } private async Task<(List Entries, string? NewMarker)> PollUsnChangesAsync( LdapConnection conn, string? marker, CancellationToken ct) { var filter = marker != null ? $"(&{_baseFilter}(uSNChanged>={marker}))" : _baseFilter; var entries = await SearchEntriesAsync(conn, filter, ct).ConfigureAwait(false); // Find highest USN for next poll string? newMarker = marker; foreach (var entry in entries) { var usn = entry.GetString("uSNChanged"); if (usn != null && (newMarker == null || string.CompareOrdinal(usn, newMarker) > 0)) newMarker = usn; } // Increment USN to avoid re-reading the same entry if (newMarker != null && long.TryParse(newMarker, out var usnVal)) newMarker = (usnVal + 1).ToString(); foreach (var entry in entries) entry.ChangeType = marker == null ? "added" : "modified"; return (entries, newMarker); } private async Task DetectDeletionsAsync(List currentEntries, CancellationToken ct) { var currentDns = new HashSet( currentEntries.Select(e => e.Dn), StringComparer.OrdinalIgnoreCase); _pollsSinceFullSync++; // On first poll or every FullSyncInterval cycles, do a full scan if (_knownDns.Count == 0 || _pollsSinceFullSync >= _options.FullSyncInterval) { _pollsSinceFullSync = 0; var conn = await _endpoint.AcquireConnectionAsync(ct).ConfigureAwait(false); try { var allEntries = await SearchEntriesAsync(conn, _baseFilter, ct) .ConfigureAwait(false); var allDns = new HashSet( allEntries.Select(e => e.Dn), StringComparer.OrdinalIgnoreCase); // Emit "deleted" for every known DN that's no longer in the directory foreach (var dn in _knownDns) { if (!allDns.Contains(dn)) { var deleted = new LdapEntry { Dn = dn, ChangeType = "deleted" }; var exchange = CreateExchange(deleted); await ProcessTracedAsync(exchange, ct).ConfigureAwait(false); ProcessedCount++; Logger?.LogDebug("LDAP deletion detected: {Dn}", dn); } } _knownDns.Clear(); foreach (var dn in allDns) _knownDns.Add(dn); } finally { _endpoint.ReleaseConnection(conn); } } else { // Incremental: add new entries to known set foreach (var dn in currentDns) _knownDns.Add(dn); } } private async Task> SearchEntriesAsync( LdapConnection conn, string filter, CancellationToken ct) { var scope = MapScope(_options.ParseScope()); var attributes = _options.ParseAttributes(); var results = new List(); var searchResults = await conn.SearchAsync(_endpoint.BaseDn, scope, filter, attributes, false, ct) .ConfigureAwait(false); while (await searchResults.HasMoreAsync(ct).ConfigureAwait(false)) { ct.ThrowIfCancellationRequested(); NovellEntry novellEntry; try { novellEntry = await searchResults.NextAsync(ct).ConfigureAwait(false); } catch (LdapException ex) when (ex.ResultCode == LdapException.SizeLimitExceeded) { Logger?.LogWarning("LDAP size limit exceeded during poll for {BaseDn}", _endpoint.BaseDn); break; } results.Add(ConvertEntry(novellEntry)); } return results; } private async Task GetInitialMarkerAsync(LdapChangeTrackingMode mode, CancellationToken ct) { if (mode == LdapChangeTrackingMode.ModifyTimestamp) return DateTime.UtcNow.ToString("yyyyMMddHHmmss") + "Z"; if (mode == LdapChangeTrackingMode.Usn) { // Read highestCommittedUSN from RootDSE var conn = await _endpoint.AcquireConnectionAsync(ct).ConfigureAwait(false); try { var searchResults = await conn.SearchAsync("", LdapConnection.ScopeBase, "(objectClass=*)", new[] { "highestCommittedUSN" }, false, ct).ConfigureAwait(false); if (await searchResults.HasMoreAsync(ct).ConfigureAwait(false)) { var entry = await searchResults.NextAsync(ct).ConfigureAwait(false); var attr = entry.Get("highestCommittedUSN"); return attr?.StringValue; } } finally { _endpoint.ReleaseConnection(conn); } } return null; } private static LdapEntry ConvertEntry(NovellEntry entry) { var result = new LdapEntry { Dn = entry.Dn }; var attrSet = entry.GetAttributeSet(); foreach (LdapAttribute attr in attrSet) { var values = attr.StringValueArray; result.Attributes[attr.Name] = values.Length == 1 ? (object)values[0] : values; } return result; } private static int MapScope(LdapSearchScope scope) => scope switch { LdapSearchScope.Base => LdapConnection.ScopeBase, LdapSearchScope.OneLevel => LdapConnection.ScopeOne, _ => LdapConnection.ScopeSub }; } 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); } } Path: redb-route/redb.Route.Ldap/LdapEndpointOptions.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/LdapEndpointOptions.cs ---- using redb.Route.Core; namespace redb.Route.Ldap; /// /// Typed options for LDAP endpoint. Bound from URI query parameters. /// public sealed class LdapEndpointOptions : EndpointOptions { // ── 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; } /// Named connection factory from the registry. [RegistryReference(typeof(LdapConnectionFactory))] public string? ConnectionFactory { 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; } // ── Search ── /// /// LDAP filter expression, e.g. (objectClass=user). /// Supports ${...} expressions via for per-request resolution. /// public DynamicValue? Filter { get; set; } /// Search scope: base, onelevel, or subtree (default). public string Scope { get; set; } = "subtree"; /// Comma-separated list of attributes to return, e.g. cn,mail,sAMAccountName. public string? Attributes { get; set; } /// Page size for paged search results (default 500). public int PageSize { get; set; } = 500; /// Server-side maximum number of entries to return (0 = unlimited). public int SizeLimit { get; set; } /// Server-side time limit in seconds (0 = unlimited). public int TimeLimit { get; set; } // ── Consumer (Watch) ── /// Poll interval in milliseconds for the Watch consumer (default 60000). public int PollInterval { get; set; } = 60000; /// Change tracking mode: modifyTimestamp, usn, or persistent. public string ChangeTrackingMode { get; set; } = "modifyTimestamp"; /// Load all matching entries on consumer startup. public bool InitialLoad { get; set; } /// Detect deleted entries by comparing known DNs with current search results (opt-in). public bool DetectDeletions { get; set; } /// Number of poll cycles between full synchronizations for deletion detection (default 10). public int FullSyncInterval { get; set; } = 10; // ── Protocol ── /// LDAP protocol version (default 3). public int ProtocolVersion { get; set; } = 3; /// Follow LDAP referrals automatically. public bool FollowReferrals { get; set; } = true; // ── Pool ── /// Maximum number of connections in the pool. public int MaxConnections { get; set; } = 10; // ── SSL options ── /// 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; } /// protected override string? UnknownParameterHint(string name) => name.Equals("skipCertificateValidation", StringComparison.OrdinalIgnoreCase) ? "'skipCertificateValidation' is renamed 'trustAllCertificates', the name every other connector uses." : null; /// public override void Validate() { if (string.IsNullOrWhiteSpace(Server)) throw new ArgumentException("LDAP server is required.", nameof(Server)); if (Port is <= 0 or > 65535) throw new ArgumentOutOfRangeException(nameof(Port), Port, "Port must be between 1 and 65535."); if (Ssl && StartTls) throw new InvalidOperationException("Ssl and StartTls are mutually exclusive. Use Ssl for LDAPS (port 636) or StartTls for upgrading a plain connection (port 389)."); if (PageSize < 0) throw new ArgumentOutOfRangeException(nameof(PageSize), PageSize, "PageSize must be >= 0 (0 disables paged results)."); if (MaxConnections <= 0) throw new ArgumentOutOfRangeException(nameof(MaxConnections), MaxConnections, "MaxConnections must be > 0."); if (ConnectTimeout <= 0) throw new ArgumentOutOfRangeException(nameof(ConnectTimeout), ConnectTimeout, "ConnectTimeout must be > 0."); if (OperationTimeout <= 0) throw new ArgumentOutOfRangeException(nameof(OperationTimeout), OperationTimeout, "OperationTimeout must be > 0."); if (PollInterval <= 0) throw new ArgumentOutOfRangeException(nameof(PollInterval), PollInterval, "PollInterval must be > 0."); if (FullSyncInterval <= 0) throw new ArgumentOutOfRangeException(nameof(FullSyncInterval), FullSyncInterval, "FullSyncInterval must be > 0."); } /// /// Parses the string into a enum. /// internal LdapSearchScope ParseScope() => Scope?.ToLowerInvariant() switch { "base" => LdapSearchScope.Base, "onelevel" or "one" => LdapSearchScope.OneLevel, _ => LdapSearchScope.Subtree }; /// /// Parses the CSV string into an array. /// Returns null if no specific attributes are requested (= return all). /// internal string[]? ParseAttributes() => string.IsNullOrWhiteSpace(Attributes) ? null : Attributes.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); /// /// Parses the string into enum. /// internal LdapChangeTrackingMode ParseChangeTrackingMode() => ChangeTrackingMode?.ToLowerInvariant() switch { "usn" => LdapChangeTrackingMode.Usn, "persistent" => LdapChangeTrackingMode.Persistent, _ => LdapChangeTrackingMode.ModifyTimestamp }; /// /// Gets the effective LDAP port: if SSL is enabled and default port is still 389, switch to 636. /// internal int EffectivePort => Ssl && Port == 389 ? 636 : Port; } Path: redb-route/redb.Route.Ldap/LdapEntry.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/LdapEntry.cs ---- namespace redb.Route.Ldap; /// /// Typed LDAP directory entry (DN + attributes). /// Returned by Search and Watch operations. /// public sealed class LdapEntry { /// Distinguished Name of the entry. public string Dn { get; set; } = ""; /// /// Attribute dictionary. Values are string for single-valued, /// string[] for multi-valued, or byte[] for binary attributes. /// public Dictionary Attributes { get; set; } = new(); /// Change type for consumer entries: "added", "modified", or "deleted". public string? ChangeType { get; set; } /// Gets a single-valued string attribute. public string? GetString(string attr) => Attributes.TryGetValue(attr, out var v) ? v?.ToString() : null; /// Gets a multi-valued string attribute. public string[]? GetStringArray(string attr) => Attributes.TryGetValue(attr, out var v) ? v as string[] : null; /// Gets a binary attribute value (first element if multi-valued). public byte[]? GetBytes(string attr) { if (!Attributes.TryGetValue(attr, out var v)) return null; if (v is byte[] single) return single; if (v is byte[][] multi) return multi.Length > 0 ? multi[0] : null; return null; } /// Gets a multi-valued binary attribute. public byte[][]? GetBytesArray(string attr) => Attributes.TryGetValue(attr, out var v) ? v as byte[][] : null; } Path: redb-route/redb.Route.Ldap/LdapHeaders.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/LdapHeaders.cs ---- namespace redb.Route.Ldap; /// /// Header constants for LDAP exchanges. All keys use the redbLdap. prefix. /// public static class LdapHeaders { /// Common prefix for all LDAP headers. public const string Prefix = "redbLdap."; // ── Common ── /// Distinguished Name of the entry. public const string Dn = "redbLdap.Dn"; /// Base DN used for the operation. public const string BaseDn = "redbLdap.BaseDn"; /// LDAP filter expression. public const string Filter = "redbLdap.Filter"; /// UTC timestamp of the exchange. public const string Timestamp = "redbLdap.Timestamp"; // ── Search ── /// Number of entries returned by a search. public const string ResultCount = "redbLdap.ResultCount"; /// Search execution time in milliseconds. public const string SearchTime = "redbLdap.SearchTime"; /// Opaque cookie for paged search continuation. public const string PageCookie = "redbLdap.PageCookie"; /// LDAP server hostname. public const string Server = "redbLdap.Server"; /// LDAP server port. public const string Port = "redbLdap.Port"; /// Whether SSL/TLS was used for the connection. public const string Ssl = "redbLdap.Ssl"; /// Search scope used (Base, OneLevel, Subtree). public const string Scope = "redbLdap.Scope"; // ── Modify ── /// Number of modifications applied. public const string ModCount = "redbLdap.ModCount"; // ── Delete ── /// Whether the entry was successfully deleted. public const string Deleted = "redbLdap.Deleted"; // ── Bind (auth) ── /// DN used for authentication. public const string AuthDn = "redbLdap.AuthDn"; /// Password for authentication (cleared after use). public const string AuthPassword = "redbLdap.AuthPassword"; /// Bind result code. public const string BindResult = "redbLdap.BindResult"; // ── Compare ── /// Attribute name to compare. public const string CompareAttribute = "redbLdap.CompareAttribute"; /// Expected attribute value to compare against. public const string CompareValue = "redbLdap.CompareValue"; /// Comparison result (true/false). public const string CompareResult = "redbLdap.CompareResult"; // ── Rename ── /// New RDN for rename operation. public const string NewRdn = "redbLdap.NewRdn"; /// New parent DN for move operation. public const string NewParentDn = "redbLdap.NewParentDn"; /// Original DN before rename. public const string OldDn = "redbLdap.OldDn"; /// Resulting DN after rename. public const string NewDn = "redbLdap.NewDn"; // ── Consumer (Watch) ── /// Type of change detected: added, modified, or deleted. public const string ChangeType = "redbLdap.ChangeType"; /// Opaque marker for change tracking position (USN or timestamp). public const string ChangeMarker = "redbLdap.ChangeMarker"; /// Checks whether a header key belongs to this connector. public static bool IsRedbHeader(string key) => key.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase); } Path: redb-route/redb.Route.Ldap/LdapOperationType.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/LdapOperationType.cs ---- namespace redb.Route.Ldap; /// /// LDAP operation types supported by the connector. /// The first path segment of the URI determines the operation. /// public enum LdapOperationType { // ── Read ── /// Search entries by filter, base DN, and scope. SEARCH, /// Compare an attribute value at a specific DN. COMPARE, // ── Write ── /// Create a new entry (DN + attributes). ADD, /// Modify attributes of an existing entry. MODIFY, /// Delete an entry by DN. DELETE, /// Rename/move an entry (ModifyDN). RENAME, // ── Auth ── /// Verify user credentials via LDAP Bind. BIND, // ── Consumer ── /// Poll directory for changes (consumer-only). WATCH } Path: redb-route/redb.Route.Ldap/LdapProducer.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/LdapProducer.cs ---- using System.Diagnostics; using System.Net.Sockets; using Microsoft.Extensions.Logging; using Novell.Directory.Ldap; using Novell.Directory.Ldap.Controls; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Telemetry; using NovellEntry = Novell.Directory.Ldap.LdapEntry; namespace redb.Route.Ldap; /// /// LDAP producer. Dispatches to the correct LDAP operation based on . /// Supports all operations: Search, Add, Modify, Delete, Compare, Rename, Bind. /// internal sealed class LdapProducer : ConnectableProducer { private readonly LdapEndpoint _endpoint; private readonly LdapEndpointOptions _options; /// Creates an LDAP producer. public LdapProducer(LdapEndpoint endpoint, LdapEndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// protected override IEndpoint ProducerEndpoint => _endpoint; /// protected override string ProducerName => $"ldap:{_endpoint.OperationType}:{_endpoint.BaseDn}"; /// protected override async Task ConnectAsync(CancellationToken ct) { // Warm up the pool with one connection to verify connectivity var conn = await _endpoint.AcquireConnectionAsync(ct).ConfigureAwait(false); _endpoint.ReleaseConnection(conn); Logger?.LogInformation("LDAP producer connected: {Name}", ProducerName); } /// // No RecordMessageOut anywhere below: the core (ToProcessor / the template) counts every // send once; per-operation self-recording doubled routed numbers (ownership audit). public override async Task Process(IExchange exchange, CancellationToken ct = default) { EnsureStarted(); using var activity = RouteTelemetryExtensions.StartTransportSpan( (_endpoint.Component as ComponentBase)?.Context, $"ldap.{_endpoint.OperationType}", ActivityKind.Client, "network.protocol.name", "ldap", _endpoint.Uri.NormalizedKey); activity?.SetTag("ldap.operation", _endpoint.OperationType.ToString()); activity?.SetTag("ldap.base_dn", _endpoint.BaseDn); activity?.SetTag("ldap.server", _options.Server); activity?.SetTag("ldap.port", _options.EffectivePort); activity?.SetTag("ldap.ssl", _options.Ssl || _options.StartTls); // BIND uses a fresh isolated connection — NOT from pool if (_endpoint.OperationType == LdapOperationType.BIND) { await ProcessBindAsync(exchange, activity, ct).ConfigureAwait(false); return; } var conn = await _endpoint.AcquireConnectionAsync(ct).ConfigureAwait(false); try { await DispatchOperationAsync(conn, exchange, activity, ct).ConfigureAwait(false); } catch (LdapException ex) { activity.RecordFailure(ex); Logger?.LogError(ex, "LDAP {Operation} failed: baseDn={BaseDn}, resultCode={Code}", _endpoint.OperationType, _endpoint.BaseDn, ex.ResultCode); _endpoint.RecordError(ex); throw; } catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested) { activity.RecordFailure(ex); Logger?.LogError(ex, "LDAP {Operation} failed: baseDn={BaseDn}", _endpoint.OperationType, _endpoint.BaseDn); _endpoint.RecordError(ex); throw; } finally { _endpoint.ReleaseConnection(conn); } } private Task DispatchOperationAsync( LdapConnection conn, IExchange exchange, Activity? activity, CancellationToken ct) { return _endpoint.OperationType switch { LdapOperationType.SEARCH => ProcessSearchAsync(conn, exchange, activity, ct), LdapOperationType.ADD => ProcessAddAsync(conn, exchange, activity, ct), LdapOperationType.MODIFY => ProcessModifyAsync(conn, exchange, activity, ct), LdapOperationType.DELETE => ProcessDeleteAsync(conn, exchange, activity, ct), LdapOperationType.COMPARE => ProcessCompareAsync(conn, exchange, activity, ct), LdapOperationType.RENAME => ProcessRenameAsync(conn, exchange, activity, ct), _ => throw new NotSupportedException($"LDAP operation not supported: {_endpoint.OperationType}") }; } // ──────────────────────────────────────────────────────── // SEARCH // ──────────────────────────────────────────────────────── private async Task ProcessSearchAsync( LdapConnection conn, IExchange exchange, Activity? activity, CancellationToken ct) { var filter = _options.Filter?.Resolve(exchange) ?? "(objectClass=*)"; var baseDn = _endpoint.BaseDn; var scope = MapScope(_options.ParseScope()); var attributes = _options.ParseAttributes(); var pageSize = _options.PageSize; activity?.SetTag("ldap.filter", filter); activity?.SetTag("ldap.scope", _options.Scope); var results = new List(); var sw = Stopwatch.StartNew(); // Set up search constraints var constraints = new LdapSearchConstraints { MaxResults = _options.SizeLimit > 0 ? _options.SizeLimit : 0, ServerTimeLimit = _options.TimeLimit > 0 ? _options.TimeLimit : 0, ReferralFollowing = _options.FollowReferrals }; // Add paged results control unless explicitly disabled (PageSize = 0). if (pageSize > 0) { var pageControl = new SimplePagedResultsControl(pageSize, Array.Empty()); constraints.SetControls(pageControl); } byte[]? cookie = null; do { ct.ThrowIfCancellationRequested(); if (pageSize > 0 && cookie != null) { var nextPageControl = new SimplePagedResultsControl(pageSize, cookie); constraints.SetControls(nextPageControl); } var searchResults = await conn.SearchAsync(baseDn, scope, filter, attributes, false, constraints, ct) .ConfigureAwait(false); while (await searchResults.HasMoreAsync(ct).ConfigureAwait(false)) { ct.ThrowIfCancellationRequested(); NovellEntry novellEntry; try { novellEntry = await searchResults.NextAsync(ct).ConfigureAwait(false); } catch (LdapException ex) when (ex.ResultCode == LdapException.SizeLimitExceeded) { Logger?.LogWarning("LDAP size limit exceeded for search on {BaseDn}", baseDn); break; } catch (LdapReferralException ex) when (!_options.FollowReferrals) { Logger?.LogDebug(ex, "LDAP referral ignored for search on {BaseDn}", baseDn); break; } results.Add(ConvertEntry(novellEntry)); } // Extract cookie for next page cookie = GetPageCookie(searchResults); } while (cookie is { Length: > 0 }); sw.Stop(); activity?.SetTag("ldap.result_count", results.Count); // Set exchange output exchange.In.Body = results; exchange.In.Headers[LdapHeaders.ResultCount] = results.Count; exchange.In.Headers[LdapHeaders.SearchTime] = sw.ElapsedMilliseconds; exchange.In.Headers[LdapHeaders.BaseDn] = baseDn; exchange.In.Headers[LdapHeaders.Filter] = filter; exchange.In.Headers[LdapHeaders.Scope] = _options.Scope; exchange.In.Headers[LdapHeaders.Server] = _options.Server; exchange.In.Headers[LdapHeaders.Port] = _options.EffectivePort; exchange.In.Headers[LdapHeaders.Ssl] = _options.Ssl || _options.StartTls; } // ──────────────────────────────────────────────────────── // ADD // ──────────────────────────────────────────────────────── private async Task ProcessAddAsync( LdapConnection conn, IExchange exchange, Activity? activity, CancellationToken ct) { var dn = exchange.In.GetHeader(LdapHeaders.Dn) ?? _endpoint.BaseDn; if (exchange.In.Body is not IDictionary attrs || attrs.Count == 0) throw new InvalidOperationException( "ADD operation requires exchange.In.Body to be a Dictionary with at least one attribute."); var attrSet = new LdapAttributeSet(); foreach (var (key, value) in attrs) { var ldapAttr = value switch { string s => new LdapAttribute(key, s), string[] arr => new LdapAttribute(key, arr), byte[] bytes => new LdapAttribute(key, bytes), IEnumerable seq => new LdapAttribute(key, seq.ToArray()), _ => new LdapAttribute(key, value?.ToString() ?? "") }; attrSet.Add(ldapAttr); } var entry = new NovellEntry(dn, attrSet); await conn.AddAsync(entry, ct).ConfigureAwait(false); activity?.SetTag("ldap.dn", dn); exchange.In.Body = dn; exchange.In.Headers[LdapHeaders.Dn] = dn; Logger?.LogDebug("LDAP ADD completed: {Dn}", dn); } // ──────────────────────────────────────────────────────── // MODIFY // ──────────────────────────────────────────────────────── private async Task ProcessModifyAsync( LdapConnection conn, IExchange exchange, Activity? activity, CancellationToken ct) { var dn = exchange.In.GetHeader(LdapHeaders.Dn) ?? _endpoint.BaseDn; LdapModification[] mods; if (exchange.In.Body is LdapModification[] explicitMods) { mods = explicitMods; } else if (exchange.In.Body is IDictionary attrs && attrs.Count > 0) { // Dictionary = REPLACE semantics for each attribute mods = attrs.Select(kv => { var attr = kv.Value switch { string s => new LdapAttribute(kv.Key, s), string[] arr => new LdapAttribute(kv.Key, arr), byte[] bytes => new LdapAttribute(kv.Key, bytes), IEnumerable seq => new LdapAttribute(kv.Key, seq.ToArray()), _ => new LdapAttribute(kv.Key, kv.Value?.ToString() ?? "") }; return new LdapModification(LdapModification.Replace, attr); }).ToArray(); } else { throw new InvalidOperationException( "MODIFY operation requires exchange.In.Body to be a Dictionary or LdapModification[]."); } await conn.ModifyAsync(dn, mods, ct).ConfigureAwait(false); activity?.SetTag("ldap.dn", dn); activity?.SetTag("ldap.mod_count", mods.Length); exchange.In.Body = dn; exchange.In.Headers[LdapHeaders.Dn] = dn; exchange.In.Headers[LdapHeaders.ModCount] = mods.Length; Logger?.LogDebug("LDAP MODIFY completed: {Dn}, {Count} modifications", dn, mods.Length); } // ──────────────────────────────────────────────────────── // DELETE // ──────────────────────────────────────────────────────── private async Task ProcessDeleteAsync( LdapConnection conn, IExchange exchange, Activity? activity, CancellationToken ct) { var dn = exchange.In.GetHeader(LdapHeaders.Dn) ?? _endpoint.BaseDn; await conn.DeleteAsync(dn, ct).ConfigureAwait(false); activity?.SetTag("ldap.dn", dn); exchange.In.Body = dn; exchange.In.Headers[LdapHeaders.Dn] = dn; exchange.In.Headers[LdapHeaders.Deleted] = true; Logger?.LogDebug("LDAP DELETE completed: {Dn}", dn); } // ──────────────────────────────────────────────────────── // COMPARE // ──────────────────────────────────────────────────────── private async Task ProcessCompareAsync( LdapConnection conn, IExchange exchange, Activity? activity, CancellationToken ct) { var dn = exchange.In.GetHeader(LdapHeaders.Dn) ?? _endpoint.BaseDn; var attrName = exchange.In.GetHeader(LdapHeaders.CompareAttribute) ?? throw new InvalidOperationException( $"COMPARE operation requires header '{LdapHeaders.CompareAttribute}'."); var attrValue = exchange.In.GetHeader(LdapHeaders.CompareValue) ?? throw new InvalidOperationException( $"COMPARE operation requires header '{LdapHeaders.CompareValue}'."); var attr = new LdapAttribute(attrName, attrValue); var result = await conn.CompareAsync(dn, attr, ct).ConfigureAwait(false); activity?.SetTag("ldap.dn", dn); activity?.SetTag("ldap.compare_result", result); exchange.In.Body = result; exchange.In.Headers[LdapHeaders.Dn] = dn; exchange.In.Headers[LdapHeaders.CompareResult] = result; Logger?.LogDebug("LDAP COMPARE {Dn}.{Attr} = {Result}", dn, attrName, result); } // ──────────────────────────────────────────────────────── // RENAME // ──────────────────────────────────────────────────────── private async Task ProcessRenameAsync( LdapConnection conn, IExchange exchange, Activity? activity, CancellationToken ct) { var dn = exchange.In.GetHeader(LdapHeaders.Dn) ?? _endpoint.BaseDn; var newRdn = exchange.In.GetHeader(LdapHeaders.NewRdn) ?? throw new InvalidOperationException( $"RENAME operation requires header '{LdapHeaders.NewRdn}'."); var newParentDn = exchange.In.GetHeader(LdapHeaders.NewParentDn); if (newParentDn != null) await conn.RenameAsync(dn, newRdn, newParentDn, true, ct).ConfigureAwait(false); else await conn.RenameAsync(dn, newRdn, true, ct).ConfigureAwait(false); // Compute new DN var parentDn = newParentDn ?? GetParentDn(dn); var resultDn = string.IsNullOrEmpty(parentDn) ? newRdn : $"{newRdn},{parentDn}"; activity?.SetTag("ldap.old_dn", dn); activity?.SetTag("ldap.new_dn", resultDn); exchange.In.Body = resultDn; exchange.In.Headers[LdapHeaders.OldDn] = dn; exchange.In.Headers[LdapHeaders.NewDn] = resultDn; exchange.In.Headers[LdapHeaders.NewRdn] = newRdn; Logger?.LogDebug("LDAP RENAME {OldDn} → {NewDn}", dn, resultDn); } // ──────────────────────────────────────────────────────── // BIND (user authentication) // ──────────────────────────────────────────────────────── private async Task ProcessBindAsync( IExchange exchange, Activity? activity, CancellationToken ct) { var authDn = exchange.In.GetHeader(LdapHeaders.AuthDn) ?? throw new InvalidOperationException( $"BIND operation requires header '{LdapHeaders.AuthDn}'."); var authPassword = exchange.In.GetHeader(LdapHeaders.AuthPassword) ?? throw new InvalidOperationException( $"BIND operation requires header '{LdapHeaders.AuthPassword}'."); try { // Use endpoint's connection options to get proper SSL/TLS configuration var connOptions = _endpoint.BuildConnectionOptions(); using var conn = new LdapConnection(connOptions); await conn.ConnectAsync(_options.Server, _options.EffectivePort, ct).ConfigureAwait(false); if (_options.StartTls) await conn.StartTlsAsync(ct).ConfigureAwait(false); await conn.BindAsync(_options.ProtocolVersion, authDn, authPassword, ct).ConfigureAwait(false); activity?.SetTag("ldap.bind_result", 0); exchange.In.Body = true; exchange.In.Headers[LdapHeaders.BindResult] = 0; exchange.In.Headers[LdapHeaders.AuthDn] = authDn; Logger?.LogDebug("LDAP BIND succeeded: {AuthDn}", authDn); } catch (LdapException ex) { activity?.SetTag("ldap.bind_result", ex.ResultCode); exchange.In.Body = false; exchange.In.Headers[LdapHeaders.BindResult] = ex.ResultCode; exchange.In.Headers[LdapHeaders.AuthDn] = authDn; Logger?.LogWarning("LDAP BIND failed for {AuthDn}: resultCode={Code}, {Message}", authDn, ex.ResultCode, ex.Message); } catch (Exception ex) when (ex is SocketException or IOException) { activity?.SetTag("ldap.bind_result", -1); exchange.In.Body = false; exchange.In.Headers[LdapHeaders.BindResult] = -1; exchange.In.Headers[LdapHeaders.AuthDn] = authDn; Logger?.LogWarning("LDAP BIND network error for {AuthDn}: {Error}", authDn, ex.Message); } finally { // Security: always clear password from headers exchange.In.Headers.Remove(LdapHeaders.AuthPassword); } } // ──────────────────────────────────────────────────────── // Helpers // ──────────────────────────────────────────────────────── private static int MapScope(LdapSearchScope scope) => scope switch { LdapSearchScope.Base => LdapConnection.ScopeBase, LdapSearchScope.OneLevel => LdapConnection.ScopeOne, LdapSearchScope.Subtree => LdapConnection.ScopeSub, _ => LdapConnection.ScopeSub }; private static LdapEntry ConvertEntry(NovellEntry entry) { var result = new LdapEntry { Dn = entry.Dn }; var attrSet = entry.GetAttributeSet(); foreach (LdapAttribute attr in attrSet) { if (attr.ByteValueArray is { Length: > 0 } byteValues && IsBinaryAttribute(attr.Name)) { // Binary attribute — store raw bytes result.Attributes[attr.Name] = byteValues.Length == 1 ? (object)byteValues[0] : byteValues; } else { var values = attr.StringValueArray; result.Attributes[attr.Name] = values.Length == 1 ? (object)values[0] : values; } } return result; } private static bool IsBinaryAttribute(string name) { // Well-known binary attributes in LDAP/AD return name.EndsWith(";binary", StringComparison.OrdinalIgnoreCase) || name.Equals("objectGUID", StringComparison.OrdinalIgnoreCase) || name.Equals("objectSid", StringComparison.OrdinalIgnoreCase) || name.Equals("thumbnailPhoto", StringComparison.OrdinalIgnoreCase) || name.Equals("jpegPhoto", StringComparison.OrdinalIgnoreCase) || name.Equals("userCertificate", StringComparison.OrdinalIgnoreCase) || name.Equals("msExchMailboxGuid", StringComparison.OrdinalIgnoreCase) || name.Equals("msExchMailboxSecurityDescriptor", StringComparison.OrdinalIgnoreCase); } private static byte[]? GetPageCookie(ILdapSearchResults results) { var controls = results.ResponseControls; if (controls == null) return null; foreach (var control in controls) { if (control is SimplePagedResultsControl pagedControl) return pagedControl.Cookie; } return null; } private static string GetParentDn(string dn) { var commaIndex = dn.IndexOf(','); return commaIndex >= 0 ? dn[(commaIndex + 1)..] : ""; } } Path: redb-route/redb.Route.Ldap/LdapSearchScope.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/LdapSearchScope.cs ---- namespace redb.Route.Ldap; /// /// LDAP search scope — controls how deep the search goes from the base DN. /// public enum LdapSearchScope { /// Only the base entry itself. Base, /// One level below the base DN (direct children only). OneLevel, /// The entire subtree below the base DN (default). Subtree } Path: redb-route/redb.Route.Ldap/README.md 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/README.md ---- # redb.Route.Ldap > Documentation and articles: LDAP / Active Directory connector for redb.Route. Search, CRUD, authentication, and change tracking — all directory operations as endpoints via Novell.Directory.Ldap.NETStandard. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Ldap?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Ldap) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Installation ```bash dotnet add package redb.Route.Ldap ``` ## Usage ### URI Format ``` ldap:OPERATION:baseDn?server=host&port=389&bindDn=cn=admin,dc=example,dc=com&bindPassword=secret ``` ### Fluent DSL ```csharp using redb.Route.Ldap; // Search users From(LdapDsl.Search("ou=users,dc=example,dc=com") .Server("ldap.example.com") .BindDn("cn=admin,dc=example,dc=com") .BindPassword("secret") .Filter("(objectClass=inetOrgPerson)") .Scope(LdapSearchScope.Subtree) .Attributes("cn", "mail", "uid") .PageSize(500)) .Log("Found: ${header['redbLdap.ResultCount']} entries") .To("direct://process"); // Watch for changes (consumer — polls for modifications) From(LdapDsl.Watch("ou=users,dc=example,dc=com") .Server("ldap.example.com") .BindDn("cn=admin,dc=example,dc=com") .BindPassword("secret") .ChangeTracking(LdapChangeTrackingMode.ModifyTimestamp) .PollInterval(5000) .InitialLoad()) .Log("Changed entry: ${body}") .To("direct://sync"); // Add entry From("direct://create-user") .To(LdapDsl.Add("ou=users,dc=example,dc=com") .Server("ldap.example.com") .BindDn("cn=admin,dc=example,dc=com") .BindPassword("secret")); // Modify entry From("direct://update-user") .To(LdapDsl.Modify("cn=alice,ou=users,dc=example,dc=com") .Server("ldap.example.com") .BindDn("cn=admin,dc=example,dc=com") .BindPassword("secret")); // Bind (authentication check) From("direct://authenticate") .To(LdapDsl.Bind("dc=example,dc=com") .Server("ldap.example.com")); ``` ## Fluent Builder API | Category | Methods | |----------|---------| | **Operations** | `LdapDsl.Search()`, `LdapDsl.Compare()`, `LdapDsl.Add()`, `LdapDsl.Modify()`, `LdapDsl.Delete()`, `Ldap.Rename()`, `LdapDsl.Bind()`, `LdapDsl.Watch()` | | **Connection** | `.Server()`, `.Port()`, `.Ssl()`, `.StartTls()`, `.ConnectionFactory()`, `.ConnectTimeout()`, `.OperationTimeout()` | | **Auth** | `.BindDn()`, `.BindPassword()` | | **Search** | `.Filter()`, `.Scope()`, `.Attributes()`, `.PageSize()`, `.SizeLimit()`, `.TimeLimit()` | | **Consumer** | `.PollInterval()`, `.ChangeTracking()`, `.InitialLoad()` | | **Protocol** | `.ProtocolVersion()`, `.Referrals()` | | **Pool** | `.MaxConnections()` | | **TLS** | `.TrustAllCertificates()`, `.ClientCert()` | > Most builder methods accept both constant values and `IExpression` for runtime resolution via the expression engine. ## Exchange Headers | Header | Description | |--------|-------------| | `redbLdap.Operation` | Operation type (Search, Add, etc.) | | `redbLdap.BaseDn` | Base DN used in the operation | | `redbLdap.Filter` | LDAP filter applied | | `redbLdap.Scope` | Search scope (Base, OneLevel, Subtree) | | `redbLdap.ResultCount` | Number of entries returned | | `redbLdap.SearchTime` | Search duration in milliseconds | | `redbLdap.Server` | Target LDAP server | | `redbLdap.Port` | Target port | | `redbLdap.Ssl` | Whether SSL/TLS was used | | `redbLdap.ChangeType` | Change type for Watch consumer | ## Change Tracking Modes | Mode | Description | |------|-------------| | `ModifyTimestamp` | Polls using `modifyTimestamp` attribute (standard LDAP) | | `Usn` | Polls using `uSNChanged` attribute (Active Directory) | | `Persistent` | Persistent search control (if supported by server) | ## Docker (for testing) ```yaml services: openldap: image: osixia/openldap:1.5.0 ports: - "389:389" - "636:636" environment: LDAP_ORGANISATION: "redb" LDAP_DOMAIN: "redb.test" LDAP_ADMIN_PASSWORD: "admin" ``` ## Part of [redb.Route](../README.md) — ESB & EIP Framework for .NET ## Named connection factory Keep credentials out of the route URI: register a factory in the context registry and reference it by name. A set-but-unknown name fails loud at startup — a typo can never silently fall back to inline URI parameters. ```csharp context.AddToRegistry("prod", new LdapConnectionFactory { Server = "dc01.corp.local", BindDn = "CN=svc,OU=Service,DC=corp,DC=local", BindPassword = secrets.LdapPassword, }); // ldap:SEARCH:dc=corp,dc=local?connectionFactory=prod ``` ## Tracing On the `redb.Route` activity source (`AddSource("redb.Route")`), with `network.protocol.name` = `ldap` and `redb.route.endpoint`: - **Consumer (WATCH).** One `Consumer` span, `ldap {baseDn} receive`, per routed entry. An entry carries no trace context, so the span is a root, never a child of the activity the poll loop inherited from whoever started the routes; a poll that finds nothing opens none. A failed route marks it an error, whether the failure stays on the exchange or escapes the pipeline; our own stop does not. - **Producer.** One `Client` span per operation, `ldap.{operation}`, with the `ldap.*` tags; an error when the operation fails, unless our own token cancelled it. A rejected `BIND` is an answer, not a failure: it is on `ldap.bind_result`. - `RouteEngineOptions.EnableTelemetry = false` opens neither span. Path: redb-route/redb.Route.Ldap/redb.Route.Ldap.csproj 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/redb.Route.Ldap.csproj ---- redb.Route.Ldap LDAP/Active Directory transport for redb.Route ESB framework. Provides Search, Add, Modify, Delete, Compare, Bind operations and directory change polling consumer. esb;messaging;ldap;activedirectory;ad;directory;redb README.md