Bundle: redb-identity / src/redb.Identity.Core.Module (src.redb.Identity.Core.Module.txt), 7 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.Core.Module/InitRoute.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.Core.Module/InitRoute.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using redb.Identity.Core; using redb.Identity.Core.Configuration; using redb.Identity.Core.Module; using redb.Identity.Contracts.Routes; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Redis; using redb.Identity.Core.Routes; using OpenIddict.Validation; // ─── Tsak module discovery contract ────────────────────────────────────────── // // Tsak determines the moduleName from the namespace of the discovered InitRoute // class (TsakModuleRegistry.DiscoverModulesInAssembly). This namespace MUST stay // in sync with: // • The .tpkg manifest.Name → "redb.Identity.Core.Module" // • The shipped {moduleName}.config.json filename → "redb.Identity.Core.Module.config.json" // • The Dependencies declared by every facade .tpkg (Http, gRPC, MQTT, …) so // Tsak loads this package first and the companion DLLs (Identity.Core, // Identity.Contracts, OpenIddict, Argon2, Fido2, …) are present in the // LoadedAssemblyTracker before any facade ALC tries to resolve them. // // ─── Why this assembly is *thin* ───────────────────────────────────────────── // // Tsak loads `manifest.EntryPoints` into a per-package isolated ALC and does // NOT register them in `LoadedAssemblyTracker` (entry points are deliberately // hidden from sibling .tpkg packages). Companion DLLs in the .tpkg ARE tracked // and shared by Assembly identity across every ALC that resolves them. // // If we shipped redb.Identity.Core.dll itself as the entry point (as the // original prototype did), no other .tpkg facade could resolve its types ─ // HttpFacadeRouteBuilder's ctor would throw FileNotFoundException for // redb.Identity.Core. Splitting the entry point into this tiny shim makes // Identity.Core.dll, Identity.Contracts.dll and every transitive NuGet dep // COMPANION DLLs that other .tpkg packages can rely on. namespace redb.Identity.Core.Module; /// /// Tsak module entry point for redb.Identity.Core.Module. /// Wires the lifecycle listeners that bootstrap the Identity DI/redb schema/key /// ring and registers 's direct-vm:// routes. /// Discovered by convention: public class InitRoute with /// static main(IRouteContext). /// /// /// One boot path, the same in a Tsak worker and in a host of its own /// (): reads "Identity" /// from the context's configuration properties and builds a child /// that owns all Identity services, disposed with the context through /// . Options registered in the host's own container are not /// read; the configuration sections are the only input. /// public static class InitRoute { public static IRouteContext main(IRouteContext context) { var hostSp = context.GetServiceProvider() ?? throw new InvalidOperationException( "IServiceProvider not available on IRouteContext. " + "Ensure the Identity Core module is loaded after DI is configured."); // Options the host registered itself (AddRedbIdentityServer on its own container) would be // silently ignored here, and the module would start on the defaults of the "Identity" section. // AddRedbIdentityServer registers the object through Options.Create (an OptionsWrapper). Any host // that ran AddOptions also answers IOptions for every T through the options manager, which is // not a registration of Identity's settings, so only the wrapper counts. if (hostSp.GetService>() is OptionsWrapper) throw new InvalidOperationException( "redb.Identity: the host container registers RedbIdentityOptions (AddRedbIdentityServer). " + "The module does not read them; it takes its settings from the 'Identity' configuration " + "section. Remove the registration and put the settings in that section " + "(see RedbIdentityHost.StartAsync)."); // Identity:Audit (targets the events are multicast to) from the same configuration. IOptions audit = Options.Create(IdentityModuleConfigBinder.BindAudit(context)); var bound = IdentityModuleConfigBinder.Bind(context); var ldap = LdapIntegrationConfigBinder.Bind(context); var childSp = IdentityModuleHost.Build(context, bound, services => { if (ldap is { Enabled: true, Providers.Count: > 0 }) { foreach (var provider in ldap.Providers) redb.Identity.Ldap.LdapServiceExtensions.AddRedbIdentityLdap(services, provider); } }); // Ensure the child container outlives the routes but dies with the context. context.AddLifecycleListener(new ChildHostDisposeListener(childSp)); IServiceProvider identitySp = childSp; var options = childSp.GetRequiredService>(); // Publish the Identity container's IServiceScopeFactory so route processors can resolve // its services (IOpenIddictApplicationManager, IBackgroundDeletionService, …) against // per-exchange scopes via IRouteContext.GetIdentityService(exchange). context.RegisterIdentityScopeFactory( name: null, identitySp.GetRequiredService()); // Initialize redb base schema BEFORE any route starts processing exchanges. // Per-Props schemas register lazily on first Query/Save. context.AddLifecycleListener(new IdentitySchemaInitListener(identitySp)); // After the base schema is live, create per-scheme partial unique indexes that // close TOCTOU races in check-then-save paths (ClientId, Scope.Name, MFA user, // idempotency keys, OIDC-extension user). Registered AFTER the schema listener // so it can look up scheme ids against an already-bootstrapped database. context.AddLifecycleListener(new IdentityUniqueIndexesInitListener(identitySp)); // V4-UNIQUE transition backfill: copy the value_string mirrors of pre-V4 // rows into Props so [RedbUnique] keys exist for them and GetByUniqueAsync sees legacy // data. Idempotent, with a convergence flag. MUST run before the seed listeners - they // look up by unique key and would otherwise recreate legacy-seeded rows. context.AddLifecycleListener(new V4UniqueBackfillListener(identitySp)); // Group names are unique (GroupNames.Key in ValueUnique). Groups created before that have // no key; this gives them one at every start and logs the ones whose name is taken. context.AddLifecycleListener(new GroupNameKeyListener(identitySp)); // R1: audit log relational table — flat schema for the // `identity_audit_log` table that backs /api/v1/identity/audit and // the user-detail Audit tab. Idempotent CREATE IF NOT EXISTS per // dialect (Postgres / MSSQL / SQLite) shipped as embedded DDL. context.AddLifecycleListener(new IdentityAuditLogTableInitListener(identitySp)); // The delivery outbox (identity_delivery_outbox): webhook deliveries are enqueued there by // the events route and sent by the delivery worker. context.AddLifecycleListener(new IdentityDeliveryOutboxInitListener(identitySp)); // B.3: seed the canonical built-in roles (system / everyone / admin / // impersonator) so /admin/roles isn't empty on a fresh install. // Idempotent — skips existing rows by name+audience. context.AddLifecycleListener(new SeedSystemRolesListener(identitySp)); // B.3: seed the IdentityScopes catalogue so the role-permissions // picker can find / attach built-in admin scopes // (identity:users.manage, identity:applications.manage, …). Idempotent. context.AddLifecycleListener(new SeedSystemScopesListener(identitySp)); // B.3 backfill: mirror bootstrap admin-group members into the admin // role for installs created BEFORE the system-roles registry landed. // Idempotent. Runs after SeedSystemRolesListener so it sees the role. context.AddLifecycleListener(new BootstrapAdminBackfillListener(identitySp)); // B.3 SQL-seed bridge: assign the canonical SeedAdmin user to the // admin system role directly. Without this, installs that never // call /internal/bootstrap-admin leave the admin role empty. context.AddLifecycleListener(new SeedAdminRoleAssignmentListener(identitySp, identitySp.GetRequiredService>())); // Administrative scopes reach a user only through a role that carries them // (RestrictAdminScopesByRoleHandler). Installs that predate that gate have an admin role // with no scopes attached, which would refuse the only administrator. Attach the management // scope when - and only when - the role carries none. Runs after the role and scope // seeders so both sides exist. Idempotent. context.AddLifecycleListener(new SeedAdminRoleScopesListener(identitySp, identitySp.GetRequiredService>())); // Seed the DataProtection key-ring snapshot BEFORE the HTTP facade serves the // first request — prevents Protect/Unprotect from racing against an empty // in-memory ring. context.AddLifecycleListener(new RedbXmlRepositoryInitListener(identitySp)); // A3: seed the PROPS signing / encryption key store AFTER the DataProtection key // ring has been loaded (PROPS rows store DataProtection-encrypted PEMs). No-op // when RedbIdentityOptions.UsePropsSigningKeyStore=false. context.AddLifecycleListener(new SigningKeyInitListener(identitySp)); // Default-credential seeders. Both run on every cold-start AND every hot-reload // (Tsak invokes OnContextStarting for the listeners on each module init), are // fully idempotent, and never fail host startup. Order matters: schema must be // live before either runs (admin password write → _users; OIDC client write → // OpenIddict PROPS tables), so they are appended LAST in the listener chain. context.AddLifecycleListener( identitySp.GetRequiredService()); context.AddLifecycleListener( identitySp.GetRequiredService()); context.AddLifecycleListener( identitySp.GetRequiredService()); // C1: When the Redis-backed rate-limit store is enabled, register the redis // component once (idempotent — overwrites by scheme key) so other parts of the // route system can also resolve redis: URIs against the same broker. if (options.Value.RateLimit.Enabled && string.Equals(options.Value.RateLimit.Backend, "redis", StringComparison.OrdinalIgnoreCase)) { context.AddComponent(new RedisComponent()); } // W1: outbound HTTP transport for webhook delivery. Producer-only — // no ServerManager (this Core context never hosts an HTTP server; the // Http facade module owns that). Without this registration, // ProducerTemplate.SendAsync to https://... URIs fails with // 'No component registered for scheme http'. if (!context.HasComponent("http")) context.AddComponent(new redb.Route.Http.HttpComponent()); if (!context.HasComponent("https")) context.AddComponent(new redb.Route.Http.HttpComponent("https")); // Phase 9b (clean rewire): construct the management/SCIM bearer-auth // processors inside Core's child SP and pass them to the route builder, which // exposes them as `direct-vm://identity-auth-{management,scim}` consumers. // The HTTP facade module then calls them inline via `.To(...)` — no static // cross-module state, no per-context registry handoff. The processors depend // on scoped OpenIddict validation services and resolve them in a scope per request. var bridgeLogger = (identitySp.GetService() ?? hostSp.GetService()) ?.CreateLogger("redb.Identity.Core.InitRoute"); IProcessor? managementAuth = null; IProcessor? scimAuth = null; try { // Each validated request gets a scope of its own (ManagementBearerAuthProcessor), so the scoped // OpenIddict stores read the token as it is stored now. var validationScopes = identitySp.GetRequiredService(); var opts = options.Value; managementAuth = new redb.Identity.Core.Routes.Processors.ManagementBearerAuthProcessor( validationScopes, // N7-1 — accept all granular admin scopes here. The per-path // GranularScopeGuardProcessor (HTTP facade) then enforces which // route a given granular scope may reach. Manage remains the // master scope and AccountScope still routes to self-service. BuildAcceptableManagementScopes(opts), // N-4 (Session C): password-recovery flows are genuinely anonymous and // share the /api/v1/identity/ root for URL stability. The auth processor // short-circuits without reading the Authorization header for these paths. // RFC 7644 §4: SCIM discovery endpoints (ServiceProviderConfig, ResourceTypes, // Schemas) must be unauthenticated; they are accessible under /api/v1/identity/scim/v2/*. anonymousPathPrefixes: new[] { "/api/v1/identity/password/", "/api/v1/identity/account/", "/api/v1/identity/federation-providers/public", "/api/v1/identity/scim/v2/ServiceProviderConfig", "/api/v1/identity/scim/v2/ResourceTypes", "/api/v1/identity/scim/v2/Schemas" }); bridgeLogger?.LogInformation( "[Identity.Core.InitRoute] Built ManagementAuth processor (scopes=[{Mgmt},{Account},+{Granular} granular])", opts.ManagementScope, opts.AccountScope, redb.Identity.Contracts.Configuration.IdentityScopes.GranularAdmin.Length); if (opts.Features.EnableScim) { scimAuth = new redb.Identity.Core.Routes.Processors.ManagementBearerAuthProcessor( validationScopes, opts.ScimScope); bridgeLogger?.LogInformation( "[Identity.Core.InitRoute] Built ScimAuth processor (scope={Scope})", opts.ScimScope); } } catch (Exception ex) { bridgeLogger?.LogError(ex, "[Identity.Core.InitRoute] Failed to build management/SCIM auth processors"); } var builder = new IdentityCoreRouteBuilder(identitySp, options, audit, managementAuth, scimAuth); ((RouteContext)context).AddRoutes(builder); return context; } /// /// N7-1 — assembles the set of OAuth scopes acceptable at the management-API gate: /// full-admin master (opts.ManagementScope), self-service /// (opts.AccountScope) and every granular admin scope registered via /// . /// The per-path GranularScopeGuardProcessor downstream is what actually /// decides whether a granular-only token may reach a given controller. /// private static string[] BuildAcceptableManagementScopes( redb.Identity.Core.Configuration.RedbIdentityOptions opts) { var granular = redb.Identity.Contracts.Configuration.IdentityScopes.GranularAdmin; var result = new string[2 + granular.Length]; result[0] = opts.ManagementScope; result[1] = opts.AccountScope; Array.Copy(granular, 0, result, 2, granular.Length); return result; } } Path: redb-identity/src/redb.Identity.Core.Module/LdapIntegrationConfigBinder.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.Core.Module/LdapIntegrationConfigBinder.cs ---- using System.Collections.Generic; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; using redb.Identity.Ldap; using redb.Route.Abstractions; namespace redb.Identity.Core.Module; /// /// Variant B LDAP integration: reads the optional Identity:Ldap sub-section /// from the Tsak-merged context configuration and produces a strongly typed /// snapshot consumed by . /// /// /// Lives in redb.Identity.Core.Module (not in redb.Identity.Core) so the /// LDAP types remain optional from Core's perspective: only this packaging shim takes /// the dependency on redb.Identity.Ldap. /// internal static class LdapIntegrationConfigBinder { private const string IdentitySection = IdentityModuleConfigBinder.SectionName; private const string LdapKey = "Ldap"; /// /// Returns null when no Identity:Ldap section is present, otherwise a /// hydrated . The caller decides whether to act on /// . /// public static LdapIntegrationConfig? Bind(IRouteContext context) { ArgumentNullException.ThrowIfNull(context); var identity = context.GetProperty>(IdentitySection); if (identity is null || !identity.TryGetValue(LdapKey, out var ldapRaw) || ldapRaw is not IDictionary ldapDict || ldapDict.Count == 0) { return null; } var flat = new Dictionary(StringComparer.OrdinalIgnoreCase); Flatten(ldapDict, prefix: string.Empty, sink: flat); var cfg = new ConfigurationBuilder() .Add(new MemoryConfigurationSource { InitialData = flat }) .Build(); var result = new LdapIntegrationConfig(); cfg.Bind(result, opt => opt.BindNonPublicProperties = false); // IConfiguration.Bind merges list elements by index; for "Providers" we want a // full replacement so an operator can shrink the list between deploys. var providersSection = cfg.GetSection("Providers"); if (providersSection.Exists()) { var providers = providersSection.Get>(); result.Providers = providers ?? new List(); } foreach (var p in result.Providers) p.NormalizeAfterBind(); return result; } private static void Flatten(IDictionary source, string prefix, IDictionary sink) { foreach (var (key, value) in source) { var path = string.IsNullOrEmpty(prefix) ? key : $"{prefix}:{key}"; switch (value) { case null: sink[path] = null; break; case IDictionary nested: Flatten(nested, path, sink); break; case System.Collections.IEnumerable list when value is not string: { var i = 0; foreach (var item in list) { var itemPath = $"{path}:{i}"; if (item is IDictionary itemDict) Flatten(itemDict, itemPath, sink); else sink[itemPath] = item?.ToString(); i++; } break; } default: sink[path] = value.ToString(); break; } } } } /// /// In-memory snapshot of the Identity:Ldap configuration sub-section. /// internal sealed class LdapIntegrationConfig { /// Master switch. When false, no LDAP services are registered. public bool Enabled { get; set; } /// List of LDAP providers to register as IExternalUserProvider. public List Providers { get; set; } = new(); } Path: redb-identity/src/redb.Identity.Core.Module/Module/manifest.json 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.Core.Module/Module/manifest.json ---- { "Name": "redb.Identity.Core.Module", "Version": "1.0.0", "EntryPoints": [ "redb.Identity.Core.Module.dll" ], "Dependencies": ["redb.Identity.Contracts"] } Path: redb-identity/src/redb.Identity.Core.Module/RedbIdentityHost.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.Core.Module/RedbIdentityHost.cs ---- using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Core; using redb.Route.Http; namespace redb.Identity.Core.Module; /// /// Registration for a process that runs redb.Identity in a host of its own, without a Tsak worker. /// public static class RedbIdentityHostServiceCollectionExtensions { /// /// Registers what the Identity modules take from the process: the shared HTTP server manager /// (one Kestrel per port, as a Tsak worker has it) and the direct-vm registry through which the /// modules call each other. Idempotent. Redb itself and logging are registered by the host as usual /// (AddRedb..., AddLogging); the Identity services are not registered here, the modules /// build them from the configuration sections when runs. /// public static IServiceCollection AddRedbIdentityHost(this IServiceCollection services) { ArgumentNullException.ThrowIfNull(services); services.AddRedbRouteHttpHosting(); services.TryAddSingleton(); return services; } } /// /// redb.Identity running in a host of its own: one route context with the Identity core module and the /// facades the host chose, started from the Identity and IdentityTransport configuration /// sections, the same sections a Tsak worker hands the modules. /// /// /// /// var services = new ServiceCollection(); /// services.AddLogging(); /// services.AddSingleton<IConfiguration>(configuration); /// services.AddRedb...(...); // the redb provider of the host /// services.AddRedbIdentityHost(); /// await using var provider = services.BuildServiceProvider(); /// /// await using var identity = await RedbIdentityHost.StartAsync(provider, configuration, /// redb.Identity.Http.InitRoute.main); /// // ... serve until shutdown; disposing the host stops it. /// /// public sealed class RedbIdentityHost : IAsyncDisposable { /// Configuration section read by the Identity core module. public const string IdentitySection = "Identity"; /// Configuration section read by the facades (ports, TLS, paths). public const string TransportSection = "IdentityTransport"; /// Route context id of the host, the one a Tsak worker gives the core module. public const string ContextId = "identity"; private readonly RouteContext _context; private int _disposed; private RedbIdentityHost(RouteContext context) => _context = context; /// /// The started route context. Its registry holds what the modules publish, for instance the scope /// factory of the Identity container under identity-sp:default. /// public IRouteContext Context => _context; /// /// Starts redb.Identity in this process. /// In order it: checks the host and the configuration and fails with a message that names the /// missing registration or key; creates a route context with the host's logger factory; copies the /// Identity and IdentityTransport sections into the context; runs the entry point of /// redb.Identity.Core.Module, then each facade in the order given; starts the context, which creates /// the schema and seeds on first start and opens the ports; and fails when a route did not start. /// Checked before anything starts: logging and /// are registered; Identity:Issuer is an absolute URI; a key source is chosen, /// Identity:UsePropsSigningKeyStore (keys kept in redb) or Identity:AllowEphemeralKeys /// (development, keys die with the process); IdentityTransport is present when a facade is given. /// /// The host's container: redb, logging and AddRedbIdentityHost(). /// The configuration holding the two sections. /// Entry points of the facades to serve, for example /// redb.Identity.Http.InitRoute.main. None gives the core alone, reachable over direct-vm. /// The running host. Dispose it to stop: routes stop taking work, running exchanges drain, /// then the ports close and the Identity container is disposed. /// The host or the configuration is incomplete, or a route /// failed to start; nothing is left running. public static async Task StartAsync( IServiceProvider provider, IConfiguration configuration, params Func[] facades) { ArgumentNullException.ThrowIfNull(provider); ArgumentNullException.ThrowIfNull(configuration); ArgumentNullException.ThrowIfNull(facades); var loggerFactory = provider.GetService() ?? throw new InvalidOperationException( "redb.Identity host: no ILoggerFactory in the container. Call services.AddLogging() before " + "building the provider; without it the modules' start-up log is lost."); if (provider.GetService() is null || provider.GetService() is null) throw new InvalidOperationException( "redb.Identity host: the container lacks the direct-vm registry or the shared HTTP server " + "manager. Call services.AddRedbIdentityHost() before building the provider."); var identity = configuration.GetSection(IdentitySection); if (!identity.Exists()) throw new InvalidOperationException( $"redb.Identity host: the configuration has no '{IdentitySection}' section. " + $"Set at least '{IdentitySection}:Issuer' and a key source."); var issuer = identity["Issuer"]; if (string.IsNullOrWhiteSpace(issuer) || !Uri.TryCreate(issuer, UriKind.Absolute, out _)) throw new InvalidOperationException( $"redb.Identity host: '{IdentitySection}:Issuer' is {(string.IsNullOrWhiteSpace(issuer) ? "missing" : $"'{issuer}', not an absolute URI")}. " + "Set it to the public address clients see, for example https://id.example.com/."); if (!IsTrue(identity["UsePropsSigningKeyStore"]) && !IsTrue(identity["AllowEphemeralKeys"])) throw new InvalidOperationException( $"redb.Identity host: no signing key source. Set '{IdentitySection}:UsePropsSigningKeyStore' " + $"to true (keys kept in redb, for production) or '{IdentitySection}:AllowEphemeralKeys' to " + "true (development; tokens die with the process)."); if (facades.Length > 0 && !configuration.GetSection(TransportSection).Exists()) throw new InvalidOperationException( $"redb.Identity host: facades were given but the configuration has no '{TransportSection}' " + $"section, so they would listen on their default ports. Set for example " + $"'{TransportSection}:Http:PublicPort'."); var context = new RouteContext(provider, ContextId, loggerFactory); try { context.SetProperty>(IdentitySection, ToDictionary(identity)); var transport = configuration.GetSection(TransportSection); if (transport.Exists()) context.SetProperty>(TransportSection, ToDictionary(transport)); InitRoute.main(context); foreach (var facade in facades) facade(context); await context.Start().ConfigureAwait(false); var errored = context.Routes.Where(r => r.Status == RouteStatus.Errored).Select(r => r.RouteId).ToList(); if (errored.Count > 0) throw new InvalidOperationException( "redb.Identity host: routes failed to start: " + string.Join(", ", errored) + ". The log of the context names the cause."); return new RedbIdentityHost(context); } catch { await context.DisposeAsync().ConfigureAwait(false); throw; } } /// Stops the routes, drains running exchanges, closes the ports and disposes the Identity container. public async ValueTask DisposeAsync() { if (Interlocked.Exchange(ref _disposed, 1) != 0) return; await _context.DisposeAsync().ConfigureAwait(false); } private static bool IsTrue(string? value) => bool.TryParse(value, out var b) && b; // A configuration section as the nested dictionary a Tsak worker hands a module: a leaf is its string // value, a section with children is a dictionary (array items keep their "0", "1", ... keys, which the // module binders read back as list positions). private static IDictionary ToDictionary(IConfigurationSection section) { var result = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var child in section.GetChildren()) result[child.Key] = child.GetChildren().Any() ? ToDictionary(child) : child.Value; return result; } } Path: redb-identity/src/redb.Identity.Core.Module/redb.Identity.Core.Module.config.example.json 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.Core.Module/redb.Identity.Core.Module.config.example.json ---- { "//": [ "redb.Identity.Core module configuration template (Tsak Layer 4: {Module}.config.json).", "Override any value via the standard Tsak 5-layer pipeline:", " Layer 1 (host appsettings): Tsak:Contexts:default:Identity:*", " Layer 2 (per-context): Tsak:Contexts:{contextName}:Identity:*", " Layer 3 (context.json): same shape as below, merged before this file", " Layer 4 (THIS file): defaults shipped with the .tpkg", " Layer 5 (Override, wins): Tsak:Contexts:{contextName}:Override:Identity:*", "Environment-variable overrides use the standard .NET IConfiguration mapping, e.g.:", " Tsak__Contexts__identity__Override__Identity__AccessTokenLifetime=01:00:00", " Tsak__Contexts__identity__Override__Identity__RateLimit__Enabled=true", "", "SECRETS — there is intentionally NO 'SecretsFilePath' option. Do NOT commit real", "secrets to this file. All secret-bearing fields are designed to be supplied at", "runtime via the Layer-5 Override channel (env-vars, Docker secrets, K8s secrets", "mounted as env, or host appsettings outside source control). The fields that", "qualify as secrets are:", " Identity:RecoveryCodePepper (base64 random)", " Identity:RecoveryCodePreviousPeppers[i] (base64, after a rotation)", " Identity:DynamicRegistrationInitialAccessToken (bearer token)", " Identity:FederationProviders[i]:ClientSecret (per provider)", " Identity:RateLimit:RedisConnectionString (if Redis backend)", " Identity:FederationState:RedisConnectionString (if Redis backend)", " Redb:{instance}:ConnectionString (DB credentials)", "Example env-var (Linux/Docker, double-underscore = section separator):", " Tsak__Contexts__identity__Override__Identity__RecoveryCodePepper=", " Tsak__Contexts__identity__Override__Identity__FederationProviders__0__ClientSecret=", "", "Cryptographic keys (SigningCredentials/EncryptionCredentials) are NOT loaded from", "JSON. Set AllowEphemeralKeys=true for development. For production they are loaded", "from a redb-backed RSA key store (mechanism #2) — see the Identity bootstrap docs.", "", "OBSERVABILITY (F3) — the Identity routes emit OTEL spans + metrics on the security-", "critical hot paths. Names are static (cardinality-safe) and surface in any OTEL or", "Prometheus exporter the host wires up:", " identity.token-request span + counter + latency histogram (token endpoint)", " identity.login span + counter + latency histogram (credential check)", " identity.mfa-verify span + counter + latency histogram (TOTP / OTP verify)", "Plus the per-module health probe registered as 'module:identity' in Tsak's", "/api/health/{startup,live,ready} endpoints (database + signing-key + DP-keyring).", "Enable Tsak's Prometheus scrape endpoint via host appsettings:", " Tsak:Metrics:Prometheus:Enabled=true", " Tsak:Metrics:Prometheus:Path=/metrics" ], "ContextName": "identity", "AutoStart": true, "Redb": { "identity-pg": { "Provider": "postgres", "UsePro": true, "ConnectionString": "Host=localhost;Port=5432;Username=postgres;Password=1;Database=redb;Pooling=true", "EnsureCreated": true } }, "Identity": { "RedbInstanceName": "identity-pg", "Issuer": "http://127.0.0.1:8080", "AllowEphemeralKeys": true, "AccessTokenLifetime": "01:00:00", "RefreshTokenLifetime": "14.00:00:00", "RefreshTokenReuseLeeway": "00:00:00", "AuthorizationCodeLifetime": "00:05:00", "IdentityTokenLifetime": "00:05:00", "DisableAccessTokenEncryption": false, "TokenThrottleMaxPerPeriod": 10, "TokenThrottlePeriod": "00:00:01", "TokenRetentionDays": 30, "TokenCleanupInterval": "01:00:00", "TokenCleanupBatchSize": 50, "SessionRetentionDays": 14, "SessionCleanupInterval": "01:00:00", "SessionCookieLifetime": "08:00:00", "ManagementScope": "identity:manage", "AccountScope": "identity:account", "EnableDynamicRegistration": false, "DynamicRegistrationAllowedGrantTypes": [ "authorization_code", "refresh_token" ], "DynamicRegistrationAllowedScopes": [ "openid", "profile", "email", "phone", "address", "offline_access", "groups", "roles" ], "DynamicRegistrationInitialAccessToken": null, "EnableDeviceCodeFlow": true, "DeviceCodeLifetime": "00:10:00", "DeviceCodePollingInterval": 5, "EnablePushedAuthorization": true, "RequirePushedAuthorizationRequests": false, "PushedAuthorizationRequestLifetime": "00:01:30", "Dpop": { "Enabled": true, "RequireForAccessTokens": false, "AllowedSigningAlgorithms": [ "ES256", "ES384", "PS256", "RS256" ], "IatToleranceSeconds": 60, "RequireNonce": false }, "Ldap": { "//": [ "Variant B integration: LDAP external user provider, opt-in.", "When Enabled=true, each entry in Providers[] is registered as an", "IExternalUserProvider in the Identity child SP and consumed by LoginService.", "The sync route (LdapSyncRouteBuilder) is NOT auto-started here — see", "src/redb.Identity.Ldap/PACKAGING.md for the rationale and follow-up.", "", "BindPassword is a SECRET — supply via Layer-5 Override channel:", " Tsak__Contexts__identity__Override__Identity__Ldap__Providers__0__BindPassword=", "", "Two presets are recognised by AttributeMap conventions (see LdapProviderOptions.ApplyPreset):", " • OpenLDAP — UserFilter '(uid={0})', externalId=uid", " • ActiveDirectory — UserFilter '(&(objectClass=user)(sAMAccountName={0}))', externalId=sAMAccountName", "Multiple providers are tried in Priority order (lower = first). Use Domains[] to route", "user@example.com / EXAMPLE\\user to a specific provider based on the hint." ], "Enabled": false, "Providers": [ { "//": "Example placeholder — REMOVE or REPLACE before enabling.", "ProviderName": "ldap-corp", "Priority": 100, "Server": "REPLACE_ME.example.com", "Port": 389, "UseSsl": false, "UseStartTls": true, "SkipCertificateValidation": false, "BindDn": "cn=svc-identity,ou=service-accounts,dc=example,dc=com", "BindPassword": null, "OperationTimeoutSeconds": 10, "ConnectTimeoutSeconds": 10, "MaxConnections": 5, "UserBaseDn": "ou=users,dc=example,dc=com", "UserFilter": "(uid={0})", "SearchScope": "Subtree", "Domains": [ "example.com" ], "CheckAccountStatus": false, "AttributeMap": { "externalId": "uid", "displayName": "cn", "email": "mail", "phone": "telephoneNumber", "givenName": "givenName", "familyName": "sn" }, "AdditionalClaimsMap": { "department": "departmentNumber", "title": "title" } } ] }, "EnablePasswordFlow": false, "EnableTokenExchange": false, "TokenExchangeAllowImpersonation": false, "TokenExchangeMaxDelegationDepth": 5, "LoginPath": "/login", "ConsentPath": "/consent", "MfaPath": "/mfa", "MfaRecoveryPath": "/mfa/recovery", "OtpCooldown": "00:01:00", "OtpMaxPerHour": 5, "MfaLockoutClockSkew": "00:00:05", "RecoveryCodePepper": null, "RecoveryCodePreviousPeppers": null, "RecoveryCodePbkdf2Iterations": 600000, "LoginTitle": "Sign In", "LogoUrl": null, "PrimaryColor": "#2563eb", "PrimaryColorHover": "#1d4ed8", "CustomCss": null, "EnableScim": false, "ScimScope": "scim", "EnableFederation": false, "FederationProviders": [ { "//": "Example placeholder — remove or replace with real providers.", "ProviderId": "google", "DisplayName": "Google", "Authority": "https://accounts.google.com", "ClientId": "REPLACE_ME", "ClientSecret": "REPLACE_ME", "Scopes": [ "openid", "profile", "email" ], "AutoProvision": true, "Priority": 100 } ], "ReverseProxies": { "//": [ "Secure-by-default: TrustForwardedFor=false ignores X-Forwarded-For entirely", "and uses the socket IP as the client IP. Enable ONLY when behind a trusted", "proxy whose IPs are listed below — otherwise per-IP rate limits can be spoofed.", "", "Format:", " KnownProxies — exact IPv4/IPv6 addresses of trusted reverse proxies.", " KnownNetworks — CIDR ranges (string 'address/prefix'), e.g. '10.0.0.0/8'.", "", "Templates (REPLACE_ME — uncomment and adjust before enabling):", " \"KnownProxies\": [ \"10.0.0.1\", \"203.0.113.7\" ],", " \"KnownNetworks\": [ \"10.0.0.0/8\", \"192.168.0.0/16\", \"fd00::/8\" ]" ], "TrustForwardedFor": false, "KnownProxies": [], "KnownNetworks": [] }, "RateLimit": { "//": "C1: per-IP and per-(IP+username) throttling on /connect/token and /login.", "Enabled": true, "PerIpPerMinute": 30, "PerIpUsernameFailures": 5, "PerIpUsernameWindow": "00:15:00", "DefaultRetryAfterSeconds": 60, "Backend": "memory", "RedisConnectionString": null, "RedisKeyPrefix": "redb:identity:rl:" }, "Validation": { "//": [ "Server-side input-length limits applied by management & registration processors.", "Regex overrides: leave null to use the source-generated defaults shown in comments.", "NOTE: password length/policy lives in 'PasswordPolicy' below — Min/MaxPasswordLength", "here remain only for legacy non-password fields (client_secret length sanity etc.)." ], "MaxIdentifierLength": 128, "MaxDisplayNameLength": 256, "MaxDescriptionLength": 1024, "MinPasswordLength": 8, "MaxPasswordLength": 512, "IdentifierPattern": null, "//IdentifierPatternDefault": "^[a-zA-Z0-9\\-_.]+$", "EmailPattern": null, "//EmailPatternDefault": "^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$", "PhonePattern": null, "//PhonePatternDefault": "^\\+[1-9]\\d{1,14}$" }, "PasswordPolicy": { "//": [ "H10 — server-side password policy applied by:", " • POST /api/v1/identity/users (admin Create)", " • PUT /api/v1/identity/users/{id}/password (admin Change)", " • PUT /me/password (self-service)", " • POST /scim/v2/Users + PATCH (SCIM)", "Defaults are STRICT (NIST SP 800-63B / OWASP ASVS 4.0.3 §2.1).", "Each knob is overridable through the standard 5-layer Tsak pipeline, e.g.:", " Tsak__Contexts__identity__Override__Identity__PasswordPolicy__MinLength=14", "Set HistoryCount=0 to disable history checks entirely.", "Set MaxAge='00:00:00' to disable forced password expiration on login.", "Set BreachCheckEnabled=true ONLY when a checker is registered (e.g. via the", "redb.Identity.PasswordPolicy.Hibp companion package); otherwise the flag is a no-op." ], "MinLength": 12, "MaxLength": 512, "RequireDigit": true, "RequireUppercase": true, "RequireLowercase": true, "RequireSpecial": false, "SpecialChars": "!@#$%^&*()-_=+[]{}|;:,.<>?/`~\"'\\\\", "HistoryCount": 5, "MaxAge": "90.00:00:00", "BreachCheckEnabled": false }, "FederationState": { "//": [ "C6 — hardening of the federation state parameter (encrypted with DataProtection).", "StateMaxAge: TTL for the encrypted blob (HH:mm:ss). Issued-at timestamp is checked against this.", "RequireOneTimeUse: reject replay of the same state blob (jti tracked in the nonce store).", "RequireBrowserBinding: tie the state to a per-flow cookie (set on /challenge, verified on /callback).", "Backend: 'memory' (default; per-process) or 'redis' (cluster-safe; required behind multiple instances).", "RedisConnectionString: optional override; falls back to RateLimit.RedisConnectionString when null." ], "StateMaxAge": "00:05:00", "RequireOneTimeUse": true, "RequireBrowserBinding": false, "BindingCookieName": "redb_fed_b", "Backend": "memory", "RedisConnectionString": null, "RedisKeyPrefix": "redb:identity:fed:nonce:" } } } Path: redb-identity/src/redb.Identity.Core.Module/redb.Identity.Core.Module.config.json 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.Core.Module/redb.Identity.Core.Module.config.json ---- { "//": [ "Tsak Layer 4 stub — module identity only.", "All business config lives in the EXTERNAL Libs/context.json (Layer 3),", "alongside the .tpkg files. See: redb.Identity.Core.Module.config.example.json", "for the full annotated template (reference, NOT shipped)." ], "ContextName": "identity.core", "AutoStart": true } Path: redb-identity/src/redb.Identity.Core.Module/redb.Identity.Core.Module.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.Core.Module/redb.Identity.Core.Module.csproj ---- redb.Identity.Core.Module redb.Identity.Core.Module redb.Tsak .tpkg host glue for redb.Identity.Core — IRouteModule entry point, configuration binding and named-redb wiring. true PreserveNewest PreserveNewest