Bundle: redb-identity / src/redb.Identity.Ldap (src.redb.Identity.Ldap.txt), 14 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-identity
Index: https://redbase.app/src/dev-2026-12-06/redb-identity/_index.txt
====
Path: redb-identity/src/redb.Identity.Ldap/Extensions/LdapServiceExtensions.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/Extensions/LdapServiceExtensions.cs
----
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using redb.Identity.Core.Services;
namespace redb.Identity.Ldap;
///
/// DI registration for LDAP external user provider and sync infrastructure.
///
public static class LdapServiceExtensions
{
///
/// Registers as an
/// using options bound from an section.
///
public static IServiceCollection AddRedbIdentityLdap(
this IServiceCollection services,
IConfiguration configuration)
{
var options = new LdapProviderOptions();
configuration.Bind(options);
options.NormalizeAfterBind();
return services.AddRedbIdentityLdap(options);
}
///
/// Registers as an
/// with explicit options. Supports multi-provider via keyed options.
///
public static IServiceCollection AddRedbIdentityLdap(
this IServiceCollection services,
LdapProviderOptions options)
{
ArgumentNullException.ThrowIfNull(options);
services.AddKeyedSingleton(options.ProviderName, options);
services.AddSingleton(sp =>
new LdapExternalUserProvider(
options,
sp.GetRequiredService>()));
return services;
}
///
/// Registers as an
/// with a configuration callback.
///
public static IServiceCollection AddRedbIdentityLdap(
this IServiceCollection services,
Action configure)
{
var options = new LdapProviderOptions();
configure(options);
return services.AddRedbIdentityLdap(options);
}
///
/// Adds an LDAP connectivity health check that probes all registered LDAP providers.
///
public static IHealthChecksBuilder AddRedbIdentityLdapCheck(
this IHealthChecksBuilder builder,
string name = "redb-identity-ldap",
HealthStatus? failureStatus = HealthStatus.Degraded,
IEnumerable? tags = null)
{
return builder.Add(new HealthCheckRegistration(
name,
sp => new LdapHealthCheck(
sp.GetServices(),
sp.GetRequiredService>()),
failureStatus,
tags));
}
///
/// Registers the LDAP sync infrastructure:
/// , ,
/// and optionally .
/// The must be registered separately
/// via AddRouteBuilder<LdapSyncRouteBuilder>().
///
public static IServiceCollection AddRedbIdentityLdapSync(
this IServiceCollection services,
Action configure)
{
var options = new LdapSyncOptions();
configure(options);
return services.AddRedbIdentityLdapSync(options);
}
///
/// Registers the LDAP sync infrastructure with explicit options.
///
public static IServiceCollection AddRedbIdentityLdapSync(
this IServiceCollection services,
LdapSyncOptions options)
{
ArgumentNullException.ThrowIfNull(options);
services.AddSingleton(options);
services.AddScoped();
if (options.SyncGroups)
{
services.AddSingleton(options.GroupMapperOptions);
services.AddScoped();
}
return services;
}
}
Path: redb-identity/src/redb.Identity.Ldap/LdapAttributeMapper.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/LdapAttributeMapper.cs
----
using redb.Identity.Core.Services;
using redb.Route.Ldap;
namespace redb.Identity.Ldap;
///
/// Maps LDAP entry attributes to fields
/// using the attribute map from .
///
public sealed class LdapAttributeMapper
{
private readonly LdapProviderOptions _options;
public LdapAttributeMapper(LdapProviderOptions options)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
}
///
/// Extracts the mapped field value from an LDAP entry.
/// Returns null if the field is not mapped or the attribute is missing.
///
public string? GetField(LdapEntry entry, string fieldName)
{
if (!_options.AttributeMap.TryGetValue(fieldName, out var ldapAttr))
return null;
return entry.GetString(ldapAttr);
}
///
/// Builds the ExternalAuthResult from an LDAP entry using the configured attribute map.
///
public ExternalAuthResult MapToResult(LdapEntry entry)
{
var externalId = GetField(entry, "externalId") ?? entry.Dn;
var displayName = GetField(entry, "displayName");
var email = GetField(entry, "email");
var phone = GetField(entry, "phone");
var givenName = GetField(entry, "givenName");
var familyName = GetField(entry, "familyName");
Dictionary? additionalClaims = null;
if (_options.AdditionalClaimsMap.Count > 0)
{
additionalClaims = new Dictionary();
foreach (var (claimName, ldapAttr) in _options.AdditionalClaimsMap)
{
var value = entry.GetString(ldapAttr);
if (value != null)
additionalClaims[claimName] = value;
}
if (additionalClaims.Count == 0)
additionalClaims = null;
}
return ExternalAuthResult.Success(
externalId: externalId,
displayName: displayName,
email: email,
phone: phone,
givenName: givenName,
familyName: familyName,
additionalClaims: additionalClaims);
}
///
/// Returns the list of LDAP attribute names needed for the search request.
/// Includes both field attributes and additional claims attributes.
///
public string[] GetRequestedAttributes()
{
var attrs = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (var ldapAttr in _options.AttributeMap.Values)
attrs.Add(ldapAttr);
foreach (var ldapAttr in _options.AdditionalClaimsMap.Values)
attrs.Add(ldapAttr);
return attrs.ToArray();
}
}
Path: redb-identity/src/redb.Identity.Ldap/LdapConnectionSettings.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/LdapConnectionSettings.cs
----
namespace redb.Identity.Ldap;
///
/// Shared LDAP connection settings. Base class for both
/// and .
///
public class LdapConnectionSettings
{
/// LDAP server hostname or IP. Default: "localhost".
public string Server { get; set; } = "localhost";
/// LDAP port. Default: 389 (636 for LDAPS).
public int Port { get; set; } = 389;
/// Use LDAPS (SSL/TLS on connect). Default: false.
public bool UseSsl { get; set; }
/// Upgrade to TLS via STARTTLS on the plain port. Default: false.
public bool UseStartTls { get; set; }
/// Skip server certificate validation (development only!). Default: false.
public bool SkipCertificateValidation { get; set; }
/// Bind DN for service-account search. Required for search+bind flow.
public string? BindDn { get; set; }
/// Bind password for service-account search.
public string? BindPassword { get; set; }
/// Client-side timeout for a single LDAP operation in seconds. 0 = no limit. Default: 10.
public int OperationTimeoutSeconds { get; set; } = 10;
///
/// Bounded DNS+TCP pre-flight probe timeout in seconds. 0 disables the
/// probe (rely on OS-level retransmit timeouts — not recommended).
///
/// LdapForNet's only caps the LDAP-protocol
/// exchange after the socket is established; it does NOT bound DNS resolution
/// nor TCP connect(). On Windows the OS-level SYN retransmit takes ~21 s
/// for a routed-but-silent destination, which would block login threads on a
/// downed AD controller. The pre-flight probe ensures we fail fast within this
/// window. Default: 10.
///
///
public int ConnectTimeoutSeconds { get; set; } = 10;
/// Maximum number of pooled connections. Default: 5.
public int MaxConnections { get; set; } = 5;
///
/// Returns the effective LDAP port (636 if SSL enabled and default port unchanged).
///
public int EffectivePort => UseSsl && Port == 389 ? 636 : Port;
///
/// Validates the connection settings.
///
public void ValidateConnection()
{
if (string.IsNullOrWhiteSpace(Server))
throw new InvalidOperationException($"{GetType().Name}.Server is required.");
if (Port is <= 0 or > 65535)
throw new InvalidOperationException($"{GetType().Name}.Port is out of range: {Port}.");
if (UseSsl && UseStartTls)
throw new InvalidOperationException(
$"{GetType().Name}: UseSsl and UseStartTls are mutually exclusive.");
if (!string.IsNullOrWhiteSpace(BindDn) && string.IsNullOrWhiteSpace(BindPassword))
throw new InvalidOperationException(
$"{GetType().Name}: BindDn is set but BindPassword is empty.");
if (string.IsNullOrWhiteSpace(BindDn) && !string.IsNullOrWhiteSpace(BindPassword))
throw new InvalidOperationException(
$"{GetType().Name}: BindPassword is set but BindDn is empty.");
}
}
Path: redb-identity/src/redb.Identity.Ldap/LdapConnectivityProbe.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/LdapConnectivityProbe.cs
----
using System.Net;
using System.Net.Sockets;
namespace redb.Identity.Ldap;
///
/// Bounded TCP/DNS pre-flight probe for LDAP endpoints.
///
/// LdapForNet's OperationTimeout bounds only the LDAP-protocol exchange
/// AFTER the socket is established. It does not cap DNS resolution nor the
/// underlying TCP connect(), so an unreachable host (firewalled IP,
/// black-holed route, NXDOMAIN behind a slow resolver) lets the OS-level SYN
/// retransmit timeout dominate latency — on Windows that is ~21 s for a routed
/// but silent destination, and 5–10 s for typical NXDOMAIN.
///
///
/// This probe runs
/// +
/// inside a single bounded and converts
/// any timeout/cancellation into a , so the
/// caller fails fast instead of blocking the request thread.
///
///
internal static class LdapConnectivityProbe
{
///
/// Verifies that : is
/// reachable within . The socket is
/// closed immediately after a successful connect — the real LDAP client
/// opens its own connection. Throws on
/// timeout, on hard refusal, or propagates
/// cancellation.
///
///
/// A no-op when ≤ 0 — callers that
/// wish to disable the probe (e.g. in environments where every LDAP host
/// blocks ICMP/SYN scans but LDAP itself is fine) can set the option to 0.
///
public static async Task ProbeAsync(
string host, int port, int timeoutSeconds, CancellationToken ct)
{
if (timeoutSeconds <= 0) return;
if (string.IsNullOrWhiteSpace(host))
throw new ArgumentException("Host is required.", nameof(host));
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds));
try
{
IPAddress[] addresses;
if (IPAddress.TryParse(host, out var literal))
{
addresses = [literal];
}
else
{
addresses = await Dns.GetHostAddressesAsync(host, cts.Token)
.ConfigureAwait(false);
if (addresses.Length == 0)
throw new SocketException((int)SocketError.HostNotFound);
}
// First-address strategy — matches what TcpClient(host, port) does
// internally. If the host is multi-homed and the first IP is
// dead, we will report a timeout; this matches LdapForNet's own
// behaviour and keeps the probe deterministic.
using var tcp = new TcpClient(addresses[0].AddressFamily) { NoDelay = true };
await tcp.ConnectAsync(addresses[0], port, cts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
throw new TimeoutException(
$"LDAP connectivity probe timed out after {timeoutSeconds}s for {host}:{port}");
}
}
}
Path: redb-identity/src/redb.Identity.Ldap/LdapExternalUserProvider.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/LdapExternalUserProvider.cs
----
using Microsoft.Extensions.Logging;
using redb.Identity.Core.Services;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Ldap;
using static redb.Route.Ldap.LdapDsl;
namespace redb.Identity.Ldap;
///
/// LDAP external user provider. Implements search+bind authentication:
/// 1. Search with service account to find user DN by uid/sAMAccountName
/// 2. Bind with found user DN + provided password to verify credentials
/// 3. Check UAC flags (if enabled) for disabled/locked accounts
/// 4. Map LDAP attributes → ExternalAuthResult
///
public sealed class LdapExternalUserProvider : IExternalUserProvider, IAsyncDisposable
{
private readonly LdapProviderOptions _options;
private readonly LdapAttributeMapper _mapper;
private readonly ILogger _logger;
// Persistent search endpoint (connection pool)
private readonly LdapComponent _searchComponent;
private readonly IEndpoint _searchEndpoint;
private readonly IProducer _searchProducer;
private bool _started;
public string ProviderName => _options.ProviderName;
public int Priority => _options.Priority;
internal LdapProviderOptions Options => _options;
public LdapExternalUserProvider(
LdapProviderOptions options,
ILogger logger)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_options.Validate();
_mapper = new LdapAttributeMapper(options);
// Build persistent search endpoint with connection pool and dynamic filter
var requestedAttrs = _options.CheckAccountStatus
? _mapper.GetRequestedAttributes().Append("userAccountControl").Distinct(StringComparer.OrdinalIgnoreCase).ToArray()
: _mapper.GetRequestedAttributes();
var searchBuilder = Search(_options.UserBaseDn)
.Server(_options.Server)
.Port(_options.EffectivePort)
.Filter("${header.ldapSearchFilter}") // resolved per-request from exchange header
.Scope(MapScope(_options.SearchScope))
.Attributes(requestedAttrs)
.SizeLimit(2);
ApplyConnectionSettings(searchBuilder);
_searchComponent = new LdapComponent();
_searchEndpoint = _searchComponent.CreateEndpoint(EndpointUriParser.Parse(searchBuilder.Build()));
_searchProducer = _searchEndpoint.CreateProducer();
_logger.LogDebug(
"LDAP provider '{Provider}' configured: server={Server}:{Port}, baseDn={BaseDn}",
_options.ProviderName, _options.Server, _options.EffectivePort, _options.UserBaseDn);
}
private async Task EnsureStartedAsync(CancellationToken ct)
{
if (_started) return;
await _searchProducer.Start(ct).ConfigureAwait(false);
_started = true;
}
public async Task AuthenticateAsync(
string username, string password, CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
return null;
var (bareUsername, domain) = ParseDomainHint(username);
if (_options.Domains.Length > 0 && domain is not null)
{
if (!_options.Domains.Any(d => d.Equals(domain, StringComparison.OrdinalIgnoreCase)))
return null;
}
var searchUsername = domain is not null ? bareUsername : username;
try
{
// Pre-flight DNS+TCP probe — fails fast on unreachable hosts instead
// of waiting on the OS-level SYN retransmit timeout (~21 s on Windows).
// LdapForNet's OperationTimeout only caps the post-connect exchange.
await LdapConnectivityProbe.ProbeAsync(
_options.Server, _options.EffectivePort,
_options.ConnectTimeoutSeconds, ct).ConfigureAwait(false);
var entry = await SearchUserAsync(searchUsername, ct).ConfigureAwait(false);
if (entry == null)
{
_logger.LogDebug("LDAP user not found: {Username}", searchUsername);
return null;
}
var bindOk = await BindUserAsync(entry.Dn, password, ct).ConfigureAwait(false);
if (!bindOk)
{
_logger.LogDebug("LDAP bind failed for DN of user: {Username}", searchUsername);
return ExternalAuthResult.Failed("Invalid credentials");
}
// Check UAC flags (AD only)
if (_options.CheckAccountStatus)
{
var uacResult = CheckAccountStatus(entry, searchUsername);
if (uacResult is not null)
return uacResult;
}
var result = _mapper.MapToResult(entry);
// Add password_expired claim if applicable
if (_options.CheckAccountStatus)
{
var uacString = entry.GetString("userAccountControl");
if (uacString is not null && int.TryParse(uacString, out var uacValue))
{
var flags = (UserAccountControlFlags)uacValue;
if (flags.HasFlag(UserAccountControlFlags.PasswordExpired))
{
result.AdditionalClaims ??= new Dictionary();
result.AdditionalClaims["password_expired"] = "true";
}
}
}
_logger.LogInformation("LDAP authentication succeeded: {Username}", searchUsername);
return result;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "LDAP authentication error for user '{Username}' on {Server}:{Port}",
searchUsername, _options.Server, _options.EffectivePort);
throw;
}
}
private ExternalAuthResult? CheckAccountStatus(LdapEntry entry, string username)
{
var uacString = entry.GetString("userAccountControl");
if (uacString is null) return null; // attribute not present → graceful skip
if (!int.TryParse(uacString, out var uacValue))
{
_logger.LogDebug("Non-numeric userAccountControl for '{Username}', skipping check", username);
return null;
}
var flags = (UserAccountControlFlags)uacValue;
if (flags.HasFlag(UserAccountControlFlags.AccountDisable))
return ExternalAuthResult.Failed("Account is disabled");
if (flags.HasFlag(UserAccountControlFlags.Lockout))
return ExternalAuthResult.Failed("Account is locked out");
return null;
}
private async Task SearchUserAsync(string username, CancellationToken ct)
{
var filter = string.Format(_options.UserFilter, EscapeLdapFilter(username));
// Use persistent search producer (connection pool) with per-request filter
await EnsureStartedAsync(ct).ConfigureAwait(false);
var exchange = new Exchange(new Message());
exchange.In.Headers["ldapSearchFilter"] = filter;
await _searchProducer.Process(exchange, ct).ConfigureAwait(false);
if (exchange.In.Body is not List entries || entries.Count == 0)
return null;
if (entries.Count > 1)
{
_logger.LogWarning(
"Ambiguous LDAP search: {Count} entries for '{Username}'",
entries.Count, username);
return null; // reject ambiguous results
}
_logger.LogDebug("LDAP search found {Count} entry for '{Username}'", entries.Count, username);
return entries[0];
}
private async Task BindUserAsync(string userDn, string password, CancellationToken ct)
{
// Ephemeral endpoint for bind — each user gets isolated connection (security)
var builder = Bind(_options.UserBaseDn)
.Server(_options.Server)
.Port(_options.EffectivePort);
ApplyConnectionSettings(builder);
var component = new LdapComponent();
var endpoint = component.CreateEndpoint(EndpointUriParser.Parse(builder.Build()));
var producer = endpoint.CreateProducer();
try
{
await producer.Start(ct).ConfigureAwait(false);
var exchange = new Exchange(new Message());
exchange.In.Headers[LdapHeaders.AuthDn] = userDn;
exchange.In.Headers[LdapHeaders.AuthPassword] = password;
await producer.Process(exchange, ct).ConfigureAwait(false);
return exchange.In.Body is true;
}
finally
{
await producer.Stop(ct).ConfigureAwait(false);
(endpoint as IDisposable)?.Dispose();
}
}
private void ApplyConnectionSettings(LdapBuilder builder)
{
if (!string.IsNullOrWhiteSpace(_options.BindDn))
builder.BindDn(_options.BindDn);
if (!string.IsNullOrWhiteSpace(_options.BindPassword))
builder.BindPassword(_options.BindPassword);
if (_options.UseSsl)
builder.Ssl();
if (_options.UseStartTls)
builder.StartTls();
if (_options.SkipCertificateValidation)
builder.TrustAllCertificates();
if (_options.MaxConnections != 5)
builder.MaxConnections(_options.MaxConnections);
if (_options.OperationTimeoutSeconds > 0)
builder.OperationTimeout(_options.OperationTimeoutSeconds * 1000);
}
///
/// Extracts bare username and domain hint from "user@domain" or "DOMAIN\user" formats.
/// Returns the original input and null domain if no hint is detected.
///
internal static (string username, string? domain) ParseDomainHint(string input)
{
// user@domain.com → (user, domain.com)
var atIdx = input.IndexOf('@');
if (atIdx > 0 && atIdx < input.Length - 1)
return (input[..atIdx], input[(atIdx + 1)..]);
// DOMAIN\user → (user, DOMAIN)
var bsIdx = input.IndexOf('\\');
if (bsIdx > 0 && bsIdx < input.Length - 1)
return (input[(bsIdx + 1)..], input[..bsIdx]);
return (input, null);
}
///
/// Escapes special characters in LDAP filter values (RFC 4515 §3).
/// Prevents LDAP injection attacks.
///
internal static string EscapeLdapFilter(string value)
{
if (string.IsNullOrEmpty(value)) return value;
// RFC 4515: escape *, (, ), \, NUL
return value
.Replace("\\", "\\5c")
.Replace("*", "\\2a")
.Replace("(", "\\28")
.Replace(")", "\\29")
.Replace("\0", "\\00");
}
private static LdapSearchScope MapScope(LdapSearchScopeOption scope) => scope switch
{
LdapSearchScopeOption.Base => LdapSearchScope.Base,
LdapSearchScopeOption.OneLevel => LdapSearchScope.OneLevel,
LdapSearchScopeOption.Subtree => LdapSearchScope.Subtree,
_ => LdapSearchScope.Subtree
};
public async ValueTask DisposeAsync()
{
if (_started)
{
await _searchProducer.Stop(CancellationToken.None).ConfigureAwait(false);
_started = false;
}
(_searchEndpoint as IDisposable)?.Dispose();
}
}
Path: redb-identity/src/redb.Identity.Ldap/LdapGroupMapper.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/LdapGroupMapper.cs
----
using System.Text;
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Models.Entities;
using redb.Core.Query;
using redb.Identity.Core.Models;
using redb.Identity.Core.Services;
using redb.Route.Ldap;
namespace redb.Identity.Ldap;
///
/// Syncs LDAP group memberships (memberOf attribute) to Identity groups.
/// Extracts CN from LDAP group DNs, auto-creates missing groups, and manages memberships.
///
public sealed class LdapGroupMapper
{
private readonly IGroupService _groupService;
private readonly IRedbService _redb;
private readonly LdapGroupMapperOptions _options;
private readonly ILogger _logger;
private Dictionary>? _groupCache;
public LdapGroupMapper(
IGroupService groupService,
IRedbService redb,
LdapGroupMapperOptions options,
ILogger logger)
{
_groupService = groupService ?? throw new ArgumentNullException(nameof(groupService));
_redb = redb ?? throw new ArgumentNullException(nameof(redb));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
///
/// Clears the group cache. Call after processing a sync batch.
///
public void ClearGroupCache() => _groupCache = null;
///
/// Syncs a user's group memberships from an LDAP entry's memberOf attribute.
///
public async Task SyncUserGroupsAsync(long userId, LdapEntry entry, CancellationToken ct = default)
{
var memberOfValues = entry.GetStringArray(_options.GroupMemberAttribute);
var ldapGroupNames = memberOfValues?
.Select(ExtractCnFromDn)
.Where(n => n is not null)
.Cast()
.ToHashSet(StringComparer.OrdinalIgnoreCase)
?? new HashSet(StringComparer.OrdinalIgnoreCase);
var currentMemberships = await _groupService.GetUserGroupsAsync(userId, ct).ConfigureAwait(false);
foreach (var groupName in ldapGroupNames)
{
if (currentMemberships.Any(m => groupName.Equals(m.GroupName, StringComparison.OrdinalIgnoreCase)))
continue;
var group = await FindOrCreateGroupAsync(groupName!, ct).ConfigureAwait(false);
if (group is null) continue;
await _groupService.AddMemberAsync(group.id, userId, _options.MemberRole, ct: ct)
.ConfigureAwait(false);
_logger.LogInformation("Added user {UserId} to group '{GroupName}' (id={GroupId})",
userId, groupName, group.id);
}
if (_options.SyncStrategy == LdapGroupSyncStrategy.Full)
{
foreach (var membership in currentMemberships)
{
if (membership.GroupName is null) continue;
if (ldapGroupNames.Contains(membership.GroupName)) continue;
await _groupService.RemoveMemberAsync(membership.GroupId, userId, ct)
.ConfigureAwait(false);
_logger.LogInformation("Removed user {UserId} from group '{GroupName}' (id={GroupId})",
userId, membership.GroupName, membership.GroupId);
}
}
}
private async Task?> FindOrCreateGroupAsync(string name, CancellationToken ct)
{
// Check cache first
if (_groupCache?.TryGetValue(name, out var cached) == true)
return cached;
// By the unique name key, so a CN that differs only in case maps onto the existing group.
var existing = await _groupService.FindGroupByNameAsync(name, ct).ConfigureAwait(false);
if (existing is not null)
{
(_groupCache ??= new(StringComparer.OrdinalIgnoreCase))[name] = existing;
return existing;
}
if (!_options.AutoCreateGroups)
{
_logger.LogDebug("Group '{GroupName}' not found and AutoCreateGroups is disabled, skipping", name);
return null;
}
_logger.LogInformation("Auto-creating group '{GroupName}' from LDAP memberOf", name);
var created = await _groupService.CreateGroupAsync(name, groupType: "ldap", ct: ct)
.ConfigureAwait(false);
if (created is not null)
(_groupCache ??= new(StringComparer.OrdinalIgnoreCase))[name] = created;
return created;
}
///
/// Extracts the CN value from an LDAP distinguished name (RFC 4514).
/// Handles escaped commas, quotes, and other special characters.
/// "cn=Smith\, John,ou=groups,dc=test" → "Smith, John"
///
internal static string? ExtractCnFromDn(string dn)
{
if (string.IsNullOrWhiteSpace(dn)) return null;
if (!dn.StartsWith("cn=", StringComparison.OrdinalIgnoreCase))
return null;
var sb = new StringBuilder();
for (int i = 3; i < dn.Length; i++)
{
if (dn[i] == '\\' && i + 1 < dn.Length)
{
sb.Append(dn[++i]);
continue;
}
if (dn[i] == ',') break;
sb.Append(dn[i]);
}
return sb.Length > 0 ? sb.ToString() : null;
}
}
///
/// Configuration for LDAP → Identity group sync.
///
public sealed class LdapGroupMapperOptions
{
/// LDAP attribute containing group DNs. Default: "memberOf".
public string GroupMemberAttribute { get; set; } = "memberOf";
/// Role assigned to synced memberships. Default: "member".
public string MemberRole { get; set; } = "member";
/// Auto-create Identity groups not yet in the system. Default: true.
public bool AutoCreateGroups { get; set; } = true;
/// Sync strategy. Full = add missing + remove extra. Additive = add only.
public LdapGroupSyncStrategy SyncStrategy { get; set; } = LdapGroupSyncStrategy.Full;
}
/// Group membership sync strategy.
public enum LdapGroupSyncStrategy
{
/// Bidirectional: add missing memberships, remove those not in LDAP.
Full,
/// Only add memberships from LDAP, never remove existing ones.
Additive
}
Path: redb-identity/src/redb.Identity.Ldap/LdapHealthCheck.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/LdapHealthCheck.cs
----
using System.Diagnostics;
using System.Net.Sockets;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using redb.Identity.Core.Services;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Ldap;
using static redb.Route.Ldap.LdapDsl;
namespace redb.Identity.Ldap;
///
/// Health check that probes each registered LDAP provider via an anonymous RootDSE search.
/// Tests the full LDAP stack: TCP → TLS → LDAP protocol.
///
public sealed class LdapHealthCheck : IHealthCheck
{
private readonly LdapExternalUserProvider[] _ldapProviders;
private readonly ILogger _logger;
public LdapHealthCheck(
IEnumerable providers,
ILogger logger)
{
_ldapProviders = (providers ?? [])
.OfType()
.ToArray();
_logger = logger;
}
public async Task CheckHealthAsync(
HealthCheckContext context, CancellationToken ct = default)
{
if (_ldapProviders.Length == 0)
return HealthCheckResult.Healthy("No LDAP providers registered.");
var data = new Dictionary();
var allHealthy = true;
foreach (var provider in _ldapProviders)
{
var key = $"ldap:{provider.ProviderName}";
var options = provider.Options;
try
{
var sw = Stopwatch.StartNew();
// Pre-flight DNS+TCP probe — bounds the unreachable-host case to
// ConnectTimeoutSeconds instead of OS-level TCP retransmit (~21 s).
await LdapConnectivityProbe.ProbeAsync(
options.Server, options.EffectivePort,
options.ConnectTimeoutSeconds, ct).ConfigureAwait(false);
var builder = Search("")
.Server(options.Server)
.Port(options.EffectivePort)
.Scope(LdapSearchScope.Base)
.Filter("(objectClass=*)")
.SizeLimit(1);
if (options.UseSsl) builder.Ssl();
if (options.UseStartTls) builder.StartTls();
if (options.SkipCertificateValidation) builder.TrustAllCertificates();
if (options.OperationTimeoutSeconds > 0)
builder.OperationTimeout(options.OperationTimeoutSeconds * 1000);
var component = new LdapComponent();
var endpoint = component.CreateEndpoint(EndpointUriParser.Parse(builder.Build()));
var producer = endpoint.CreateProducer();
try
{
await producer.Start(ct).ConfigureAwait(false);
var exchange = new Exchange(new Message());
await producer.Process(exchange, ct).ConfigureAwait(false);
sw.Stop();
data[key] = $"OK ({sw.ElapsedMilliseconds}ms) {options.Server}:{options.EffectivePort}";
_logger.LogDebug("LDAP health OK: {Provider} {Server}:{Port} in {Ms}ms",
provider.ProviderName, options.Server, options.EffectivePort, sw.ElapsedMilliseconds);
}
finally
{
await producer.Stop(ct).ConfigureAwait(false);
(endpoint as IDisposable)?.Dispose();
}
}
catch (OperationCanceledException)
{
allHealthy = false;
data[key] = $"Timeout {options.Server}:{options.EffectivePort}";
}
catch (TimeoutException ex)
{
allHealthy = false;
data[key] = $"Connect timeout: {options.Server}:{options.EffectivePort} ({ex.Message})";
_logger.LogWarning("LDAP health check connect-timeout for {Provider}: {Error}",
provider.ProviderName, ex.Message);
}
catch (SocketException ex)
{
allHealthy = false;
data[key] = $"Connection failed: {options.Server}:{options.EffectivePort} ({ex.Message})";
_logger.LogWarning("LDAP health check failed for {Provider}: {Error}",
provider.ProviderName, ex.Message);
}
catch (Exception ex)
{
allHealthy = false;
data[key] = $"Error: {options.Server}:{options.EffectivePort} ({ex.Message})";
_logger.LogWarning(ex, "LDAP health check failed for {Provider}",
provider.ProviderName);
}
}
var status = allHealthy
? HealthCheckResult.Healthy("All LDAP servers reachable.", data)
: new HealthCheckResult(
context?.Registration.FailureStatus ?? HealthStatus.Degraded,
"One or more LDAP servers unreachable.",
data: data);
return status;
}
}
Path: redb-identity/src/redb.Identity.Ldap/LdapProviderOptions.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/LdapProviderOptions.cs
----
namespace redb.Identity.Ldap;
///
/// Configuration for LDAP external user provider.
///
public sealed class LdapProviderOptions : LdapConnectionSettings
{
/// Provider name reported to LoginService. Default: "ldap".
public string ProviderName { get; set; } = "ldap";
/// Priority in the external provider chain (lower = tried first). Default: 100.
public int Priority { get; set; } = 100;
// ── User search ──
/// Base DN for user search, e.g. "ou=users,dc=example,dc=com".
public string UserBaseDn { get; set; } = "";
///
/// LDAP search filter template. Use {0} for username substitution.
/// Default: "(uid={0})" for OpenLDAP. For AD use "(&(objectClass=user)(sAMAccountName={0}))".
///
public string UserFilter { get; set; } = "(uid={0})";
/// Search scope. Default: subtree.
public LdapSearchScopeOption SearchScope { get; set; } = LdapSearchScopeOption.Subtree;
// ── Attribute mapping ──
///
/// Map of identity fields to LDAP attribute names.
/// Keys: "externalId", "displayName", "email", "phone", "givenName", "familyName".
/// Unmapped fields are not populated.
///
public Dictionary AttributeMap { get; set; } = new(StringComparer.OrdinalIgnoreCase);
///
/// Extra LDAP attributes mapped to AdditionalClaims.
/// Key = claim name, Value = LDAP attribute name.
/// Example: { "department" = "departmentNumber", "title" = "title" }.
///
public Dictionary AdditionalClaimsMap { get; set; } = new(StringComparer.OrdinalIgnoreCase);
// ── Domain routing ──
///
/// Accepted domain hints (e.g. "corp.example.com", "CORP").
/// When non-empty, only usernames with a matching domain hint (user@domain or DOMAIN\user) are accepted.
/// Usernames without a domain hint are passed through as-is.
/// Empty array = accept all usernames (no domain filtering).
///
public string[] Domains { get; set; } = [];
/// Whether to check userAccountControl flags (AD only). Default: false.
public bool CheckAccountStatus { get; set; }
///
/// Apply a named preset (overwrites AttributeMap and UserFilter).
///
public void ApplyPreset(LdapPreset preset)
{
var (filter, map) = preset switch
{
LdapPreset.OpenLDAP => (
"(uid={0})",
new Dictionary(StringComparer.OrdinalIgnoreCase)
{
["externalId"] = "uid",
["displayName"] = "cn",
["email"] = "mail",
["phone"] = "telephoneNumber",
["givenName"] = "givenName",
["familyName"] = "sn"
}),
LdapPreset.ActiveDirectory => (
"(&(objectClass=user)(sAMAccountName={0}))",
new Dictionary(StringComparer.OrdinalIgnoreCase)
{
["externalId"] = "sAMAccountName",
["displayName"] = "displayName",
["email"] = "mail",
["phone"] = "telephoneNumber",
["givenName"] = "givenName",
["familyName"] = "sn"
}),
_ => throw new ArgumentOutOfRangeException(nameof(preset))
};
UserFilter = filter;
AttributeMap = map;
if (preset == LdapPreset.ActiveDirectory)
CheckAccountStatus = true;
}
///
/// Restores case-insensitive comparers on dictionaries after IConfiguration.Bind().
///
public void NormalizeAfterBind()
{
if (AttributeMap.Comparer != StringComparer.OrdinalIgnoreCase)
AttributeMap = new Dictionary(AttributeMap, StringComparer.OrdinalIgnoreCase);
if (AdditionalClaimsMap.Comparer != StringComparer.OrdinalIgnoreCase)
AdditionalClaimsMap = new Dictionary(AdditionalClaimsMap, StringComparer.OrdinalIgnoreCase);
}
///
/// Validates the options and throws on misconfiguration.
///
public void Validate()
{
ValidateConnection();
if (string.IsNullOrWhiteSpace(UserBaseDn))
throw new InvalidOperationException("LdapProviderOptions.UserBaseDn is required.");
if (string.IsNullOrWhiteSpace(UserFilter) || !UserFilter.Contains("{0}"))
throw new InvalidOperationException("LdapProviderOptions.UserFilter must contain '{0}' placeholder.");
}
}
/// Known LDAP directory presets.
public enum LdapPreset
{
/// OpenLDAP / 389DS defaults (uid, cn, mail, etc.).
OpenLDAP,
/// Active Directory defaults (sAMAccountName, displayName, mail, etc.).
ActiveDirectory
}
/// LDAP search scope.
public enum LdapSearchScopeOption
{
/// Search only the base DN entry.
Base,
/// Search one level below the base DN.
OneLevel,
/// Search the entire subtree below the base DN.
Subtree
}
Path: redb-identity/src/redb.Identity.Ldap/LdapSyncHandler.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/LdapSyncHandler.cs
----
using Microsoft.Extensions.Logging;
using redb.Core;
using redb.Core.Models.Contracts;
using redb.Core.Models.Entities;
using redb.Core.Models.Users;
using redb.Core.Query;
using redb.Identity.Core.Models;
using redb.Identity.Core.Services;
using redb.Route.Ldap;
namespace redb.Identity.Ldap;
///
/// Processes LDAP change events from the Watch consumer.
/// Creates/updates/disables users and optionally syncs group memberships.
/// Designed to be resolved from DI via Bean<LdapSyncHandler> in the route.
///
public sealed class LdapSyncHandler
{
private readonly IRedbService _redb;
private readonly LdapSyncOptions _options;
private readonly LdapAttributeMapper _mapper;
private readonly LdapGroupMapper? _groupMapper;
private readonly ILogger _logger;
private readonly TimeProvider _timeProvider;
public LdapSyncHandler(
IRedbService redb,
LdapSyncOptions options,
ILogger logger,
LdapGroupMapper? groupMapper = null,
TimeProvider? timeProvider = null)
{
_redb = redb ?? throw new ArgumentNullException(nameof(redb));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_groupMapper = groupMapper;
_timeProvider = timeProvider ?? TimeProvider.System;
var mapperOptions = new LdapProviderOptions
{
UserBaseDn = "dc=sync", // placeholder — mapper only uses AttributeMap
AttributeMap = options.AttributeMap,
AdditionalClaimsMap = options.AdditionalClaimsMap
};
_mapper = new LdapAttributeMapper(mapperOptions);
}
///
/// Process a single LDAP change entry.
///
public async Task ProcessEntryAsync(LdapEntry entry, CancellationToken ct = default)
{
if (entry is null) return;
var changeType = entry.ChangeType ?? "modified";
_logger.LogDebug("Processing LDAP sync event: {ChangeType} {Dn}", changeType, entry.Dn);
switch (changeType)
{
case "added":
case "modified":
await UpsertUserAsync(entry, ct).ConfigureAwait(false);
break;
case "deleted":
await HandleDeletionAsync(entry, ct).ConfigureAwait(false);
break;
default:
_logger.LogWarning("Unknown LDAP change type: {ChangeType} for DN={Dn}", changeType, entry.Dn);
break;
}
}
private async Task UpsertUserAsync(LdapEntry entry, CancellationToken ct)
{
var authResult = _mapper.MapToResult(entry);
var externalId = authResult.ExternalId ?? entry.Dn;
// Find existing user by external ID stored in UserProps
var existingProps = await _redb.Query()
.WhereRedb(o => o.ValueString == $"{_options.ProviderName}:{externalId}")
.FirstOrDefaultAsync()
.ConfigureAwait(false);
IRedbUser coreUser;
if (existingProps is not null)
{
// Update existing user
var userId = existingProps.key
?? throw new InvalidOperationException("Sync props has null key.");
coreUser = await _redb.UserProvider.GetUserByIdAsync(userId)
.ConfigureAwait(false)
?? throw new InvalidOperationException(
$"User id={userId} referenced by sync props but not found in _users.");
var updateReq = new UpdateUserRequest();
var needsUpdate = false;
if (authResult.DisplayName is not null && authResult.DisplayName != coreUser.Name)
{ updateReq.Name = authResult.DisplayName; needsUpdate = true; }
if (authResult.Email is not null && authResult.Email != coreUser.Email)
{ updateReq.Email = authResult.Email; needsUpdate = true; }
if (authResult.Phone is not null && authResult.Phone != coreUser.Phone)
{ updateReq.Phone = authResult.Phone; needsUpdate = true; }
if (needsUpdate)
await _redb.UserProvider.UpdateUserAsync(coreUser, updateReq).ConfigureAwait(false);
_logger.LogDebug("Synced existing user '{ExternalId}' (id={UserId})", externalId, coreUser.Id);
}
else
{
// Create new user
var login = externalId;
coreUser = await _redb.UserProvider.CreateUserAsync(new CreateUserRequest
{
Login = login,
Password = Guid.NewGuid().ToString("N") + "Aa1!",
Name = authResult.DisplayName ?? login,
Email = authResult.Email,
Phone = authResult.Phone,
Enabled = true,
CodeString = _options.ProviderName
}).ConfigureAwait(false);
_logger.LogInformation("Created user '{ExternalId}' (id={UserId}) from LDAP sync",
externalId, coreUser.Id);
}
// Upsert UserProps with sync marker
// S12: skip fallback query for newly created users (existingProps is null + user just created)
RedbObject? oidcObj;
if (existingProps is not null)
{
oidcObj = existingProps;
}
else if (existingProps is null && coreUser is not null)
{
// New user: create props directly, skip query for just-created user
oidcObj = new RedbObject(new UserProps { UserId = coreUser.Id }); // V4-UNIQUE
oidcObj.name = externalId;
oidcObj.key = coreUser.Id;
oidcObj.value_guid = Guid.NewGuid();
}
else
{
oidcObj = new RedbObject(new UserProps { UserId = coreUser!.Id }); // V4-UNIQUE
oidcObj.name = externalId;
oidcObj.key = coreUser!.Id;
oidcObj.value_guid = Guid.NewGuid();
}
oidcObj.Props.ExternalIdentities ??= new Dictionary();
oidcObj.Props.ExternalIdentities[_options.ProviderName] = new ExternalIdentity
{
Sub = externalId,
LinkedAt = _timeProvider.GetUtcNow()
};
oidcObj.value_string = $"{_options.ProviderName}:{externalId}"; // sync lookup key
oidcObj.note = entry.Dn; // store DN for deletion lookup
if (authResult.GivenName is not null) oidcObj.Props.GivenName = authResult.GivenName;
if (authResult.FamilyName is not null) oidcObj.Props.FamilyName = authResult.FamilyName;
if (authResult.AdditionalClaims is { Count: > 0 })
{
oidcObj.Props.CustomClaims ??= new Dictionary();
foreach (var (key, value) in authResult.AdditionalClaims)
oidcObj.Props.CustomClaims[key] = value;
}
await _redb.SaveAsync(oidcObj).ConfigureAwait(false);
// Group sync
if (_options.SyncGroups && _groupMapper is not null)
{
await _groupMapper.SyncUserGroupsAsync(coreUser.Id, entry, ct).ConfigureAwait(false);
}
}
private async Task HandleDeletionAsync(LdapEntry entry, CancellationToken ct)
{
if (!_options.DisableDeletedUsers) return;
// Try to extract externalId from entry attributes (if available)
var authResult = entry.Attributes?.Count > 0 ? _mapper.MapToResult(entry) : null;
var externalId = authResult?.ExternalId;
RedbObject? props = null;
// Primary: search by externalId (entry with attributes)
if (externalId is not null)
{
props = await _redb.Query()
.WhereRedb(o => o.ValueString == $"{_options.ProviderName}:{externalId}")
.FirstOrDefaultAsync()
.ConfigureAwait(false);
}
// Fallback: search by DN stored in note (deletion event — only DN available)
if (props is null)
{
props = await _redb.Query()
.WhereRedb(o => o.Note == entry.Dn
&& o.ValueString!.StartsWith($"{_options.ProviderName}:"))
.FirstOrDefaultAsync()
.ConfigureAwait(false);
}
if (props?.key is not { } deletedUserId)
{
_logger.LogWarning("No local user found for deleted LDAP entry: {Dn}", entry.Dn);
return;
}
var user = await _redb.UserProvider.GetUserByIdAsync(deletedUserId).ConfigureAwait(false);
if (user is null || !user.Enabled) return;
await _redb.UserProvider.UpdateUserAsync(user, new UpdateUserRequest { Enabled = false })
.ConfigureAwait(false);
_logger.LogInformation("Disabled user '{Login}' (id={UserId}) — deleted from LDAP",
user.Login, user.Id);
}
}
Path: redb-identity/src/redb.Identity.Ldap/LdapSyncOptions.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/LdapSyncOptions.cs
----
namespace redb.Identity.Ldap;
///
/// Configuration for the LDAP directory sync route (Watch consumer).
/// Extends connection settings with sync-specific options.
///
public sealed class LdapSyncOptions : LdapConnectionSettings
{
/// Route identifier. Default: "ldap-sync".
public string RouteId { get; set; } = "ldap-sync";
// ── Search ──
/// Base DN for user search.
public string UserBaseDn { get; set; } = "";
/// LDAP filter for user entries. Default: "(objectClass=inetOrgPerson)".
public string UserFilter { get; set; } = "(objectClass=inetOrgPerson)";
/// LDAP attributes to request.
public string[] Attributes { get; set; } = [];
// ── Change tracking ──
/// Poll interval in milliseconds. Default: 60000 (1 min).
public int PollIntervalMs { get; set; } = 60_000;
/// Change tracking mode. Default: ModifyTimestamp.
public string ChangeTrackingMode { get; set; } = "ModifyTimestamp";
/// Load all entries on first poll. Default: true.
public bool InitialLoad { get; set; } = true;
/// Detect deleted entries. Default: true.
public bool DetectDeletions { get; set; } = true;
/// Full sync interval in poll cycles (for deletion detection). Default: 10.
public int FullSyncInterval { get; set; } = 10;
// ── Identity integration ──
/// Provider name stored in user's ExternalProvider field. Default: "ldap-sync".
public string ProviderName { get; set; } = "ldap-sync";
///
/// Attribute map for converting LDAP entries to user profiles.
/// Keys: "externalId", "displayName", "email", "phone", "givenName", "familyName".
///
public Dictionary AttributeMap { get; set; } = new(StringComparer.OrdinalIgnoreCase);
/// Extra LDAP attributes mapped to custom claims.
public Dictionary AdditionalClaimsMap { get; set; } = new(StringComparer.OrdinalIgnoreCase);
/// Enable group sync from memberOf attribute. Default: false.
public bool SyncGroups { get; set; }
/// Group mapper options (used when SyncGroups = true).
public LdapGroupMapperOptions GroupMapperOptions { get; set; } = new();
/// Whether to disable users when they are deleted from LDAP. Default: true.
public bool DisableDeletedUsers { get; set; } = true;
private static readonly HashSet ValidTrackingModes = new(StringComparer.OrdinalIgnoreCase)
{
"ModifyTimestamp", "Usn", "Persistent"
};
public void Validate()
{
ValidateConnection();
if (string.IsNullOrWhiteSpace(UserBaseDn))
throw new InvalidOperationException("LdapSyncOptions.UserBaseDn is required.");
if (PollIntervalMs <= 0)
throw new InvalidOperationException(
$"LdapSyncOptions.PollIntervalMs must be positive, got: {PollIntervalMs}.");
if (!ValidTrackingModes.Contains(ChangeTrackingMode))
throw new InvalidOperationException(
$"LdapSyncOptions.ChangeTrackingMode '{ChangeTrackingMode}' is not valid. Use: {string.Join(", ", ValidTrackingModes)}.");
}
}
Path: redb-identity/src/redb.Identity.Ldap/LdapSyncRouteBuilder.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/LdapSyncRouteBuilder.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Core;
using redb.Route.Ldap;
using static redb.Route.Ldap.LdapDsl;
namespace redb.Identity.Ldap;
///
/// Route definition that watches an LDAP directory for changes and syncs
/// user profiles (and optionally group memberships) to the Identity system.
///
public sealed class LdapSyncRouteBuilder : RouteBuilder
{
private readonly LdapSyncOptions _options;
private readonly ILogger? _logger;
public LdapSyncRouteBuilder(LdapSyncOptions options, ILogger? logger = null)
{
_options = options ?? throw new ArgumentNullException(nameof(options));
_options.Validate();
_logger = logger;
}
protected override void Configure()
{
From(BuildWatchUri())
.RouteId(_options.RouteId)
.Log($"LDAP sync: ${{header.{LdapHeaders.ChangeType}}} ${{header.{LdapHeaders.Dn}}}")
.Bean(async (handler, exchange, ct) =>
{
if (exchange.In.Body is LdapEntry entry)
{
try
{
await handler.ProcessEntryAsync(entry, ct);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger?.LogError(ex, "Failed to process LDAP entry: {Dn}", entry.Dn);
}
}
else
{
_logger?.LogDebug("Unexpected body type in sync route: {Type}",
exchange.In.Body?.GetType());
}
});
}
private string BuildWatchUri()
{
var builder = Watch(_options.UserBaseDn)
.Server(_options.Server)
.Port(_options.Port)
.Filter(_options.UserFilter)
.PollInterval(_options.PollIntervalMs)
.ChangeTracking(ParseChangeTrackingMode());
if (_options.InitialLoad)
builder.InitialLoad();
if (_options.DetectDeletions)
builder.DetectDeletions();
if (_options.FullSyncInterval > 0)
builder.FullSyncInterval(_options.FullSyncInterval);
// Connection settings
if (!string.IsNullOrWhiteSpace(_options.BindDn))
builder.BindDn(_options.BindDn);
if (!string.IsNullOrWhiteSpace(_options.BindPassword))
builder.BindPassword(_options.BindPassword);
if (_options.UseSsl)
builder.Ssl();
if (_options.UseStartTls)
builder.StartTls();
if (_options.SkipCertificateValidation)
builder.TrustAllCertificates();
if (_options.Attributes.Length > 0)
builder.Attributes(_options.Attributes);
return builder.Build();
}
private LdapChangeTrackingMode ParseChangeTrackingMode() =>
_options.ChangeTrackingMode?.ToLowerInvariant() switch
{
"modifytimestamp" => LdapChangeTrackingMode.ModifyTimestamp,
"usn" => LdapChangeTrackingMode.Usn,
"persistent" => LdapChangeTrackingMode.Persistent,
_ => throw new InvalidOperationException(
$"Unknown ChangeTrackingMode: '{_options.ChangeTrackingMode}'.")
};
}
Path: redb-identity/src/redb.Identity.Ldap/PACKAGING.md
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/PACKAGING.md
----
# redb.Identity.Ldap — packaging notes
Status (2026-04-30): the LDAP integration is **shipped today as part of
`redb.Identity.Core.Module.tpkg`**. It is opt-in via configuration:
```jsonc
// redb.Identity.Core.Module.config.json (or any of the 5 layers above it)
"Identity": {
"Ldap": {
"Enabled": false, // master switch (default: false)
"Providers": [
{
"ProviderName": "ldap",
"Server": "ldap.example.com",
"Port": 389,
"BindDn": "cn=svc,dc=example,dc=com",
"BindPassword": null, // supply via Override layer / env / secret
"UserBaseDn": "ou=users,dc=example,dc=com",
"UserFilter": "(uid={0})",
"Domains": [ "example.com" ],
"AttributeMap": {
"externalId": "uid",
"displayName": "cn",
"email": "mail"
}
}
],
"Sync": {
"Enabled": false // see "Sync route — known limitation" below
}
}
}
```
When `Identity.Ldap.Enabled = true`, `IdentityModuleHost` registers
`LdapExternalUserProvider` instances inside the **Identity child SP** so the
existing `LoginService` picks them up without any additional wiring.
`redb.Identity.Ldap.dll` (~150 KB plus its `redb.Route.Ldap` transitive) is
included unconditionally inside `redb.Identity.Core.Module.tpkg` even when the
feature is disabled. This is a deliberate trade-off — see "Why not a separate
.tpkg" below.
---
## Sync route — known limitation
`LdapSyncRouteBuilder` (the `Watch(...)` consumer that streams directory entries
into the local user store) is **not** activated by the in-Core integration. It
needs to be registered as an `IRouteBuilder` against the route context's
builder pipeline, which happens *outside* the Identity child SP. Until a
`AddRouteBuilder` extension point is exposed on
`IRouteContext`, sync remains a feature you wire up by hand in a custom host.
Two reasonable paths to lift the limitation, both small:
1. Expose `IdentityCoreRouteBuilder.AppendBuilder(IRouteBuilder)` and call it
from `InitRoute` when `Identity:Ldap:Sync:Enabled = true`. Cheapest.
2. Add a `LdapSyncInitListener : IRouteLifecycleListener` to the Identity child
SP that builds the sync route and hands it to `IRouteContext.RegisterRoute`
on startup. Cleanest separation, but requires confirming that route
registration on a started context is supported by Tsak.
---
## Why not a separate `redb.Identity.Ldap.Module.tpkg`?
It is technically possible — it would mirror the shape of
`redb.Identity.Core.Module` — but the integration cost is **not** in the .tpkg
plumbing; it is in the cross-module DI bridge.
`LdapExternalUserProvider` implements `IExternalUserProvider`, an SPI that the
Core's `LoginService` consumes by enumerating `IEnumerable`
**from the Core child SP**. If LDAP lives in its own child SP, Core cannot see
it. The two ways to bridge the gap:
### Option A1 — child-SP extension point
Have `redb.Identity.Core.Module` expose a registration callback (something like
`IdentityCoreOptionsExtensionPoint.AddSink(Action)`) that
external `.tpkg` modules can publish to before the Identity child SP is built.
The LDAP module would register its callback during its own init so that, when
Identity.Core.Module later builds its child SP, it finds the callback in the
host root SP and applies it.
- Pros: native DI, zero runtime overhead, Core code unchanged after the hook
exists.
- Cons: introduces a load-order coupling between `.tpkg`s (LDAP must initialise
before Identity.Core's `InitRoute` runs); breaks the "modules are
independent" mental model.
### Option A2 — message bus mediation
Convert `IExternalUserProvider` from a synchronous SPI into a request/response
contract over `direct-vm://identity-external-providers`. Core publishes a
"resolve user" envelope, every external provider module subscribes, the first
non-null response wins (or a configured priority order). LDAP module owns the
consumer side end-to-end.
- Pros: zero DI coupling between modules; LDAP can be deployed, replaced, or
removed without touching Identity; clean cluster story (provider can run on
a dedicated worker).
- Cons: round-trip latency on every login; requires correlation IDs, timeouts,
and a fallback policy when no provider responds; existing
`IExternalUserProvider` test surface needs reshaping.
### Verdict
Either option is a real refactor — not a packaging exercise — and is justified
only when at least one of the following becomes true:
1. LDAP needs its own deploy/upgrade cadence independent of Core.
2. Multiple Identity instances share a single LDAP backend deployed once.
3. A second external provider (e.g. SCIM-pull, custom HR system) appears, and
the sync layer between Identity and providers becomes a real component.
Until then the shipped Variant B (LDAP wired into Core.Module by flag) is the
right level of investment.
---
## File-level checklist for promoting to a standalone `.tpkg` (later)
1. Create `redb.Identity.Ldap.Module/redb.Identity.Ldap.Module.csproj` mirroring
`redb.Identity.Core.Module`. Reference both `redb.Identity.Ldap` and
`redb.Identity.Core` (for `RedbIdentityOptions` if needed).
2. Add `LdapModuleHost.Build(IRouteContext, LdapModuleOptions)` that builds a
child SP with `LdapExternalUserProvider[]`, `LdapSyncHandler`, and
`LdapHealthCheck`.
3. Add `InitRoute` (`AutoStart = true`) that calls `LdapModuleHost.Build` and
registers a `ChildHostDisposeListener`.
4. Add `redb.Identity.Ldap.Module.config.json` with the `Identity.Ldap.*`
schema documented above.
5. Pick A1 or A2 from above for the DI / SPI bridge to Identity.Core.
6. Update `pack-tpkg.ps1` to emit a third `.tpkg` and copy it to
`redb.Tsak.Worker/Libs/`.
7. Remove the `Identity:Ldap` block from
`redb.Identity.Core.Module.config.json` and the `ProjectReference` from
`redb.Identity.Core.Module.csproj` to drop the ~150 KB unconditional
payload.
The path is open; nothing in the current Variant B implementation forecloses
it. The only thing that would have to change in Core when migrating is the
removal of the LDAP-specific code path inside `IdentityModuleHost.Build`,
which is fenced behind `if (options.Ldap.Enabled)` and easy to lift.
Path: redb-identity/src/redb.Identity.Ldap/UserAccountControlFlags.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/UserAccountControlFlags.cs
----
namespace redb.Identity.Ldap;
///
/// Active Directory userAccountControl bitmask flags.
/// See https://learn.microsoft.com/en-us/troubleshoot/windows-server/active-directory/useraccountcontrol-manipulate
///
[Flags]
public enum UserAccountControlFlags
{
None = 0,
AccountDisable = 0x0002,
Lockout = 0x0010,
NormalAccount = 0x0200,
PasswordExpired = 0x800000,
}
Path: redb-identity/src/redb.Identity.Ldap/redb.Identity.Ldap.csproj
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Ldap/redb.Identity.Ldap.csproj
----
redb.Identity.Ldap
redb.Identity.Ldap
LDAP / Active Directory federation provider for redb.Identity — directory sync + bind-on-login.